blob: a8d54a50325db93a66b1afda7155e93165d5e607 [file] [log] [blame]
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Jun 11
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 Moolenaare2cc9702005-03-15 22:43:58 +000012done, the features in this document are not available. See |+eval| and
Bram Moolenaard8b02732005-01-14 21:48:43 +000013|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|
Bram Moolenaar7c626922005-02-07 22:01:03 +000018 1.3 Lists |Lists|
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 Moolenaar748bf032005-02-02 23:04:36 +000083< *E745* *E728* *E703* *E729* *E730* *E731*
84List, Dictionary 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 Moolenaar748bf032005-02-02 23:04:36 +000096 *Funcref* *E695* *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 Moolenaar383f9bc2005-01-19 22:18:32 +0000121 :let func = string(Fn)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000122
123You can use |call()| to invoke a Funcref and use a list variable for the
124arguments: >
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000125 :let r = call(Fn, mylist)
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000126
127
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001281.3 Lists ~
Bram Moolenaar7c626922005-02-07 22:01:03 +0000129 *List* *Lists* *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]
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000173 :let mylist += [7, 8]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000174
175To prepend or append an item turn the item into a list by putting [] around
176it. To change a list in-place see |list-modification| below.
177
178
179Sublist ~
180
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000181A part of the List can be obtained by specifying the first and last index,
182separated by a colon in square brackets: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000183 :let shortlist = mylist[2:-1] " get List [3, "four"]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000184
185Omitting the first index is similar to zero. Omitting the last index is
186similar to -1. The difference is that there is no error if the items are not
187available. >
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000188 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
189 :let shortlist = mylist[2:2] " List with one item: [3]
190 :let otherlist = mylist[:] " make a copy of the List
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000191
Bram Moolenaard8b02732005-01-14 21:48:43 +0000192The second index can be just before the first index. In that case the result
193is an empty list. If the second index is lower, this results in an error. >
194 :echo mylist[2:1] " result: []
195 :echo mylist[2:0] " error!
196
Bram Moolenaara7fc0102005-05-18 22:17:12 +0000197NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for
198using a single letter variable before the ":". Insert a space when needed:
199mylist[s : e].
200
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000201
Bram Moolenaar13065c42005-01-08 16:08:21 +0000202List identity ~
Bram Moolenaard8b02732005-01-14 21:48:43 +0000203 *list-identity*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000204When variable "aa" is a list and you assign it to another variable "bb", both
205variables refer to the same list. Thus changing the list "aa" will also
206change "bb": >
207 :let aa = [1, 2, 3]
208 :let bb = aa
209 :call add(aa, 4)
210 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000211< [1, 2, 3, 4]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000212
213Making a copy of a list is done with the |copy()| function. Using [:] also
214works, as explained above. This creates a shallow copy of the list: Changing
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000215a list item in the list will also change the item in the copied list: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000216 :let aa = [[1, 'a'], 2, 3]
217 :let bb = copy(aa)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000218 :call add(aa, 4)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000219 :let aa[0][1] = 'aaa'
220 :echo aa
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000221< [[1, aaa], 2, 3, 4] >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000222 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000223< [[1, aaa], 2, 3]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000224
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000225To make a completely independent list use |deepcopy()|. This also makes a
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000226copy of the values in the list, recursively. Up to a hundred levels deep.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000227
228The operator "is" can be used to check if two variables refer to the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000229List. "isnot" does the opposite. In contrast "==" compares if two lists have
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000230the same value. >
231 :let alist = [1, 2, 3]
232 :let blist = [1, 2, 3]
233 :echo alist is blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000234< 0 >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000235 :echo alist == blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000236< 1
Bram Moolenaar13065c42005-01-08 16:08:21 +0000237
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000238Note about comparing lists: Two lists are considered equal if they have the
239same length and all items compare equal, as with using "==". There is one
240exception: When comparing a number with a string and the string contains extra
241characters beside the number they are not equal. Example: >
242 echo 4 == "4x"
243< 1 >
244 echo [4] == ["4x"]
245< 0
246
247This is to fix the odd behavior of == that can't be changed for backward
248compatibility reasons.
249
Bram Moolenaar13065c42005-01-08 16:08:21 +0000250
251List unpack ~
252
253To unpack the items in a list to individual variables, put the variables in
254square brackets, like list items: >
255 :let [var1, var2] = mylist
256
257When the number of variables does not match the number of items in the list
258this produces an error. To handle any extra items from the list append ";"
259and a variable name: >
260 :let [var1, var2; rest] = mylist
261
262This works like: >
263 :let var1 = mylist[0]
264 :let var2 = mylist[1]
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000265 :let rest = mylist[2:]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000266
267Except that there is no error if there are only two items. "rest" will be an
268empty list then.
269
270
271List modification ~
272 *list-modification*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000273To change a specific item of a list use |:let| this way: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000274 :let list[4] = "four"
275 :let listlist[0][3] = item
276
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000277To change part of a list you can specify the first and last item to be
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000278modified. The value must at least have the number of items in the range: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000279 :let list[3:5] = [3, 4, 5]
280
Bram Moolenaar13065c42005-01-08 16:08:21 +0000281Adding and removing items from a list is done with functions. Here are a few
282examples: >
283 :call insert(list, 'a') " prepend item 'a'
284 :call insert(list, 'a', 3) " insert item 'a' before list[3]
285 :call add(list, "new") " append String item
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000286 :call add(list, [1, 2]) " append a List as one new item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000287 :call extend(list, [1, 2]) " extend the list with two more items
288 :let i = remove(list, 3) " remove item 3
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000289 :unlet list[3] " idem
Bram Moolenaar13065c42005-01-08 16:08:21 +0000290 :let l = remove(list, 3, -1) " remove items 3 to last item
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000291 :unlet list[3 : ] " idem
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000292 :call filter(list, 'v:val !~ "x"') " remove items with an 'x'
Bram Moolenaar13065c42005-01-08 16:08:21 +0000293
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000294Changing the order of items in a list: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000295 :call sort(list) " sort a list alphabetically
296 :call reverse(list) " reverse the order of items
297
Bram Moolenaar13065c42005-01-08 16:08:21 +0000298
299For loop ~
300
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000301The |:for| loop executes commands for each item in a list. A variable is set
302to each item in the list in sequence. Example: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000303 :for item in mylist
304 : call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000305 :endfor
306
307This works like: >
308 :let index = 0
309 :while index < len(mylist)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000310 : let item = mylist[index]
311 : :call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000312 : let index = index + 1
313 :endwhile
314
315Note that all items in the list should be of the same type, otherwise this
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000316results in error |E706|. To avoid this |:unlet| the variable at the end of
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000317the loop.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000318
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000319If all you want to do is modify each item in the list then the |map()|
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000320function will be a simpler method than a for loop.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000321
Bram Moolenaar13065c42005-01-08 16:08:21 +0000322Just like the |:let| command, |:for| also accepts a list of variables. This
323requires the argument to be a list of lists. >
324 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
325 : call Doit(lnum, col)
326 :endfor
327
328This works like a |:let| command is done for each list item. Again, the types
329must remain the same to avoid an error.
330
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000331It is also possible to put remaining items in a List variable: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000332 :for [i, j; rest] in listlist
333 : call Doit(i, j)
334 : if !empty(rest)
335 : echo "remainder: " . string(rest)
336 : endif
337 :endfor
338
339
340List functions ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000341 *E714*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000342Functions that are useful with a List: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000343 :let r = call(funcname, list) " call a function with an argument list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000344 :if empty(list) " check if list is empty
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000345 :let l = len(list) " number of items in list
346 :let big = max(list) " maximum value in list
347 :let small = min(list) " minimum value in list
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000348 :let xs = count(list, 'x') " count nr of times 'x' appears in list
349 :let i = index(list, 'x') " index of first 'x' in list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000350 :let lines = getline(1, 10) " get ten text lines from buffer
351 :call append('$', lines) " append text lines in buffer
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000352 :let list = split("a b c") " create list from items in a string
353 :let string = join(list, ', ') " create string from list items
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000354 :let s = string(list) " String representation of list
355 :call map(list, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000356
Bram Moolenaar0cb032e2005-04-23 20:52:00 +0000357Don't forget that a combination of features can make things simple. For
358example, to add up all the numbers in a list: >
359 :exe 'let sum = ' . join(nrlist, '+')
360
Bram Moolenaar13065c42005-01-08 16:08:21 +0000361
Bram Moolenaard8b02732005-01-14 21:48:43 +00003621.4 Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000363 *Dictionaries* *Dictionary*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000364A Dictionary is an associative array: Each entry has a key and a value. The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000365entry can be located with the key. The entries are stored without a specific
366ordering.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000367
368
369Dictionary creation ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000370 *E720* *E721* *E722* *E723*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000371A Dictionary is created with a comma separated list of entries in curly
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000372braces. Each entry has a key and a value, separated by a colon. Each key can
373only appear once. Examples: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000374 :let mydict = {1: 'one', 2: 'two', 3: 'three'}
375 :let emptydict = {}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000376< *E713* *E716* *E717*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000377A key is always a String. You can use a Number, it will be converted to a
378String automatically. Thus the String '4' and the number 4 will find the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000379entry. Note that the String '04' and the Number 04 are different, since the
380Number will be converted to the String '4'.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000381
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000382A value can be any expression. Using a Dictionary for a value creates a
Bram Moolenaard8b02732005-01-14 21:48:43 +0000383nested Dictionary: >
384 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
385
386An extra comma after the last entry is ignored.
387
388
389Accessing entries ~
390
391The normal way to access an entry is by putting the key in square brackets: >
392 :let val = mydict["one"]
393 :let mydict["four"] = 4
394
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000395You can add new entries to an existing Dictionary this way, unlike Lists.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000396
397For keys that consist entirely of letters, digits and underscore the following
398form can be used |expr-entry|: >
399 :let val = mydict.one
400 :let mydict.four = 4
401
402Since an entry can be any type, also a List and a Dictionary, the indexing and
403key lookup can be repeated: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000404 :echo dict.key[idx].key
Bram Moolenaard8b02732005-01-14 21:48:43 +0000405
406
407Dictionary to List conversion ~
408
409You may want to loop over the entries in a dictionary. For this you need to
410turn the Dictionary into a List and pass it to |:for|.
411
412Most often you want to loop over the keys, using the |keys()| function: >
413 :for key in keys(mydict)
414 : echo key . ': ' . mydict[key]
415 :endfor
416
417The List of keys is unsorted. You may want to sort them first: >
418 :for key in sort(keys(mydict))
419
420To loop over the values use the |values()| function: >
421 :for v in values(mydict)
422 : echo "value: " . v
423 :endfor
424
425If you want both the key and the value use the |items()| function. It returns
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000426a List in which each item is a List with two items, the key and the value: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000427 :for entry in items(mydict)
428 : echo entry[0] . ': ' . entry[1]
429 :endfor
430
431
432Dictionary identity ~
Bram Moolenaar7c626922005-02-07 22:01:03 +0000433 *dict-identity*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000434Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
435Dictionary. Otherwise, assignment results in referring to the same
436Dictionary: >
437 :let onedict = {'a': 1, 'b': 2}
438 :let adict = onedict
439 :let adict['a'] = 11
440 :echo onedict['a']
441 11
442
443For more info see |list-identity|.
444
445
446Dictionary modification ~
447 *dict-modification*
448To change an already existing entry of a Dictionary, or to add a new entry,
449use |:let| this way: >
450 :let dict[4] = "four"
451 :let dict['one'] = item
452
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000453Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
454Three ways to remove the entry with key "aaa" from dict: >
455 :let i = remove(dict, 'aaa')
456 :unlet dict.aaa
457 :unlet dict['aaa']
Bram Moolenaard8b02732005-01-14 21:48:43 +0000458
459Merging a Dictionary with another is done with |extend()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000460 :call extend(adict, bdict)
461This extends adict with all entries from bdict. Duplicate keys cause entries
462in adict to be overwritten. An optional third argument can change this.
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000463Note that the order of entries in a Dictionary is irrelevant, thus don't
464expect ":echo adict" to show the items from bdict after the older entries in
465adict.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000466
467Weeding out entries from a Dictionary can be done with |filter()|: >
Bram Moolenaare2cc9702005-03-15 22:43:58 +0000468 :call filter(dict 'v:val =~ "x"')
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000469This removes all entries from "dict" with a value not matching 'x'.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000470
471
472Dictionary function ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000473 *Dictionary-function* *self* *E725*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000474When a function is defined with the "dict" attribute it can be used in a
475special way with a dictionary. Example: >
476 :function Mylen() dict
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000477 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000478 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000479 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
480 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000481
482This is like a method in object oriented programming. The entry in the
483Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
484the function was invoked from.
485
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000486It is also possible to add a function without the "dict" attribute as a
487Funcref to a Dictionary, but the "self" variable is not available then.
488
489 *numbered-function*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000490To avoid the extra name for the function it can be defined and directly
491assigned to a Dictionary in this way: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000492 :let mydict = {'data': [0, 1, 2, 3]}
493 :function mydict.len() dict
494 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000495 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000496 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000497
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000498The function will then get a number and the value of dict.len is a |Funcref|
499that references this function. The function can only be used through a
500|Funcref|. It will automatically be deleted when there is no |Funcref|
501remaining that refers to it.
502
503It is not necessary to use the "dict" attribute for a numbered function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000504
505
506Functions for Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000507 *E715*
508Functions that can be used with a Dictionary: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000509 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
510 :if empty(dict) " TRUE if dict is empty
511 :let l = len(dict) " number of items in dict
512 :let big = max(dict) " maximum value in dict
513 :let small = min(dict) " minimum value in dict
514 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
515 :let s = string(dict) " String representation of dict
516 :call map(dict, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaard8b02732005-01-14 21:48:43 +0000517
518
5191.5 More about variables ~
Bram Moolenaar13065c42005-01-08 16:08:21 +0000520 *more-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521If you need to know the type of a variable or expression, use the |type()|
522function.
523
524When the '!' flag is included in the 'viminfo' option, global variables that
525start with an uppercase letter, and don't contain a lowercase letter, are
526stored in the viminfo file |viminfo-file|.
527
528When the 'sessionoptions' option contains "global", global variables that
529start with an uppercase letter and contain at least one lowercase letter are
530stored in the session file |session-file|.
531
532variable name can be stored where ~
533my_var_6 not
534My_Var_6 session file
535MY_VAR_6 viminfo file
536
537
538It's possible to form a variable name with curly braces, see
539|curly-braces-names|.
540
541==============================================================================
5422. Expression syntax *expression-syntax*
543
544Expression syntax summary, from least to most significant:
545
546|expr1| expr2 ? expr1 : expr1 if-then-else
547
548|expr2| expr3 || expr3 .. logical OR
549
550|expr3| expr4 && expr4 .. logical AND
551
552|expr4| expr5 == expr5 equal
553 expr5 != expr5 not equal
554 expr5 > expr5 greater than
555 expr5 >= expr5 greater than or equal
556 expr5 < expr5 smaller than
557 expr5 <= expr5 smaller than or equal
558 expr5 =~ expr5 regexp matches
559 expr5 !~ expr5 regexp doesn't match
560
561 expr5 ==? expr5 equal, ignoring case
562 expr5 ==# expr5 equal, match case
563 etc. As above, append ? for ignoring case, # for
564 matching case
565
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000566 expr5 is expr5 same List instance
567 expr5 isnot expr5 different List instance
568
569|expr5| expr6 + expr6 .. number addition or list concatenation
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 expr6 - expr6 .. number subtraction
571 expr6 . expr6 .. string concatenation
572
573|expr6| expr7 * expr7 .. number multiplication
574 expr7 / expr7 .. number division
575 expr7 % expr7 .. number modulo
576
577|expr7| ! expr7 logical NOT
578 - expr7 unary minus
579 + expr7 unary plus
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000582|expr8| expr8[expr1] byte of a String or item of a List
583 expr8[expr1 : expr1] substring of a String or sublist of a List
584 expr8.name entry in a Dictionary
585 expr8(expr1, ...) function call with Funcref variable
586
587|expr9| number number constant
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000588 "string" string constant, backslash is special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000589 'string' string constant, ' is doubled
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000590 [expr1, ...] List
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000591 {expr1: expr1, ...} Dictionary
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592 &option option value
593 (expr1) nested expression
594 variable internal variable
595 va{ria}ble internal variable with curly braces
596 $VAR environment variable
597 @r contents of register 'r'
598 function(expr1, ...) function call
599 func{ti}on(expr1, ...) function call with curly braces
600
601
602".." indicates that the operations in this level can be concatenated.
603Example: >
604 &nu || &list && &shell == "csh"
605
606All expressions within one level are parsed from left to right.
607
608
609expr1 *expr1* *E109*
610-----
611
612expr2 ? expr1 : expr1
613
614The expression before the '?' is evaluated to a number. If it evaluates to
615non-zero, the result is the value of the expression between the '?' and ':',
616otherwise the result is the value of the expression after the ':'.
617Example: >
618 :echo lnum == 1 ? "top" : lnum
619
620Since the first expression is an "expr2", it cannot contain another ?:. The
621other two expressions can, thus allow for recursive use of ?:.
622Example: >
623 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
624
625To keep this readable, using |line-continuation| is suggested: >
626 :echo lnum == 1
627 :\ ? "top"
628 :\ : lnum == 1000
629 :\ ? "last"
630 :\ : lnum
631
632
633expr2 and expr3 *expr2* *expr3*
634---------------
635
636 *expr-barbar* *expr-&&*
637The "||" and "&&" operators take one argument on each side. The arguments
638are (converted to) Numbers. The result is:
639
640 input output ~
641n1 n2 n1 || n2 n1 && n2 ~
642zero zero zero zero
643zero non-zero non-zero zero
644non-zero zero non-zero zero
645non-zero non-zero non-zero non-zero
646
647The operators can be concatenated, for example: >
648
649 &nu || &list && &shell == "csh"
650
651Note that "&&" takes precedence over "||", so this has the meaning of: >
652
653 &nu || (&list && &shell == "csh")
654
655Once the result is known, the expression "short-circuits", that is, further
656arguments are not evaluated. This is like what happens in C. For example: >
657
658 let a = 1
659 echo a || b
660
661This is valid even if there is no variable called "b" because "a" is non-zero,
662so the result must be non-zero. Similarly below: >
663
664 echo exists("b") && b == "yes"
665
666This is valid whether "b" has been defined or not. The second clause will
667only be evaluated if "b" has been defined.
668
669
670expr4 *expr4*
671-----
672
673expr5 {cmp} expr5
674
675Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
676if it evaluates to true.
677
678 *expr-==* *expr-!=* *expr->* *expr->=*
679 *expr-<* *expr-<=* *expr-=~* *expr-!~*
680 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
681 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
682 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
683 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000684 *expr-is*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685 use 'ignorecase' match case ignore case ~
686equal == ==# ==?
687not equal != !=# !=?
688greater than > ># >?
689greater than or equal >= >=# >=?
690smaller than < <# <?
691smaller than or equal <= <=# <=?
692regexp matches =~ =~# =~?
693regexp doesn't match !~ !~# !~?
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000694same instance is
695different instance isnot
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696
697Examples:
698"abc" ==# "Abc" evaluates to 0
699"abc" ==? "Abc" evaluates to 1
700"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
701
Bram Moolenaar13065c42005-01-08 16:08:21 +0000702 *E691* *E692*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000703A List can only be compared with a List and only "equal", "not equal" and "is"
704can be used. This compares the values of the list, recursively. Ignoring
705case means case is ignored when comparing item values.
706
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000707 *E735* *E736*
708A Dictionary can only be compared with a Dictionary and only "equal", "not
709equal" and "is" can be used. This compares the key/values of the Dictionary,
710recursively. Ignoring case means case is ignored when comparing item values.
711
Bram Moolenaar13065c42005-01-08 16:08:21 +0000712 *E693* *E694*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000713A Funcref can only be compared with a Funcref and only "equal" and "not equal"
714can be used. Case is never ignored.
715
716When using "is" or "isnot" with a List this checks if the expressions are
717referring to the same List instance. A copy of a List is different from the
718original List. When using "is" without a List it is equivalent to using
719"equal", using "isnot" equivalent to using "not equal". Except that a
720different type means the values are different. "4 == '4'" is true, "4 is '4'"
721is false.
722
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723When comparing a String with a Number, the String is converted to a Number,
724and the comparison is done on Numbers. This means that "0 == 'x'" is TRUE,
725because 'x' converted to a Number is zero.
726
727When comparing two Strings, this is done with strcmp() or stricmp(). This
728results in the mathematical difference (comparing byte values), not
729necessarily the alphabetical difference in the local language.
730
731When using the operators with a trailing '#", or the short version and
732'ignorecase' is off, the comparing is done with strcmp().
733
734When using the operators with a trailing '?', or the short version and
735'ignorecase' is set, the comparing is done with stricmp().
736
737The "=~" and "!~" operators match the lefthand argument with the righthand
738argument, which is used as a pattern. See |pattern| for what a pattern is.
739This matching is always done like 'magic' was set and 'cpoptions' is empty, no
740matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
741portable. To avoid backslashes in the regexp pattern to be doubled, use a
742single-quote string, see |literal-string|.
743Since a string is considered to be a single line, a multi-line pattern
744(containing \n, backslash-n) will not match. However, a literal NL character
745can be matched like an ordinary character. Examples:
746 "foo\nbar" =~ "\n" evaluates to 1
747 "foo\nbar" =~ "\\n" evaluates to 0
748
749
750expr5 and expr6 *expr5* *expr6*
751---------------
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000752expr6 + expr6 .. Number addition or List concatenation *expr-+*
753expr6 - expr6 .. Number subtraction *expr--*
754expr6 . expr6 .. String concatenation *expr-.*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000756For Lists only "+" is possible and then both expr6 must be a list. The result
757is a new list with the two lists Concatenated.
758
759expr7 * expr7 .. number multiplication *expr-star*
760expr7 / expr7 .. number division *expr-/*
761expr7 % expr7 .. number modulo *expr-%*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762
763For all, except ".", Strings are converted to Numbers.
764
765Note the difference between "+" and ".":
766 "123" + "456" = 579
767 "123" . "456" = "123456"
768
769When the righthand side of '/' is zero, the result is 0x7fffffff.
770When the righthand side of '%' is zero, the result is 0.
771
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000772None of these work for Funcrefs.
773
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774
775expr7 *expr7*
776-----
777! expr7 logical NOT *expr-!*
778- expr7 unary minus *expr-unary--*
779+ expr7 unary plus *expr-unary-+*
780
781For '!' non-zero becomes zero, zero becomes one.
782For '-' the sign of the number is changed.
783For '+' the number is unchanged.
784
785A String will be converted to a Number first.
786
787These three can be repeated and mixed. Examples:
788 !-1 == 0
789 !!8 == 1
790 --9 == 9
791
792
793expr8 *expr8*
794-----
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000795expr8[expr1] item of String or List *expr-[]* *E111*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000797If expr8 is a Number or String this results in a String that contains the
798expr1'th single byte from expr8. expr8 is used as a String, expr1 as a
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000799Number. Note that this doesn't recognize multi-byte encodings.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000801Index zero gives the first character. This is like it works in C. Careful:
802text column numbers start with one! Example, to get the character under the
803cursor: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 :let c = getline(line("."))[col(".") - 1]
805
806If the length of the String is less than the index, the result is an empty
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000807String. A negative index always results in an empty string (reason: backwards
808compatibility). Use [-1:] to get the last byte.
809
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000810If expr8 is a List then it results the item at index expr1. See |list-index|
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000811for possible index values. If the index is out of range this results in an
812error. Example: >
813 :let item = mylist[-1] " get last item
814
815Generally, if a List index is equal to or higher than the length of the List,
816or more negative than the length of the List, this results in an error.
817
Bram Moolenaard8b02732005-01-14 21:48:43 +0000818
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000819expr8[expr1a : expr1b] substring or sublist *expr-[:]*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000820
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000821If expr8 is a Number or String this results in the substring with the bytes
822from expr1a to and including expr1b. expr8 is used as a String, expr1a and
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000823expr1b are used as a Number. Note that this doesn't recognize multi-byte
824encodings.
825
826If expr1a is omitted zero is used. If expr1b is omitted the length of the
827string minus one is used.
828
829A negative number can be used to measure from the end of the string. -1 is
830the last character, -2 the last but one, etc.
831
832If an index goes out of range for the string characters are omitted. If
833expr1b is smaller than expr1a the result is an empty string.
834
835Examples: >
836 :let c = name[-1:] " last byte of a string
837 :let c = name[-2:-2] " last but one byte of a string
838 :let s = line(".")[4:] " from the fifth byte to the end
839 :let s = s[:-3] " remove last two bytes
840
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000841If expr8 is a List this results in a new List with the items indicated by the
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000842indexes expr1a and expr1b. This works like with a String, as explained just
843above, except that indexes out of range cause an error. Examples: >
844 :let l = mylist[:3] " first four items
845 :let l = mylist[4:4] " List with one item
846 :let l = mylist[:] " shallow copy of a List
847
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000848Using expr8[expr1] or expr8[expr1a : expr1b] on a Funcref results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849
Bram Moolenaard8b02732005-01-14 21:48:43 +0000850
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000851expr8.name entry in a Dictionary *expr-entry*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000852
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000853If expr8 is a Dictionary and it is followed by a dot, then the following name
854will be used as a key in the Dictionary. This is just like: expr8[name].
Bram Moolenaard8b02732005-01-14 21:48:43 +0000855
856The name must consist of alphanumeric characters, just like a variable name,
857but it may start with a number. Curly braces cannot be used.
858
859There must not be white space before or after the dot.
860
861Examples: >
862 :let dict = {"one": 1, 2: "two"}
863 :echo dict.one
864 :echo dict .2
865
866Note that the dot is also used for String concatenation. To avoid confusion
867always put spaces around the dot for String concatenation.
868
869
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000870expr8(expr1, ...) Funcref function call
871
872When expr8 is a |Funcref| type variable, invoke the function it refers to.
873
874
875
876 *expr9*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877number
878------
879number number constant *expr-number*
880
881Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
882
883
884string *expr-string* *E114*
885------
886"string" string constant *expr-quote*
887
888Note that double quotes are used.
889
890A string constant accepts these special characters:
891\... three-digit octal number (e.g., "\316")
892\.. two-digit octal number (must be followed by non-digit)
893\. one-digit octal number (must be followed by non-digit)
894\x.. byte specified with two hex numbers (e.g., "\x1f")
895\x. byte specified with one hex number (must be followed by non-hex char)
896\X.. same as \x..
897\X. same as \x.
898\u.... character specified with up to 4 hex numbers, stored according to the
899 current value of 'encoding' (e.g., "\u02a4")
900\U.... same as \u....
901\b backspace <BS>
902\e escape <Esc>
903\f formfeed <FF>
904\n newline <NL>
905\r return <CR>
906\t tab <Tab>
907\\ backslash
908\" double quote
909\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W.
910
911Note that "\000" and "\x00" force the end of the string.
912
913
914literal-string *literal-string* *E115*
915---------------
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000916'string' string constant *expr-'*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918Note that single quotes are used.
919
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000920This string is taken as it is. No backslashes are removed or have a special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000921meaning. The only exception is that two quotes stand for one quote.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000922
923Single quoted strings are useful for patterns, so that backslashes do not need
924to be doubled. These two commands are equivalent: >
925 if a =~ "\\s*"
926 if a =~ '\s*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
928
929option *expr-option* *E112* *E113*
930------
931&option option value, local value if possible
932&g:option global option value
933&l:option local option value
934
935Examples: >
936 echo "tabstop is " . &tabstop
937 if &insertmode
938
939Any option name can be used here. See |options|. When using the local value
940and there is no buffer-local or window-local value, the global value is used
941anyway.
942
943
944register *expr-register*
945--------
946@r contents of register 'r'
947
948The result is the contents of the named register, as a single string.
949Newlines are inserted where required. To get the contents of the unnamed
950register use @" or @@. The '=' register can not be used here. See
951|registers| for an explanation of the available registers.
952
953
954nesting *expr-nesting* *E110*
955-------
956(expr1) nested expression
957
958
959environment variable *expr-env*
960--------------------
961$VAR environment variable
962
963The String value of any environment variable. When it is not defined, the
964result is an empty string.
965 *expr-env-expand*
966Note that there is a difference between using $VAR directly and using
967expand("$VAR"). Using it directly will only expand environment variables that
968are known inside the current Vim session. Using expand() will first try using
969the environment variables known inside the current Vim session. If that
970fails, a shell will be used to expand the variable. This can be slow, but it
971does expand all variables that the shell knows about. Example: >
972 :echo $version
973 :echo expand("$version")
974The first one probably doesn't echo anything, the second echoes the $version
975variable (if your shell supports it).
976
977
978internal variable *expr-variable*
979-----------------
980variable internal variable
981See below |internal-variables|.
982
983
Bram Moolenaar05159a02005-02-26 23:04:13 +0000984function call *expr-function* *E116* *E118* *E119* *E120*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985-------------
986function(expr1, ...) function call
987See below |functions|.
988
989
990==============================================================================
9913. Internal variable *internal-variables* *E121*
992 *E461*
993An internal variable name can be made up of letters, digits and '_'. But it
994cannot start with a digit. It's also possible to use curly braces, see
995|curly-braces-names|.
996
997An internal variable is created with the ":let" command |:let|.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000998An internal variable is explicitly destroyed with the ":unlet" command
999|:unlet|.
1000Using a name that is not an internal variable or refers to a variable that has
1001been destroyed results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002
1003There are several name spaces for variables. Which one is to be used is
1004specified by what is prepended:
1005
1006 (nothing) In a function: local to a function; otherwise: global
1007|buffer-variable| b: Local to the current buffer.
1008|window-variable| w: Local to the current window.
1009|global-variable| g: Global.
1010|local-variable| l: Local to a function.
1011|script-variable| s: Local to a |:source|'ed Vim script.
1012|function-argument| a: Function argument (only inside a function).
1013|vim-variable| v: Global, predefined by Vim.
1014
Bram Moolenaar8f999f12005-01-25 22:12:55 +00001015The scope name by itself can be used as a Dictionary. For example, to delete
1016all script-local variables: >
1017 :for k in keys(s:)
1018 : unlet s:[k]
1019 :endfor
1020<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021 *buffer-variable* *b:var*
1022A variable name that is preceded with "b:" is local to the current buffer.
1023Thus you can have several "b:foo" variables, one for each buffer.
1024This kind of variable is deleted when the buffer is wiped out or deleted with
1025|:bdelete|.
1026
1027One local buffer variable is predefined:
1028 *b:changedtick-variable* *changetick*
1029b:changedtick The total number of changes to the current buffer. It is
1030 incremented for each change. An undo command is also a change
1031 in this case. This can be used to perform an action only when
1032 the buffer has changed. Example: >
1033 :if my_changedtick != b:changedtick
1034 : let my_changedtick = b:changedtick
1035 : call My_Update()
1036 :endif
1037<
1038 *window-variable* *w:var*
1039A variable name that is preceded with "w:" is local to the current window. It
1040is deleted when the window is closed.
1041
1042 *global-variable* *g:var*
1043Inside functions global variables are accessed with "g:". Omitting this will
1044access a variable local to a function. But "g:" can also be used in any other
1045place if you like.
1046
1047 *local-variable* *l:var*
1048Inside functions local variables are accessed without prepending anything.
1049But you can also prepend "l:" if you like.
1050
1051 *script-variable* *s:var*
1052In a Vim script variables starting with "s:" can be used. They cannot be
1053accessed from outside of the scripts, thus are local to the script.
1054
1055They can be used in:
1056- commands executed while the script is sourced
1057- functions defined in the script
1058- autocommands defined in the script
1059- functions and autocommands defined in functions and autocommands which were
1060 defined in the script (recursively)
1061- user defined commands defined in the script
1062Thus not in:
1063- other scripts sourced from this one
1064- mappings
1065- etc.
1066
1067script variables can be used to avoid conflicts with global variable names.
1068Take this example:
1069
1070 let s:counter = 0
1071 function MyCounter()
1072 let s:counter = s:counter + 1
1073 echo s:counter
1074 endfunction
1075 command Tick call MyCounter()
1076
1077You can now invoke "Tick" from any script, and the "s:counter" variable in
1078that script will not be changed, only the "s:counter" in the script where
1079"Tick" was defined is used.
1080
1081Another example that does the same: >
1082
1083 let s:counter = 0
1084 command Tick let s:counter = s:counter + 1 | echo s:counter
1085
1086When calling a function and invoking a user-defined command, the context for
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001087script variables is set to the script where the function or command was
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088defined.
1089
1090The script variables are also available when a function is defined inside a
1091function that is defined in a script. Example: >
1092
1093 let s:counter = 0
1094 function StartCounting(incr)
1095 if a:incr
1096 function MyCounter()
1097 let s:counter = s:counter + 1
1098 endfunction
1099 else
1100 function MyCounter()
1101 let s:counter = s:counter - 1
1102 endfunction
1103 endif
1104 endfunction
1105
1106This defines the MyCounter() function either for counting up or counting down
1107when calling StartCounting(). It doesn't matter from where StartCounting() is
1108called, the s:counter variable will be accessible in MyCounter().
1109
1110When the same script is sourced again it will use the same script variables.
1111They will remain valid as long as Vim is running. This can be used to
1112maintain a counter: >
1113
1114 if !exists("s:counter")
1115 let s:counter = 1
1116 echo "script executed for the first time"
1117 else
1118 let s:counter = s:counter + 1
1119 echo "script executed " . s:counter . " times now"
1120 endif
1121
1122Note that this means that filetype plugins don't get a different set of script
1123variables for each buffer. Use local buffer variables instead |b:var|.
1124
1125
1126Predefined Vim variables: *vim-variable* *v:var*
1127
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001128 *v:beval_col* *beval_col-variable*
1129v:beval_col The number of the column, over which the mouse pointer is.
1130 This is the byte index in the |v:beval_lnum| line.
1131 Only valid while evaluating the 'balloonexpr' option.
1132
1133 *v:beval_bufnr* *beval_bufnr-variable*
1134v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
1135 valid while evaluating the 'balloonexpr' option.
1136
1137 *v:beval_lnum* *beval_lnum-variable*
1138v:beval_lnum The number of the line, over which the mouse pointer is. Only
1139 valid while evaluating the 'balloonexpr' option.
1140
1141 *v:beval_text* *beval_text-variable*
1142v:beval_text The text under or after the mouse pointer. Usually a word as it is
1143 useful for debugging a C program. 'iskeyword' applies, but a
1144 dot and "->" before the position is included. When on a ']'
1145 the text before it is used, including the matching '[' and
1146 word before it. When on a Visual area within one line the
1147 highlighted text is used.
1148 Only valid while evaluating the 'balloonexpr' option.
1149
1150 *v:beval_winnr* *beval_winnr-variable*
1151v:beval_winnr The number of the window, over which the mouse pointer is. Only
1152 valid while evaluating the 'balloonexpr' option.
1153
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 *v:charconvert_from* *charconvert_from-variable*
1155v:charconvert_from
1156 The name of the character encoding of a file to be converted.
1157 Only valid while evaluating the 'charconvert' option.
1158
1159 *v:charconvert_to* *charconvert_to-variable*
1160v:charconvert_to
1161 The name of the character encoding of a file after conversion.
1162 Only valid while evaluating the 'charconvert' option.
1163
1164 *v:cmdarg* *cmdarg-variable*
1165v:cmdarg This variable is used for two purposes:
1166 1. The extra arguments given to a file read/write command.
1167 Currently these are "++enc=" and "++ff=". This variable is
1168 set before an autocommand event for a file read/write
1169 command is triggered. There is a leading space to make it
1170 possible to append this variable directly after the
1171 read/write command. Note: The "+cmd" argument isn't
1172 included here, because it will be executed anyway.
1173 2. When printing a PostScript file with ":hardcopy" this is
1174 the argument for the ":hardcopy" command. This can be used
1175 in 'printexpr'.
1176
1177 *v:cmdbang* *cmdbang-variable*
1178v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1179 was used the value is 1, otherwise it is 0. Note that this
1180 can only be used in autocommands. For user commands |<bang>|
1181 can be used.
1182
1183 *v:count* *count-variable*
1184v:count The count given for the last Normal mode command. Can be used
1185 to get the count before a mapping. Read-only. Example: >
1186 :map _x :<C-U>echo "the count is " . v:count<CR>
1187< Note: The <C-U> is required to remove the line range that you
1188 get when typing ':' after a count.
1189 "count" also works, for backwards compatibility.
1190
1191 *v:count1* *count1-variable*
1192v:count1 Just like "v:count", but defaults to one when no count is
1193 used.
1194
1195 *v:ctype* *ctype-variable*
1196v:ctype The current locale setting for characters of the runtime
1197 environment. This allows Vim scripts to be aware of the
1198 current locale encoding. Technical: it's the value of
1199 LC_CTYPE. When not using a locale the value is "C".
1200 This variable can not be set directly, use the |:language|
1201 command.
1202 See |multi-lang|.
1203
1204 *v:dying* *dying-variable*
1205v:dying Normally zero. When a deadly signal is caught it's set to
1206 one. When multiple signals are caught the number increases.
1207 Can be used in an autocommand to check if Vim didn't
1208 terminate normally. {only works on Unix}
1209 Example: >
1210 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
1211<
1212 *v:errmsg* *errmsg-variable*
1213v:errmsg Last given error message. It's allowed to set this variable.
1214 Example: >
1215 :let v:errmsg = ""
1216 :silent! next
1217 :if v:errmsg != ""
1218 : ... handle error
1219< "errmsg" also works, for backwards compatibility.
1220
1221 *v:exception* *exception-variable*
1222v:exception The value of the exception most recently caught and not
1223 finished. See also |v:throwpoint| and |throw-variables|.
1224 Example: >
1225 :try
1226 : throw "oops"
1227 :catch /.*/
1228 : echo "caught" v:exception
1229 :endtry
1230< Output: "caught oops".
1231
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001232 *v:fcs_reason* *fcs_reason-variable*
1233v:fcs_reason The reason why the |FileChangedShell| event was triggered.
1234 Can be used in an autocommand to decide what to do and/or what
1235 to set v:fcs_choice to. Possible values:
1236 deleted file no longer exists
1237 conflict file contents, mode or timestamp was
1238 changed and buffer is modified
1239 changed file contents has changed
1240 mode mode of file changed
1241 time only file timestamp changed
1242
1243 *v:fcs_choice* *fcs_choice-variable*
1244v:fcs_choice What should happen after a |FileChangedShell| event was
1245 triggered. Can be used in an autocommand to tell Vim what to
1246 do with the affected buffer:
1247 reload Reload the buffer (does not work if
1248 the file was deleted).
1249 ask Ask the user what to do, as if there
1250 was no autocommand. Except that when
1251 only the timestamp changed nothing
1252 will happen.
1253 <empty> Nothing, the autocommand should do
1254 everything that needs to be done.
1255 The default is empty. If another (invalid) value is used then
1256 Vim behaves like it is empty, there is no warning message.
1257
Bram Moolenaar071d4272004-06-13 20:20:40 +00001258 *v:fname_in* *fname_in-variable*
1259v:fname_in The name of the input file. Only valid while evaluating:
1260 option used for ~
1261 'charconvert' file to be converted
1262 'diffexpr' original file
1263 'patchexpr' original file
1264 'printexpr' file to be printed
1265
1266 *v:fname_out* *fname_out-variable*
1267v:fname_out The name of the output file. Only valid while
1268 evaluating:
1269 option used for ~
1270 'charconvert' resulting converted file (*)
1271 'diffexpr' output of diff
1272 'patchexpr' resulting patched file
1273 (*) When doing conversion for a write command (e.g., ":w
1274 file") it will be equal to v:fname_in. When doing conversion
1275 for a read command (e.g., ":e file") it will be a temporary
1276 file and different from v:fname_in.
1277
1278 *v:fname_new* *fname_new-variable*
1279v:fname_new The name of the new version of the file. Only valid while
1280 evaluating 'diffexpr'.
1281
1282 *v:fname_diff* *fname_diff-variable*
1283v:fname_diff The name of the diff (patch) file. Only valid while
1284 evaluating 'patchexpr'.
1285
1286 *v:folddashes* *folddashes-variable*
1287v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
1288 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001289 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290
1291 *v:foldlevel* *foldlevel-variable*
1292v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001293 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294
1295 *v:foldend* *foldend-variable*
1296v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001297 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298
1299 *v:foldstart* *foldstart-variable*
1300v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001301 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302
Bram Moolenaar843ee412004-06-30 16:16:41 +00001303 *v:insertmode* *insertmode-variable*
1304v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
1305 events. Values:
1306 i Insert mode
1307 r Replace mode
1308 v Virtual Replace mode
1309
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001310 *v:key* *key-variable*
1311v:key Key of the current item of a Dictionary. Only valid while
1312 evaluating the expression used with |map()| and |filter()|.
1313 Read-only.
1314
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315 *v:lang* *lang-variable*
1316v:lang The current locale setting for messages of the runtime
1317 environment. This allows Vim scripts to be aware of the
1318 current language. Technical: it's the value of LC_MESSAGES.
1319 The value is system dependent.
1320 This variable can not be set directly, use the |:language|
1321 command.
1322 It can be different from |v:ctype| when messages are desired
1323 in a different language than what is used for character
1324 encoding. See |multi-lang|.
1325
1326 *v:lc_time* *lc_time-variable*
1327v:lc_time The current locale setting for time messages of the runtime
1328 environment. This allows Vim scripts to be aware of the
1329 current language. Technical: it's the value of LC_TIME.
1330 This variable can not be set directly, use the |:language|
1331 command. See |multi-lang|.
1332
1333 *v:lnum* *lnum-variable*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001334v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr'
1335 expressions. Only valid while one of these expressions is
1336 being evaluated. Read-only when in the |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337
1338 *v:prevcount* *prevcount-variable*
1339v:prevcount The count given for the last but one Normal mode command.
1340 This is the v:count value of the previous command. Useful if
1341 you want to cancel Visual mode and then use the count. >
1342 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
1343< Read-only.
1344
Bram Moolenaar05159a02005-02-26 23:04:13 +00001345 *v:profiling* *profiling-variable*
1346v:profiling Normally zero. Set to one after using ":profile start".
1347 See |profiling|.
1348
Bram Moolenaar071d4272004-06-13 20:20:40 +00001349 *v:progname* *progname-variable*
1350v:progname Contains the name (with path removed) with which Vim was
1351 invoked. Allows you to do special initialisations for "view",
1352 "evim" etc., or any other name you might symlink to Vim.
1353 Read-only.
1354
1355 *v:register* *register-variable*
1356v:register The name of the register supplied to the last normal mode
1357 command. Empty if none were supplied. |getreg()| |setreg()|
1358
1359 *v:servername* *servername-variable*
1360v:servername The resulting registered |x11-clientserver| name if any.
1361 Read-only.
1362
1363 *v:shell_error* *shell_error-variable*
1364v:shell_error Result of the last shell command. When non-zero, the last
1365 shell command had an error. When zero, there was no problem.
1366 This only works when the shell returns the error code to Vim.
1367 The value -1 is often used when the command could not be
1368 executed. Read-only.
1369 Example: >
1370 :!mv foo bar
1371 :if v:shell_error
1372 : echo 'could not rename "foo" to "bar"!'
1373 :endif
1374< "shell_error" also works, for backwards compatibility.
1375
1376 *v:statusmsg* *statusmsg-variable*
1377v:statusmsg Last given status message. It's allowed to set this variable.
1378
1379 *v:termresponse* *termresponse-variable*
1380v:termresponse The escape sequence returned by the terminal for the |t_RV|
1381 termcap entry. It is set when Vim receives an escape sequence
1382 that starts with ESC [ or CSI and ends in a 'c', with only
1383 digits, ';' and '.' in between.
1384 When this option is set, the TermResponse autocommand event is
1385 fired, so that you can react to the response from the
1386 terminal.
1387 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
1388 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
1389 patch level (since this was introduced in patch 95, it's
1390 always 95 or bigger). Pc is always zero.
1391 {only when compiled with |+termresponse| feature}
1392
1393 *v:this_session* *this_session-variable*
1394v:this_session Full filename of the last loaded or saved session file. See
1395 |:mksession|. It is allowed to set this variable. When no
1396 session file has been saved, this variable is empty.
1397 "this_session" also works, for backwards compatibility.
1398
1399 *v:throwpoint* *throwpoint-variable*
1400v:throwpoint The point where the exception most recently caught and not
1401 finished was thrown. Not set when commands are typed. See
1402 also |v:exception| and |throw-variables|.
1403 Example: >
1404 :try
1405 : throw "oops"
1406 :catch /.*/
1407 : echo "Exception from" v:throwpoint
1408 :endtry
1409< Output: "Exception from test.vim, line 2"
1410
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001411 *v:val* *val-variable*
1412v:val Value of the current item of a List or Dictionary. Only valid
1413 while evaluating the expression used with |map()| and
1414 |filter()|. Read-only.
1415
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416 *v:version* *version-variable*
1417v:version Version number of Vim: Major version number times 100 plus
1418 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
1419 is 501. Read-only. "version" also works, for backwards
1420 compatibility.
1421 Use |has()| to check if a certain patch was included, e.g.: >
1422 if has("patch123")
1423< Note that patch numbers are specific to the version, thus both
1424 version 5.0 and 5.1 may have a patch 123, but these are
1425 completely different.
1426
1427 *v:warningmsg* *warningmsg-variable*
1428v:warningmsg Last given warning message. It's allowed to set this variable.
1429
1430==============================================================================
14314. Builtin Functions *functions*
1432
1433See |function-list| for a list grouped by what the function is used for.
1434
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001435(Use CTRL-] on the function name to jump to the full explanation.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436
1437USAGE RESULT DESCRIPTION ~
1438
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001439add( {list}, {item}) List append {item} to List {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001440append( {lnum}, {string}) Number append {string} below line {lnum}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001441append( {lnum}, {list}) Number append lines {list} below line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442argc() Number number of files in the argument list
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001443argidx() Number current index in the argument list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444argv( {nr}) String {nr} entry of the argument list
1445browse( {save}, {title}, {initdir}, {default})
1446 String put up a file requester
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001447browsedir( {title}, {initdir}) String put up a directory requester
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448bufexists( {expr}) Number TRUE if buffer {expr} exists
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001449buflisted( {expr}) Number TRUE if buffer {expr} is listed
1450bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451bufname( {expr}) String Name of the buffer {expr}
1452bufnr( {expr}) Number Number of the buffer {expr}
1453bufwinnr( {expr}) Number window number of buffer {expr}
1454byte2line( {byte}) Number line number at byte count {byte}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001455byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001456call( {func}, {arglist} [, {dict}])
1457 any call {func} with arguments {arglist}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458char2nr( {expr}) Number ASCII value of first char in {expr}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001459cindent( {lnum}) Number C indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460col( {expr}) Number column nr of cursor or mark
1461confirm( {msg} [, {choices} [, {default} [, {type}]]])
1462 Number number of choice picked by user
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001463copy( {expr}) any make a shallow copy of {expr}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001464count( {list}, {expr} [, {start} [, {ic}]])
1465 Number count how many {expr} are in {list}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466cscope_connection( [{num} , {dbpath} [, {prepend}]])
1467 Number checks existence of cscope connection
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001468cursor( {lnum}, {col}) Number position cursor at {lnum}, {col}
1469deepcopy( {expr}) any make a full copy of {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470delete( {fname}) Number delete file {fname}
1471did_filetype() Number TRUE if FileType autocommand event used
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001472diff_filler( {lnum}) Number diff filler lines about {lnum}
1473diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
Bram Moolenaar13065c42005-01-08 16:08:21 +00001474empty( {expr}) Number TRUE if {expr} is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475escape( {string}, {chars}) String escape {chars} in {string} with '\'
Bram Moolenaare2cc9702005-03-15 22:43:58 +00001476eval( {string}) any evaluate {string} into its value
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001477eventhandler( ) Number TRUE if inside an event handler
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478executable( {expr}) Number 1 if executable {expr} exists
1479exists( {expr}) Number TRUE if {expr} exists
1480expand( {expr}) String expand special keywords in {expr}
1481filereadable( {file}) Number TRUE if {file} is a readable file
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001482filter( {expr}, {string}) List/Dict remove items from {expr} where
1483 {string} is 0
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001484finddir( {name}[, {path}[, {count}]])
1485 String Find directory {name} in {path}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001486findfile( {name}[, {path}[, {count}]])
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001487 String Find file {name} in {path}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488filewritable( {file}) Number TRUE if {file} is a writable file
1489fnamemodify( {fname}, {mods}) String modify file name
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001490foldclosed( {lnum}) Number first line of fold at {lnum} if closed
1491foldclosedend( {lnum}) Number last line of fold at {lnum} if closed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492foldlevel( {lnum}) Number fold level at {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001493foldtext( ) String line displayed for closed fold
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494foreground( ) Number bring the Vim window to the foreground
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001495function( {name}) Funcref reference to function {name}
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001496get( {list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001497get( {dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001498getchar( [expr]) Number get one character from the user
1499getcharmod( ) Number modifiers for the last typed character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500getbufvar( {expr}, {varname}) variable {varname} in buffer {expr}
1501getcmdline() String return the current command-line
1502getcmdpos() Number return cursor position in command-line
1503getcwd() String the current working directory
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001504getfperm( {fname}) String file permissions of file {fname}
1505getfsize( {fname}) Number size in bytes of file {fname}
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001506getfontname( [{name}]) String name of font being used
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507getftime( {fname}) Number last modification time of file
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001508getftype( {fname}) String description of type of file {fname}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001509getline( {lnum}) String line {lnum} of current buffer
1510getline( {lnum}, {end}) List lines {lnum} to {end} of current buffer
Bram Moolenaar68b76a62005-03-25 21:53:48 +00001511getqflist() List list of quickfix items
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00001512getreg( [{regname} [, 1]]) String contents of register
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001513getregtype( [{regname}]) String type of register
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514getwinposx() Number X coord in pixels of GUI Vim window
1515getwinposy() Number Y coord in pixels of GUI Vim window
1516getwinvar( {nr}, {varname}) variable {varname} in window {nr}
1517glob( {expr}) String expand file wildcards in {expr}
1518globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path}
1519has( {feature}) Number TRUE if feature {feature} supported
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001520has_key( {dict}, {key}) Number TRUE if {dict} has entry {key}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists
1522histadd( {history},{item}) String add an item to a history
1523histdel( {history} [, {item}]) String remove an item from a history
1524histget( {history} [, {index}]) String get the item {index} from a history
1525histnr( {history}) Number highest index of a history
1526hlexists( {name}) Number TRUE if highlight group {name} exists
1527hlID( {name}) Number syntax ID of highlight group {name}
1528hostname() String name of the machine Vim is running on
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001529iconv( {expr}, {from}, {to}) String convert encoding of {expr}
1530indent( {lnum}) Number indent of line {lnum}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001531index( {list}, {expr} [, {start} [, {ic}]])
1532 Number index in {list} where {expr} appears
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533input( {prompt} [, {text}]) String get input from the user
1534inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001535inputrestore() Number restore typeahead
1536inputsave() Number save and clear typeahead
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537inputsecret( {prompt} [, {text}]) String like input() but hiding the text
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001538insert( {list}, {item} [, {idx}]) List insert {item} in {list} [before {idx}]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539isdirectory( {directory}) Number TRUE if {directory} is a directory
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00001540islocked( {expr}) Number TRUE if {expr} is locked
Bram Moolenaar677ee682005-01-27 14:41:15 +00001541items( {dict}) List List of key-value pairs in {dict}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001542join( {list} [, {sep}]) String join {list} items into one String
Bram Moolenaard8b02732005-01-14 21:48:43 +00001543keys( {dict}) List List of keys in {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001544len( {expr}) Number the length of {expr}
1545libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number
1547line( {expr}) Number line nr of cursor, last line or mark
1548line2byte( {lnum}) Number byte count of line {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001549lispindent( {lnum}) Number Lisp indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550localtime() Number current time
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001551map( {expr}, {string}) List/Dict change each item in {expr} to {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
1553mapcheck( {name}[, {mode}]) String check for mappings matching {name}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001554match( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 Number position where {pat} matches in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001556matchend( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 Number position where {pat} ends in {expr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001558matchlist( {expr}, {pat}[, {start}[, {count}]])
1559 List match and submatches of {pat} in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001560matchstr( {expr}, {pat}[, {start}[, {count}]])
1561 String {count}'th match of {pat} in {expr}
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001562max({list}) Number maximum value of items in {list}
1563min({list}) Number minumum value of items in {list}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001564mkdir({name} [, {path} [, {prot}]])
1565 Number create directory {name}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001566mode() String current editing mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum}
1568nr2char( {expr}) String single char with ASCII value {expr}
1569prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001570range( {expr} [, {max} [, {stride}]])
1571 List items from {expr} to {max}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001572readfile({fname} [, {binary} [, {max}]])
1573 List get list of lines from file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574remote_expr( {server}, {string} [, {idvar}])
1575 String send expression
1576remote_foreground( {server}) Number bring Vim server to the foreground
1577remote_peek( {serverid} [, {retvar}])
1578 Number check for reply string
1579remote_read( {serverid}) String read reply string
1580remote_send( {server}, {string} [, {idvar}])
1581 String send key sequence
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001582remove( {list}, {idx} [, {end}]) any remove items {idx}-{end} from {list}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001583remove( {dict}, {key}) any remove entry {key} from {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001584rename( {from}, {to}) Number rename (move) file from {from} to {to}
1585repeat( {expr}, {count}) String repeat {expr} {count} times
1586resolve( {filename}) String get filename a shortcut points to
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001587reverse( {list}) List reverse {list} in-place
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001588search( {pattern} [, {flags}]) Number search for {pattern}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001590 Number search for other end of start/end pair
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591server2client( {clientid}, {string})
1592 Number send reply string
1593serverlist() String get a list of available servers
1594setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val}
1595setcmdpos( {pos}) Number set cursor position in command-line
1596setline( {lnum}, {line}) Number set line {lnum} to {line}
Bram Moolenaar35c54e52005-05-20 21:25:31 +00001597setqflist( {list}[, {action}]) Number set list of quickfix items using {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001598setreg( {n}, {v}[, {opt}]) Number set register to value and type
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001600simplify( {filename}) String simplify filename as much as possible
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001601sort( {list} [, {func}]) List sort {list}, using {func} to compare
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00001602split( {expr} [, {pat} [, {keepempty}]])
1603 List make List from {pat} separated {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604strftime( {format}[, {time}]) String time in specified format
Bram Moolenaar8f999f12005-01-25 22:12:55 +00001605stridx( {haystack}, {needle}[, {start}])
1606 Number index of {needle} in {haystack}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001607string( {expr}) String String representation of {expr} value
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608strlen( {expr}) Number length of the String {expr}
1609strpart( {src}, {start}[, {len}])
1610 String {len} characters of {src} at {start}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001611strridx( {haystack}, {needle} [, {start}])
1612 Number last index of {needle} in {haystack}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613strtrans( {expr}) String translate string to make it printable
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001614submatch( {nr}) String specific match in ":substitute"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615substitute( {expr}, {pat}, {sub}, {flags})
1616 String all {pat} in {expr} replaced with {sub}
Bram Moolenaar47136d72004-10-12 20:02:24 +00001617synID( {lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618synIDattr( {synID}, {what} [, {mode}])
1619 String attribute {what} of syntax ID {synID}
1620synIDtrans( {synID}) Number translated syntax ID of {synID}
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001621system( {expr} [, {input}]) String output of shell command/filter {expr}
Bram Moolenaare2cc9702005-03-15 22:43:58 +00001622taglist({expr}) List list of tags matching {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623tempname() String name for a temporary file
1624tolower( {expr}) String the String {expr} switched to lowercase
1625toupper( {expr}) String the String {expr} switched to uppercase
Bram Moolenaar8299df92004-07-10 09:47:34 +00001626tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr}
1627 to chars in {tostr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628type( {name}) Number type of variable {name}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001629values( {dict}) List List of values in {dict}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630virtcol( {expr}) Number screen column of cursor or mark
1631visualmode( [expr]) String last visual mode used
1632winbufnr( {nr}) Number buffer number of window {nr}
1633wincol() Number window column of the cursor
1634winheight( {nr}) Number height of window {nr}
1635winline() Number window line of the cursor
1636winnr() Number number of current window
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001637winrestcmd() String returns command to restore window sizes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638winwidth( {nr}) Number width of window {nr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001639writefile({list}, {fname} [, {binary}])
1640 Number write list of lines to file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001642add({list}, {expr}) *add()*
1643 Append the item {expr} to List {list}. Returns the resulting
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001644 List. Examples: >
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001645 :let alist = add([1, 2, 3], item)
1646 :call add(mylist, "woodstock")
1647< Note that when {expr} is a List it is appended as a single
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001648 item. Use |extend()| to concatenate Lists.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001649 Use |insert()| to add an item at another position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001651
1652append({lnum}, {expr}) *append()*
Bram Moolenaar748bf032005-02-02 23:04:36 +00001653 When {expr} is a List: Append each item of the List as a text
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001654 line below line {lnum} in the current buffer.
Bram Moolenaar748bf032005-02-02 23:04:36 +00001655 Otherwise append {expr} as one text line below line {lnum} in
1656 the current buffer.
1657 {lnum} can be zero to insert a line before the first one.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001658 Returns 1 for failure ({lnum} out of range or out of memory),
1659 0 for success. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001660 :let failed = append(line('$'), "# THE END")
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001661 :let failed = append(0, ["Chapter 1", "the beginning"])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001662<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 *argc()*
1664argc() The result is the number of files in the argument list of the
1665 current window. See |arglist|.
1666
1667 *argidx()*
1668argidx() The result is the current index in the argument list. 0 is
1669 the first file. argc() - 1 is the last one. See |arglist|.
1670
1671 *argv()*
1672argv({nr}) The result is the {nr}th file in the argument list of the
1673 current window. See |arglist|. "argv(0)" is the first one.
1674 Example: >
1675 :let i = 0
1676 :while i < argc()
1677 : let f = escape(argv(i), '. ')
1678 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
1679 : let i = i + 1
1680 :endwhile
1681<
1682 *browse()*
1683browse({save}, {title}, {initdir}, {default})
1684 Put up a file requester. This only works when "has("browse")"
1685 returns non-zero (only in some GUI versions).
1686 The input fields are:
1687 {save} when non-zero, select file to write
1688 {title} title for the requester
1689 {initdir} directory to start browsing in
1690 {default} default file name
1691 When the "Cancel" button is hit, something went wrong, or
1692 browsing is not possible, an empty string is returned.
1693
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001694 *browsedir()*
1695browsedir({title}, {initdir})
1696 Put up a directory requester. This only works when
1697 "has("browse")" returns non-zero (only in some GUI versions).
1698 On systems where a directory browser is not supported a file
1699 browser is used. In that case: select a file in the directory
1700 to be used.
1701 The input fields are:
1702 {title} title for the requester
1703 {initdir} directory to start browsing in
1704 When the "Cancel" button is hit, something went wrong, or
1705 browsing is not possible, an empty string is returned.
1706
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707bufexists({expr}) *bufexists()*
1708 The result is a Number, which is non-zero if a buffer called
1709 {expr} exists.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001710 If the {expr} argument is a number, buffer numbers are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 If the {expr} argument is a string it must match a buffer name
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001712 exactly. The name can be:
1713 - Relative to the current directory.
1714 - A full path.
1715 - The name of a buffer with 'filetype' set to "nofile".
1716 - A URL name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 Unlisted buffers will be found.
1718 Note that help files are listed by their short name in the
1719 output of |:buffers|, but bufexists() requires using their
1720 long name to be able to find them.
1721 Use "bufexists(0)" to test for the existence of an alternate
1722 file name.
1723 *buffer_exists()*
1724 Obsolete name: buffer_exists().
1725
1726buflisted({expr}) *buflisted()*
1727 The result is a Number, which is non-zero if a buffer called
1728 {expr} exists and is listed (has the 'buflisted' option set).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001729 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730
1731bufloaded({expr}) *bufloaded()*
1732 The result is a Number, which is non-zero if a buffer called
1733 {expr} exists and is loaded (shown in a window or hidden).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001734 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735
1736bufname({expr}) *bufname()*
1737 The result is the name of a buffer, as it is displayed by the
1738 ":ls" command.
1739 If {expr} is a Number, that buffer number's name is given.
1740 Number zero is the alternate buffer for the current window.
1741 If {expr} is a String, it is used as a |file-pattern| to match
1742 with the buffer names. This is always done like 'magic' is
1743 set and 'cpoptions' is empty. When there is more than one
1744 match an empty string is returned.
1745 "" or "%" can be used for the current buffer, "#" for the
1746 alternate buffer.
1747 A full match is preferred, otherwise a match at the start, end
1748 or middle of the buffer name is accepted.
1749 Listed buffers are found first. If there is a single match
1750 with a listed buffer, that one is returned. Next unlisted
1751 buffers are searched for.
1752 If the {expr} is a String, but you want to use it as a buffer
1753 number, force it to be a Number by adding zero to it: >
1754 :echo bufname("3" + 0)
1755< If the buffer doesn't exist, or doesn't have a name, an empty
1756 string is returned. >
1757 bufname("#") alternate buffer name
1758 bufname(3) name of buffer 3
1759 bufname("%") name of current buffer
1760 bufname("file2") name of buffer where "file2" matches.
1761< *buffer_name()*
1762 Obsolete name: buffer_name().
1763
1764 *bufnr()*
1765bufnr({expr}) The result is the number of a buffer, as it is displayed by
1766 the ":ls" command. For the use of {expr}, see |bufname()|
1767 above. If the buffer doesn't exist, -1 is returned.
1768 bufnr("$") is the last buffer: >
1769 :let last_buffer = bufnr("$")
1770< The result is a Number, which is the highest buffer number
1771 of existing buffers. Note that not all buffers with a smaller
1772 number necessarily exist, because ":bwipeout" may have removed
1773 them. Use bufexists() to test for the existence of a buffer.
1774 *buffer_number()*
1775 Obsolete name: buffer_number().
1776 *last_buffer_nr()*
1777 Obsolete name for bufnr("$"): last_buffer_nr().
1778
1779bufwinnr({expr}) *bufwinnr()*
1780 The result is a Number, which is the number of the first
1781 window associated with buffer {expr}. For the use of {expr},
1782 see |bufname()| above. If buffer {expr} doesn't exist or
1783 there is no such window, -1 is returned. Example: >
1784
1785 echo "A window containing buffer 1 is " . (bufwinnr(1))
1786
1787< The number can be used with |CTRL-W_w| and ":wincmd w"
1788 |:wincmd|.
1789
1790
1791byte2line({byte}) *byte2line()*
1792 Return the line number that contains the character at byte
1793 count {byte} in the current buffer. This includes the
1794 end-of-line character, depending on the 'fileformat' option
1795 for the current buffer. The first character has byte count
1796 one.
1797 Also see |line2byte()|, |go| and |:goto|.
1798 {not available when compiled without the |+byte_offset|
1799 feature}
1800
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001801byteidx({expr}, {nr}) *byteidx()*
1802 Return byte index of the {nr}'th character in the string
1803 {expr}. Use zero for the first character, it returns zero.
1804 This function is only useful when there are multibyte
1805 characters, otherwise the returned value is equal to {nr}.
1806 Composing characters are counted as a separate character.
1807 Example : >
1808 echo matchstr(str, ".", byteidx(str, 3))
1809< will display the fourth character. Another way to do the
1810 same: >
1811 let s = strpart(str, byteidx(str, 3))
1812 echo strpart(s, 0, byteidx(s, 1))
1813< If there are less than {nr} characters -1 is returned.
1814 If there are exactly {nr} characters the length of the string
1815 is returned.
1816
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001817call({func}, {arglist} [, {dict}]) *call()* *E699*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001818 Call function {func} with the items in List {arglist} as
1819 arguments.
1820 {func} can either be a Funcref or the name of a function.
1821 a:firstline and a:lastline are set to the cursor line.
1822 Returns the return value of the called function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001823 {dict} is for functions with the "dict" attribute. It will be
1824 used to set the local variable "self". |Dictionary-function|
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001825
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826char2nr({expr}) *char2nr()*
1827 Return number value of the first char in {expr}. Examples: >
1828 char2nr(" ") returns 32
1829 char2nr("ABC") returns 65
1830< The current 'encoding' is used. Example for "utf-8": >
1831 char2nr("á") returns 225
1832 char2nr("á"[0]) returns 195
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001833< nr2char() does the opposite.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834
1835cindent({lnum}) *cindent()*
1836 Get the amount of indent for line {lnum} according the C
1837 indenting rules, as with 'cindent'.
1838 The indent is counted in spaces, the value of 'tabstop' is
1839 relevant. {lnum} is used just like in |getline()|.
1840 When {lnum} is invalid or Vim was not compiled the |+cindent|
1841 feature, -1 is returned.
1842
1843 *col()*
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001844col({expr}) The result is a Number, which is the byte index of the column
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845 position given with {expr}. The accepted positions are:
1846 . the cursor position
1847 $ the end of the cursor line (the result is the
1848 number of characters in the cursor line plus one)
1849 'x position of mark x (if the mark is not set, 0 is
1850 returned)
1851 For the screen column position use |virtcol()|.
1852 Note that only marks in the current file can be used.
1853 Examples: >
1854 col(".") column of cursor
1855 col("$") length of cursor line plus one
1856 col("'t") column of mark t
1857 col("'" . markname) column of mark markname
1858< The first column is 1. 0 is returned for an error.
1859 For the cursor position, when 'virtualedit' is active, the
1860 column is one higher if the cursor is after the end of the
1861 line. This can be used to obtain the column in Insert mode: >
1862 :imap <F2> <C-O>:let save_ve = &ve<CR>
1863 \<C-O>:set ve=all<CR>
1864 \<C-O>:echo col(".") . "\n" <Bar>
1865 \let &ve = save_ve<CR>
1866<
1867 *confirm()*
1868confirm({msg} [, {choices} [, {default} [, {type}]]])
1869 Confirm() offers the user a dialog, from which a choice can be
1870 made. It returns the number of the choice. For the first
1871 choice this is 1.
1872 Note: confirm() is only supported when compiled with dialog
1873 support, see |+dialog_con| and |+dialog_gui|.
1874 {msg} is displayed in a |dialog| with {choices} as the
1875 alternatives. When {choices} is missing or empty, "&OK" is
1876 used (and translated).
1877 {msg} is a String, use '\n' to include a newline. Only on
1878 some systems the string is wrapped when it doesn't fit.
1879 {choices} is a String, with the individual choices separated
1880 by '\n', e.g. >
1881 confirm("Save changes?", "&Yes\n&No\n&Cancel")
1882< The letter after the '&' is the shortcut key for that choice.
1883 Thus you can type 'c' to select "Cancel". The shortcut does
1884 not need to be the first letter: >
1885 confirm("file has been modified", "&Save\nSave &All")
1886< For the console, the first letter of each choice is used as
1887 the default shortcut key.
1888 The optional {default} argument is the number of the choice
1889 that is made if the user hits <CR>. Use 1 to make the first
1890 choice the default one. Use 0 to not set a default. If
1891 {default} is omitted, 1 is used.
1892 The optional {type} argument gives the type of dialog. This
1893 is only used for the icon of the Win32 GUI. It can be one of
1894 these values: "Error", "Question", "Info", "Warning" or
1895 "Generic". Only the first character is relevant. When {type}
1896 is omitted, "Generic" is used.
1897 If the user aborts the dialog by pressing <Esc>, CTRL-C,
1898 or another valid interrupt key, confirm() returns 0.
1899
1900 An example: >
1901 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
1902 :if choice == 0
1903 : echo "make up your mind!"
1904 :elseif choice == 3
1905 : echo "tasteful"
1906 :else
1907 : echo "I prefer bananas myself."
1908 :endif
1909< In a GUI dialog, buttons are used. The layout of the buttons
1910 depends on the 'v' flag in 'guioptions'. If it is included,
1911 the buttons are always put vertically. Otherwise, confirm()
1912 tries to put the buttons in one horizontal line. If they
1913 don't fit, a vertical layout is used anyway. For some systems
1914 the horizontal layout is always used.
1915
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001916 *copy()*
1917copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
1918 different from using {expr} directly.
1919 When {expr} is a List a shallow copy is created. This means
1920 that the original List can be changed without changing the
1921 copy, and vise versa. But the items are identical, thus
1922 changing an item changes the contents of both Lists. Also see
1923 |deepcopy()|.
1924
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001925count({comp}, {expr} [, {ic} [, {start}]]) *count()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001926 Return the number of times an item with value {expr} appears
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001927 in List or Dictionary {comp}.
1928 If {start} is given then start with the item with this index.
1929 {start} can only be used with a List.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001930 When {ic} is given and it's non-zero then case is ignored.
1931
1932
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 *cscope_connection()*
1934cscope_connection([{num} , {dbpath} [, {prepend}]])
1935 Checks for the existence of a |cscope| connection. If no
1936 parameters are specified, then the function returns:
1937 0, if cscope was not available (not compiled in), or
1938 if there are no cscope connections;
1939 1, if there is at least one cscope connection.
1940
1941 If parameters are specified, then the value of {num}
1942 determines how existence of a cscope connection is checked:
1943
1944 {num} Description of existence check
1945 ----- ------------------------------
1946 0 Same as no parameters (e.g., "cscope_connection()").
1947 1 Ignore {prepend}, and use partial string matches for
1948 {dbpath}.
1949 2 Ignore {prepend}, and use exact string matches for
1950 {dbpath}.
1951 3 Use {prepend}, use partial string matches for both
1952 {dbpath} and {prepend}.
1953 4 Use {prepend}, use exact string matches for both
1954 {dbpath} and {prepend}.
1955
1956 Note: All string comparisons are case sensitive!
1957
1958 Examples. Suppose we had the following (from ":cs show"): >
1959
1960 # pid database name prepend path
1961 0 27664 cscope.out /usr/local
1962<
1963 Invocation Return Val ~
1964 ---------- ---------- >
1965 cscope_connection() 1
1966 cscope_connection(1, "out") 1
1967 cscope_connection(2, "out") 0
1968 cscope_connection(3, "out") 0
1969 cscope_connection(3, "out", "local") 1
1970 cscope_connection(4, "out") 0
1971 cscope_connection(4, "out", "local") 0
1972 cscope_connection(4, "cscope.out", "/usr/local") 1
1973<
1974cursor({lnum}, {col}) *cursor()*
1975 Positions the cursor at the column {col} in the line {lnum}.
1976 Does not change the jumplist.
1977 If {lnum} is greater than the number of lines in the buffer,
1978 the cursor will be positioned at the last line in the buffer.
1979 If {lnum} is zero, the cursor will stay in the current line.
1980 If {col} is greater than the number of characters in the line,
1981 the cursor will be positioned at the last character in the
1982 line.
1983 If {col} is zero, the cursor will stay in the current column.
1984
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001985
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001986deepcopy({expr}[, {noref}]) *deepcopy()* *E698*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001987 Make a copy of {expr}. For Numbers and Strings this isn't
1988 different from using {expr} directly.
1989 When {expr} is a List a full copy is created. This means
1990 that the original List can be changed without changing the
1991 copy, and vise versa. When an item is a List, a copy for it
1992 is made, recursively. Thus changing an item in the copy does
1993 not change the contents of the original List.
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001994 When {noref} is omitted or zero a contained List or Dictionary
1995 is only copied once. All references point to this single
1996 copy. With {noref} set to 1 every occurrence of a List or
1997 Dictionary results in a new copy. This also means that a
1998 cyclic reference causes deepcopy() to fail.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001999 *E724*
2000 Nesting is possible up to 100 levels. When there is an item
Bram Moolenaar4399ef42005-02-12 14:29:27 +00002001 that refers back to a higher level making a deep copy with
2002 {noref} set to 1 will fail.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002003 Also see |copy()|.
2004
2005delete({fname}) *delete()*
2006 Deletes the file by the name {fname}. The result is a Number,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 which is 0 if the file was deleted successfully, and non-zero
2008 when the deletion failed.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002009 Use |remove()| to delete an item from a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010
2011 *did_filetype()*
2012did_filetype() Returns non-zero when autocommands are being executed and the
2013 FileType event has been triggered at least once. Can be used
2014 to avoid triggering the FileType event again in the scripts
2015 that detect the file type. |FileType|
2016 When editing another file, the counter is reset, thus this
2017 really checks if the FileType event has been triggered for the
2018 current buffer. This allows an autocommand that starts
2019 editing another buffer to set 'filetype' and load a syntax
2020 file.
2021
Bram Moolenaar47136d72004-10-12 20:02:24 +00002022diff_filler({lnum}) *diff_filler()*
2023 Returns the number of filler lines above line {lnum}.
2024 These are the lines that were inserted at this point in
2025 another diff'ed window. These filler lines are shown in the
2026 display but don't exist in the buffer.
2027 {lnum} is used like with |getline()|. Thus "." is the current
2028 line, "'m" mark m, etc.
2029 Returns 0 if the current window is not in diff mode.
2030
2031diff_hlID({lnum}, {col}) *diff_hlID()*
2032 Returns the highlight ID for diff mode at line {lnum} column
2033 {col} (byte index). When the current line does not have a
2034 diff change zero is returned.
2035 {lnum} is used like with |getline()|. Thus "." is the current
2036 line, "'m" mark m, etc.
2037 {col} is 1 for the leftmost column, {lnum} is 1 for the first
2038 line.
2039 The highlight ID can be used with |synIDattr()| to obtain
2040 syntax information about the highlighting.
2041
Bram Moolenaar13065c42005-01-08 16:08:21 +00002042empty({expr}) *empty()*
2043 Return the Number 1 if {expr} is empty, zero otherwise.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002044 A List or Dictionary is empty when it does not have any items.
Bram Moolenaar13065c42005-01-08 16:08:21 +00002045 A Number is empty when its value is zero.
2046 For a long List this is much faster then comparing the length
2047 with zero.
2048
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049escape({string}, {chars}) *escape()*
2050 Escape the characters in {chars} that occur in {string} with a
2051 backslash. Example: >
2052 :echo escape('c:\program files\vim', ' \')
2053< results in: >
2054 c:\\program\ files\\vim
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002055
2056< *eval()*
2057eval({string}) Evaluate {string} and return the result. Especially useful to
2058 turn the result of |string()| back into the original value.
2059 This works for Numbers, Strings and composites of them.
2060 Also works for Funcrefs that refer to existing functions.
2061
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062eventhandler() *eventhandler()*
2063 Returns 1 when inside an event handler. That is that Vim got
2064 interrupted while waiting for the user to type a character,
2065 e.g., when dropping a file on Vim. This means interactive
2066 commands cannot be used. Otherwise zero is returned.
2067
2068executable({expr}) *executable()*
2069 This function checks if an executable with the name {expr}
2070 exists. {expr} must be the name of the program without any
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002071 arguments.
2072 executable() uses the value of $PATH and/or the normal
2073 searchpath for programs. *PATHEXT*
2074 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
2075 optionally be included. Then the extensions in $PATHEXT are
2076 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
2077 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
2078 used. A dot by itself can be used in $PATHEXT to try using
2079 the name without an extension. When 'shell' looks like a
2080 Unix shell, then the name is also tried without adding an
2081 extension.
2082 On MS-DOS and MS-Windows it only checks if the file exists and
2083 is not a directory, not if it's really executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084 The result is a Number:
2085 1 exists
2086 0 does not exist
2087 -1 not implemented on this system
2088
2089 *exists()*
2090exists({expr}) The result is a Number, which is non-zero if {expr} is
2091 defined, zero otherwise. The {expr} argument is a string,
2092 which contains one of these:
2093 &option-name Vim option (only checks if it exists,
2094 not if it really works)
2095 +option-name Vim option that works.
2096 $ENVNAME environment variable (could also be
2097 done by comparing with an empty
2098 string)
2099 *funcname built-in function (see |functions|)
2100 or user defined function (see
2101 |user-functions|).
2102 varname internal variable (see
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002103 |internal-variables|). Also works
2104 for |curly-braces-names|, Dictionary
2105 entries, List items, etc. Beware that
2106 this may cause functions to be
2107 invoked cause an error message for an
2108 invalid expression.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 :cmdname Ex command: built-in command, user
2110 command or command modifier |:command|.
2111 Returns:
2112 1 for match with start of a command
2113 2 full match with a command
2114 3 matches several user commands
2115 To check for a supported command
2116 always check the return value to be 2.
2117 #event autocommand defined for this event
2118 #event#pattern autocommand defined for this event and
2119 pattern (the pattern is taken
2120 literally and compared to the
2121 autocommand patterns character by
2122 character)
2123 For checking for a supported feature use |has()|.
2124
2125 Examples: >
2126 exists("&shortname")
2127 exists("$HOSTNAME")
2128 exists("*strftime")
2129 exists("*s:MyFunc")
2130 exists("bufcount")
2131 exists(":Make")
2132 exists("#CursorHold");
2133 exists("#BufReadPre#*.gz")
2134< There must be no space between the symbol (&/$/*/#) and the
2135 name.
2136 Note that the argument must be a string, not the name of the
2137 variable itself! For example: >
2138 exists(bufcount)
2139< This doesn't check for existence of the "bufcount" variable,
2140 but gets the contents of "bufcount", and checks if that
2141 exists.
2142
2143expand({expr} [, {flag}]) *expand()*
2144 Expand wildcards and the following special keywords in {expr}.
2145 The result is a String.
2146
2147 When there are several matches, they are separated by <NL>
2148 characters. [Note: in version 5.0 a space was used, which
2149 caused problems when a file name contains a space]
2150
2151 If the expansion fails, the result is an empty string. A name
2152 for a non-existing file is not included.
2153
2154 When {expr} starts with '%', '#' or '<', the expansion is done
2155 like for the |cmdline-special| variables with their associated
2156 modifiers. Here is a short overview:
2157
2158 % current file name
2159 # alternate file name
2160 #n alternate file name n
2161 <cfile> file name under the cursor
2162 <afile> autocmd file name
2163 <abuf> autocmd buffer number (as a String!)
2164 <amatch> autocmd matched name
2165 <sfile> sourced script file name
2166 <cword> word under the cursor
2167 <cWORD> WORD under the cursor
2168 <client> the {clientid} of the last received
2169 message |server2client()|
2170 Modifiers:
2171 :p expand to full path
2172 :h head (last path component removed)
2173 :t tail (last path component only)
2174 :r root (one extension removed)
2175 :e extension only
2176
2177 Example: >
2178 :let &tags = expand("%:p:h") . "/tags"
2179< Note that when expanding a string that starts with '%', '#' or
2180 '<', any following text is ignored. This does NOT work: >
2181 :let doesntwork = expand("%:h.bak")
2182< Use this: >
2183 :let doeswork = expand("%:h") . ".bak"
2184< Also note that expanding "<cfile>" and others only returns the
2185 referenced file name without further expansion. If "<cfile>"
2186 is "~/.cshrc", you need to do another expand() to have the
2187 "~/" expanded into the path of the home directory: >
2188 :echo expand(expand("<cfile>"))
2189<
2190 There cannot be white space between the variables and the
2191 following modifier. The |fnamemodify()| function can be used
2192 to modify normal file names.
2193
2194 When using '%' or '#', and the current or alternate file name
2195 is not defined, an empty string is used. Using "%:p" in a
2196 buffer with no name, results in the current directory, with a
2197 '/' added.
2198
2199 When {expr} does not start with '%', '#' or '<', it is
2200 expanded like a file name is expanded on the command line.
2201 'suffixes' and 'wildignore' are used, unless the optional
2202 {flag} argument is given and it is non-zero. Names for
2203 non-existing files are included.
2204
2205 Expand() can also be used to expand variables and environment
2206 variables that are only known in a shell. But this can be
2207 slow, because a shell must be started. See |expr-env-expand|.
2208 The expanded variable is still handled like a list of file
2209 names. When an environment variable cannot be expanded, it is
2210 left unchanged. Thus ":echo expand('$FOOBAR')" results in
2211 "$FOOBAR".
2212
2213 See |glob()| for finding existing files. See |system()| for
2214 getting the raw output of an external command.
2215
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002216extend({expr1}, {expr2} [, {expr3}]) *extend()*
2217 {expr1} and {expr2} must be both Lists or both Dictionaries.
2218
2219 If they are Lists: Append {expr2} to {expr1}.
2220 If {expr3} is given insert the items of {expr2} before item
2221 {expr3} in {expr1}. When {expr3} is zero insert before the
2222 first item. When {expr3} is equal to len({expr1}) then
2223 {expr2} is appended.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002224 Examples: >
2225 :echo sort(extend(mylist, [7, 5]))
2226 :call extend(mylist, [2, 3], 1)
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002227< Use |add()| to concatenate one item to a list. To concatenate
2228 two lists into a new list use the + operator: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002229 :let newlist = [1, 2, 3] + [4, 5]
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002230<
2231 If they are Dictionaries:
2232 Add all entries from {expr2} to {expr1}.
2233 If a key exists in both {expr1} and {expr2} then {expr3} is
2234 used to decide what to do:
2235 {expr3} = "keep": keep the value of {expr1}
2236 {expr3} = "force": use the value of {expr2}
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00002237 {expr3} = "error": give an error message *E737*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002238 When {expr3} is omitted then "force" is assumed.
2239
2240 {expr1} is changed when {expr2} is not empty. If necessary
2241 make a copy of {expr1} first.
2242 {expr2} remains unchanged.
2243 Returns {expr1}.
2244
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002245
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246filereadable({file}) *filereadable()*
2247 The result is a Number, which is TRUE when a file with the
2248 name {file} exists, and can be read. If {file} doesn't exist,
2249 or is a directory, the result is FALSE. {file} is any
2250 expression, which is used as a String.
2251 *file_readable()*
2252 Obsolete name: file_readable().
2253
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002254
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002255filter({expr}, {string}) *filter()*
2256 {expr} must be a List or a Dictionary.
2257 For each item in {expr} evaluate {string} and when the result
2258 is zero remove the item from the List or Dictionary.
2259 Inside {string} |v:val| has the value of the current item.
2260 For a Dictionary |v:key| has the key of the current item.
2261 Examples: >
2262 :call filter(mylist, 'v:val !~ "OLD"')
2263< Removes the items where "OLD" appears. >
2264 :call filter(mydict, 'v:key >= 8')
2265< Removes the items with a key below 8. >
2266 :call filter(var, 0)
Bram Moolenaard8b02732005-01-14 21:48:43 +00002267< Removes all the items, thus clears the List or Dictionary.
2268
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002269 Note that {string} is the result of expression and is then
2270 used as an expression again. Often it is good to use a
2271 |literal-string| to avoid having to double backslashes.
2272
2273 The operation is done in-place. If you want a List or
2274 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002275 :let l = filter(copy(mylist), '& =~ "KEEP"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002276
2277< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002278
2279
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002280finddir({name}[, {path}[, {count}]]) *finddir()*
2281 Find directory {name} in {path}.
2282 If {path} is omitted or empty then 'path' is used.
2283 If the optional {count} is given, find {count}'s occurrence of
2284 {name} in {path}.
2285 This is quite similar to the ex-command |:find|.
2286 When the found directory is below the current directory a
2287 relative path is returned. Otherwise a full path is returned.
2288 Example: >
2289 :echo findfile("tags.vim", ".;")
2290< Searches from the current directory upwards until it finds
2291 the file "tags.vim".
2292 {only available when compiled with the +file_in_path feature}
2293
2294findfile({name}[, {path}[, {count}]]) *findfile()*
2295 Just like |finddir()|, but find a file instead of a directory.
2296
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297filewritable({file}) *filewritable()*
2298 The result is a Number, which is 1 when a file with the
2299 name {file} exists, and can be written. If {file} doesn't
2300 exist, or is not writable, the result is 0. If (file) is a
2301 directory, and we can write to it, the result is 2.
2302
2303fnamemodify({fname}, {mods}) *fnamemodify()*
2304 Modify file name {fname} according to {mods}. {mods} is a
2305 string of characters like it is used for file names on the
2306 command line. See |filename-modifiers|.
2307 Example: >
2308 :echo fnamemodify("main.c", ":p:h")
2309< results in: >
2310 /home/mool/vim/vim/src
2311< Note: Environment variables and "~" don't work in {fname}, use
2312 |expand()| first then.
2313
2314foldclosed({lnum}) *foldclosed()*
2315 The result is a Number. If the line {lnum} is in a closed
2316 fold, the result is the number of the first line in that fold.
2317 If the line {lnum} is not in a closed fold, -1 is returned.
2318
2319foldclosedend({lnum}) *foldclosedend()*
2320 The result is a Number. If the line {lnum} is in a closed
2321 fold, the result is the number of the last line in that fold.
2322 If the line {lnum} is not in a closed fold, -1 is returned.
2323
2324foldlevel({lnum}) *foldlevel()*
2325 The result is a Number, which is the foldlevel of line {lnum}
2326 in the current buffer. For nested folds the deepest level is
2327 returned. If there is no fold at line {lnum}, zero is
2328 returned. It doesn't matter if the folds are open or closed.
2329 When used while updating folds (from 'foldexpr') -1 is
2330 returned for lines where folds are still to be updated and the
2331 foldlevel is unknown. As a special case the level of the
2332 previous line is usually available.
2333
2334 *foldtext()*
2335foldtext() Returns a String, to be displayed for a closed fold. This is
2336 the default function used for the 'foldtext' option and should
2337 only be called from evaluating 'foldtext'. It uses the
2338 |v:foldstart|, |v:foldend| and |v:folddashes| variables.
2339 The returned string looks like this: >
2340 +-- 45 lines: abcdef
2341< The number of dashes depends on the foldlevel. The "45" is
2342 the number of lines in the fold. "abcdef" is the text in the
2343 first non-blank line of the fold. Leading white space, "//"
2344 or "/*" and the text from the 'foldmarker' and 'commentstring'
2345 options is removed.
2346 {not available when compiled without the |+folding| feature}
2347
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002348foldtextresult({lnum}) *foldtextresult()*
2349 Returns the text that is displayed for the closed fold at line
2350 {lnum}. Evaluates 'foldtext' in the appropriate context.
2351 When there is no closed fold at {lnum} an empty string is
2352 returned.
2353 {lnum} is used like with |getline()|. Thus "." is the current
2354 line, "'m" mark m, etc.
2355 Useful when exporting folded text, e.g., to HTML.
2356 {not available when compiled without the |+folding| feature}
2357
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 *foreground()*
2359foreground() Move the Vim window to the foreground. Useful when sent from
2360 a client to a Vim server. |remote_send()|
2361 On Win32 systems this might not work, the OS does not always
2362 allow a window to bring itself to the foreground. Use
2363 |remote_foreground()| instead.
2364 {only in the Win32, Athena, Motif and GTK GUI versions and the
2365 Win32 console version}
2366
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002367
Bram Moolenaar13065c42005-01-08 16:08:21 +00002368function({name}) *function()* *E700*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002369 Return a Funcref variable that refers to function {name}.
2370 {name} can be a user defined function or an internal function.
2371
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002372
Bram Moolenaar677ee682005-01-27 14:41:15 +00002373get({list}, {idx} [, {default}]) *get()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002374 Get item {idx} from List {list}. When this item is not
2375 available return {default}. Return zero when {default} is
2376 omitted.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002377get({dict}, {key} [, {default}])
2378 Get item with key {key} from Dictionary {dict}. When this
2379 item is not available return {default}. Return zero when
2380 {default} is omitted.
2381
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002382
2383getbufvar({expr}, {varname}) *getbufvar()*
2384 The result is the value of option or local buffer variable
2385 {varname} in buffer {expr}. Note that the name without "b:"
2386 must be used.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00002387 This also works for a global or buffer-local option, but it
2388 doesn't work for a global variable, window-local variable or
2389 window-local option.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002390 For the use of {expr}, see |bufname()| above.
2391 When the buffer or variable doesn't exist an empty string is
2392 returned, there is no error message.
2393 Examples: >
2394 :let bufmodified = getbufvar(1, "&mod")
2395 :echo "todo myvar = " . getbufvar("todo", "myvar")
2396<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397getchar([expr]) *getchar()*
2398 Get a single character from the user. If it is an 8-bit
2399 character, the result is a number. Otherwise a String is
2400 returned with the encoded character. For a special key it's a
2401 sequence of bytes starting with 0x80 (decimal: 128).
2402 If [expr] is omitted, wait until a character is available.
2403 If [expr] is 0, only get a character when one is available.
2404 If [expr] is 1, only check if a character is available, it is
2405 not consumed. If a normal character is
2406 available, it is returned, otherwise a
2407 non-zero value is returned.
2408 If a normal character available, it is returned as a Number.
2409 Use nr2char() to convert it to a String.
2410 The returned value is zero if no character is available.
2411 The returned value is a string of characters for special keys
2412 and when a modifier (shift, control, alt) was used.
2413 There is no prompt, you will somehow have to make clear to the
2414 user that a character has to be typed.
2415 There is no mapping for the character.
2416 Key codes are replaced, thus when the user presses the <Del>
2417 key you get the code for the <Del> key, not the raw character
2418 sequence. Examples: >
2419 getchar() == "\<Del>"
2420 getchar() == "\<S-Left>"
2421< This example redefines "f" to ignore case: >
2422 :nmap f :call FindChar()<CR>
2423 :function FindChar()
2424 : let c = nr2char(getchar())
2425 : while col('.') < col('$') - 1
2426 : normal l
2427 : if getline('.')[col('.') - 1] ==? c
2428 : break
2429 : endif
2430 : endwhile
2431 :endfunction
2432
2433getcharmod() *getcharmod()*
2434 The result is a Number which is the state of the modifiers for
2435 the last obtained character with getchar() or in another way.
2436 These values are added together:
2437 2 shift
2438 4 control
2439 8 alt (meta)
2440 16 mouse double click
2441 32 mouse triple click
2442 64 mouse quadruple click
2443 128 Macintosh only: command
2444 Only the modifiers that have not been included in the
2445 character itself are obtained. Thus Shift-a results in "A"
2446 with no modifier.
2447
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448getcmdline() *getcmdline()*
2449 Return the current command-line. Only works when the command
2450 line is being edited, thus requires use of |c_CTRL-\_e| or
2451 |c_CTRL-R_=|.
2452 Example: >
2453 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
2454< Also see |getcmdpos()| and |setcmdpos()|.
2455
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002456getcmdpos() *getcmdpos()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 Return the position of the cursor in the command line as a
2458 byte count. The first column is 1.
2459 Only works when editing the command line, thus requires use of
2460 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
2461 Also see |setcmdpos()| and |getcmdline()|.
2462
2463 *getcwd()*
2464getcwd() The result is a String, which is the name of the current
2465 working directory.
2466
2467getfsize({fname}) *getfsize()*
2468 The result is a Number, which is the size in bytes of the
2469 given file {fname}.
2470 If {fname} is a directory, 0 is returned.
2471 If the file {fname} can't be found, -1 is returned.
2472
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002473getfontname([{name}]) *getfontname()*
2474 Without an argument returns the name of the normal font being
2475 used. Like what is used for the Normal highlight group
2476 |hl-Normal|.
2477 With an argument a check is done whether {name} is a valid
2478 font name. If not then an empty string is returned.
2479 Otherwise the actual font name is returned, or {name} if the
2480 GUI does not support obtaining the real name.
2481 Only works when the GUI is running, thus not you your vimrc or
2482 Note that the GTK 2 GUI accepts any font name, thus checking
2483 for a valid name does not work.
2484 gvimrc file. Use the |GUIEnter| autocommand to use this
2485 function just after the GUI has started.
2486
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002487getfperm({fname}) *getfperm()*
2488 The result is a String, which is the read, write, and execute
2489 permissions of the given file {fname}.
2490 If {fname} does not exist or its directory cannot be read, an
2491 empty string is returned.
2492 The result is of the form "rwxrwxrwx", where each group of
2493 "rwx" flags represent, in turn, the permissions of the owner
2494 of the file, the group the file belongs to, and other users.
2495 If a user does not have a given permission the flag for this
2496 is replaced with the string "-". Example: >
2497 :echo getfperm("/etc/passwd")
2498< This will hopefully (from a security point of view) display
2499 the string "rw-r--r--" or even "rw-------".
Bram Moolenaare2cc9702005-03-15 22:43:58 +00002500
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501getftime({fname}) *getftime()*
2502 The result is a Number, which is the last modification time of
2503 the given file {fname}. The value is measured as seconds
2504 since 1st Jan 1970, and may be passed to strftime(). See also
2505 |localtime()| and |strftime()|.
2506 If the file {fname} can't be found -1 is returned.
2507
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002508getftype({fname}) *getftype()*
2509 The result is a String, which is a description of the kind of
2510 file of the given file {fname}.
2511 If {fname} does not exist an empty string is returned.
2512 Here is a table over different kinds of files and their
2513 results:
2514 Normal file "file"
2515 Directory "dir"
2516 Symbolic link "link"
2517 Block device "bdev"
2518 Character device "cdev"
2519 Socket "socket"
2520 FIFO "fifo"
2521 All other "other"
2522 Example: >
2523 getftype("/home")
2524< Note that a type such as "link" will only be returned on
2525 systems that support it. On some systems only "dir" and
2526 "file" are returned.
2527
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 *getline()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002529getline({lnum} [, {end}])
2530 Without {end} the result is a String, which is line {lnum}
2531 from the current buffer. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 getline(1)
2533< When {lnum} is a String that doesn't start with a
2534 digit, line() is called to translate the String into a Number.
2535 To get the line under the cursor: >
2536 getline(".")
2537< When {lnum} is smaller than 1 or bigger than the number of
2538 lines in the buffer, an empty string is returned.
2539
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002540 When {end} is given the result is a List where each item is a
2541 line from the current buffer in the range {lnum} to {end},
2542 including line {end}.
2543 {end} is used in the same way as {lnum}.
2544 Non-existing lines are silently omitted.
2545 When {end} is before {lnum} an error is given.
2546 Example: >
2547 :let start = line('.')
2548 :let end = search("^$") - 1
2549 :let lines = getline(start, end)
2550
2551
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002552getqflist() *getqflist()*
2553 Returns a list with all the current quickfix errors. Each
2554 list item is a dictionary with these entries:
2555 bufnr number of buffer that has the file name, use
2556 bufname() to get the name
2557 lnum line number in the buffer (first line is 1)
2558 col column number (first column is 1)
Bram Moolenaar582fd852005-03-28 20:58:01 +00002559 vcol non-zero: "col" is visual column
2560 zero: "col" is byte index
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002561 nr error number
2562 text description of the error
2563 type type of the error, 'E', '1', etc.
2564 valid non-zero: recognized error message
2565
2566 Useful application: Find pattern matches in multiple files and
2567 do something with them: >
2568 :vimgrep /theword/jg *.c
2569 :for d in getqflist()
2570 : echo bufname(d.bufnr) ':' d.lnum '=' d.text
2571 :endfor
2572
2573
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00002574getreg([{regname} [, 1]]) *getreg()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 The result is a String, which is the contents of register
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002576 {regname}. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 :let cliptext = getreg('*')
2578< getreg('=') returns the last evaluated value of the expression
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002579 register. (For use in maps.)
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00002580 getreg('=', 1) returns the expression itself, so that it can
2581 be restored with |setreg()|. For other registers the extra
2582 argument is ignored, thus you can always give it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 If {regname} is not specified, |v:register| is used.
2584
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002585
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586getregtype([{regname}]) *getregtype()*
2587 The result is a String, which is type of register {regname}.
2588 The value will be one of:
2589 "v" for |characterwise| text
2590 "V" for |linewise| text
2591 "<CTRL-V>{width}" for |blockwise-visual| text
2592 0 for an empty or unknown register
2593 <CTRL-V> is one character with value 0x16.
2594 If {regname} is not specified, |v:register| is used.
2595
2596 *getwinposx()*
2597getwinposx() The result is a Number, which is the X coordinate in pixels of
2598 the left hand side of the GUI Vim window. The result will be
2599 -1 if the information is not available.
2600
2601 *getwinposy()*
2602getwinposy() The result is a Number, which is the Y coordinate in pixels of
2603 the top of the GUI Vim window. The result will be -1 if the
2604 information is not available.
2605
2606getwinvar({nr}, {varname}) *getwinvar()*
2607 The result is the value of option or local window variable
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002608 {varname} in window {nr}. When {nr} is zero the current
2609 window is used.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00002610 This also works for a global option, buffer-local option and
2611 window-local option, but it doesn't work for a global variable
2612 or buffer-local variable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 Note that the name without "w:" must be used.
2614 Examples: >
2615 :let list_is_on = getwinvar(2, '&list')
2616 :echo "myvar = " . getwinvar(1, 'myvar')
2617<
2618 *glob()*
2619glob({expr}) Expand the file wildcards in {expr}. The result is a String.
2620 When there are several matches, they are separated by <NL>
2621 characters.
2622 If the expansion fails, the result is an empty string.
2623 A name for a non-existing file is not included.
2624
2625 For most systems backticks can be used to get files names from
2626 any external command. Example: >
2627 :let tagfiles = glob("`find . -name tags -print`")
2628 :let &tags = substitute(tagfiles, "\n", ",", "g")
2629< The result of the program inside the backticks should be one
2630 item per line. Spaces inside an item are allowed.
2631
2632 See |expand()| for expanding special Vim variables. See
2633 |system()| for getting the raw output of an external command.
2634
2635globpath({path}, {expr}) *globpath()*
2636 Perform glob() on all directories in {path} and concatenate
2637 the results. Example: >
2638 :echo globpath(&rtp, "syntax/c.vim")
2639< {path} is a comma-separated list of directory names. Each
2640 directory name is prepended to {expr} and expanded like with
2641 glob(). A path separator is inserted when needed.
2642 To add a comma inside a directory name escape it with a
2643 backslash. Note that on MS-Windows a directory may have a
2644 trailing backslash, remove it if you put a comma after it.
2645 If the expansion fails for one of the directories, there is no
2646 error message.
2647 The 'wildignore' option applies: Names matching one of the
2648 patterns in 'wildignore' will be skipped.
2649
2650 *has()*
2651has({feature}) The result is a Number, which is 1 if the feature {feature} is
2652 supported, zero otherwise. The {feature} argument is a
2653 string. See |feature-list| below.
2654 Also see |exists()|.
2655
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002656
2657has_key({dict}, {key}) *has_key()*
2658 The result is a Number, which is 1 if Dictionary {dict} has an
2659 entry with key {key}. Zero otherwise.
2660
2661
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662hasmapto({what} [, {mode}]) *hasmapto()*
2663 The result is a Number, which is 1 if there is a mapping that
2664 contains {what} in somewhere in the rhs (what it is mapped to)
2665 and this mapping exists in one of the modes indicated by
2666 {mode}.
2667 Both the global mappings and the mappings local to the current
2668 buffer are checked for a match.
2669 If no matching mapping is found 0 is returned.
2670 The following characters are recognized in {mode}:
2671 n Normal mode
2672 v Visual mode
2673 o Operator-pending mode
2674 i Insert mode
2675 l Language-Argument ("r", "f", "t", etc.)
2676 c Command-line mode
2677 When {mode} is omitted, "nvo" is used.
2678
2679 This function is useful to check if a mapping already exists
2680 to a function in a Vim script. Example: >
2681 :if !hasmapto('\ABCdoit')
2682 : map <Leader>d \ABCdoit
2683 :endif
2684< This installs the mapping to "\ABCdoit" only if there isn't
2685 already a mapping to "\ABCdoit".
2686
2687histadd({history}, {item}) *histadd()*
2688 Add the String {item} to the history {history} which can be
2689 one of: *hist-names*
2690 "cmd" or ":" command line history
2691 "search" or "/" search pattern history
2692 "expr" or "=" typed expression history
2693 "input" or "@" input line history
2694 If {item} does already exist in the history, it will be
2695 shifted to become the newest entry.
2696 The result is a Number: 1 if the operation was successful,
2697 otherwise 0 is returned.
2698
2699 Example: >
2700 :call histadd("input", strftime("%Y %b %d"))
2701 :let date=input("Enter date: ")
2702< This function is not available in the |sandbox|.
2703
2704histdel({history} [, {item}]) *histdel()*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002705 Clear {history}, i.e. delete all its entries. See |hist-names|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 for the possible values of {history}.
2707
2708 If the parameter {item} is given as String, this is seen
2709 as regular expression. All entries matching that expression
2710 will be removed from the history (if there are any).
2711 Upper/lowercase must match, unless "\c" is used |/\c|.
2712 If {item} is a Number, it will be interpreted as index, see
2713 |:history-indexing|. The respective entry will be removed
2714 if it exists.
2715
2716 The result is a Number: 1 for a successful operation,
2717 otherwise 0 is returned.
2718
2719 Examples:
2720 Clear expression register history: >
2721 :call histdel("expr")
2722<
2723 Remove all entries starting with "*" from the search history: >
2724 :call histdel("/", '^\*')
2725<
2726 The following three are equivalent: >
2727 :call histdel("search", histnr("search"))
2728 :call histdel("search", -1)
2729 :call histdel("search", '^'.histget("search", -1).'$')
2730<
2731 To delete the last search pattern and use the last-but-one for
2732 the "n" command and 'hlsearch': >
2733 :call histdel("search", -1)
2734 :let @/ = histget("search", -1)
2735
2736histget({history} [, {index}]) *histget()*
2737 The result is a String, the entry with Number {index} from
2738 {history}. See |hist-names| for the possible values of
2739 {history}, and |:history-indexing| for {index}. If there is
2740 no such entry, an empty String is returned. When {index} is
2741 omitted, the most recent item from the history is used.
2742
2743 Examples:
2744 Redo the second last search from history. >
2745 :execute '/' . histget("search", -2)
2746
2747< Define an Ex command ":H {num}" that supports re-execution of
2748 the {num}th entry from the output of |:history|. >
2749 :command -nargs=1 H execute histget("cmd", 0+<args>)
2750<
2751histnr({history}) *histnr()*
2752 The result is the Number of the current entry in {history}.
2753 See |hist-names| for the possible values of {history}.
2754 If an error occurred, -1 is returned.
2755
2756 Example: >
2757 :let inp_index = histnr("expr")
2758<
2759hlexists({name}) *hlexists()*
2760 The result is a Number, which is non-zero if a highlight group
2761 called {name} exists. This is when the group has been
2762 defined in some way. Not necessarily when highlighting has
2763 been defined for it, it may also have been used for a syntax
2764 item.
2765 *highlight_exists()*
2766 Obsolete name: highlight_exists().
2767
2768 *hlID()*
2769hlID({name}) The result is a Number, which is the ID of the highlight group
2770 with name {name}. When the highlight group doesn't exist,
2771 zero is returned.
2772 This can be used to retrieve information about the highlight
2773 group. For example, to get the background color of the
2774 "Comment" group: >
2775 :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
2776< *highlightID()*
2777 Obsolete name: highlightID().
2778
2779hostname() *hostname()*
2780 The result is a String, which is the name of the machine on
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002781 which Vim is currently running. Machine names greater than
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 256 characters long are truncated.
2783
2784iconv({expr}, {from}, {to}) *iconv()*
2785 The result is a String, which is the text {expr} converted
2786 from encoding {from} to encoding {to}.
2787 When the conversion fails an empty string is returned.
2788 The encoding names are whatever the iconv() library function
2789 can accept, see ":!man 3 iconv".
2790 Most conversions require Vim to be compiled with the |+iconv|
2791 feature. Otherwise only UTF-8 to latin1 conversion and back
2792 can be done.
2793 This can be used to display messages with special characters,
2794 no matter what 'encoding' is set to. Write the message in
2795 UTF-8 and use: >
2796 echo iconv(utf8_str, "utf-8", &enc)
2797< Note that Vim uses UTF-8 for all Unicode encodings, conversion
2798 from/to UCS-2 is automatically changed to use UTF-8. You
2799 cannot use UCS-2 in a string anyway, because of the NUL bytes.
2800 {only available when compiled with the +multi_byte feature}
2801
2802 *indent()*
2803indent({lnum}) The result is a Number, which is indent of line {lnum} in the
2804 current buffer. The indent is counted in spaces, the value
2805 of 'tabstop' is relevant. {lnum} is used just like in
2806 |getline()|.
2807 When {lnum} is invalid -1 is returned.
2808
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002809
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002810index({list}, {expr} [, {start} [, {ic}]]) *index()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002811 Return the lowest index in List {list} where the item has a
2812 value equal to {expr}.
Bram Moolenaar748bf032005-02-02 23:04:36 +00002813 If {start} is given then start looking at the item with index
2814 {start} (may be negative for an item relative to the end).
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002815 When {ic} is given and it is non-zero, ignore case. Otherwise
2816 case must match.
2817 -1 is returned when {expr} is not found in {list}.
2818 Example: >
2819 :let idx = index(words, "the")
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002820 :if index(numbers, 123) >= 0
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002821
2822
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823input({prompt} [, {text}]) *input()*
2824 The result is a String, which is whatever the user typed on
2825 the command-line. The parameter is either a prompt string, or
2826 a blank string (for no prompt). A '\n' can be used in the
2827 prompt to start a new line. The highlighting set with
2828 |:echohl| is used for the prompt. The input is entered just
2829 like a command-line, with the same editing commands and
2830 mappings. There is a separate history for lines typed for
2831 input().
2832 If the optional {text} is present, this is used for the
2833 default reply, as if the user typed this.
2834 NOTE: This must not be used in a startup file, for the
2835 versions that only run in GUI mode (e.g., the Win32 GUI).
2836 Note: When input() is called from within a mapping it will
2837 consume remaining characters from that mapping, because a
2838 mapping is handled like the characters were typed.
2839 Use |inputsave()| before input() and |inputrestore()|
2840 after input() to avoid that. Another solution is to avoid
2841 that further characters follow in the mapping, e.g., by using
2842 |:execute| or |:normal|.
2843
2844 Example: >
2845 :if input("Coffee or beer? ") == "beer"
2846 : echo "Cheers!"
2847 :endif
2848< Example with default text: >
2849 :let color = input("Color? ", "white")
2850< Example with a mapping: >
2851 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
2852 :function GetFoo()
2853 : call inputsave()
2854 : let g:Foo = input("enter search pattern: ")
2855 : call inputrestore()
2856 :endfunction
2857
2858inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
2859 Like input(), but when the GUI is running and text dialogs are
2860 supported, a dialog window pops up to input the text.
2861 Example: >
2862 :let n = inputdialog("value for shiftwidth", &sw)
2863 :if n != ""
2864 : let &sw = n
2865 :endif
2866< When the dialog is cancelled {cancelreturn} is returned. When
2867 omitted an empty string is returned.
2868 Hitting <Enter> works like pressing the OK button. Hitting
2869 <Esc> works like pressing the Cancel button.
2870
2871inputrestore() *inputrestore()*
2872 Restore typeahead that was saved with a previous inputsave().
2873 Should be called the same number of times inputsave() is
2874 called. Calling it more often is harmless though.
2875 Returns 1 when there is nothing to restore, 0 otherwise.
2876
2877inputsave() *inputsave()*
2878 Preserve typeahead (also from mappings) and clear it, so that
2879 a following prompt gets input from the user. Should be
2880 followed by a matching inputrestore() after the prompt. Can
2881 be used several times, in which case there must be just as
2882 many inputrestore() calls.
2883 Returns 1 when out of memory, 0 otherwise.
2884
2885inputsecret({prompt} [, {text}]) *inputsecret()*
2886 This function acts much like the |input()| function with but
2887 two exceptions:
2888 a) the user's response will be displayed as a sequence of
2889 asterisks ("*") thereby keeping the entry secret, and
2890 b) the user's response will not be recorded on the input
2891 |history| stack.
2892 The result is a String, which is whatever the user actually
2893 typed on the command-line in response to the issued prompt.
2894
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002895insert({list}, {item} [, {idx}]) *insert()*
2896 Insert {item} at the start of List {list}.
2897 If {idx} is specified insert {item} before the item with index
2898 {idx}. If {idx} is zero it goes before the first item, just
2899 like omitting {idx}. A negative {idx} is also possible, see
2900 |list-index|. -1 inserts just before the last item.
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002901 Returns the resulting List. Examples: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002902 :let mylist = insert([2, 3, 5], 1)
2903 :call insert(mylist, 4, -1)
2904 :call insert(mylist, 6, len(mylist))
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002905< The last example can be done simpler with |add()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002906 Note that when {item} is a List it is inserted as a single
2907 item. Use |extend()| to concatenate Lists.
2908
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909isdirectory({directory}) *isdirectory()*
2910 The result is a Number, which is non-zero when a directory
2911 with the name {directory} exists. If {directory} doesn't
2912 exist, or isn't a directory, the result is FALSE. {directory}
2913 is any expression, which is used as a String.
2914
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002915islocked({expr}) *islocked()*
2916 The result is a Number, which is non-zero when {expr} is the
2917 name of a locked variable.
2918 {expr} must be the name of a variable, List item or Dictionary
2919 entry, not the variable itself! Example: >
2920 :let alist = [0, ['a', 'b'], 2, 3]
2921 :lockvar 1 alist
2922 :echo islocked('alist') " 1
2923 :echo islocked('alist[1]') " 0
2924
2925< When {expr} is a variable that does not exist you get an error
2926 message. Use |exists()| to check for existance.
2927
Bram Moolenaar677ee682005-01-27 14:41:15 +00002928items({dict}) *items()*
2929 Return a List with all the key-value pairs of {dict}. Each
2930 List item is a list with two items: the key of a {dict} entry
2931 and the value of this entry. The List is in arbitrary order.
2932
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002933
2934join({list} [, {sep}]) *join()*
2935 Join the items in {list} together into one String.
2936 When {sep} is specified it is put in between the items. If
2937 {sep} is omitted a single space is used.
2938 Note that {sep} is not added at the end. You might want to
2939 add it there too: >
2940 let lines = join(mylist, "\n") . "\n"
2941< String items are used as-is. Lists and Dictionaries are
2942 converted into a string like with |string()|.
2943 The opposite function is |split()|.
2944
Bram Moolenaard8b02732005-01-14 21:48:43 +00002945keys({dict}) *keys()*
2946 Return a List with all the keys of {dict}. The List is in
2947 arbitrary order.
2948
Bram Moolenaar13065c42005-01-08 16:08:21 +00002949 *len()* *E701*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002950len({expr}) The result is a Number, which is the length of the argument.
2951 When {expr} is a String or a Number the length in bytes is
2952 used, as with |strlen()|.
2953 When {expr} is a List the number of items in the List is
2954 returned.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002955 When {expr} is a Dictionary the number of entries in the
2956 Dictionary is returned.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002957 Otherwise an error is given.
2958
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 *libcall()* *E364* *E368*
2960libcall({libname}, {funcname}, {argument})
2961 Call function {funcname} in the run-time library {libname}
2962 with single argument {argument}.
2963 This is useful to call functions in a library that you
2964 especially made to be used with Vim. Since only one argument
2965 is possible, calling standard library functions is rather
2966 limited.
2967 The result is the String returned by the function. If the
2968 function returns NULL, this will appear as an empty string ""
2969 to Vim.
2970 If the function returns a number, use libcallnr()!
2971 If {argument} is a number, it is passed to the function as an
2972 int; if {argument} is a string, it is passed as a
2973 null-terminated string.
2974 This function will fail in |restricted-mode|.
2975
2976 libcall() allows you to write your own 'plug-in' extensions to
2977 Vim without having to recompile the program. It is NOT a
2978 means to call system functions! If you try to do so Vim will
2979 very probably crash.
2980
2981 For Win32, the functions you write must be placed in a DLL
2982 and use the normal C calling convention (NOT Pascal which is
2983 used in Windows System DLLs). The function must take exactly
2984 one parameter, either a character pointer or a long integer,
2985 and must return a character pointer or NULL. The character
2986 pointer returned must point to memory that will remain valid
2987 after the function has returned (e.g. in static data in the
2988 DLL). If it points to allocated memory, that memory will
2989 leak away. Using a static buffer in the function should work,
2990 it's then freed when the DLL is unloaded.
2991
2992 WARNING: If the function returns a non-valid pointer, Vim may
2993 crash! This also happens if the function returns a number,
2994 because Vim thinks it's a pointer.
2995 For Win32 systems, {libname} should be the filename of the DLL
2996 without the ".DLL" suffix. A full path is only required if
2997 the DLL is not in the usual places.
2998 For Unix: When compiling your own plugins, remember that the
2999 object code must be compiled as position-independent ('PIC').
3000 {only in Win32 on some Unix versions, when the |+libcall|
3001 feature is present}
3002 Examples: >
3003 :echo libcall("libc.so", "getenv", "HOME")
3004 :echo libcallnr("/usr/lib/libc.so", "getpid", "")
3005<
3006 *libcallnr()*
3007libcallnr({libname}, {funcname}, {argument})
3008 Just like libcall(), but used for a function that returns an
3009 int instead of a string.
3010 {only in Win32 on some Unix versions, when the |+libcall|
3011 feature is present}
3012 Example (not very useful...): >
3013 :call libcallnr("libc.so", "printf", "Hello World!\n")
3014 :call libcallnr("libc.so", "sleep", 10)
3015<
3016 *line()*
3017line({expr}) The result is a Number, which is the line number of the file
3018 position given with {expr}. The accepted positions are:
3019 . the cursor position
3020 $ the last line in the current buffer
3021 'x position of mark x (if the mark is not set, 0 is
3022 returned)
3023 Note that only marks in the current file can be used.
3024 Examples: >
3025 line(".") line number of the cursor
3026 line("'t") line number of mark t
3027 line("'" . marker) line number of mark marker
3028< *last-position-jump*
3029 This autocommand jumps to the last known position in a file
3030 just after opening it, if the '" mark is set: >
3031 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003032
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033line2byte({lnum}) *line2byte()*
3034 Return the byte count from the start of the buffer for line
3035 {lnum}. This includes the end-of-line character, depending on
3036 the 'fileformat' option for the current buffer. The first
3037 line returns 1.
3038 This can also be used to get the byte count for the line just
3039 below the last line: >
3040 line2byte(line("$") + 1)
3041< This is the file size plus one.
3042 When {lnum} is invalid, or the |+byte_offset| feature has been
3043 disabled at compile time, -1 is returned.
3044 Also see |byte2line()|, |go| and |:goto|.
3045
3046lispindent({lnum}) *lispindent()*
3047 Get the amount of indent for line {lnum} according the lisp
3048 indenting rules, as with 'lisp'.
3049 The indent is counted in spaces, the value of 'tabstop' is
3050 relevant. {lnum} is used just like in |getline()|.
3051 When {lnum} is invalid or Vim was not compiled the
3052 |+lispindent| feature, -1 is returned.
3053
3054localtime() *localtime()*
3055 Return the current time, measured as seconds since 1st Jan
3056 1970. See also |strftime()| and |getftime()|.
3057
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003058
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003059map({expr}, {string}) *map()*
3060 {expr} must be a List or a Dictionary.
3061 Replace each item in {expr} with the result of evaluating
3062 {string}.
3063 Inside {string} |v:val| has the value of the current item.
3064 For a Dictionary |v:key| has the key of the current item.
3065 Example: >
3066 :call map(mylist, '"> " . v:val . " <"')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003067< This puts "> " before and " <" after each item in "mylist".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003068
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003069 Note that {string} is the result of an expression and is then
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003070 used as an expression again. Often it is good to use a
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003071 |literal-string| to avoid having to double backslashes. You
3072 still have to double ' quotes
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003073
3074 The operation is done in-place. If you want a List or
3075 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00003076 :let tlist = map(copy(mylist), ' & . "\t"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003077
3078< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003079
3080
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081maparg({name}[, {mode}]) *maparg()*
3082 Return the rhs of mapping {name} in mode {mode}. When there
3083 is no mapping for {name}, an empty String is returned.
3084 These characters can be used for {mode}:
3085 "n" Normal
3086 "v" Visual
3087 "o" Operator-pending
3088 "i" Insert
3089 "c" Cmd-line
3090 "l" langmap |language-mapping|
3091 "" Normal, Visual and Operator-pending
3092 When {mode} is omitted, the modes from "" are used.
3093 The {name} can have special key names, like in the ":map"
3094 command. The returned String has special characters
3095 translated like in the output of the ":map" command listing.
3096 The mappings local to the current buffer are checked first,
3097 then the global mappings.
3098
3099mapcheck({name}[, {mode}]) *mapcheck()*
3100 Check if there is a mapping that matches with {name} in mode
3101 {mode}. See |maparg()| for {mode} and special names in
3102 {name}.
3103 A match happens with a mapping that starts with {name} and
3104 with a mapping which is equal to the start of {name}.
3105
3106 matches mapping "a" "ab" "abc" ~
3107 mapcheck("a") yes yes yes
3108 mapcheck("abc") yes yes yes
3109 mapcheck("ax") yes no no
3110 mapcheck("b") no no no
3111
3112 The difference with maparg() is that mapcheck() finds a
3113 mapping that matches with {name}, while maparg() only finds a
3114 mapping for {name} exactly.
3115 When there is no mapping that starts with {name}, an empty
3116 String is returned. If there is one, the rhs of that mapping
3117 is returned. If there are several mappings that start with
3118 {name}, the rhs of one of them is returned.
3119 The mappings local to the current buffer are checked first,
3120 then the global mappings.
3121 This function can be used to check if a mapping can be added
3122 without being ambiguous. Example: >
3123 :if mapcheck("_vv") == ""
3124 : map _vv :set guifont=7x13<CR>
3125 :endif
3126< This avoids adding the "_vv" mapping when there already is a
3127 mapping for "_v" or for "_vvv".
3128
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003129match({expr}, {pat}[, {start}[, {count}]]) *match()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003130 When {expr} is a List then this returns the index of the first
3131 item where {pat} matches. Each item is used as a String,
3132 Lists and Dictionaries are used as echoed.
3133 Otherwise, {expr} is used as a String. The result is a
3134 Number, which gives the index (byte offset) in {expr} where
3135 {pat} matches.
3136 A match at the first character or List item returns zero.
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003137 If there is no match -1 is returned.
3138 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003139 :echo match("testing", "ing") " results in 4
3140 :echo match([1, 'x'], '\a') " results in 2
3141< See |string-match| for how {pat} is used.
Bram Moolenaar05159a02005-02-26 23:04:13 +00003142 *strpbrk()*
3143 Vim doesn't have a strpbrk() function. But you can do: >
3144 :let sepidx = match(line, '[.,;: \t]')
3145< *strcasestr()*
3146 Vim doesn't have a strcasestr() function. But you can add
3147 "\c" to the pattern to ignore case: >
3148 :let idx = match(haystack, '\cneedle')
3149<
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003150 When {count} is given use the {count}'th match. When a match
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003151 is found in a String the search for the next one starts on
3152 character further. Thus this example results in 1: >
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003153 echo match("testing", "..", 0, 2)
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003154< In a List the search continues in the next item.
3155
3156 If {start} is given, the search starts from byte index
3157 {start} in a String or item {start} in a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 The result, however, is still the index counted from the
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003159 first character/item. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 :echo match("testing", "ing", 2)
3161< result is again "4". >
3162 :echo match("testing", "ing", 4)
3163< result is again "4". >
3164 :echo match("testing", "t", 2)
3165< result is "3".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003166 For a String, if {start} < 0, it will be set to 0. For a list
3167 the index is counted from the end.
3168 If {start} is out of range (> strlen({expr} for a String or
3169 > len({expr} for a List) -1 is returned.
3170
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 See |pattern| for the patterns that are accepted.
3172 The 'ignorecase' option is used to set the ignore-caseness of
3173 the pattern. 'smartcase' is NOT used. The matching is always
3174 done like 'magic' is set and 'cpoptions' is empty.
3175
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003176matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 Same as match(), but return the index of first character after
3178 the match. Example: >
3179 :echo matchend("testing", "ing")
3180< results in "7".
Bram Moolenaar05159a02005-02-26 23:04:13 +00003181 *strspn()* *strcspn()*
3182 Vim doesn't have a strspn() or strcspn() function, but you can
3183 do it with matchend(): >
3184 :let span = matchend(line, '[a-zA-Z]')
3185 :let span = matchend(line, '[^a-zA-Z]')
3186< Except that -1 is returned when there are no matches.
3187
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 The {start}, if given, has the same meaning as for match(). >
3189 :echo matchend("testing", "ing", 2)
3190< results in "7". >
3191 :echo matchend("testing", "ing", 5)
3192< result is "-1".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003193 When {expr} is a List the result is equal to match().
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003195matchlist({expr}, {pat}[, {start}[, {count}]]) *matchlist()*
3196 Same as match(), but return a List. The first item in the
3197 list is the matched string, same as what matchstr() would
3198 return. Following items are submatches, like "\1", "\2", etc.
3199 in |:substitute|.
3200 When there is no match an empty list is returned.
3201
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003202matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203 Same as match(), but return the matched string. Example: >
3204 :echo matchstr("testing", "ing")
3205< results in "ing".
3206 When there is no match "" is returned.
3207 The {start}, if given, has the same meaning as for match(). >
3208 :echo matchstr("testing", "ing", 2)
3209< results in "ing". >
3210 :echo matchstr("testing", "ing", 5)
3211< result is "".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003212 When {expr} is a List then the matching item is returned.
3213 The type isn't changed, it's not necessarily a String.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003215 *max()*
3216max({list}) Return the maximum value of all items in {list}.
3217 If {list} is not a list or one of the items in {list} cannot
3218 be used as a Number this results in an error.
3219 An empty List results in zero.
3220
3221 *min()*
3222min({list}) Return the minumum value of all items in {list}.
3223 If {list} is not a list or one of the items in {list} cannot
3224 be used as a Number this results in an error.
3225 An empty List results in zero.
3226
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003227 *mkdir()* *E749*
3228mkdir({name} [, {path} [, {prot}]])
3229 Create directory {name}.
3230 If {path} is "p" then intermediate directories are created as
3231 necessary. Otherwise it must be "".
3232 If {prot} is given it is used to set the protection bits of
3233 the new directory. The default is 0755 (rwxr-xr-x: r/w for
3234 the user readable for others). Use 0700 to make it unreadable
3235 for others.
3236 This function is not available in the |sandbox|.
3237 Not available on all systems. To check use: >
3238 :if exists("*mkdir")
3239<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 *mode()*
3241mode() Return a string that indicates the current mode:
3242 n Normal
3243 v Visual by character
3244 V Visual by line
3245 CTRL-V Visual blockwise
3246 s Select by character
3247 S Select by line
3248 CTRL-S Select blockwise
3249 i Insert
3250 R Replace
3251 c Command-line
3252 r Hit-enter prompt
3253 This is useful in the 'statusline' option. In most other
3254 places it always returns "c" or "n".
3255
3256nextnonblank({lnum}) *nextnonblank()*
3257 Return the line number of the first line at or below {lnum}
3258 that is not blank. Example: >
3259 if getline(nextnonblank(1)) =~ "Java"
3260< When {lnum} is invalid or there is no non-blank line at or
3261 below it, zero is returned.
3262 See also |prevnonblank()|.
3263
3264nr2char({expr}) *nr2char()*
3265 Return a string with a single character, which has the number
3266 value {expr}. Examples: >
3267 nr2char(64) returns "@"
3268 nr2char(32) returns " "
3269< The current 'encoding' is used. Example for "utf-8": >
3270 nr2char(300) returns I with bow character
3271< Note that a NUL character in the file is specified with
3272 nr2char(10), because NULs are represented with newline
3273 characters. nr2char(0) is a real NUL and terminates the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003274 string, thus results in an empty string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275
3276prevnonblank({lnum}) *prevnonblank()*
3277 Return the line number of the first line at or above {lnum}
3278 that is not blank. Example: >
3279 let ind = indent(prevnonblank(v:lnum - 1))
3280< When {lnum} is invalid or there is no non-blank line at or
3281 above it, zero is returned.
3282 Also see |nextnonblank()|.
3283
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003284 *E726* *E727*
Bram Moolenaard8b02732005-01-14 21:48:43 +00003285range({expr} [, {max} [, {stride}]]) *range()*
3286 Returns a List with Numbers:
3287 - If only {expr} is specified: [0, 1, ..., {expr} - 1]
3288 - If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
3289 - If {stride} is specified: [{expr}, {expr} + {stride}, ...,
3290 {max}] (increasing {expr} with {stride} each time, not
3291 producing a value past {max}).
3292 Examples: >
3293 range(4) " [0, 1, 2, 3]
3294 range(2, 4) " [2, 3, 4]
3295 range(2, 9, 3) " [2, 5, 8]
3296 range(2, -2, -1) " [2, 1, 0, -1, -2]
3297<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003298 *readfile()*
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003299readfile({fname} [, {binary} [, {max}]])
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003300 Read file {fname} and return a List, each line of the file as
3301 an item. Lines broken at NL characters. Macintosh files
3302 separated with CR will result in a single long line (unless a
3303 NL appears somewhere).
3304 When {binary} is equal to "b" binary mode is used:
3305 - When the last line ends in a NL an extra empty list item is
3306 added.
3307 - No CR characters are removed.
3308 Otherwise:
3309 - CR characters that appear before a NL are removed.
3310 - Whether the last line ends in a NL or not does not matter.
3311 All NUL characters are replaced with a NL character.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003312 When {max} is given this specifies the maximum number of lines
3313 to be read. Useful if you only want to check the first ten
3314 lines of a file: >
3315 :for line in readfile(fname, '', 10)
3316 : if line =~ 'Date' | echo line | endif
3317 :endfor
Bram Moolenaar582fd852005-03-28 20:58:01 +00003318< When {max} is negative -{max} lines from the end of the file
3319 are returned, or as many as there are.
3320 When {max} is zero the result is an empty list.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003321 Note that without {max} the whole file is read into memory.
3322 Also note that there is no recognition of encoding. Read a
3323 file into a buffer if you need to.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003324 When the file can't be opened an error message is given and
3325 the result is an empty list.
3326 Also see |writefile()|.
3327
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 *remote_expr()* *E449*
3329remote_expr({server}, {string} [, {idvar}])
3330 Send the {string} to {server}. The string is sent as an
3331 expression and the result is returned after evaluation.
3332 If {idvar} is present, it is taken as the name of a
3333 variable and a {serverid} for later use with
3334 remote_read() is stored there.
3335 See also |clientserver| |RemoteReply|.
3336 This function is not available in the |sandbox|.
3337 {only available when compiled with the |+clientserver| feature}
3338 Note: Any errors will cause a local error message to be issued
3339 and the result will be the empty string.
3340 Examples: >
3341 :echo remote_expr("gvim", "2+2")
3342 :echo remote_expr("gvim1", "b:current_syntax")
3343<
3344
3345remote_foreground({server}) *remote_foreground()*
3346 Move the Vim server with the name {server} to the foreground.
3347 This works like: >
3348 remote_expr({server}, "foreground()")
3349< Except that on Win32 systems the client does the work, to work
3350 around the problem that the OS doesn't always allow the server
3351 to bring itself to the foreground.
3352 This function is not available in the |sandbox|.
3353 {only in the Win32, Athena, Motif and GTK GUI versions and the
3354 Win32 console version}
3355
3356
3357remote_peek({serverid} [, {retvar}]) *remote_peek()*
3358 Returns a positive number if there are available strings
3359 from {serverid}. Copies any reply string into the variable
3360 {retvar} if specified. {retvar} must be a string with the
3361 name of a variable.
3362 Returns zero if none are available.
3363 Returns -1 if something is wrong.
3364 See also |clientserver|.
3365 This function is not available in the |sandbox|.
3366 {only available when compiled with the |+clientserver| feature}
3367 Examples: >
3368 :let repl = ""
3369 :echo "PEEK: ".remote_peek(id, "repl").": ".repl
3370
3371remote_read({serverid}) *remote_read()*
3372 Return the oldest available reply from {serverid} and consume
3373 it. It blocks until a reply is available.
3374 See also |clientserver|.
3375 This function is not available in the |sandbox|.
3376 {only available when compiled with the |+clientserver| feature}
3377 Example: >
3378 :echo remote_read(id)
3379<
3380 *remote_send()* *E241*
3381remote_send({server}, {string} [, {idvar}])
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003382 Send the {string} to {server}. The string is sent as input
3383 keys and the function returns immediately. At the Vim server
3384 the keys are not mapped |:map|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 If {idvar} is present, it is taken as the name of a
3386 variable and a {serverid} for later use with
3387 remote_read() is stored there.
3388 See also |clientserver| |RemoteReply|.
3389 This function is not available in the |sandbox|.
3390 {only available when compiled with the |+clientserver| feature}
3391 Note: Any errors will be reported in the server and may mess
3392 up the display.
3393 Examples: >
3394 :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
3395 \ remote_read(serverid)
3396
3397 :autocmd NONE RemoteReply *
3398 \ echo remote_read(expand("<amatch>"))
3399 :echo remote_send("gvim", ":sleep 10 | echo ".
3400 \ 'server2client(expand("<client>"), "HELLO")<CR>')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003401<
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003402remove({list}, {idx} [, {end}]) *remove()*
3403 Without {end}: Remove the item at {idx} from List {list} and
3404 return it.
3405 With {end}: Remove items from {idx} to {end} (inclusive) and
3406 return a list with these items. When {idx} points to the same
3407 item as {end} a list with one item is returned. When {end}
3408 points to an item before {idx} this is an error.
3409 See |list-index| for possible values of {idx} and {end}.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003410 Example: >
3411 :echo "last item: " . remove(mylist, -1)
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003412 :call remove(mylist, 0, 9)
Bram Moolenaard8b02732005-01-14 21:48:43 +00003413remove({dict}, {key})
3414 Remove the entry from {dict} with key {key}. Example: >
3415 :echo "removed " . remove(dict, "one")
3416< If there is no {key} in {dict} this is an error.
3417
3418 Use |delete()| to remove a file.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003419
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420rename({from}, {to}) *rename()*
3421 Rename the file by the name {from} to the name {to}. This
3422 should also work to move files across file systems. The
3423 result is a Number, which is 0 if the file was renamed
3424 successfully, and non-zero when the renaming failed.
3425 This function is not available in the |sandbox|.
3426
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003427repeat({expr}, {count}) *repeat()*
3428 Repeat {expr} {count} times and return the concatenated
3429 result. Example: >
3430 :let seperator = repeat('-', 80)
3431< When {count} is zero or negative the result is empty.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003432 When {expr} is a List the result is {expr} concatenated
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003433 {count} times. Example: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003434 :let longlist = repeat(['a', 'b'], 3)
3435< Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003436
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003437
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438resolve({filename}) *resolve()* *E655*
3439 On MS-Windows, when {filename} is a shortcut (a .lnk file),
3440 returns the path the shortcut points to in a simplified form.
3441 On Unix, repeat resolving symbolic links in all path
3442 components of {filename} and return the simplified result.
3443 To cope with link cycles, resolving of symbolic links is
3444 stopped after 100 iterations.
3445 On other systems, return the simplified {filename}.
3446 The simplification step is done as by |simplify()|.
3447 resolve() keeps a leading path component specifying the
3448 current directory (provided the result is still a relative
3449 path name) and also keeps a trailing path separator.
3450
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003451 *reverse()*
3452reverse({list}) Reverse the order of items in {list} in-place. Returns
3453 {list}.
3454 If you want a list to remain unmodified make a copy first: >
3455 :let revlist = reverse(copy(mylist))
3456
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457search({pattern} [, {flags}]) *search()*
3458 Search for regexp pattern {pattern}. The search starts at the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003459 cursor position (you can use |cursor()| to set it).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 {flags} is a String, which can contain these character flags:
3461 'b' search backward instead of forward
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003462 'n' do Not move the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463 'w' wrap around the end of the file
3464 'W' don't wrap around the end of the file
3465 If neither 'w' or 'W' is given, the 'wrapscan' option applies.
3466
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003467 When a match has been found its line number is returned.
3468 The cursor will be positioned at the match, unless the 'n'
3469 flag is used).
3470 If there is no match a 0 is returned and the cursor doesn't
3471 move. No error message is given.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472
3473 Example (goes over all files in the argument list): >
3474 :let n = 1
3475 :while n <= argc() " loop over all files in arglist
3476 : exe "argument " . n
3477 : " start at the last char in the file and wrap for the
3478 : " first search to find match at start of file
3479 : normal G$
3480 : let flags = "w"
3481 : while search("foo", flags) > 0
3482 : s/foo/bar/g
3483 : let flags = "W"
3484 : endwhile
3485 : update " write the file if modified
3486 : let n = n + 1
3487 :endwhile
3488<
3489 *searchpair()*
3490searchpair({start}, {middle}, {end} [, {flags} [, {skip}]])
3491 Search for the match of a nested start-end pair. This can be
3492 used to find the "endif" that matches an "if", while other
3493 if/endif pairs in between are ignored.
3494 The search starts at the cursor. If a match is found, the
3495 cursor is positioned at it and the line number is returned.
3496 If no match is found 0 or -1 is returned and the cursor
3497 doesn't move. No error message is given.
3498
3499 {start}, {middle} and {end} are patterns, see |pattern|. They
3500 must not contain \( \) pairs. Use of \%( \) is allowed. When
3501 {middle} is not empty, it is found when searching from either
3502 direction, but only when not in a nested start-end pair. A
3503 typical use is: >
3504 searchpair('\<if\>', '\<else\>', '\<endif\>')
3505< By leaving {middle} empty the "else" is skipped.
3506
3507 {flags} are used like with |search()|. Additionally:
3508 'n' do Not move the cursor
3509 'r' Repeat until no more matches found; will find the
3510 outer pair
3511 'm' return number of Matches instead of line number with
3512 the match; will only be > 1 when 'r' is used.
3513
3514 When a match for {start}, {middle} or {end} is found, the
3515 {skip} expression is evaluated with the cursor positioned on
3516 the start of the match. It should return non-zero if this
3517 match is to be skipped. E.g., because it is inside a comment
3518 or a string.
3519 When {skip} is omitted or empty, every match is accepted.
3520 When evaluating {skip} causes an error the search is aborted
3521 and -1 returned.
3522
3523 The value of 'ignorecase' is used. 'magic' is ignored, the
3524 patterns are used like it's on.
3525
3526 The search starts exactly at the cursor. A match with
3527 {start}, {middle} or {end} at the next character, in the
3528 direction of searching, is the first one found. Example: >
3529 if 1
3530 if 2
3531 endif 2
3532 endif 1
3533< When starting at the "if 2", with the cursor on the "i", and
3534 searching forwards, the "endif 2" is found. When starting on
3535 the character just before the "if 2", the "endif 1" will be
3536 found. That's because the "if 2" will be found first, and
3537 then this is considered to be a nested if/endif from "if 2" to
3538 "endif 2".
3539 When searching backwards and {end} is more than one character,
3540 it may be useful to put "\zs" at the end of the pattern, so
3541 that when the cursor is inside a match with the end it finds
3542 the matching start.
3543
3544 Example, to find the "endif" command in a Vim script: >
3545
3546 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
3547 \ 'getline(".") =~ "^\\s*\""')
3548
3549< The cursor must be at or after the "if" for which a match is
3550 to be found. Note that single-quote strings are used to avoid
3551 having to double the backslashes. The skip expression only
3552 catches comments at the start of a line, not after a command.
3553 Also, a word "en" or "if" halfway a line is considered a
3554 match.
3555 Another example, to search for the matching "{" of a "}": >
3556
3557 :echo searchpair('{', '', '}', 'bW')
3558
3559< This works when the cursor is at or before the "}" for which a
3560 match is to be found. To reject matches that syntax
3561 highlighting recognized as strings: >
3562
3563 :echo searchpair('{', '', '}', 'bW',
3564 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
3565<
3566server2client( {clientid}, {string}) *server2client()*
3567 Send a reply string to {clientid}. The most recent {clientid}
3568 that sent a string can be retrieved with expand("<client>").
3569 {only available when compiled with the |+clientserver| feature}
3570 Note:
3571 This id has to be stored before the next command can be
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003572 received. I.e. before returning from the received command and
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 before calling any commands that waits for input.
3574 See also |clientserver|.
3575 Example: >
3576 :echo server2client(expand("<client>"), "HELLO")
3577<
3578serverlist() *serverlist()*
3579 Return a list of available server names, one per line.
3580 When there are no servers or the information is not available
3581 an empty string is returned. See also |clientserver|.
3582 {only available when compiled with the |+clientserver| feature}
3583 Example: >
3584 :echo serverlist()
3585<
3586setbufvar({expr}, {varname}, {val}) *setbufvar()*
3587 Set option or local variable {varname} in buffer {expr} to
3588 {val}.
3589 This also works for a global or local window option, but it
3590 doesn't work for a global or local window variable.
3591 For a local window option the global value is unchanged.
3592 For the use of {expr}, see |bufname()| above.
3593 Note that the variable name without "b:" must be used.
3594 Examples: >
3595 :call setbufvar(1, "&mod", 1)
3596 :call setbufvar("todo", "myvar", "foobar")
3597< This function is not available in the |sandbox|.
3598
3599setcmdpos({pos}) *setcmdpos()*
3600 Set the cursor position in the command line to byte position
3601 {pos}. The first position is 1.
3602 Use |getcmdpos()| to obtain the current position.
3603 Only works while editing the command line, thus you must use
Bram Moolenaard8b02732005-01-14 21:48:43 +00003604 |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
3605 |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
3606 set after the command line is set to the expression. For
3607 |c_CTRL-R_=| it is set after evaluating the expression but
3608 before inserting the resulting text.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609 When the number is too big the cursor is put at the end of the
3610 line. A number smaller than one has undefined results.
3611 Returns 0 when successful, 1 when not editing the command
3612 line.
3613
3614setline({lnum}, {line}) *setline()*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003615 Set line {lnum} of the current buffer to {line}.
3616 {lnum} is used like with |getline()|.
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003617 When {lnum} is just below the last line the {line} will be
3618 added as a new line.
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003619 If this succeeds, 0 is returned. If this fails (most likely
3620 because {lnum} is invalid) 1 is returned. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 :call setline(5, strftime("%c"))
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003622< When {line} is a List then line {lnum} and following lines
3623 will be set to the items in the list. Example: >
3624 :call setline(5, ['aaa', 'bbb', 'ccc'])
3625< This is equivalent to: >
3626 :for [n, l] in [[5, 6, 7], ['aaa', 'bbb', 'ccc']]
3627 : call setline(n, l)
3628 :endfor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629< Note: The '[ and '] marks are not set.
3630
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003631
Bram Moolenaar35c54e52005-05-20 21:25:31 +00003632setqflist({list} [, {action}]) *setqflist()*
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003633 Creates a quickfix list using the items in {list}. Each item
3634 in {list} is a dictionary. Non-dictionary items in {list} are
3635 ignored. Each dictionary item can contain the following
3636 entries:
3637
3638 filename name of a file
3639 lnum line number in the file
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003640 pattern search pattern used to locate the error
Bram Moolenaar582fd852005-03-28 20:58:01 +00003641 col column number
3642 vcol when non-zero: "col" is visual column
3643 when zero: "col" is byte index
3644 nr error number
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003645 text description of the error
Bram Moolenaar582fd852005-03-28 20:58:01 +00003646 type single-character error type, 'E', 'W', etc.
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003647
Bram Moolenaar582fd852005-03-28 20:58:01 +00003648 The "col", "vcol", "nr", "type" and "text" entries are
3649 optional. Either "lnum" or "pattern" entry can be used to
3650 locate a matching error line.
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003651 If the "filename" entry is not present or neither the "lnum"
3652 or "pattern" entries are present, then the item will not be
3653 handled as an error line.
3654 If both "pattern" and "lnum" are present then "pattern" will
3655 be used.
3656
Bram Moolenaar35c54e52005-05-20 21:25:31 +00003657 If {action} is set to 'a', then the items from {list} are
3658 added to the existing quickfix list. If there is no existing
3659 list, then a new list is created. If {action} is set to 'r',
3660 then the items from the current quickfix list are replaced
3661 with the items from {list}. If {action} is not present or is
3662 set to ' ', then a new list is created.
3663
Bram Moolenaar68b76a62005-03-25 21:53:48 +00003664 Returns zero for success, -1 for failure.
3665
3666 This function can be used to create a quickfix list
3667 independent of the 'errorformat' setting. Use a command like
3668 ":cc 1" to jump to the first position.
3669
3670
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671 *setreg()*
3672setreg({regname}, {value} [,{options}])
3673 Set the register {regname} to {value}.
3674 If {options} contains "a" or {regname} is upper case,
3675 then the value is appended.
3676 {options} can also contains a register type specification:
3677 "c" or "v" |characterwise| mode
3678 "l" or "V" |linewise| mode
3679 "b" or "<CTRL-V>" |blockwise-visual| mode
3680 If a number immediately follows "b" or "<CTRL-V>" then this is
3681 used as the width of the selection - if it is not specified
3682 then the width of the block is set to the number of characters
3683 in the longest line (counting a <TAB> as 1 character).
3684
3685 If {options} contains no register settings, then the default
3686 is to use character mode unless {value} ends in a <NL>.
3687 Setting the '=' register is not possible.
3688 Returns zero for success, non-zero for failure.
3689
3690 Examples: >
3691 :call setreg(v:register, @*)
3692 :call setreg('*', @%, 'ac')
3693 :call setreg('a', "1\n2\n3", 'b5')
3694
3695< This example shows using the functions to save and restore a
3696 register. >
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003697 :let var_a = getreg('a', 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 :let var_amode = getregtype('a')
3699 ....
3700 :call setreg('a', var_a, var_amode)
3701
3702< You can also change the type of a register by appending
3703 nothing: >
3704 :call setreg('a', '', 'al')
3705
3706setwinvar({nr}, {varname}, {val}) *setwinvar()*
3707 Set option or local variable {varname} in window {nr} to
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003708 {val}. When {nr} is zero the current window is used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709 This also works for a global or local buffer option, but it
3710 doesn't work for a global or local buffer variable.
3711 For a local buffer option the global value is unchanged.
3712 Note that the variable name without "w:" must be used.
3713 Examples: >
3714 :call setwinvar(1, "&list", 0)
3715 :call setwinvar(2, "myvar", "foobar")
3716< This function is not available in the |sandbox|.
3717
3718simplify({filename}) *simplify()*
3719 Simplify the file name as much as possible without changing
3720 the meaning. Shortcuts (on MS-Windows) or symbolic links (on
3721 Unix) are not resolved. If the first path component in
3722 {filename} designates the current directory, this will be
3723 valid for the result as well. A trailing path separator is
3724 not removed either.
3725 Example: >
3726 simplify("./dir/.././/file/") == "./file/"
3727< Note: The combination "dir/.." is only removed if "dir" is
3728 a searchable directory or does not exist. On Unix, it is also
3729 removed when "dir" is a symbolic link within the same
3730 directory. In order to resolve all the involved symbolic
3731 links before simplifying the path name, use |resolve()|.
3732
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003733
Bram Moolenaar13065c42005-01-08 16:08:21 +00003734sort({list} [, {func}]) *sort()* *E702*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003735 Sort the items in {list} in-place. Returns {list}. If you
3736 want a list to remain unmodified make a copy first: >
3737 :let sortedlist = sort(copy(mylist))
3738< Uses the string representation of each item to sort on.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003739 Numbers sort after Strings, Lists after Numbers.
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003740 For sorting text in the current buffer use |:sort|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003741 When {func} is given and it is one then case is ignored.
3742 When {func} is a Funcref or a function name, this function is
3743 called to compare items. The function is invoked with two
3744 items as argument and must return zero if they are equal, 1 if
3745 the first one sorts after the second one, -1 if the first one
3746 sorts before the second one. Example: >
3747 func MyCompare(i1, i2)
3748 return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
3749 endfunc
3750 let sortedlist = sort(mylist, "MyCompare")
3751
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003752split({expr} [, {pattern} [, {keepempty}]]) *split()*
3753 Make a List out of {expr}. When {pattern} is omitted or empty
3754 each white-separated sequence of characters becomes an item.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003755 Otherwise the string is split where {pattern} matches,
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003756 removing the matched characters.
3757 When the first or last item is empty it is omitted, unless the
3758 {keepempty} argument is given and it's non-zero.
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003759 Other empty items are kept when {pattern} matches at least one
3760 character or when {keepempty} is non-zero.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003761 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003762 :let words = split(getline('.'), '\W\+')
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003763< To split a string in individual characters: >
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003764 :for c in split(mystring, '\zs')
Bram Moolenaar0cb032e2005-04-23 20:52:00 +00003765< If you want to keep the separator you can also use '\zs': >
3766 :echo split('abc:def:ghi', ':\zs')
3767< ['abc:', 'def:', 'ghi'] ~
Bram Moolenaar2389c3c2005-05-22 22:07:59 +00003768 Splitting a table where the first element can be empty: >
3769 :let items = split(line, ':', 1)
3770< The opposite function is |join()|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003771
3772
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773strftime({format} [, {time}]) *strftime()*
3774 The result is a String, which is a formatted date and time, as
3775 specified by the {format} string. The given {time} is used,
3776 or the current time if no time is given. The accepted
3777 {format} depends on your system, thus this is not portable!
3778 See the manual page of the C function strftime() for the
3779 format. The maximum length of the result is 80 characters.
3780 See also |localtime()| and |getftime()|.
3781 The language can be changed with the |:language| command.
3782 Examples: >
3783 :echo strftime("%c") Sun Apr 27 11:49:23 1997
3784 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
3785 :echo strftime("%y%m%d %T") 970427 11:53:55
3786 :echo strftime("%H:%M") 11:55
3787 :echo strftime("%c", getftime("file.c"))
3788 Show mod time of file.c.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003789< Not available on all systems. To check use: >
3790 :if exists("*strftime")
3791
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003792stridx({haystack}, {needle} [, {start}]) *stridx()*
3793 The result is a Number, which gives the byte index in
3794 {haystack} of the first occurrence of the String {needle}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003795 If {start} is specified, the search starts at index {start}.
3796 This can be used to find a second match: >
3797 :let comma1 = stridx(line, ",")
3798 :let comma2 = stridx(line, ",", comma1 + 1)
3799< The search is done case-sensitive.
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003800 For pattern searches use |match()|.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003801 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003802 See also |strridx()|.
3803 Examples: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 :echo stridx("An Example", "Example") 3
3805 :echo stridx("Starting point", "Start") 0
3806 :echo stridx("Starting point", "start") -1
Bram Moolenaar05159a02005-02-26 23:04:13 +00003807< *strstr()* *strchr()*
3808 stridx() works similar to the C function strstr(). When used
3809 with a single character it works similar to strchr().
3810
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003811 *string()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003812string({expr}) Return {expr} converted to a String. If {expr} is a Number,
3813 String or a composition of them, then the result can be parsed
3814 back with |eval()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003815 {expr} type result ~
Bram Moolenaard8b02732005-01-14 21:48:43 +00003816 String 'string'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003817 Number 123
Bram Moolenaard8b02732005-01-14 21:48:43 +00003818 Funcref function('name')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003819 List [item, item]
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003820 Dictionary {key: value, key: value}
Bram Moolenaard8b02732005-01-14 21:48:43 +00003821 Note that in String values the ' character is doubled.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003822
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 *strlen()*
3824strlen({expr}) The result is a Number, which is the length of the String
3825 {expr} in bytes. If you want to count the number of
3826 multi-byte characters use something like this: >
3827
3828 :let len = strlen(substitute(str, ".", "x", "g"))
3829
3830< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003831 If the argument is a Number it is first converted to a String.
3832 For other types an error is given.
3833 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834
3835strpart({src}, {start}[, {len}]) *strpart()*
3836 The result is a String, which is part of {src}, starting from
3837 byte {start}, with the length {len}.
3838 When non-existing bytes are included, this doesn't result in
3839 an error, the bytes are simply omitted.
3840 If {len} is missing, the copy continues from {start} till the
3841 end of the {src}. >
3842 strpart("abcdefg", 3, 2) == "de"
3843 strpart("abcdefg", -2, 4) == "ab"
3844 strpart("abcdefg", 5, 4) == "fg"
3845 strpart("abcdefg", 3) == "defg"
3846< Note: To get the first character, {start} must be 0. For
3847 example, to get three bytes under and after the cursor: >
3848 strpart(getline(line(".")), col(".") - 1, 3)
3849<
Bram Moolenaar677ee682005-01-27 14:41:15 +00003850strridx({haystack}, {needle} [, {start}]) *strridx()*
3851 The result is a Number, which gives the byte index in
3852 {haystack} of the last occurrence of the String {needle}.
3853 When {start} is specified, matches beyond this index are
3854 ignored. This can be used to find a match before a previous
3855 match: >
3856 :let lastcomma = strridx(line, ",")
3857 :let comma2 = strridx(line, ",", lastcomma - 1)
3858< The search is done case-sensitive.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003859 For pattern searches use |match()|.
3860 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003861 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003862 See also |stridx()|. Examples: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 :echo strridx("an angry armadillo", "an") 3
Bram Moolenaar05159a02005-02-26 23:04:13 +00003864< *strrchr()*
3865 When used with a single character it works similar to the C
3866 function strrchr().
3867
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868strtrans({expr}) *strtrans()*
3869 The result is a String, which is {expr} with all unprintable
3870 characters translated into printable characters |'isprint'|.
3871 Like they are shown in a window. Example: >
3872 echo strtrans(@a)
3873< This displays a newline in register a as "^@" instead of
3874 starting a new line.
3875
3876submatch({nr}) *submatch()*
3877 Only for an expression in a |:substitute| command. Returns
3878 the {nr}'th submatch of the matched text. When {nr} is 0
3879 the whole matched text is returned.
3880 Example: >
3881 :s/\d\+/\=submatch(0) + 1/
3882< This finds the first number in the line and adds one to it.
3883 A line break is included as a newline character.
3884
3885substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
3886 The result is a String, which is a copy of {expr}, in which
3887 the first match of {pat} is replaced with {sub}. This works
3888 like the ":substitute" command (without any flags). But the
3889 matching with {pat} is always done like the 'magic' option is
3890 set and 'cpoptions' is empty (to make scripts portable).
3891 See |string-match| for how {pat} is used.
3892 And a "~" in {sub} is not replaced with the previous {sub}.
3893 Note that some codes in {sub} have a special meaning
3894 |sub-replace-special|. For example, to replace something with
3895 "\n" (two characters), use "\\\\n" or '\\n'.
3896 When {pat} does not match in {expr}, {expr} is returned
3897 unmodified.
3898 When {flags} is "g", all matches of {pat} in {expr} are
3899 replaced. Otherwise {flags} should be "".
3900 Example: >
3901 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
3902< This removes the last component of the 'path' option. >
3903 :echo substitute("testing", ".*", "\\U\\0", "")
3904< results in "TESTING".
3905
Bram Moolenaar47136d72004-10-12 20:02:24 +00003906synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00003908 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 The syntax ID can be used with |synIDattr()| and
3910 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00003911 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 line.
3913 When {trans} is non-zero, transparent items are reduced to the
3914 item that they reveal. This is useful when wanting to know
3915 the effective color. When {trans} is zero, the transparent
3916 item is returned. This is useful when wanting to know which
3917 syntax item is effective (e.g. inside parens).
3918 Warning: This function can be very slow. Best speed is
3919 obtained by going through the file in forward direction.
3920
3921 Example (echoes the name of the syntax item under the cursor): >
3922 :echo synIDattr(synID(line("."), col("."), 1), "name")
3923<
3924synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
3925 The result is a String, which is the {what} attribute of
3926 syntax ID {synID}. This can be used to obtain information
3927 about a syntax item.
3928 {mode} can be "gui", "cterm" or "term", to get the attributes
3929 for that mode. When {mode} is omitted, or an invalid value is
3930 used, the attributes for the currently active highlighting are
3931 used (GUI, cterm or term).
3932 Use synIDtrans() to follow linked highlight groups.
3933 {what} result
3934 "name" the name of the syntax item
3935 "fg" foreground color (GUI: color name used to set
3936 the color, cterm: color number as a string,
3937 term: empty string)
3938 "bg" background color (like "fg")
3939 "fg#" like "fg", but for the GUI and the GUI is
3940 running the name in "#RRGGBB" form
3941 "bg#" like "fg#" for "bg"
3942 "bold" "1" if bold
3943 "italic" "1" if italic
3944 "reverse" "1" if reverse
3945 "inverse" "1" if inverse (= reverse)
3946 "underline" "1" if underlined
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003947 "undercurl" "1" if undercurled
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948
3949 Example (echoes the color of the syntax item under the
3950 cursor): >
3951 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
3952<
3953synIDtrans({synID}) *synIDtrans()*
3954 The result is a Number, which is the translated syntax ID of
3955 {synID}. This is the syntax group ID of what is being used to
3956 highlight the character. Highlight links given with
3957 ":highlight link" are followed.
3958
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003959system({expr} [, {input}]) *system()* *E677*
3960 Get the output of the shell command {expr}.
3961 When {input} is given, this string is written to a file and
3962 passed as stdin to the command. The string is written as-is,
3963 you need to take care of using the correct line separators
Bram Moolenaar05159a02005-02-26 23:04:13 +00003964 yourself. Pipes are not used.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003965 Note: newlines in {expr} may cause the command to fail. The
3966 characters in 'shellquote' and 'shellxquote' may also cause
3967 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 This is not to be used for interactive commands.
3969 The result is a String. Example: >
3970
3971 :let files = system("ls")
3972
3973< To make the result more system-independent, the shell output
3974 is filtered to replace <CR> with <NL> for Macintosh, and
3975 <CR><NL> with <NL> for DOS-like systems.
3976 The command executed is constructed using several options:
3977 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
3978 ({tmp} is an automatically generated file name).
3979 For Unix and OS/2 braces are put around {expr} to allow for
3980 concatenated commands.
3981
3982 The resulting error code can be found in |v:shell_error|.
3983 This function will fail in |restricted-mode|.
3984 Unlike ":!cmd" there is no automatic check for changed files.
3985 Use |:checktime| to force a check.
3986
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003987
3988taglist({expr}) *taglist()*
3989 Returns a list of tags matching the regular expression {expr}.
3990 Each list item is a dictionary with the following entries:
3991 name name of the tag.
3992 filename name of the file where the tag is
3993 defined.
3994 cmd Ex command used to locate the tag in
3995 the file.
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003996 kind type of the tag. The value for this
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003997 entry depends on the language specific
3998 kind values generated by the ctags
3999 tool.
4000 static a file specific tag. Refer to
4001 |static-tag| for more information.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004002 The "kind" entry is only available when using Exuberant ctags
4003 generated tags file. More entries may be present, depending
4004 on the content of the tags file: access, implementation,
4005 inherits and signature. Refer to the ctags documentation for
4006 information about these fields. For C code the fields
4007 "struct", "class" and "enum" may appear, they give the name of
4008 the entity the tag is contained in.
4009
4010 The ex-command 'cmd' can be either an ex search pattern, a
4011 line number or a line number followed by a byte number.
Bram Moolenaare2cc9702005-03-15 22:43:58 +00004012
4013 If there are no matching tags, then an empty list is returned.
4014
4015 To get an exact tag match, the anchors '^' and '$' should be
4016 used in {expr}. Refer to |tag-regexp| for more information
4017 about the tag search regular expression pattern.
4018
4019 Refer to |'tags'| for information about how the tags file is
4020 located by Vim. Refer to |tags-file-format| for the format of
4021 the tags file generated by the different ctags tools.
4022
4023
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024tempname() *tempname()* *temp-file-name*
4025 The result is a String, which is the name of a file that
4026 doesn't exist. It can be used for a temporary file. The name
4027 is different for at least 26 consecutive calls. Example: >
4028 :let tmpfile = tempname()
4029 :exe "redir > " . tmpfile
4030< For Unix, the file will be in a private directory (only
4031 accessible by the current user) to avoid security problems
4032 (e.g., a symlink attack or other people reading your file).
4033 When Vim exits the directory and all files in it are deleted.
4034 For MS-Windows forward slashes are used when the 'shellslash'
4035 option is set or when 'shellcmdflag' starts with '-'.
4036
4037tolower({expr}) *tolower()*
4038 The result is a copy of the String given, with all uppercase
4039 characters turned into lowercase (just like applying |gu| to
4040 the string).
4041
4042toupper({expr}) *toupper()*
4043 The result is a copy of the String given, with all lowercase
4044 characters turned into uppercase (just like applying |gU| to
4045 the string).
4046
Bram Moolenaar8299df92004-07-10 09:47:34 +00004047tr({src}, {fromstr}, {tostr}) *tr()*
4048 The result is a copy of the {src} string with all characters
4049 which appear in {fromstr} replaced by the character in that
4050 position in the {tostr} string. Thus the first character in
4051 {fromstr} is translated into the first character in {tostr}
4052 and so on. Exactly like the unix "tr" command.
4053 This code also deals with multibyte characters properly.
4054
4055 Examples: >
4056 echo tr("hello there", "ht", "HT")
4057< returns "Hello THere" >
4058 echo tr("<blob>", "<>", "{}")
4059< returns "{blob}"
4060
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004061 *type()*
4062type({expr}) The result is a Number, depending on the type of {expr}:
Bram Moolenaar748bf032005-02-02 23:04:36 +00004063 Number: 0
4064 String: 1
4065 Funcref: 2
4066 List: 3
4067 Dictionary: 4
4068 To avoid the magic numbers it should be used this way: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004069 :if type(myvar) == type(0)
4070 :if type(myvar) == type("")
4071 :if type(myvar) == type(function("tr"))
4072 :if type(myvar) == type([])
Bram Moolenaar748bf032005-02-02 23:04:36 +00004073 :if type(myvar) == type({})
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074
Bram Moolenaar677ee682005-01-27 14:41:15 +00004075values({dict}) *values()*
4076 Return a List with all the values of {dict}. The List is in
4077 arbitrary order.
4078
4079
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080virtcol({expr}) *virtcol()*
4081 The result is a Number, which is the screen column of the file
4082 position given with {expr}. That is, the last screen position
4083 occupied by the character at that position, when the screen
4084 would be of unlimited width. When there is a <Tab> at the
4085 position, the returned Number will be the column at the end of
4086 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
4087 set to 8, it returns 8.
4088 For the byte position use |col()|.
4089 When Virtual editing is active in the current mode, a position
4090 beyond the end of the line can be returned. |'virtualedit'|
4091 The accepted positions are:
4092 . the cursor position
4093 $ the end of the cursor line (the result is the
4094 number of displayed characters in the cursor line
4095 plus one)
4096 'x position of mark x (if the mark is not set, 0 is
4097 returned)
4098 Note that only marks in the current file can be used.
4099 Examples: >
4100 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
4101 virtcol("$") with text "foo^Lbar", returns 9
4102 virtcol("'t") with text " there", with 't at 'h', returns 6
4103< The first column is 1. 0 is returned for an error.
4104
4105visualmode([expr]) *visualmode()*
4106 The result is a String, which describes the last Visual mode
4107 used. Initially it returns an empty string, but once Visual
4108 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
4109 single CTRL-V character) for character-wise, line-wise, or
4110 block-wise Visual mode respectively.
4111 Example: >
4112 :exe "normal " . visualmode()
4113< This enters the same Visual mode as before. It is also useful
4114 in scripts if you wish to act differently depending on the
4115 Visual mode that was used.
4116
4117 If an expression is supplied that results in a non-zero number
4118 or a non-empty string, then the Visual mode will be cleared
4119 and the old value is returned. Note that " " and "0" are also
4120 non-empty strings, thus cause the mode to be cleared.
4121
4122 *winbufnr()*
4123winbufnr({nr}) The result is a Number, which is the number of the buffer
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00004124 associated with window {nr}. When {nr} is zero, the number of
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 the buffer in the current window is returned. When window
4126 {nr} doesn't exist, -1 is returned.
4127 Example: >
4128 :echo "The file in the current window is " . bufname(winbufnr(0))
4129<
4130 *wincol()*
4131wincol() The result is a Number, which is the virtual column of the
4132 cursor in the window. This is counting screen cells from the
4133 left side of the window. The leftmost column is one.
4134
4135winheight({nr}) *winheight()*
4136 The result is a Number, which is the height of window {nr}.
4137 When {nr} is zero, the height of the current window is
4138 returned. When window {nr} doesn't exist, -1 is returned.
4139 An existing window always has a height of zero or more.
4140 Examples: >
4141 :echo "The current window has " . winheight(0) . " lines."
4142<
4143 *winline()*
4144winline() The result is a Number, which is the screen line of the cursor
4145 in the window. This is counting screen lines from the top of
4146 the window. The first line is one.
4147
4148 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004149winnr([{arg}]) The result is a Number, which is the number of the current
4150 window. The top window has number 1.
4151 When the optional argument is "$", the number of the
4152 last window is returnd (the window count).
4153 When the optional argument is "#", the number of the last
4154 accessed window is returned (where |CTRL-W_p| goes to).
4155 If there is no previous window 0 is returned.
4156 The number can be used with |CTRL-W_w| and ":wincmd w"
4157 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158
4159 *winrestcmd()*
4160winrestcmd() Returns a sequence of |:resize| commands that should restore
4161 the current window sizes. Only works properly when no windows
4162 are opened or closed and the current window is unchanged.
4163 Example: >
4164 :let cmd = winrestcmd()
4165 :call MessWithWindowSizes()
4166 :exe cmd
4167
4168winwidth({nr}) *winwidth()*
4169 The result is a Number, which is the width of window {nr}.
4170 When {nr} is zero, the width of the current window is
4171 returned. When window {nr} doesn't exist, -1 is returned.
4172 An existing window always has a width of zero or more.
4173 Examples: >
4174 :echo "The current window has " . winwidth(0) . " columns."
4175 :if winwidth(0) <= 50
4176 : exe "normal 50\<C-W>|"
4177 :endif
4178<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00004179 *writefile()*
4180writefile({list}, {fname} [, {binary}])
4181 Write List {list} to file {fname}. Each list item is
4182 separated with a NL. Each list item must be a String or
4183 Number.
4184 When {binary} is equal to "b" binary mode is used: There will
4185 not be a NL after the last list item. An empty item at the
4186 end does cause the last line in the file to end in a NL.
4187 All NL characters are replaced with a NUL character.
4188 Inserting CR characters needs to be done before passing {list}
4189 to writefile().
4190 An existing file is overwritten, if possible.
4191 When the write fails -1 is returned, otherwise 0. There is an
4192 error message if the file can't be created or when writing
4193 fails.
4194 Also see |readfile()|.
4195 To copy a file byte for byte: >
4196 :let fl = readfile("foo", "b")
4197 :call writefile(fl, "foocopy", "b")
4198<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199
4200 *feature-list*
4201There are three types of features:
42021. Features that are only supported when they have been enabled when Vim
4203 was compiled |+feature-list|. Example: >
4204 :if has("cindent")
42052. Features that are only supported when certain conditions have been met.
4206 Example: >
4207 :if has("gui_running")
4208< *has-patch*
42093. Included patches. First check |v:version| for the version of Vim.
4210 Then the "patch123" feature means that patch 123 has been included for
4211 this version. Example (checking version 6.2.148 or later): >
4212 :if v:version > 602 || v:version == 602 && has("patch148")
4213
4214all_builtin_terms Compiled with all builtin terminals enabled.
4215amiga Amiga version of Vim.
4216arabic Compiled with Arabic support |Arabic|.
4217arp Compiled with ARP support (Amiga).
4218autocmd Compiled with autocommands support.
4219balloon_eval Compiled with |balloon-eval| support.
4220beos BeOS version of Vim.
4221browse Compiled with |:browse| support, and browse() will
4222 work.
4223builtin_terms Compiled with some builtin terminals.
4224byte_offset Compiled with support for 'o' in 'statusline'
4225cindent Compiled with 'cindent' support.
4226clientserver Compiled with remote invocation support |clientserver|.
4227clipboard Compiled with 'clipboard' support.
4228cmdline_compl Compiled with |cmdline-completion| support.
4229cmdline_hist Compiled with |cmdline-history| support.
4230cmdline_info Compiled with 'showcmd' and 'ruler' support.
4231comments Compiled with |'comments'| support.
4232cryptv Compiled with encryption support |encryption|.
4233cscope Compiled with |cscope| support.
4234compatible Compiled to be very Vi compatible.
4235debug Compiled with "DEBUG" defined.
4236dialog_con Compiled with console dialog support.
4237dialog_gui Compiled with GUI dialog support.
4238diff Compiled with |vimdiff| and 'diff' support.
4239digraphs Compiled with support for digraphs.
4240dnd Compiled with support for the "~ register |quote_~|.
4241dos32 32 bits DOS (DJGPP) version of Vim.
4242dos16 16 bits DOS version of Vim.
4243ebcdic Compiled on a machine with ebcdic character set.
4244emacs_tags Compiled with support for Emacs tags.
4245eval Compiled with expression evaluation support. Always
4246 true, of course!
4247ex_extra Compiled with extra Ex commands |+ex_extra|.
4248extra_search Compiled with support for |'incsearch'| and
4249 |'hlsearch'|
4250farsi Compiled with Farsi support |farsi|.
4251file_in_path Compiled with support for |gf| and |<cfile>|
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004252filterpipe When 'shelltemp' is off pipes are used for shell
4253 read/write/filter commands
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254find_in_path Compiled with support for include file searches
4255 |+find_in_path|.
4256fname_case Case in file names matters (for Amiga, MS-DOS, and
4257 Windows this is not present).
4258folding Compiled with |folding| support.
4259footer Compiled with GUI footer support. |gui-footer|
4260fork Compiled to use fork()/exec() instead of system().
4261gettext Compiled with message translation |multi-lang|
4262gui Compiled with GUI enabled.
4263gui_athena Compiled with Athena GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264gui_gtk Compiled with GTK+ GUI (any version).
4265gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00004266gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267gui_mac Compiled with Macintosh GUI.
4268gui_motif Compiled with Motif GUI.
4269gui_photon Compiled with Photon GUI.
4270gui_win32 Compiled with MS Windows Win32 GUI.
4271gui_win32s idem, and Win32s system being used (Windows 3.1)
4272gui_running Vim is running in the GUI, or it will start soon.
4273hangul_input Compiled with Hangul input support. |hangul|
4274iconv Can use iconv() for conversion.
4275insert_expand Compiled with support for CTRL-X expansion commands in
4276 Insert mode.
4277jumplist Compiled with |jumplist| support.
4278keymap Compiled with 'keymap' support.
4279langmap Compiled with 'langmap' support.
4280libcall Compiled with |libcall()| support.
4281linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
4282 support.
4283lispindent Compiled with support for lisp indenting.
4284listcmds Compiled with commands for the buffer list |:files|
4285 and the argument list |arglist|.
4286localmap Compiled with local mappings and abbr. |:map-local|
4287mac Macintosh version of Vim.
4288macunix Macintosh version of Vim, using Unix files (OS-X).
4289menu Compiled with support for |:menu|.
4290mksession Compiled with support for |:mksession|.
4291modify_fname Compiled with file name modifiers. |filename-modifiers|
4292mouse Compiled with support mouse.
4293mouseshape Compiled with support for 'mouseshape'.
4294mouse_dec Compiled with support for Dec terminal mouse.
4295mouse_gpm Compiled with support for gpm (Linux console mouse)
4296mouse_netterm Compiled with support for netterm mouse.
4297mouse_pterm Compiled with support for qnx pterm mouse.
4298mouse_xterm Compiled with support for xterm mouse.
4299multi_byte Compiled with support for editing Korean et al.
4300multi_byte_ime Compiled with support for IME input method.
4301multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004302mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00004304netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305ole Compiled with OLE automation support for Win32.
4306os2 OS/2 version of Vim.
4307osfiletype Compiled with support for osfiletypes |+osfiletype|
4308path_extra Compiled with up/downwards search in 'path' and 'tags'
4309perl Compiled with Perl interface.
4310postscript Compiled with PostScript file printing.
4311printer Compiled with |:hardcopy| support.
Bram Moolenaar05159a02005-02-26 23:04:13 +00004312profile Compiled with |:profile| support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313python Compiled with Python interface.
4314qnx QNX version of Vim.
4315quickfix Compiled with |quickfix| support.
4316rightleft Compiled with 'rightleft' support.
4317ruby Compiled with Ruby interface |ruby|.
4318scrollbind Compiled with 'scrollbind' support.
4319showcmd Compiled with 'showcmd' support.
4320signs Compiled with |:sign| support.
4321smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004322sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323statusline Compiled with support for 'statusline', 'rulerformat'
4324 and special formats of 'titlestring' and 'iconstring'.
4325sun_workshop Compiled with support for Sun |workshop|.
Bram Moolenaar82cf9b62005-06-07 21:09:25 +00004326spell Compiled with spell checking support |spell|.
4327syntax Compiled with syntax highlighting support |syntax|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328syntax_items There are active syntax highlighting items for the
4329 current buffer.
4330system Compiled to use system() instead of fork()/exec().
4331tag_binary Compiled with binary searching in tags files
4332 |tag-binary-search|.
4333tag_old_static Compiled with support for old static tags
4334 |tag-old-static|.
4335tag_any_white Compiled with support for any white characters in tags
4336 files |tag-any-white|.
4337tcl Compiled with Tcl interface.
4338terminfo Compiled with terminfo instead of termcap.
4339termresponse Compiled with support for |t_RV| and |v:termresponse|.
4340textobjects Compiled with support for |text-objects|.
4341tgetent Compiled with tgetent support, able to use a termcap
4342 or terminfo file.
4343title Compiled with window title support |'title'|.
4344toolbar Compiled with support for |gui-toolbar|.
4345unix Unix version of Vim.
4346user_commands User-defined commands.
4347viminfo Compiled with viminfo support.
4348vim_starting True while initial source'ing takes place.
4349vertsplit Compiled with vertically split windows |:vsplit|.
4350virtualedit Compiled with 'virtualedit' option.
4351visual Compiled with Visual mode.
4352visualextra Compiled with extra Visual mode commands.
4353 |blockwise-operators|.
4354vms VMS version of Vim.
4355vreplace Compiled with |gR| and |gr| commands.
4356wildignore Compiled with 'wildignore' option.
4357wildmenu Compiled with 'wildmenu' option.
4358windows Compiled with support for more than one window.
4359winaltkeys Compiled with 'winaltkeys' option.
4360win16 Win16 version of Vim (MS-Windows 3.1).
4361win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
4362win64 Win64 version of Vim (MS-Windows 64 bit).
4363win32unix Win32 version of Vim, using Unix files (Cygwin)
4364win95 Win32 version for MS-Windows 95/98/ME.
4365writebackup Compiled with 'writebackup' default on.
4366xfontset Compiled with X fontset support |xfontset|.
4367xim Compiled with X input method support |xim|.
4368xsmp Compiled with X session management support.
4369xsmp_interact Compiled with interactive X session management support.
4370xterm_clipboard Compiled with support for xterm clipboard.
4371xterm_save Compiled with support for saving and restoring the
4372 xterm screen.
4373x11 Compiled with X11 support.
4374
4375 *string-match*
4376Matching a pattern in a String
4377
4378A regexp pattern as explained at |pattern| is normally used to find a match in
4379the buffer lines. When a pattern is used to find a match in a String, almost
4380everything works in the same way. The difference is that a String is handled
4381like it is one line. When it contains a "\n" character, this is not seen as a
4382line break for the pattern. It can be matched with a "\n" in the pattern, or
4383with ".". Example: >
4384 :let a = "aaaa\nxxxx"
4385 :echo matchstr(a, "..\n..")
4386 aa
4387 xx
4388 :echo matchstr(a, "a.x")
4389 a
4390 x
4391
4392Don't forget that "^" will only match at the first character of the String and
4393"$" at the last character of the string. They don't match after or before a
4394"\n".
4395
4396==============================================================================
43975. Defining functions *user-functions*
4398
4399New functions can be defined. These can be called just like builtin
4400functions. The function executes a sequence of Ex commands. Normal mode
4401commands can be executed with the |:normal| command.
4402
4403The function name must start with an uppercase letter, to avoid confusion with
4404builtin functions. To prevent from using the same name in different scripts
4405avoid obvious, short names. A good habit is to start the function name with
4406the name of the script, e.g., "HTMLcolor()".
4407
4408It's also possible to use curly braces, see |curly-braces-names|.
4409
4410 *local-function*
4411A function local to a script must start with "s:". A local script function
4412can only be called from within the script and from functions, user commands
4413and autocommands defined in the script. It is also possible to call the
4414function from a mappings defined in the script, but then |<SID>| must be used
4415instead of "s:" when the mapping is expanded outside of the script.
4416
4417 *:fu* *:function* *E128* *E129* *E123*
4418:fu[nction] List all functions and their arguments.
4419
4420:fu[nction] {name} List function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004421 {name} can also be a Dictionary entry that is a
4422 Funcref: >
4423 :function dict.init
4424< *E124* *E125*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004425:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426 Define a new function by the name {name}. The name
4427 must be made of alphanumeric characters and '_', and
4428 must start with a capital or "s:" (see above).
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004429
4430 {name} can also be a Dictionary entry that is a
4431 Funcref: >
4432 :function dict.init(arg)
4433< "dict" must be an existing dictionary. The entry
4434 "init" is added if it didn't exist yet. Otherwise [!]
4435 is required to overwrite an existing function. The
4436 result is a |Funcref| to a numbered function. The
4437 function can only be used with a |Funcref| and will be
4438 deleted if there are no more references to it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 *E127* *E122*
4440 When a function by this name already exists and [!] is
4441 not used an error message is given. When [!] is used,
4442 an existing function is silently replaced. Unless it
4443 is currently being executed, that is an error.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004444
4445 For the {arguments} see |function-argument|.
4446
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 *a:firstline* *a:lastline*
4448 When the [range] argument is added, the function is
4449 expected to take care of a range itself. The range is
4450 passed as "a:firstline" and "a:lastline". If [range]
4451 is excluded, ":{range}call" will call the function for
4452 each line in the range, with the cursor on the start
4453 of each line. See |function-range-example|.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004454
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455 When the [abort] argument is added, the function will
4456 abort as soon as an error is detected.
4457 The last used search pattern and the redo command "."
4458 will not be changed by the function.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004459
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004460 When the [dict] argument is added, the function must
4461 be invoked through an entry in a Dictionary. The
4462 local variable "self" will then be set to the
4463 dictionary. See |Dictionary-function|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464
4465 *:endf* *:endfunction* *E126* *E193*
4466:endf[unction] The end of a function definition. Must be on a line
4467 by its own, without other commands.
4468
4469 *:delf* *:delfunction* *E130* *E131*
4470:delf[unction] {name} Delete function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004471 {name} can also be a Dictionary entry that is a
4472 Funcref: >
4473 :delfunc dict.init
4474< This will remove the "init" entry from "dict". The
4475 function is deleted if there are no more references to
4476 it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 *:retu* *:return* *E133*
4478:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
4479 evaluated and returned as the result of the function.
4480 If "[expr]" is not given, the number 0 is returned.
4481 When a function ends without an explicit ":return",
4482 the number 0 is returned.
4483 Note that there is no check for unreachable lines,
4484 thus there is no warning if commands follow ":return".
4485
4486 If the ":return" is used after a |:try| but before the
4487 matching |:finally| (if present), the commands
4488 following the ":finally" up to the matching |:endtry|
4489 are executed first. This process applies to all
4490 nested ":try"s inside the function. The function
4491 returns at the outermost ":endtry".
4492
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004493 *function-argument* *a:var*
4494An argument can be defined by giving its name. In the function this can then
4495be used as "a:name" ("a:" for argument).
4496 *a:0* *a:1* *a:000* *E740*
4497Up to 20 arguments can be given, separated by commas. After the named
4498arguments an argument "..." can be specified, which means that more arguments
4499may optionally be following. In the function the extra arguments can be used
4500as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004501can be 0). "a:000" is set to a List that contains these arguments. Note that
4502"a:1" is the same as "a:000[0]".
4503 *E742*
4504The a: scope and the variables in it cannot be changed, they are fixed.
4505However, if a List or Dictionary is used, you can changes their contents.
4506Thus you can pass a List to a function and have the function add an item to
4507it. If you want to make sure the function cannot change a List or Dictionary
4508use |:lockvar|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004510When not using "...", the number of arguments in a function call must be equal
4511to the number of named arguments. When using "...", the number of arguments
4512may be larger.
4513
4514It is also possible to define a function without any arguments. You must
4515still supply the () then. The body of the function follows in the next lines,
4516until the matching |:endfunction|. It is allowed to define another function
4517inside a function body.
4518
4519 *local-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520Inside a function variables can be used. These are local variables, which
4521will disappear when the function returns. Global variables need to be
4522accessed with "g:".
4523
4524Example: >
4525 :function Table(title, ...)
4526 : echohl Title
4527 : echo a:title
4528 : echohl None
Bram Moolenaar677ee682005-01-27 14:41:15 +00004529 : echo a:0 . " items:"
4530 : for s in a:000
4531 : echon ' ' . s
4532 : endfor
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 :endfunction
4534
4535This function can then be called with: >
Bram Moolenaar677ee682005-01-27 14:41:15 +00004536 call Table("Table", "line1", "line2")
4537 call Table("Empty Table")
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538
4539To return more than one value, pass the name of a global variable: >
4540 :function Compute(n1, n2, divname)
4541 : if a:n2 == 0
4542 : return "fail"
4543 : endif
4544 : let g:{a:divname} = a:n1 / a:n2
4545 : return "ok"
4546 :endfunction
4547
4548This function can then be called with: >
4549 :let success = Compute(13, 1324, "div")
4550 :if success == "ok"
4551 : echo div
4552 :endif
4553
4554An alternative is to return a command that can be executed. This also works
4555with local variables in a calling function. Example: >
4556 :function Foo()
4557 : execute Bar()
4558 : echo "line " . lnum . " column " . col
4559 :endfunction
4560
4561 :function Bar()
4562 : return "let lnum = " . line(".") . " | let col = " . col(".")
4563 :endfunction
4564
4565The names "lnum" and "col" could also be passed as argument to Bar(), to allow
4566the caller to set the names.
4567
4568 *:cal* *:call* *E107*
4569:[range]cal[l] {name}([arguments])
4570 Call a function. The name of the function and its arguments
4571 are as specified with |:function|. Up to 20 arguments can be
4572 used.
4573 Without a range and for functions that accept a range, the
4574 function is called once. When a range is given the cursor is
4575 positioned at the start of the first line before executing the
4576 function.
4577 When a range is given and the function doesn't handle it
4578 itself, the function is executed for each line in the range,
4579 with the cursor in the first column of that line. The cursor
4580 is left at the last line (possibly moved by the last function
4581 call). The arguments are re-evaluated for each line. Thus
4582 this works:
4583 *function-range-example* >
4584 :function Mynumber(arg)
4585 : echo line(".") . " " . a:arg
4586 :endfunction
4587 :1,5call Mynumber(getline("."))
4588<
4589 The "a:firstline" and "a:lastline" are defined anyway, they
4590 can be used to do something different at the start or end of
4591 the range.
4592
4593 Example of a function that handles the range itself: >
4594
4595 :function Cont() range
4596 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
4597 :endfunction
4598 :4,8call Cont()
4599<
4600 This function inserts the continuation character "\" in front
4601 of all the lines in the range, except the first one.
4602
4603 *E132*
4604The recursiveness of user functions is restricted with the |'maxfuncdepth'|
4605option.
4606
Bram Moolenaar7c626922005-02-07 22:01:03 +00004607
4608AUTOMATICALLY LOADING FUNCTIONS ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609 *autoload-functions*
4610When using many or large functions, it's possible to automatically define them
Bram Moolenaar7c626922005-02-07 22:01:03 +00004611only when they are used. There are two methods: with an autocommand and with
4612the "autoload" directory in 'runtimepath'.
4613
4614
4615Using an autocommand ~
4616
Bram Moolenaar05159a02005-02-26 23:04:13 +00004617This is introduced in the user manual, section |41.14|.
4618
Bram Moolenaar7c626922005-02-07 22:01:03 +00004619The autocommand is useful if you have a plugin that is a long Vim script file.
4620You can define the autocommand and quickly quit the script with |:finish|.
4621That makes Vim startup faster. The autocommand should then load the same file
4622again, setting a variable to skip the |:finish| command.
4623
4624Use the FuncUndefined autocommand event with a pattern that matches the
4625function(s) to be defined. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626
4627 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
4628
4629The file "~/vim/bufnetfuncs.vim" should then define functions that start with
4630"BufNet". Also see |FuncUndefined|.
4631
Bram Moolenaar7c626922005-02-07 22:01:03 +00004632
4633Using an autoload script ~
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004634 *autoload* *E746*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004635This is introduced in the user manual, section |41.15|.
4636
Bram Moolenaar7c626922005-02-07 22:01:03 +00004637Using a script in the "autoload" directory is simpler, but requires using
4638exactly the right file name. A function that can be autoloaded has a name
4639like this: >
4640
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004641 :call filename#funcname()
Bram Moolenaar7c626922005-02-07 22:01:03 +00004642
4643When such a function is called, and it is not defined yet, Vim will search the
4644"autoload" directories in 'runtimepath' for a script file called
4645"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
4646then define the function like this: >
4647
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004648 function filename#funcname()
Bram Moolenaar7c626922005-02-07 22:01:03 +00004649 echo "Done!"
4650 endfunction
4651
4652The file name and the name used before the colon in the function must match
4653exactly, and the defined function must have the name exactly as it will be
4654called.
4655
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004656It is possible to use subdirectories. Every # in the function name works like
4657a path separator. Thus when calling a function: >
Bram Moolenaar7c626922005-02-07 22:01:03 +00004658
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004659 :call foo#bar#func()
Bram Moolenaar7c626922005-02-07 22:01:03 +00004660
4661Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
4662
4663The name before the first colon must be at least two characters long,
4664otherwise it looks like a scope, such as "s:".
4665
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004666This also works when reading a variable that has not been set yet: >
4667
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004668 :let l = foo#bar#lvar
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004669
4670When assigning a value to such a variable nothing special happens. This can
4671be used to pass settings to the autoload script before it's loaded: >
4672
Bram Moolenaara7fc0102005-05-18 22:17:12 +00004673 :let foo#bar#toggle = 1
4674 :call foo#bar#func()
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004675
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004676Note that when you make a mistake and call a function that is supposed to be
4677defined in an autoload script, but the script doesn't actually define the
4678function, the script will be sourced every time you try to call the function.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004679And you will get an error message every time.
4680
4681Also note that if you have two script files, and one calls a function in the
4682other and vise versa, before the used function is defined, it won't work.
4683Avoid using the autoload functionality at the toplevel.
Bram Moolenaar7c626922005-02-07 22:01:03 +00004684
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685==============================================================================
46866. Curly braces names *curly-braces-names*
4687
4688Wherever you can use a variable, you can use a "curly braces name" variable.
4689This is a regular variable name with one or more expressions wrapped in braces
4690{} like this: >
4691 my_{adjective}_variable
4692
4693When Vim encounters this, it evaluates the expression inside the braces, puts
4694that in place of the expression, and re-interprets the whole as a variable
4695name. So in the above example, if the variable "adjective" was set to
4696"noisy", then the reference would be to "my_noisy_variable", whereas if
4697"adjective" was set to "quiet", then it would be to "my_quiet_variable".
4698
4699One application for this is to create a set of variables governed by an option
4700value. For example, the statement >
4701 echo my_{&background}_message
4702
4703would output the contents of "my_dark_message" or "my_light_message" depending
4704on the current value of 'background'.
4705
4706You can use multiple brace pairs: >
4707 echo my_{adverb}_{adjective}_message
4708..or even nest them: >
4709 echo my_{ad{end_of_word}}_message
4710where "end_of_word" is either "verb" or "jective".
4711
4712However, the expression inside the braces must evaluate to a valid single
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00004713variable name, e.g. this is invalid: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714 :let foo='a + b'
4715 :echo c{foo}d
4716.. since the result of expansion is "ca + bd", which is not a variable name.
4717
4718 *curly-braces-function-names*
4719You can call and define functions by an evaluated name in a similar way.
4720Example: >
4721 :let func_end='whizz'
4722 :call my_func_{func_end}(parameter)
4723
4724This would call the function "my_func_whizz(parameter)".
4725
4726==============================================================================
47277. Commands *expression-commands*
4728
4729:let {var-name} = {expr1} *:let* *E18*
4730 Set internal variable {var-name} to the result of the
4731 expression {expr1}. The variable will get the type
4732 from the {expr}. If {var-name} didn't exist yet, it
4733 is created.
4734
Bram Moolenaar13065c42005-01-08 16:08:21 +00004735:let {var-name}[{idx}] = {expr1} *E689*
4736 Set a list item to the result of the expression
4737 {expr1}. {var-name} must refer to a list and {idx}
4738 must be a valid index in that list. For nested list
4739 the index can be repeated.
4740 This cannot be used to add an item to a list.
4741
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004742 *E711* *E719*
4743:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004744 Set a sequence of items in a List to the result of the
4745 expression {expr1}, which must be a list with the
4746 correct number of items.
4747 {idx1} can be omitted, zero is used instead.
4748 {idx2} can be omitted, meaning the end of the list.
4749 When the selected range of items is partly past the
4750 end of the list, items will be added.
4751
Bram Moolenaar748bf032005-02-02 23:04:36 +00004752 *:let+=* *:let-=* *:let.=* *E734*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004753:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
4754:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
4755:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
4756 These fail if {var} was not set yet and when the type
4757 of {var} and {expr1} don't fit the operator.
4758
4759
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760:let ${env-name} = {expr1} *:let-environment* *:let-$*
4761 Set environment variable {env-name} to the result of
4762 the expression {expr1}. The type is always String.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004763:let ${env-name} .= {expr1}
4764 Append {expr1} to the environment variable {env-name}.
4765 If the environment variable didn't exist yet this
4766 works like "=".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767
4768:let @{reg-name} = {expr1} *:let-register* *:let-@*
4769 Write the result of the expression {expr1} in register
4770 {reg-name}. {reg-name} must be a single letter, and
4771 must be the name of a writable register (see
4772 |registers|). "@@" can be used for the unnamed
4773 register, "@/" for the search pattern.
4774 If the result of {expr1} ends in a <CR> or <NL>, the
4775 register will be linewise, otherwise it will be set to
4776 characterwise.
4777 This can be used to clear the last search pattern: >
4778 :let @/ = ""
4779< This is different from searching for an empty string,
4780 that would match everywhere.
4781
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004782:let @{reg-name} .= {expr1}
4783 Append {expr1} to register {reg-name}. If the
4784 register was empty it's like setting it to {expr1}.
4785
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786:let &{option-name} = {expr1} *:let-option* *:let-star*
4787 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004788 expression {expr1}. A String or Number value is
4789 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 For an option local to a window or buffer the effect
4791 is just like using the |:set| command: both the local
4792 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004793 Example: >
4794 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004796:let &{option-name} .= {expr1}
4797 For a string option: Append {expr1} to the value.
4798 Does not insert a comma like |:set+=|.
4799
4800:let &{option-name} += {expr1}
4801:let &{option-name} -= {expr1}
4802 For a number or boolean option: Add or subtract
4803 {expr1}.
4804
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805:let &l:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004806:let &l:{option-name} .= {expr1}
4807:let &l:{option-name} += {expr1}
4808:let &l:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 Like above, but only set the local value of an option
4810 (if there is one). Works like |:setlocal|.
4811
4812:let &g:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004813:let &g:{option-name} .= {expr1}
4814:let &g:{option-name} += {expr1}
4815:let &g:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 Like above, but only set the global value of an option
4817 (if there is one). Works like |:setglobal|.
4818
Bram Moolenaar13065c42005-01-08 16:08:21 +00004819:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004820 {expr1} must evaluate to a List. The first item in
4821 the list is assigned to {name1}, the second item to
4822 {name2}, etc.
4823 The number of names must match the number of items in
4824 the List.
4825 Each name can be one of the items of the ":let"
4826 command as mentioned above.
4827 Example: >
4828 :let [s, item] = GetItem(s)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004829< Detail: {expr1} is evaluated first, then the
4830 assignments are done in sequence. This matters if
4831 {name2} depends on {name1}. Example: >
4832 :let x = [0, 1]
4833 :let i = 0
4834 :let [i, x[i]] = [1, 2]
4835 :echo x
4836< The result is [0, 2].
4837
4838:let [{name1}, {name2}, ...] .= {expr1}
4839:let [{name1}, {name2}, ...] += {expr1}
4840:let [{name1}, {name2}, ...] -= {expr1}
4841 Like above, but append/add/subtract the value for each
4842 List item.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004843
4844:let [{name}, ..., ; {lastname}] = {expr1}
Bram Moolenaar677ee682005-01-27 14:41:15 +00004845 Like |:let-unpack| above, but the List may have more
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004846 items than there are names. A list of the remaining
4847 items is assigned to {lastname}. If there are no
4848 remaining items {lastname} is set to an empty list.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004849 Example: >
4850 :let [a, b; rest] = ["aval", "bval", 3, 4]
4851<
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004852:let [{name}, ..., ; {lastname}] .= {expr1}
4853:let [{name}, ..., ; {lastname}] += {expr1}
4854:let [{name}, ..., ; {lastname}] -= {expr1}
4855 Like above, but append/add/subtract the value for each
4856 List item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 *E106*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004858:let {var-name} .. List the value of variable {var-name}. Multiple
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00004859 variable names may be given. Special names recognized
4860 here: *E738*
4861 g: global variables.
4862 b: local buffer variables.
4863 w: local window variables.
4864 v: Vim variables.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00004866:let List the values of all variables. The type of the
4867 variable is indicated before the value:
4868 <nothing> String
4869 # Number
4870 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004872
4873:unl[et][!] {name} ... *:unlet* *:unl* *E108*
4874 Remove the internal variable {name}. Several variable
4875 names can be given, they are all removed. The name
4876 may also be a List or Dictionary item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 With [!] no error message is given for non-existing
4878 variables.
Bram Moolenaar9cd15162005-01-16 22:02:49 +00004879 One or more items from a List can be removed: >
4880 :unlet list[3] " remove fourth item
4881 :unlet list[3:] " remove fourth item to last
4882< One item from a Dictionary can be removed at a time: >
4883 :unlet dict['two']
4884 :unlet dict.two
Bram Moolenaar071d4272004-06-13 20:20:40 +00004885
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004886:lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv*
4887 Lock the internal variable {name}. Locking means that
4888 it can no longer be changed (until it is unlocked).
4889 A locked variable can be deleted: >
4890 :lockvar v
4891 :let v = 'asdf' " fails!
4892 :unlet v
4893< *E741*
4894 If you try to change a locked variable you get an
4895 error message: "E741: Value of {name} is locked"
4896
4897 [depth] is relevant when locking a List or Dictionary.
4898 It specifies how deep the locking goes:
4899 1 Lock the List or Dictionary itself,
4900 cannot add or remove items, but can
4901 still change their values.
4902 2 Also lock the values, cannot change
4903 the items. If an item is a List or
4904 Dictionary, cannot add or remove
4905 items, but can still change the
4906 values.
4907 3 Like 2 but for the List/Dictionary in
4908 the List/Dictionary, one level deeper.
4909 The default [depth] is 2, thus when {name} is a List
4910 or Dictionary the values cannot be changed.
4911 *E743*
4912 For unlimited depth use [!] and omit [depth].
4913 However, there is a maximum depth of 100 to catch
4914 loops.
4915
4916 Note that when two variables refer to the same List
4917 and you lock one of them, the List will also be locked
4918 when used through the other variable. Example: >
4919 :let l = [0, 1, 2, 3]
4920 :let cl = l
4921 :lockvar l
4922 :let cl[1] = 99 " won't work!
4923< You may want to make a copy of a list to avoid this.
4924 See |deepcopy()|.
4925
4926
4927:unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo*
4928 Unlock the internal variable {name}. Does the
4929 opposite of |:lockvar|.
4930
4931
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
4933:en[dif] Execute the commands until the next matching ":else"
4934 or ":endif" if {expr1} evaluates to non-zero.
4935
4936 From Vim version 4.5 until 5.0, every Ex command in
4937 between the ":if" and ":endif" is ignored. These two
4938 commands were just to allow for future expansions in a
4939 backwards compatible way. Nesting was allowed. Note
4940 that any ":else" or ":elseif" was ignored, the "else"
4941 part was not executed either.
4942
4943 You can use this to remain compatible with older
4944 versions: >
4945 :if version >= 500
4946 : version-5-specific-commands
4947 :endif
4948< The commands still need to be parsed to find the
4949 "endif". Sometimes an older Vim has a problem with a
4950 new command. For example, ":silent" is recognized as
4951 a ":substitute" command. In that case ":execute" can
4952 avoid problems: >
4953 :if version >= 600
4954 : execute "silent 1,$delete"
4955 :endif
4956<
4957 NOTE: The ":append" and ":insert" commands don't work
4958 properly in between ":if" and ":endif".
4959
4960 *:else* *:el* *E581* *E583*
4961:el[se] Execute the commands until the next matching ":else"
4962 or ":endif" if they previously were not being
4963 executed.
4964
4965 *:elseif* *:elsei* *E582* *E584*
4966:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
4967 is no extra ":endif".
4968
4969:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004970 *E170* *E585* *E588* *E733*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971:endw[hile] Repeat the commands between ":while" and ":endwhile",
4972 as long as {expr1} evaluates to non-zero.
4973 When an error is detected from a command inside the
4974 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00004975 Example: >
4976 :let lnum = 1
4977 :while lnum <= line("$")
4978 :call FixLine(lnum)
4979 :let lnum = lnum + 1
4980 :endwhile
4981<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00004983 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004985:for {var} in {list} *:for* *E690* *E732*
Bram Moolenaar12805862005-01-05 22:16:17 +00004986:endfo[r] *:endfo* *:endfor*
4987 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00004988 each item in {list}. Variable {var} is set to the
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004989 value of each item.
4990 When an error is detected for a command inside the
Bram Moolenaar12805862005-01-05 22:16:17 +00004991 loop, execution continues after the "endfor".
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004992 Changing {list} affects what items are used. Make a
4993 copy if this is unwanted: >
4994 :for item in copy(mylist)
4995< When not making a copy, Vim stores a reference to the
4996 next item in the list, before executing the commands
4997 with the current item. Thus the current item can be
4998 removed without effect. Removing any later item means
4999 it will not be found. Thus the following example
5000 works (an inefficient way to make a list empty): >
5001 :for item in mylist
Bram Moolenaar12805862005-01-05 22:16:17 +00005002 :call remove(mylist, 0)
5003 :endfor
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00005004< Note that reordering the list (e.g., with sort() or
5005 reverse()) may have unexpected effects.
5006 Note that the type of each list item should be
Bram Moolenaar12805862005-01-05 22:16:17 +00005007 identical to avoid errors for the type of {var}
5008 changing. Unlet the variable at the end of the loop
5009 to allow multiple item types.
5010
5011:for {var} in {string}
5012:endfo[r] Like ":for" above, but use each character in {string}
5013 as a list item.
5014 Composing characters are used as separate characters.
5015 A Number is first converted to a String.
5016
5017:for [{var1}, {var2}, ...] in {listlist}
5018:endfo[r]
5019 Like ":for" above, but each item in {listlist} must be
5020 a list, of which each item is assigned to {var1},
5021 {var2}, etc. Example: >
5022 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
5023 :echo getline(lnum)[col]
5024 :endfor
5025<
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00005027:con[tinue] When used inside a ":while" or ":for" loop, jumps back
5028 to the start of the loop.
5029 If it is used after a |:try| inside the loop but
5030 before the matching |:finally| (if present), the
5031 commands following the ":finally" up to the matching
5032 |:endtry| are executed first. This process applies to
5033 all nested ":try"s inside the loop. The outermost
5034 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035
5036 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00005037:brea[k] When used inside a ":while" or ":for" loop, skips to
5038 the command after the matching ":endwhile" or
5039 ":endfor".
5040 If it is used after a |:try| inside the loop but
5041 before the matching |:finally| (if present), the
5042 commands following the ":finally" up to the matching
5043 |:endtry| are executed first. This process applies to
5044 all nested ":try"s inside the loop. The outermost
5045 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046
5047:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
5048:endt[ry] Change the error handling for the commands between
5049 ":try" and ":endtry" including everything being
5050 executed across ":source" commands, function calls,
5051 or autocommand invocations.
5052
5053 When an error or interrupt is detected and there is
5054 a |:finally| command following, execution continues
5055 after the ":finally". Otherwise, or when the
5056 ":endtry" is reached thereafter, the next
5057 (dynamically) surrounding ":try" is checked for
5058 a corresponding ":finally" etc. Then the script
5059 processing is terminated. (Whether a function
5060 definition has an "abort" argument does not matter.)
5061 Example: >
5062 :try | edit too much | finally | echo "cleanup" | endtry
5063 :echo "impossible" " not reached, script terminated above
5064<
5065 Moreover, an error or interrupt (dynamically) inside
5066 ":try" and ":endtry" is converted to an exception. It
5067 can be caught as if it were thrown by a |:throw|
5068 command (see |:catch|). In this case, the script
5069 processing is not terminated.
5070
5071 The value "Vim:Interrupt" is used for an interrupt
5072 exception. An error in a Vim command is converted
5073 to a value of the form "Vim({command}):{errmsg}",
5074 other errors are converted to a value of the form
5075 "Vim:{errmsg}". {command} is the full command name,
5076 and {errmsg} is the message that is displayed if the
5077 error exception is not caught, always beginning with
5078 the error number.
5079 Examples: >
5080 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
5081 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
5082<
5083 *:cat* *:catch* *E603* *E604* *E605*
5084:cat[ch] /{pattern}/ The following commands until the next ":catch",
5085 |:finally|, or |:endtry| that belongs to the same
5086 |:try| as the ":catch" are executed when an exception
5087 matching {pattern} is being thrown and has not yet
5088 been caught by a previous ":catch". Otherwise, these
5089 commands are skipped.
5090 When {pattern} is omitted all errors are caught.
5091 Examples: >
5092 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
5093 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
5094 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
5095 :catch /^Vim(write):/ " catch all errors in :write
5096 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
5097 :catch /my-exception/ " catch user exception
5098 :catch /.*/ " catch everything
5099 :catch " same as /.*/
5100<
5101 Another character can be used instead of / around the
5102 {pattern}, so long as it does not have a special
5103 meaning (e.g., '|' or '"') and doesn't occur inside
5104 {pattern}.
5105 NOTE: It is not reliable to ":catch" the TEXT of
5106 an error message because it may vary in different
5107 locales.
5108
5109 *:fina* *:finally* *E606* *E607*
5110:fina[lly] The following commands until the matching |:endtry|
5111 are executed whenever the part between the matching
5112 |:try| and the ":finally" is left: either by falling
5113 through to the ":finally" or by a |:continue|,
5114 |:break|, |:finish|, or |:return|, or by an error or
5115 interrupt or exception (see |:throw|).
5116
5117 *:th* *:throw* *E608*
5118:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
5119 If the ":throw" is used after a |:try| but before the
5120 first corresponding |:catch|, commands are skipped
5121 until the first ":catch" matching {expr1} is reached.
5122 If there is no such ":catch" or if the ":throw" is
5123 used after a ":catch" but before the |:finally|, the
5124 commands following the ":finally" (if present) up to
5125 the matching |:endtry| are executed. If the ":throw"
5126 is after the ":finally", commands up to the ":endtry"
5127 are skipped. At the ":endtry", this process applies
5128 again for the next dynamically surrounding ":try"
5129 (which may be found in a calling function or sourcing
5130 script), until a matching ":catch" has been found.
5131 If the exception is not caught, the command processing
5132 is terminated.
5133 Example: >
5134 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
5135<
5136
5137 *:ec* *:echo*
5138:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
5139 first {expr1} starts on a new line.
5140 Also see |:comment|.
5141 Use "\n" to start a new line. Use "\r" to move the
5142 cursor to the first column.
5143 Uses the highlighting set by the |:echohl| command.
5144 Cannot be followed by a comment.
5145 Example: >
5146 :echo "the value of 'shell' is" &shell
5147< A later redraw may make the message disappear again.
5148 To avoid that a command from before the ":echo" causes
5149 a redraw afterwards (redraws are often postponed until
5150 you type something), force a redraw with the |:redraw|
5151 command. Example: >
5152 :new | redraw | echo "there is a new window"
5153<
5154 *:echon*
5155:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
5156 |:comment|.
5157 Uses the highlighting set by the |:echohl| command.
5158 Cannot be followed by a comment.
5159 Example: >
5160 :echon "the value of 'shell' is " &shell
5161<
5162 Note the difference between using ":echo", which is a
5163 Vim command, and ":!echo", which is an external shell
5164 command: >
5165 :!echo % --> filename
5166< The arguments of ":!" are expanded, see |:_%|. >
5167 :!echo "%" --> filename or "filename"
5168< Like the previous example. Whether you see the double
5169 quotes or not depends on your 'shell'. >
5170 :echo % --> nothing
5171< The '%' is an illegal character in an expression. >
5172 :echo "%" --> %
5173< This just echoes the '%' character. >
5174 :echo expand("%") --> filename
5175< This calls the expand() function to expand the '%'.
5176
5177 *:echoh* *:echohl*
5178:echoh[l] {name} Use the highlight group {name} for the following
5179 |:echo|, |:echon| and |:echomsg| commands. Also used
5180 for the |input()| prompt. Example: >
5181 :echohl WarningMsg | echo "Don't panic!" | echohl None
5182< Don't forget to set the group back to "None",
5183 otherwise all following echo's will be highlighted.
5184
5185 *:echom* *:echomsg*
5186:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
5187 message in the |message-history|.
5188 Spaces are placed between the arguments as with the
5189 |:echo| command. But unprintable characters are
5190 displayed, not interpreted.
5191 Uses the highlighting set by the |:echohl| command.
5192 Example: >
5193 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
5194<
5195 *:echoe* *:echoerr*
5196:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
5197 message in the |message-history|. When used in a
5198 script or function the line number will be added.
5199 Spaces are placed between the arguments as with the
5200 :echo command. When used inside a try conditional,
5201 the message is raised as an error exception instead
5202 (see |try-echoerr|).
5203 Example: >
5204 :echoerr "This script just failed!"
5205< If you just want a highlighted message use |:echohl|.
5206 And to get a beep: >
5207 :exe "normal \<Esc>"
5208<
5209 *:exe* *:execute*
5210:exe[cute] {expr1} .. Executes the string that results from the evaluation
5211 of {expr1} as an Ex command. Multiple arguments are
5212 concatenated, with a space in between. {expr1} is
5213 used as the processed command, command line editing
5214 keys are not recognized.
5215 Cannot be followed by a comment.
5216 Examples: >
5217 :execute "buffer " nextbuf
5218 :execute "normal " count . "w"
5219<
5220 ":execute" can be used to append a command to commands
5221 that don't accept a '|'. Example: >
5222 :execute '!ls' | echo "theend"
5223
5224< ":execute" is also a nice way to avoid having to type
5225 control characters in a Vim script for a ":normal"
5226 command: >
5227 :execute "normal ixxx\<Esc>"
5228< This has an <Esc> character, see |expr-string|.
5229
5230 Note: The executed string may be any command-line, but
Bram Moolenaard8b02732005-01-14 21:48:43 +00005231 you cannot start or end a "while", "for" or "if"
5232 command. Thus this is illegal: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 :execute 'while i > 5'
5234 :execute 'echo "test" | break'
5235<
5236 It is allowed to have a "while" or "if" command
5237 completely in the executed string: >
5238 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
5239<
5240
5241 *:comment*
5242 ":execute", ":echo" and ":echon" cannot be followed by
5243 a comment directly, because they see the '"' as the
5244 start of a string. But, you can use '|' followed by a
5245 comment. Example: >
5246 :echo "foo" | "this is a comment
5247
5248==============================================================================
52498. Exception handling *exception-handling*
5250
5251The Vim script language comprises an exception handling feature. This section
5252explains how it can be used in a Vim script.
5253
5254Exceptions may be raised by Vim on an error or on interrupt, see
5255|catch-errors| and |catch-interrupt|. You can also explicitly throw an
5256exception by using the ":throw" command, see |throw-catch|.
5257
5258
5259TRY CONDITIONALS *try-conditionals*
5260
5261Exceptions can be caught or can cause cleanup code to be executed. You can
5262use a try conditional to specify catch clauses (that catch exceptions) and/or
5263a finally clause (to be executed for cleanup).
5264 A try conditional begins with a |:try| command and ends at the matching
5265|:endtry| command. In between, you can use a |:catch| command to start
5266a catch clause, or a |:finally| command to start a finally clause. There may
5267be none or multiple catch clauses, but there is at most one finally clause,
5268which must not be followed by any catch clauses. The lines before the catch
5269clauses and the finally clause is called a try block. >
5270
5271 :try
5272 : ...
5273 : ... TRY BLOCK
5274 : ...
5275 :catch /{pattern}/
5276 : ...
5277 : ... CATCH CLAUSE
5278 : ...
5279 :catch /{pattern}/
5280 : ...
5281 : ... CATCH CLAUSE
5282 : ...
5283 :finally
5284 : ...
5285 : ... FINALLY CLAUSE
5286 : ...
5287 :endtry
5288
5289The try conditional allows to watch code for exceptions and to take the
5290appropriate actions. Exceptions from the try block may be caught. Exceptions
5291from the try block and also the catch clauses may cause cleanup actions.
5292 When no exception is thrown during execution of the try block, the control
5293is transferred to the finally clause, if present. After its execution, the
5294script continues with the line following the ":endtry".
5295 When an exception occurs during execution of the try block, the remaining
5296lines in the try block are skipped. The exception is matched against the
5297patterns specified as arguments to the ":catch" commands. The catch clause
5298after the first matching ":catch" is taken, other catch clauses are not
5299executed. The catch clause ends when the next ":catch", ":finally", or
5300":endtry" command is reached - whatever is first. Then, the finally clause
5301(if present) is executed. When the ":endtry" is reached, the script execution
5302continues in the following line as usual.
5303 When an exception that does not match any of the patterns specified by the
5304":catch" commands is thrown in the try block, the exception is not caught by
5305that try conditional and none of the catch clauses is executed. Only the
5306finally clause, if present, is taken. The exception pends during execution of
5307the finally clause. It is resumed at the ":endtry", so that commands after
5308the ":endtry" are not executed and the exception might be caught elsewhere,
5309see |try-nesting|.
5310 When during execution of a catch clause another exception is thrown, the
5311remaining lines in that catch clause are not executed. The new exception is
5312not matched against the patterns in any of the ":catch" commands of the same
5313try conditional and none of its catch clauses is taken. If there is, however,
5314a finally clause, it is executed, and the exception pends during its
5315execution. The commands following the ":endtry" are not executed. The new
5316exception might, however, be caught elsewhere, see |try-nesting|.
5317 When during execution of the finally clause (if present) an exception is
5318thrown, the remaining lines in the finally clause are skipped. If the finally
5319clause has been taken because of an exception from the try block or one of the
5320catch clauses, the original (pending) exception is discarded. The commands
5321following the ":endtry" are not executed, and the exception from the finally
5322clause is propagated and can be caught elsewhere, see |try-nesting|.
5323
5324The finally clause is also executed, when a ":break" or ":continue" for
5325a ":while" loop enclosing the complete try conditional is executed from the
5326try block or a catch clause. Or when a ":return" or ":finish" is executed
5327from the try block or a catch clause of a try conditional in a function or
5328sourced script, respectively. The ":break", ":continue", ":return", or
5329":finish" pends during execution of the finally clause and is resumed when the
5330":endtry" is reached. It is, however, discarded when an exception is thrown
5331from the finally clause.
5332 When a ":break" or ":continue" for a ":while" loop enclosing the complete
5333try conditional or when a ":return" or ":finish" is encountered in the finally
5334clause, the rest of the finally clause is skipped, and the ":break",
5335":continue", ":return" or ":finish" is executed as usual. If the finally
5336clause has been taken because of an exception or an earlier ":break",
5337":continue", ":return", or ":finish" from the try block or a catch clause,
5338this pending exception or command is discarded.
5339
5340For examples see |throw-catch| and |try-finally|.
5341
5342
5343NESTING OF TRY CONDITIONALS *try-nesting*
5344
5345Try conditionals can be nested arbitrarily. That is, a complete try
5346conditional can be put into the try block, a catch clause, or the finally
5347clause of another try conditional. If the inner try conditional does not
5348catch an exception thrown in its try block or throws a new exception from one
5349of its catch clauses or its finally clause, the outer try conditional is
5350checked according to the rules above. If the inner try conditional is in the
5351try block of the outer try conditional, its catch clauses are checked, but
5352otherwise only the finally clause is executed. It does not matter for
5353nesting, whether the inner try conditional is directly contained in the outer
5354one, or whether the outer one sources a script or calls a function containing
5355the inner try conditional.
5356
5357When none of the active try conditionals catches an exception, just their
5358finally clauses are executed. Thereafter, the script processing terminates.
5359An error message is displayed in case of an uncaught exception explicitly
5360thrown by a ":throw" command. For uncaught error and interrupt exceptions
5361implicitly raised by Vim, the error message(s) or interrupt message are shown
5362as usual.
5363
5364For examples see |throw-catch|.
5365
5366
5367EXAMINING EXCEPTION HANDLING CODE *except-examine*
5368
5369Exception handling code can get tricky. If you are in doubt what happens, set
5370'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
5371script file. Then you see when an exception is thrown, discarded, caught, or
5372finished. When using a verbosity level of at least 14, things pending in
5373a finally clause are also shown. This information is also given in debug mode
5374(see |debug-scripts|).
5375
5376
5377THROWING AND CATCHING EXCEPTIONS *throw-catch*
5378
5379You can throw any number or string as an exception. Use the |:throw| command
5380and pass the value to be thrown as argument: >
5381 :throw 4711
5382 :throw "string"
5383< *throw-expression*
5384You can also specify an expression argument. The expression is then evaluated
5385first, and the result is thrown: >
5386 :throw 4705 + strlen("string")
5387 :throw strpart("strings", 0, 6)
5388
5389An exception might be thrown during evaluation of the argument of the ":throw"
5390command. Unless it is caught there, the expression evaluation is abandoned.
5391The ":throw" command then does not throw a new exception.
5392 Example: >
5393
5394 :function! Foo(arg)
5395 : try
5396 : throw a:arg
5397 : catch /foo/
5398 : endtry
5399 : return 1
5400 :endfunction
5401 :
5402 :function! Bar()
5403 : echo "in Bar"
5404 : return 4710
5405 :endfunction
5406 :
5407 :throw Foo("arrgh") + Bar()
5408
5409This throws "arrgh", and "in Bar" is not displayed since Bar() is not
5410executed. >
5411 :throw Foo("foo") + Bar()
5412however displays "in Bar" and throws 4711.
5413
5414Any other command that takes an expression as argument might also be
5415abandoned by an (uncaught) exception during the expression evaluation. The
5416exception is then propagated to the caller of the command.
5417 Example: >
5418
5419 :if Foo("arrgh")
5420 : echo "then"
5421 :else
5422 : echo "else"
5423 :endif
5424
5425Here neither of "then" or "else" is displayed.
5426
5427 *catch-order*
5428Exceptions can be caught by a try conditional with one or more |:catch|
5429commands, see |try-conditionals|. The values to be caught by each ":catch"
5430command can be specified as a pattern argument. The subsequent catch clause
5431gets executed when a matching exception is caught.
5432 Example: >
5433
5434 :function! Foo(value)
5435 : try
5436 : throw a:value
5437 : catch /^\d\+$/
5438 : echo "Number thrown"
5439 : catch /.*/
5440 : echo "String thrown"
5441 : endtry
5442 :endfunction
5443 :
5444 :call Foo(0x1267)
5445 :call Foo('string')
5446
5447The first call to Foo() displays "Number thrown", the second "String thrown".
5448An exception is matched against the ":catch" commands in the order they are
5449specified. Only the first match counts. So you should place the more
5450specific ":catch" first. The following order does not make sense: >
5451
5452 : catch /.*/
5453 : echo "String thrown"
5454 : catch /^\d\+$/
5455 : echo "Number thrown"
5456
5457The first ":catch" here matches always, so that the second catch clause is
5458never taken.
5459
5460 *throw-variables*
5461If you catch an exception by a general pattern, you may access the exact value
5462in the variable |v:exception|: >
5463
5464 : catch /^\d\+$/
5465 : echo "Number thrown. Value is" v:exception
5466
5467You may also be interested where an exception was thrown. This is stored in
5468|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
5469exception most recently caught as long it is not finished.
5470 Example: >
5471
5472 :function! Caught()
5473 : if v:exception != ""
5474 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
5475 : else
5476 : echo 'Nothing caught'
5477 : endif
5478 :endfunction
5479 :
5480 :function! Foo()
5481 : try
5482 : try
5483 : try
5484 : throw 4711
5485 : finally
5486 : call Caught()
5487 : endtry
5488 : catch /.*/
5489 : call Caught()
5490 : throw "oops"
5491 : endtry
5492 : catch /.*/
5493 : call Caught()
5494 : finally
5495 : call Caught()
5496 : endtry
5497 :endfunction
5498 :
5499 :call Foo()
5500
5501This displays >
5502
5503 Nothing caught
5504 Caught "4711" in function Foo, line 4
5505 Caught "oops" in function Foo, line 10
5506 Nothing caught
5507
5508A practical example: The following command ":LineNumber" displays the line
5509number in the script or function where it has been used: >
5510
5511 :function! LineNumber()
5512 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
5513 :endfunction
5514 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
5515<
5516 *try-nested*
5517An exception that is not caught by a try conditional can be caught by
5518a surrounding try conditional: >
5519
5520 :try
5521 : try
5522 : throw "foo"
5523 : catch /foobar/
5524 : echo "foobar"
5525 : finally
5526 : echo "inner finally"
5527 : endtry
5528 :catch /foo/
5529 : echo "foo"
5530 :endtry
5531
5532The inner try conditional does not catch the exception, just its finally
5533clause is executed. The exception is then caught by the outer try
5534conditional. The example displays "inner finally" and then "foo".
5535
5536 *throw-from-catch*
5537You can catch an exception and throw a new one to be caught elsewhere from the
5538catch clause: >
5539
5540 :function! Foo()
5541 : throw "foo"
5542 :endfunction
5543 :
5544 :function! Bar()
5545 : try
5546 : call Foo()
5547 : catch /foo/
5548 : echo "Caught foo, throw bar"
5549 : throw "bar"
5550 : endtry
5551 :endfunction
5552 :
5553 :try
5554 : call Bar()
5555 :catch /.*/
5556 : echo "Caught" v:exception
5557 :endtry
5558
5559This displays "Caught foo, throw bar" and then "Caught bar".
5560
5561 *rethrow*
5562There is no real rethrow in the Vim script language, but you may throw
5563"v:exception" instead: >
5564
5565 :function! Bar()
5566 : try
5567 : call Foo()
5568 : catch /.*/
5569 : echo "Rethrow" v:exception
5570 : throw v:exception
5571 : endtry
5572 :endfunction
5573< *try-echoerr*
5574Note that this method cannot be used to "rethrow" Vim error or interrupt
5575exceptions, because it is not possible to fake Vim internal exceptions.
5576Trying so causes an error exception. You should throw your own exception
5577denoting the situation. If you want to cause a Vim error exception containing
5578the original error exception value, you can use the |:echoerr| command: >
5579
5580 :try
5581 : try
5582 : asdf
5583 : catch /.*/
5584 : echoerr v:exception
5585 : endtry
5586 :catch /.*/
5587 : echo v:exception
5588 :endtry
5589
5590This code displays
5591
5592 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
5593
5594
5595CLEANUP CODE *try-finally*
5596
5597Scripts often change global settings and restore them at their end. If the
5598user however interrupts the script by pressing CTRL-C, the settings remain in
5599an inconsistent state. The same may happen to you in the development phase of
5600a script when an error occurs or you explicitly throw an exception without
5601catching it. You can solve these problems by using a try conditional with
5602a finally clause for restoring the settings. Its execution is guaranteed on
5603normal control flow, on error, on an explicit ":throw", and on interrupt.
5604(Note that errors and interrupts from inside the try conditional are converted
5605to exceptions. When not caught, they terminate the script after the finally
5606clause has been executed.)
5607Example: >
5608
5609 :try
5610 : let s:saved_ts = &ts
5611 : set ts=17
5612 :
5613 : " Do the hard work here.
5614 :
5615 :finally
5616 : let &ts = s:saved_ts
5617 : unlet s:saved_ts
5618 :endtry
5619
5620This method should be used locally whenever a function or part of a script
5621changes global settings which need to be restored on failure or normal exit of
5622that function or script part.
5623
5624 *break-finally*
5625Cleanup code works also when the try block or a catch clause is left by
5626a ":continue", ":break", ":return", or ":finish".
5627 Example: >
5628
5629 :let first = 1
5630 :while 1
5631 : try
5632 : if first
5633 : echo "first"
5634 : let first = 0
5635 : continue
5636 : else
5637 : throw "second"
5638 : endif
5639 : catch /.*/
5640 : echo v:exception
5641 : break
5642 : finally
5643 : echo "cleanup"
5644 : endtry
5645 : echo "still in while"
5646 :endwhile
5647 :echo "end"
5648
5649This displays "first", "cleanup", "second", "cleanup", and "end". >
5650
5651 :function! Foo()
5652 : try
5653 : return 4711
5654 : finally
5655 : echo "cleanup\n"
5656 : endtry
5657 : echo "Foo still active"
5658 :endfunction
5659 :
5660 :echo Foo() "returned by Foo"
5661
5662This displays "cleanup" and "4711 returned by Foo". You don't need to add an
5663extra ":return" in the finally clause. (Above all, this would override the
5664return value.)
5665
5666 *except-from-finally*
5667Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
5668a finally clause is possible, but not recommended since it abandons the
5669cleanup actions for the try conditional. But, of course, interrupt and error
5670exceptions might get raised from a finally clause.
5671 Example where an error in the finally clause stops an interrupt from
5672working correctly: >
5673
5674 :try
5675 : try
5676 : echo "Press CTRL-C for interrupt"
5677 : while 1
5678 : endwhile
5679 : finally
5680 : unlet novar
5681 : endtry
5682 :catch /novar/
5683 :endtry
5684 :echo "Script still running"
5685 :sleep 1
5686
5687If you need to put commands that could fail into a finally clause, you should
5688think about catching or ignoring the errors in these commands, see
5689|catch-errors| and |ignore-errors|.
5690
5691
5692CATCHING ERRORS *catch-errors*
5693
5694If you want to catch specific errors, you just have to put the code to be
5695watched in a try block and add a catch clause for the error message. The
5696presence of the try conditional causes all errors to be converted to an
5697exception. No message is displayed and |v:errmsg| is not set then. To find
5698the right pattern for the ":catch" command, you have to know how the format of
5699the error exception is.
5700 Error exceptions have the following format: >
5701
5702 Vim({cmdname}):{errmsg}
5703or >
5704 Vim:{errmsg}
5705
5706{cmdname} is the name of the command that failed; the second form is used when
5707the command name is not known. {errmsg} is the error message usually produced
5708when the error occurs outside try conditionals. It always begins with
5709a capital "E", followed by a two or three-digit error number, a colon, and
5710a space.
5711
5712Examples:
5713
5714The command >
5715 :unlet novar
5716normally produces the error message >
5717 E108: No such variable: "novar"
5718which is converted inside try conditionals to an exception >
5719 Vim(unlet):E108: No such variable: "novar"
5720
5721The command >
5722 :dwim
5723normally produces the error message >
5724 E492: Not an editor command: dwim
5725which is converted inside try conditionals to an exception >
5726 Vim:E492: Not an editor command: dwim
5727
5728You can catch all ":unlet" errors by a >
5729 :catch /^Vim(unlet):/
5730or all errors for misspelled command names by a >
5731 :catch /^Vim:E492:/
5732
5733Some error messages may be produced by different commands: >
5734 :function nofunc
5735and >
5736 :delfunction nofunc
5737both produce the error message >
5738 E128: Function name must start with a capital: nofunc
5739which is converted inside try conditionals to an exception >
5740 Vim(function):E128: Function name must start with a capital: nofunc
5741or >
5742 Vim(delfunction):E128: Function name must start with a capital: nofunc
5743respectively. You can catch the error by its number independently on the
5744command that caused it if you use the following pattern: >
5745 :catch /^Vim(\a\+):E128:/
5746
5747Some commands like >
5748 :let x = novar
5749produce multiple error messages, here: >
5750 E121: Undefined variable: novar
5751 E15: Invalid expression: novar
5752Only the first is used for the exception value, since it is the most specific
5753one (see |except-several-errors|). So you can catch it by >
5754 :catch /^Vim(\a\+):E121:/
5755
5756You can catch all errors related to the name "nofunc" by >
5757 :catch /\<nofunc\>/
5758
5759You can catch all Vim errors in the ":write" and ":read" commands by >
5760 :catch /^Vim(\(write\|read\)):E\d\+:/
5761
5762You can catch all Vim errors by the pattern >
5763 :catch /^Vim\((\a\+)\)\=:E\d\+:/
5764<
5765 *catch-text*
5766NOTE: You should never catch the error message text itself: >
5767 :catch /No such variable/
5768only works in the english locale, but not when the user has selected
5769a different language by the |:language| command. It is however helpful to
5770cite the message text in a comment: >
5771 :catch /^Vim(\a\+):E108:/ " No such variable
5772
5773
5774IGNORING ERRORS *ignore-errors*
5775
5776You can ignore errors in a specific Vim command by catching them locally: >
5777
5778 :try
5779 : write
5780 :catch
5781 :endtry
5782
5783But you are strongly recommended NOT to use this simple form, since it could
5784catch more than you want. With the ":write" command, some autocommands could
5785be executed and cause errors not related to writing, for instance: >
5786
5787 :au BufWritePre * unlet novar
5788
5789There could even be such errors you are not responsible for as a script
5790writer: a user of your script might have defined such autocommands. You would
5791then hide the error from the user.
5792 It is much better to use >
5793
5794 :try
5795 : write
5796 :catch /^Vim(write):/
5797 :endtry
5798
5799which only catches real write errors. So catch only what you'd like to ignore
5800intentionally.
5801
5802For a single command that does not cause execution of autocommands, you could
5803even suppress the conversion of errors to exceptions by the ":silent!"
5804command: >
5805 :silent! nunmap k
5806This works also when a try conditional is active.
5807
5808
5809CATCHING INTERRUPTS *catch-interrupt*
5810
5811When there are active try conditionals, an interrupt (CTRL-C) is converted to
5812the exception "Vim:Interrupt". You can catch it like every exception. The
5813script is not terminated, then.
5814 Example: >
5815
5816 :function! TASK1()
5817 : sleep 10
5818 :endfunction
5819
5820 :function! TASK2()
5821 : sleep 20
5822 :endfunction
5823
5824 :while 1
5825 : let command = input("Type a command: ")
5826 : try
5827 : if command == ""
5828 : continue
5829 : elseif command == "END"
5830 : break
5831 : elseif command == "TASK1"
5832 : call TASK1()
5833 : elseif command == "TASK2"
5834 : call TASK2()
5835 : else
5836 : echo "\nIllegal command:" command
5837 : continue
5838 : endif
5839 : catch /^Vim:Interrupt$/
5840 : echo "\nCommand interrupted"
5841 : " Caught the interrupt. Continue with next prompt.
5842 : endtry
5843 :endwhile
5844
5845You can interrupt a task here by pressing CTRL-C; the script then asks for
5846a new command. If you press CTRL-C at the prompt, the script is terminated.
5847
5848For testing what happens when CTRL-C would be pressed on a specific line in
5849your script, use the debug mode and execute the |>quit| or |>interrupt|
5850command on that line. See |debug-scripts|.
5851
5852
5853CATCHING ALL *catch-all*
5854
5855The commands >
5856
5857 :catch /.*/
5858 :catch //
5859 :catch
5860
5861catch everything, error exceptions, interrupt exceptions and exceptions
5862explicitly thrown by the |:throw| command. This is useful at the top level of
5863a script in order to catch unexpected things.
5864 Example: >
5865
5866 :try
5867 :
5868 : " do the hard work here
5869 :
5870 :catch /MyException/
5871 :
5872 : " handle known problem
5873 :
5874 :catch /^Vim:Interrupt$/
5875 : echo "Script interrupted"
5876 :catch /.*/
5877 : echo "Internal error (" . v:exception . ")"
5878 : echo " - occurred at " . v:throwpoint
5879 :endtry
5880 :" end of script
5881
5882Note: Catching all might catch more things than you want. Thus, you are
5883strongly encouraged to catch only for problems that you can really handle by
5884specifying a pattern argument to the ":catch".
5885 Example: Catching all could make it nearly impossible to interrupt a script
5886by pressing CTRL-C: >
5887
5888 :while 1
5889 : try
5890 : sleep 1
5891 : catch
5892 : endtry
5893 :endwhile
5894
5895
5896EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
5897
5898Exceptions may be used during execution of autocommands. Example: >
5899
5900 :autocmd User x try
5901 :autocmd User x throw "Oops!"
5902 :autocmd User x catch
5903 :autocmd User x echo v:exception
5904 :autocmd User x endtry
5905 :autocmd User x throw "Arrgh!"
5906 :autocmd User x echo "Should not be displayed"
5907 :
5908 :try
5909 : doautocmd User x
5910 :catch
5911 : echo v:exception
5912 :endtry
5913
5914This displays "Oops!" and "Arrgh!".
5915
5916 *except-autocmd-Pre*
5917For some commands, autocommands get executed before the main action of the
5918command takes place. If an exception is thrown and not caught in the sequence
5919of autocommands, the sequence and the command that caused its execution are
5920abandoned and the exception is propagated to the caller of the command.
5921 Example: >
5922
5923 :autocmd BufWritePre * throw "FAIL"
5924 :autocmd BufWritePre * echo "Should not be displayed"
5925 :
5926 :try
5927 : write
5928 :catch
5929 : echo "Caught:" v:exception "from" v:throwpoint
5930 :endtry
5931
5932Here, the ":write" command does not write the file currently being edited (as
5933you can see by checking 'modified'), since the exception from the BufWritePre
5934autocommand abandons the ":write". The exception is then caught and the
5935script displays: >
5936
5937 Caught: FAIL from BufWrite Auto commands for "*"
5938<
5939 *except-autocmd-Post*
5940For some commands, autocommands get executed after the main action of the
5941command has taken place. If this main action fails and the command is inside
5942an active try conditional, the autocommands are skipped and an error exception
5943is thrown that can be caught by the caller of the command.
5944 Example: >
5945
5946 :autocmd BufWritePost * echo "File successfully written!"
5947 :
5948 :try
5949 : write /i/m/p/o/s/s/i/b/l/e
5950 :catch
5951 : echo v:exception
5952 :endtry
5953
5954This just displays: >
5955
5956 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
5957
5958If you really need to execute the autocommands even when the main action
5959fails, trigger the event from the catch clause.
5960 Example: >
5961
5962 :autocmd BufWritePre * set noreadonly
5963 :autocmd BufWritePost * set readonly
5964 :
5965 :try
5966 : write /i/m/p/o/s/s/i/b/l/e
5967 :catch
5968 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
5969 :endtry
5970<
5971You can also use ":silent!": >
5972
5973 :let x = "ok"
5974 :let v:errmsg = ""
5975 :autocmd BufWritePost * if v:errmsg != ""
5976 :autocmd BufWritePost * let x = "after fail"
5977 :autocmd BufWritePost * endif
5978 :try
5979 : silent! write /i/m/p/o/s/s/i/b/l/e
5980 :catch
5981 :endtry
5982 :echo x
5983
5984This displays "after fail".
5985
5986If the main action of the command does not fail, exceptions from the
5987autocommands will be catchable by the caller of the command: >
5988
5989 :autocmd BufWritePost * throw ":-("
5990 :autocmd BufWritePost * echo "Should not be displayed"
5991 :
5992 :try
5993 : write
5994 :catch
5995 : echo v:exception
5996 :endtry
5997<
5998 *except-autocmd-Cmd*
5999For some commands, the normal action can be replaced by a sequence of
6000autocommands. Exceptions from that sequence will be catchable by the caller
6001of the command.
6002 Example: For the ":write" command, the caller cannot know whether the file
6003had actually been written when the exception occurred. You need to tell it in
6004some way. >
6005
6006 :if !exists("cnt")
6007 : let cnt = 0
6008 :
6009 : autocmd BufWriteCmd * if &modified
6010 : autocmd BufWriteCmd * let cnt = cnt + 1
6011 : autocmd BufWriteCmd * if cnt % 3 == 2
6012 : autocmd BufWriteCmd * throw "BufWriteCmdError"
6013 : autocmd BufWriteCmd * endif
6014 : autocmd BufWriteCmd * write | set nomodified
6015 : autocmd BufWriteCmd * if cnt % 3 == 0
6016 : autocmd BufWriteCmd * throw "BufWriteCmdError"
6017 : autocmd BufWriteCmd * endif
6018 : autocmd BufWriteCmd * echo "File successfully written!"
6019 : autocmd BufWriteCmd * endif
6020 :endif
6021 :
6022 :try
6023 : write
6024 :catch /^BufWriteCmdError$/
6025 : if &modified
6026 : echo "Error on writing (file contents not changed)"
6027 : else
6028 : echo "Error after writing"
6029 : endif
6030 :catch /^Vim(write):/
6031 : echo "Error on writing"
6032 :endtry
6033
6034When this script is sourced several times after making changes, it displays
6035first >
6036 File successfully written!
6037then >
6038 Error on writing (file contents not changed)
6039then >
6040 Error after writing
6041etc.
6042
6043 *except-autocmd-ill*
6044You cannot spread a try conditional over autocommands for different events.
6045The following code is ill-formed: >
6046
6047 :autocmd BufWritePre * try
6048 :
6049 :autocmd BufWritePost * catch
6050 :autocmd BufWritePost * echo v:exception
6051 :autocmd BufWritePost * endtry
6052 :
6053 :write
6054
6055
6056EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
6057
6058Some programming languages allow to use hierarchies of exception classes or to
6059pass additional information with the object of an exception class. You can do
6060similar things in Vim.
6061 In order to throw an exception from a hierarchy, just throw the complete
6062class name with the components separated by a colon, for instance throw the
6063string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
6064 When you want to pass additional information with your exception class, add
6065it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
6066for an error when writing "myfile".
6067 With the appropriate patterns in the ":catch" command, you can catch for
6068base classes or derived classes of your hierarchy. Additional information in
6069parentheses can be cut out from |v:exception| with the ":substitute" command.
6070 Example: >
6071
6072 :function! CheckRange(a, func)
6073 : if a:a < 0
6074 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
6075 : endif
6076 :endfunction
6077 :
6078 :function! Add(a, b)
6079 : call CheckRange(a:a, "Add")
6080 : call CheckRange(a:b, "Add")
6081 : let c = a:a + a:b
6082 : if c < 0
6083 : throw "EXCEPT:MATHERR:OVERFLOW"
6084 : endif
6085 : return c
6086 :endfunction
6087 :
6088 :function! Div(a, b)
6089 : call CheckRange(a:a, "Div")
6090 : call CheckRange(a:b, "Div")
6091 : if (a:b == 0)
6092 : throw "EXCEPT:MATHERR:ZERODIV"
6093 : endif
6094 : return a:a / a:b
6095 :endfunction
6096 :
6097 :function! Write(file)
6098 : try
6099 : execute "write" a:file
6100 : catch /^Vim(write):/
6101 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
6102 : endtry
6103 :endfunction
6104 :
6105 :try
6106 :
6107 : " something with arithmetics and I/O
6108 :
6109 :catch /^EXCEPT:MATHERR:RANGE/
6110 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
6111 : echo "Range error in" function
6112 :
6113 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
6114 : echo "Math error"
6115 :
6116 :catch /^EXCEPT:IO/
6117 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
6118 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
6119 : if file !~ '^/'
6120 : let file = dir . "/" . file
6121 : endif
6122 : echo 'I/O error for "' . file . '"'
6123 :
6124 :catch /^EXCEPT/
6125 : echo "Unspecified error"
6126 :
6127 :endtry
6128
6129The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
6130a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
6131exceptions with the "Vim" prefix; they are reserved for Vim.
6132 Vim error exceptions are parameterized with the name of the command that
6133failed, if known. See |catch-errors|.
6134
6135
6136PECULIARITIES
6137 *except-compat*
6138The exception handling concept requires that the command sequence causing the
6139exception is aborted immediately and control is transferred to finally clauses
6140and/or a catch clause.
6141
6142In the Vim script language there are cases where scripts and functions
6143continue after an error: in functions without the "abort" flag or in a command
6144after ":silent!", control flow goes to the following line, and outside
6145functions, control flow goes to the line following the outermost ":endwhile"
6146or ":endif". On the other hand, errors should be catchable as exceptions
6147(thus, requiring the immediate abortion).
6148
6149This problem has been solved by converting errors to exceptions and using
6150immediate abortion (if not suppressed by ":silent!") only when a try
6151conditional is active. This is no restriction since an (error) exception can
6152be caught only from an active try conditional. If you want an immediate
6153termination without catching the error, just use a try conditional without
6154catch clause. (You can cause cleanup code being executed before termination
6155by specifying a finally clause.)
6156
6157When no try conditional is active, the usual abortion and continuation
6158behavior is used instead of immediate abortion. This ensures compatibility of
6159scripts written for Vim 6.1 and earlier.
6160
6161However, when sourcing an existing script that does not use exception handling
6162commands (or when calling one of its functions) from inside an active try
6163conditional of a new script, you might change the control flow of the existing
6164script on error. You get the immediate abortion on error and can catch the
6165error in the new script. If however the sourced script suppresses error
6166messages by using the ":silent!" command (checking for errors by testing
6167|v:errmsg| if appropriate), its execution path is not changed. The error is
6168not converted to an exception. (See |:silent|.) So the only remaining cause
6169where this happens is for scripts that don't care about errors and produce
6170error messages. You probably won't want to use such code from your new
6171scripts.
6172
6173 *except-syntax-err*
6174Syntax errors in the exception handling commands are never caught by any of
6175the ":catch" commands of the try conditional they belong to. Its finally
6176clauses, however, is executed.
6177 Example: >
6178
6179 :try
6180 : try
6181 : throw 4711
6182 : catch /\(/
6183 : echo "in catch with syntax error"
6184 : catch
6185 : echo "inner catch-all"
6186 : finally
6187 : echo "inner finally"
6188 : endtry
6189 :catch
6190 : echo 'outer catch-all caught "' . v:exception . '"'
6191 : finally
6192 : echo "outer finally"
6193 :endtry
6194
6195This displays: >
6196 inner finally
6197 outer catch-all caught "Vim(catch):E54: Unmatched \("
6198 outer finally
6199The original exception is discarded and an error exception is raised, instead.
6200
6201 *except-single-line*
6202The ":try", ":catch", ":finally", and ":endtry" commands can be put on
6203a single line, but then syntax errors may make it difficult to recognize the
6204"catch" line, thus you better avoid this.
6205 Example: >
6206 :try | unlet! foo # | catch | endtry
6207raises an error exception for the trailing characters after the ":unlet!"
6208argument, but does not see the ":catch" and ":endtry" commands, so that the
6209error exception is discarded and the "E488: Trailing characters" message gets
6210displayed.
6211
6212 *except-several-errors*
6213When several errors appear in a single command, the first error message is
6214usually the most specific one and therefor converted to the error exception.
6215 Example: >
6216 echo novar
6217causes >
6218 E121: Undefined variable: novar
6219 E15: Invalid expression: novar
6220The value of the error exception inside try conditionals is: >
6221 Vim(echo):E121: Undefined variable: novar
6222< *except-syntax-error*
6223But when a syntax error is detected after a normal error in the same command,
6224the syntax error is used for the exception being thrown.
6225 Example: >
6226 unlet novar #
6227causes >
6228 E108: No such variable: "novar"
6229 E488: Trailing characters
6230The value of the error exception inside try conditionals is: >
6231 Vim(unlet):E488: Trailing characters
6232This is done because the syntax error might change the execution path in a way
6233not intended by the user. Example: >
6234 try
6235 try | unlet novar # | catch | echo v:exception | endtry
6236 catch /.*/
6237 echo "outer catch:" v:exception
6238 endtry
6239This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
6240a "E600: Missing :endtry" error message is given, see |except-single-line|.
6241
6242==============================================================================
62439. Examples *eval-examples*
6244
6245Printing in Hex ~
6246>
6247 :" The function Nr2Hex() returns the Hex string of a number.
6248 :func Nr2Hex(nr)
6249 : let n = a:nr
6250 : let r = ""
6251 : while n
6252 : let r = '0123456789ABCDEF'[n % 16] . r
6253 : let n = n / 16
6254 : endwhile
6255 : return r
6256 :endfunc
6257
6258 :" The function String2Hex() converts each character in a string to a two
6259 :" character Hex string.
6260 :func String2Hex(str)
6261 : let out = ''
6262 : let ix = 0
6263 : while ix < strlen(a:str)
6264 : let out = out . Nr2Hex(char2nr(a:str[ix]))
6265 : let ix = ix + 1
6266 : endwhile
6267 : return out
6268 :endfunc
6269
6270Example of its use: >
6271 :echo Nr2Hex(32)
6272result: "20" >
6273 :echo String2Hex("32")
6274result: "3332"
6275
6276
6277Sorting lines (by Robert Webb) ~
6278
6279Here is a Vim script to sort lines. Highlight the lines in Vim and type
6280":Sort". This doesn't call any external programs so it'll work on any
6281platform. The function Sort() actually takes the name of a comparison
6282function as its argument, like qsort() does in C. So you could supply it
6283with different comparison functions in order to sort according to date etc.
6284>
6285 :" Function for use with Sort(), to compare two strings.
6286 :func! Strcmp(str1, str2)
6287 : if (a:str1 < a:str2)
6288 : return -1
6289 : elseif (a:str1 > a:str2)
6290 : return 1
6291 : else
6292 : return 0
6293 : endif
6294 :endfunction
6295
6296 :" Sort lines. SortR() is called recursively.
6297 :func! SortR(start, end, cmp)
6298 : if (a:start >= a:end)
6299 : return
6300 : endif
6301 : let partition = a:start - 1
6302 : let middle = partition
6303 : let partStr = getline((a:start + a:end) / 2)
6304 : let i = a:start
6305 : while (i <= a:end)
6306 : let str = getline(i)
6307 : exec "let result = " . a:cmp . "(str, partStr)"
6308 : if (result <= 0)
6309 : " Need to put it before the partition. Swap lines i and partition.
6310 : let partition = partition + 1
6311 : if (result == 0)
6312 : let middle = partition
6313 : endif
6314 : if (i != partition)
6315 : let str2 = getline(partition)
6316 : call setline(i, str2)
6317 : call setline(partition, str)
6318 : endif
6319 : endif
6320 : let i = i + 1
6321 : endwhile
6322
6323 : " Now we have a pointer to the "middle" element, as far as partitioning
6324 : " goes, which could be anywhere before the partition. Make sure it is at
6325 : " the end of the partition.
6326 : if (middle != partition)
6327 : let str = getline(middle)
6328 : let str2 = getline(partition)
6329 : call setline(middle, str2)
6330 : call setline(partition, str)
6331 : endif
6332 : call SortR(a:start, partition - 1, a:cmp)
6333 : call SortR(partition + 1, a:end, a:cmp)
6334 :endfunc
6335
6336 :" To Sort a range of lines, pass the range to Sort() along with the name of a
6337 :" function that will compare two lines.
6338 :func! Sort(cmp) range
6339 : call SortR(a:firstline, a:lastline, a:cmp)
6340 :endfunc
6341
6342 :" :Sort takes a range of lines and sorts them.
6343 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
6344<
6345 *sscanf*
6346There is no sscanf() function in Vim. If you need to extract parts from a
6347line, you can use matchstr() and substitute() to do it. This example shows
6348how to get the file name, line number and column number out of a line like
6349"foobar.txt, 123, 45". >
6350 :" Set up the match bit
6351 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
6352 :"get the part matching the whole expression
6353 :let l = matchstr(line, mx)
6354 :"get each item out of the match
6355 :let file = substitute(l, mx, '\1', '')
6356 :let lnum = substitute(l, mx, '\2', '')
6357 :let col = substitute(l, mx, '\3', '')
6358
6359The input is in the variable "line", the results in the variables "file",
6360"lnum" and "col". (idea from Michael Geddes)
6361
6362==============================================================================
636310. No +eval feature *no-eval-feature*
6364
6365When the |+eval| feature was disabled at compile time, none of the expression
6366evaluation commands are available. To prevent this from causing Vim scripts
6367to generate all kinds of errors, the ":if" and ":endif" commands are still
6368recognized, though the argument of the ":if" and everything between the ":if"
6369and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
6370only if the commands are at the start of the line. The ":else" command is not
6371recognized.
6372
6373Example of how to avoid executing commands when the |+eval| feature is
6374missing: >
6375
6376 :if 1
6377 : echo "Expression evaluation is compiled in"
6378 :else
6379 : echo "You will _never_ see this message"
6380 :endif
6381
6382==============================================================================
638311. The sandbox *eval-sandbox* *sandbox* *E48*
6384
6385The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
6386options are evaluated in a sandbox. This means that you are protected from
6387these expressions having nasty side effects. This gives some safety for when
6388these options are set from a modeline. It is also used when the command from
6389a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006390The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391
6392These items are not allowed in the sandbox:
6393 - changing the buffer text
6394 - defining or changing mapping, autocommands, functions, user commands
6395 - setting certain options (see |option-summary|)
6396 - executing a shell command
6397 - reading or writing a file
6398 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006399This is not guaranteed 100% secure, but it should block most attacks.
6400
6401 *:san* *:sandbox*
6402:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
6403 option that may have been set from a modeline, e.g.
6404 'foldexpr'.
6405
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406
6407 vim:tw=78:ts=8:ft=help:norl: