blob: 028aa089fc51cb31cd865f4b2807a72241095cbc [file] [log] [blame]
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Feb 21
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Expression evaluation *expression* *expr* *E15* *eval*
8
9Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|.
10
11Note: Expression evaluation can be disabled at compile time. If this has been
Bram Moolenaard8b02732005-01-14 21:48:43 +000012done, the features in this document are not available. See |+eval| and
13|no-eval-feature|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000014
Bram Moolenaar13065c42005-01-08 16:08:21 +0000151. Variables |variables|
16 1.1 Variable types
Bram Moolenaar9588a0f2005-01-08 21:45:39 +000017 1.2 Function references |Funcref|
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 Moolenaard7ee7ce2005-01-03 21:02:03 +0000197
Bram Moolenaar13065c42005-01-08 16:08:21 +0000198List identity ~
Bram Moolenaard8b02732005-01-14 21:48:43 +0000199 *list-identity*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000200When variable "aa" is a list and you assign it to another variable "bb", both
201variables refer to the same list. Thus changing the list "aa" will also
202change "bb": >
203 :let aa = [1, 2, 3]
204 :let bb = aa
205 :call add(aa, 4)
206 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000207< [1, 2, 3, 4]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000208
209Making a copy of a list is done with the |copy()| function. Using [:] also
210works, as explained above. This creates a shallow copy of the list: Changing
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000211a list item in the list will also change the item in the copied list: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000212 :let aa = [[1, 'a'], 2, 3]
213 :let bb = copy(aa)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000214 :call add(aa, 4)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000215 :let aa[0][1] = 'aaa'
216 :echo aa
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000217< [[1, aaa], 2, 3, 4] >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000218 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000219< [[1, aaa], 2, 3]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000220
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000221To make a completely independent list use |deepcopy()|. This also makes a
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000222copy of the values in the list, recursively. Up to a hundred levels deep.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000223
224The operator "is" can be used to check if two variables refer to the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000225List. "isnot" does the opposite. In contrast "==" compares if two lists have
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000226the same value. >
227 :let alist = [1, 2, 3]
228 :let blist = [1, 2, 3]
229 :echo alist is blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000230< 0 >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000231 :echo alist == blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000232< 1
Bram Moolenaar13065c42005-01-08 16:08:21 +0000233
234
235List unpack ~
236
237To unpack the items in a list to individual variables, put the variables in
238square brackets, like list items: >
239 :let [var1, var2] = mylist
240
241When the number of variables does not match the number of items in the list
242this produces an error. To handle any extra items from the list append ";"
243and a variable name: >
244 :let [var1, var2; rest] = mylist
245
246This works like: >
247 :let var1 = mylist[0]
248 :let var2 = mylist[1]
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000249 :let rest = mylist[2:]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000250
251Except that there is no error if there are only two items. "rest" will be an
252empty list then.
253
254
255List modification ~
256 *list-modification*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000257To change a specific item of a list use |:let| this way: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000258 :let list[4] = "four"
259 :let listlist[0][3] = item
260
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000261To change part of a list you can specify the first and last item to be
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000262modified. The value must at least have the number of items in the range: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000263 :let list[3:5] = [3, 4, 5]
264
Bram Moolenaar13065c42005-01-08 16:08:21 +0000265Adding and removing items from a list is done with functions. Here are a few
266examples: >
267 :call insert(list, 'a') " prepend item 'a'
268 :call insert(list, 'a', 3) " insert item 'a' before list[3]
269 :call add(list, "new") " append String item
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000270 :call add(list, [1, 2]) " append a List as one new item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000271 :call extend(list, [1, 2]) " extend the list with two more items
272 :let i = remove(list, 3) " remove item 3
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000273 :unlet list[3] " idem
Bram Moolenaar13065c42005-01-08 16:08:21 +0000274 :let l = remove(list, 3, -1) " remove items 3 to last item
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000275 :unlet list[3 : ] " idem
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000276 :call filter(list, 'v:val !~ "x"') " remove items with an 'x'
Bram Moolenaar13065c42005-01-08 16:08:21 +0000277
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000278Changing the order of items in a list: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000279 :call sort(list) " sort a list alphabetically
280 :call reverse(list) " reverse the order of items
281
Bram Moolenaar13065c42005-01-08 16:08:21 +0000282
283For loop ~
284
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000285The |:for| loop executes commands for each item in a list. A variable is set
286to each item in the list in sequence. Example: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000287 :for item in mylist
288 : call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000289 :endfor
290
291This works like: >
292 :let index = 0
293 :while index < len(mylist)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000294 : let item = mylist[index]
295 : :call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000296 : let index = index + 1
297 :endwhile
298
299Note that all items in the list should be of the same type, otherwise this
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000300results in error |E706|. To avoid this |:unlet| the variable at the end of
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000301the loop.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000302
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000303If all you want to do is modify each item in the list then the |map()|
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000304function will be a simpler method than a for loop.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000305
Bram Moolenaar13065c42005-01-08 16:08:21 +0000306Just like the |:let| command, |:for| also accepts a list of variables. This
307requires the argument to be a list of lists. >
308 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
309 : call Doit(lnum, col)
310 :endfor
311
312This works like a |:let| command is done for each list item. Again, the types
313must remain the same to avoid an error.
314
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000315It is also possible to put remaining items in a List variable: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000316 :for [i, j; rest] in listlist
317 : call Doit(i, j)
318 : if !empty(rest)
319 : echo "remainder: " . string(rest)
320 : endif
321 :endfor
322
323
324List functions ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000325 *E714*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000326Functions that are useful with a List: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000327 :let r = call(funcname, list) " call a function with an argument list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000328 :if empty(list) " check if list is empty
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000329 :let l = len(list) " number of items in list
330 :let big = max(list) " maximum value in list
331 :let small = min(list) " minimum value in list
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000332 :let xs = count(list, 'x') " count nr of times 'x' appears in list
333 :let i = index(list, 'x') " index of first 'x' in list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000334 :let lines = getline(1, 10) " get ten text lines from buffer
335 :call append('$', lines) " append text lines in buffer
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000336 :let list = split("a b c") " create list from items in a string
337 :let string = join(list, ', ') " create string from list items
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000338 :let s = string(list) " String representation of list
339 :call map(list, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000340
341
Bram Moolenaard8b02732005-01-14 21:48:43 +00003421.4 Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000343 *Dictionaries* *Dictionary*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000344A Dictionary is an associative array: Each entry has a key and a value. The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000345entry can be located with the key. The entries are stored without a specific
346ordering.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000347
348
349Dictionary creation ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000350 *E720* *E721* *E722* *E723*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000351A Dictionary is created with a comma separated list of entries in curly
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000352braces. Each entry has a key and a value, separated by a colon. Each key can
353only appear once. Examples: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000354 :let mydict = {1: 'one', 2: 'two', 3: 'three'}
355 :let emptydict = {}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000356< *E713* *E716* *E717*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000357A key is always a String. You can use a Number, it will be converted to a
358String automatically. Thus the String '4' and the number 4 will find the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000359entry. Note that the String '04' and the Number 04 are different, since the
360Number will be converted to the String '4'.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000361
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000362A value can be any expression. Using a Dictionary for a value creates a
Bram Moolenaard8b02732005-01-14 21:48:43 +0000363nested Dictionary: >
364 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
365
366An extra comma after the last entry is ignored.
367
368
369Accessing entries ~
370
371The normal way to access an entry is by putting the key in square brackets: >
372 :let val = mydict["one"]
373 :let mydict["four"] = 4
374
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000375You can add new entries to an existing Dictionary this way, unlike Lists.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000376
377For keys that consist entirely of letters, digits and underscore the following
378form can be used |expr-entry|: >
379 :let val = mydict.one
380 :let mydict.four = 4
381
382Since an entry can be any type, also a List and a Dictionary, the indexing and
383key lookup can be repeated: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000384 :echo dict.key[idx].key
Bram Moolenaard8b02732005-01-14 21:48:43 +0000385
386
387Dictionary to List conversion ~
388
389You may want to loop over the entries in a dictionary. For this you need to
390turn the Dictionary into a List and pass it to |:for|.
391
392Most often you want to loop over the keys, using the |keys()| function: >
393 :for key in keys(mydict)
394 : echo key . ': ' . mydict[key]
395 :endfor
396
397The List of keys is unsorted. You may want to sort them first: >
398 :for key in sort(keys(mydict))
399
400To loop over the values use the |values()| function: >
401 :for v in values(mydict)
402 : echo "value: " . v
403 :endfor
404
405If you want both the key and the value use the |items()| function. It returns
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000406a List in which each item is a List with two items, the key and the value: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000407 :for entry in items(mydict)
408 : echo entry[0] . ': ' . entry[1]
409 :endfor
410
411
412Dictionary identity ~
Bram Moolenaar7c626922005-02-07 22:01:03 +0000413 *dict-identity*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000414Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
415Dictionary. Otherwise, assignment results in referring to the same
416Dictionary: >
417 :let onedict = {'a': 1, 'b': 2}
418 :let adict = onedict
419 :let adict['a'] = 11
420 :echo onedict['a']
421 11
422
423For more info see |list-identity|.
424
425
426Dictionary modification ~
427 *dict-modification*
428To change an already existing entry of a Dictionary, or to add a new entry,
429use |:let| this way: >
430 :let dict[4] = "four"
431 :let dict['one'] = item
432
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000433Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
434Three ways to remove the entry with key "aaa" from dict: >
435 :let i = remove(dict, 'aaa')
436 :unlet dict.aaa
437 :unlet dict['aaa']
Bram Moolenaard8b02732005-01-14 21:48:43 +0000438
439Merging a Dictionary with another is done with |extend()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000440 :call extend(adict, bdict)
441This extends adict with all entries from bdict. Duplicate keys cause entries
442in adict to be overwritten. An optional third argument can change this.
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000443Note that the order of entries in a Dictionary is irrelevant, thus don't
444expect ":echo adict" to show the items from bdict after the older entries in
445adict.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000446
447Weeding out entries from a Dictionary can be done with |filter()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000448 :call filter(dict 'v:val =~ "x"')
449This removes all entries from "dict" with a value not matching 'x'.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000450
451
452Dictionary function ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000453 *Dictionary-function* *self* *E725*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000454When a function is defined with the "dict" attribute it can be used in a
455special way with a dictionary. Example: >
456 :function Mylen() dict
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000457 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000458 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000459 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
460 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000461
462This is like a method in object oriented programming. The entry in the
463Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
464the function was invoked from.
465
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000466It is also possible to add a function without the "dict" attribute as a
467Funcref to a Dictionary, but the "self" variable is not available then.
468
469 *numbered-function*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000470To avoid the extra name for the function it can be defined and directly
471assigned to a Dictionary in this way: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000472 :let mydict = {'data': [0, 1, 2, 3]}
473 :function mydict.len() dict
474 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000475 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000476 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000477
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000478The function will then get a number and the value of dict.len is a |Funcref|
479that references this function. The function can only be used through a
480|Funcref|. It will automatically be deleted when there is no |Funcref|
481remaining that refers to it.
482
483It is not necessary to use the "dict" attribute for a numbered function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000484
485
486Functions for Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000487 *E715*
488Functions that can be used with a Dictionary: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000489 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
490 :if empty(dict) " TRUE if dict is empty
491 :let l = len(dict) " number of items in dict
492 :let big = max(dict) " maximum value in dict
493 :let small = min(dict) " minimum value in dict
494 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
495 :let s = string(dict) " String representation of dict
496 :call map(dict, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaard8b02732005-01-14 21:48:43 +0000497
498
4991.5 More about variables ~
Bram Moolenaar13065c42005-01-08 16:08:21 +0000500 *more-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501If you need to know the type of a variable or expression, use the |type()|
502function.
503
504When the '!' flag is included in the 'viminfo' option, global variables that
505start with an uppercase letter, and don't contain a lowercase letter, are
506stored in the viminfo file |viminfo-file|.
507
508When the 'sessionoptions' option contains "global", global variables that
509start with an uppercase letter and contain at least one lowercase letter are
510stored in the session file |session-file|.
511
512variable name can be stored where ~
513my_var_6 not
514My_Var_6 session file
515MY_VAR_6 viminfo file
516
517
518It's possible to form a variable name with curly braces, see
519|curly-braces-names|.
520
521==============================================================================
5222. Expression syntax *expression-syntax*
523
524Expression syntax summary, from least to most significant:
525
526|expr1| expr2 ? expr1 : expr1 if-then-else
527
528|expr2| expr3 || expr3 .. logical OR
529
530|expr3| expr4 && expr4 .. logical AND
531
532|expr4| expr5 == expr5 equal
533 expr5 != expr5 not equal
534 expr5 > expr5 greater than
535 expr5 >= expr5 greater than or equal
536 expr5 < expr5 smaller than
537 expr5 <= expr5 smaller than or equal
538 expr5 =~ expr5 regexp matches
539 expr5 !~ expr5 regexp doesn't match
540
541 expr5 ==? expr5 equal, ignoring case
542 expr5 ==# expr5 equal, match case
543 etc. As above, append ? for ignoring case, # for
544 matching case
545
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000546 expr5 is expr5 same List instance
547 expr5 isnot expr5 different List instance
548
549|expr5| expr6 + expr6 .. number addition or list concatenation
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550 expr6 - expr6 .. number subtraction
551 expr6 . expr6 .. string concatenation
552
553|expr6| expr7 * expr7 .. number multiplication
554 expr7 / expr7 .. number division
555 expr7 % expr7 .. number modulo
556
557|expr7| ! expr7 logical NOT
558 - expr7 unary minus
559 + expr7 unary plus
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000562|expr8| expr8[expr1] byte of a String or item of a List
563 expr8[expr1 : expr1] substring of a String or sublist of a List
564 expr8.name entry in a Dictionary
565 expr8(expr1, ...) function call with Funcref variable
566
567|expr9| number number constant
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000568 "string" string constant, backslash is special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000569 'string' string constant, ' is doubled
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000570 [expr1, ...] List
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000571 {expr1: expr1, ...} Dictionary
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 &option option value
573 (expr1) nested expression
574 variable internal variable
575 va{ria}ble internal variable with curly braces
576 $VAR environment variable
577 @r contents of register 'r'
578 function(expr1, ...) function call
579 func{ti}on(expr1, ...) function call with curly braces
580
581
582".." indicates that the operations in this level can be concatenated.
583Example: >
584 &nu || &list && &shell == "csh"
585
586All expressions within one level are parsed from left to right.
587
588
589expr1 *expr1* *E109*
590-----
591
592expr2 ? expr1 : expr1
593
594The expression before the '?' is evaluated to a number. If it evaluates to
595non-zero, the result is the value of the expression between the '?' and ':',
596otherwise the result is the value of the expression after the ':'.
597Example: >
598 :echo lnum == 1 ? "top" : lnum
599
600Since the first expression is an "expr2", it cannot contain another ?:. The
601other two expressions can, thus allow for recursive use of ?:.
602Example: >
603 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
604
605To keep this readable, using |line-continuation| is suggested: >
606 :echo lnum == 1
607 :\ ? "top"
608 :\ : lnum == 1000
609 :\ ? "last"
610 :\ : lnum
611
612
613expr2 and expr3 *expr2* *expr3*
614---------------
615
616 *expr-barbar* *expr-&&*
617The "||" and "&&" operators take one argument on each side. The arguments
618are (converted to) Numbers. The result is:
619
620 input output ~
621n1 n2 n1 || n2 n1 && n2 ~
622zero zero zero zero
623zero non-zero non-zero zero
624non-zero zero non-zero zero
625non-zero non-zero non-zero non-zero
626
627The operators can be concatenated, for example: >
628
629 &nu || &list && &shell == "csh"
630
631Note that "&&" takes precedence over "||", so this has the meaning of: >
632
633 &nu || (&list && &shell == "csh")
634
635Once the result is known, the expression "short-circuits", that is, further
636arguments are not evaluated. This is like what happens in C. For example: >
637
638 let a = 1
639 echo a || b
640
641This is valid even if there is no variable called "b" because "a" is non-zero,
642so the result must be non-zero. Similarly below: >
643
644 echo exists("b") && b == "yes"
645
646This is valid whether "b" has been defined or not. The second clause will
647only be evaluated if "b" has been defined.
648
649
650expr4 *expr4*
651-----
652
653expr5 {cmp} expr5
654
655Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
656if it evaluates to true.
657
658 *expr-==* *expr-!=* *expr->* *expr->=*
659 *expr-<* *expr-<=* *expr-=~* *expr-!~*
660 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
661 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
662 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
663 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000664 *expr-is*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 use 'ignorecase' match case ignore case ~
666equal == ==# ==?
667not equal != !=# !=?
668greater than > ># >?
669greater than or equal >= >=# >=?
670smaller than < <# <?
671smaller than or equal <= <=# <=?
672regexp matches =~ =~# =~?
673regexp doesn't match !~ !~# !~?
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000674same instance is
675different instance isnot
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676
677Examples:
678"abc" ==# "Abc" evaluates to 0
679"abc" ==? "Abc" evaluates to 1
680"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
681
Bram Moolenaar13065c42005-01-08 16:08:21 +0000682 *E691* *E692*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000683A List can only be compared with a List and only "equal", "not equal" and "is"
684can be used. This compares the values of the list, recursively. Ignoring
685case means case is ignored when comparing item values.
686
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000687 *E735* *E736*
688A Dictionary can only be compared with a Dictionary and only "equal", "not
689equal" and "is" can be used. This compares the key/values of the Dictionary,
690recursively. Ignoring case means case is ignored when comparing item values.
691
Bram Moolenaar13065c42005-01-08 16:08:21 +0000692 *E693* *E694*
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000693A Funcref can only be compared with a Funcref and only "equal" and "not equal"
694can be used. Case is never ignored.
695
696When using "is" or "isnot" with a List this checks if the expressions are
697referring to the same List instance. A copy of a List is different from the
698original List. When using "is" without a List it is equivalent to using
699"equal", using "isnot" equivalent to using "not equal". Except that a
700different type means the values are different. "4 == '4'" is true, "4 is '4'"
701is false.
702
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703When comparing a String with a Number, the String is converted to a Number,
704and the comparison is done on Numbers. This means that "0 == 'x'" is TRUE,
705because 'x' converted to a Number is zero.
706
707When comparing two Strings, this is done with strcmp() or stricmp(). This
708results in the mathematical difference (comparing byte values), not
709necessarily the alphabetical difference in the local language.
710
711When using the operators with a trailing '#", or the short version and
712'ignorecase' is off, the comparing is done with strcmp().
713
714When using the operators with a trailing '?', or the short version and
715'ignorecase' is set, the comparing is done with stricmp().
716
717The "=~" and "!~" operators match the lefthand argument with the righthand
718argument, which is used as a pattern. See |pattern| for what a pattern is.
719This matching is always done like 'magic' was set and 'cpoptions' is empty, no
720matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
721portable. To avoid backslashes in the regexp pattern to be doubled, use a
722single-quote string, see |literal-string|.
723Since a string is considered to be a single line, a multi-line pattern
724(containing \n, backslash-n) will not match. However, a literal NL character
725can be matched like an ordinary character. Examples:
726 "foo\nbar" =~ "\n" evaluates to 1
727 "foo\nbar" =~ "\\n" evaluates to 0
728
729
730expr5 and expr6 *expr5* *expr6*
731---------------
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000732expr6 + expr6 .. Number addition or List concatenation *expr-+*
733expr6 - expr6 .. Number subtraction *expr--*
734expr6 . expr6 .. String concatenation *expr-.*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000736For Lists only "+" is possible and then both expr6 must be a list. The result
737is a new list with the two lists Concatenated.
738
739expr7 * expr7 .. number multiplication *expr-star*
740expr7 / expr7 .. number division *expr-/*
741expr7 % expr7 .. number modulo *expr-%*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742
743For all, except ".", Strings are converted to Numbers.
744
745Note the difference between "+" and ".":
746 "123" + "456" = 579
747 "123" . "456" = "123456"
748
749When the righthand side of '/' is zero, the result is 0x7fffffff.
750When the righthand side of '%' is zero, the result is 0.
751
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000752None of these work for Funcrefs.
753
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
755expr7 *expr7*
756-----
757! expr7 logical NOT *expr-!*
758- expr7 unary minus *expr-unary--*
759+ expr7 unary plus *expr-unary-+*
760
761For '!' non-zero becomes zero, zero becomes one.
762For '-' the sign of the number is changed.
763For '+' the number is unchanged.
764
765A String will be converted to a Number first.
766
767These three can be repeated and mixed. Examples:
768 !-1 == 0
769 !!8 == 1
770 --9 == 9
771
772
773expr8 *expr8*
774-----
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000775expr8[expr1] item of String or List *expr-[]* *E111*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000777If expr8 is a Number or String this results in a String that contains the
778expr1'th single byte from expr8. expr8 is used as a String, expr1 as a
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000779Number. Note that this doesn't recognize multi-byte encodings.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000781Index zero gives the first character. This is like it works in C. Careful:
782text column numbers start with one! Example, to get the character under the
783cursor: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 :let c = getline(line("."))[col(".") - 1]
785
786If the length of the String is less than the index, the result is an empty
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000787String. A negative index always results in an empty string (reason: backwards
788compatibility). Use [-1:] to get the last byte.
789
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000790If expr8 is a List then it results the item at index expr1. See |list-index|
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000791for possible index values. If the index is out of range this results in an
792error. Example: >
793 :let item = mylist[-1] " get last item
794
795Generally, if a List index is equal to or higher than the length of the List,
796or more negative than the length of the List, this results in an error.
797
Bram Moolenaard8b02732005-01-14 21:48:43 +0000798
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000799expr8[expr1a : expr1b] substring or sublist *expr-[:]*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000800
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000801If expr8 is a Number or String this results in the substring with the bytes
802from expr1a to and including expr1b. expr8 is used as a String, expr1a and
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000803expr1b are used as a Number. Note that this doesn't recognize multi-byte
804encodings.
805
806If expr1a is omitted zero is used. If expr1b is omitted the length of the
807string minus one is used.
808
809A negative number can be used to measure from the end of the string. -1 is
810the last character, -2 the last but one, etc.
811
812If an index goes out of range for the string characters are omitted. If
813expr1b is smaller than expr1a the result is an empty string.
814
815Examples: >
816 :let c = name[-1:] " last byte of a string
817 :let c = name[-2:-2] " last but one byte of a string
818 :let s = line(".")[4:] " from the fifth byte to the end
819 :let s = s[:-3] " remove last two bytes
820
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000821If expr8 is a List this results in a new List with the items indicated by the
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000822indexes expr1a and expr1b. This works like with a String, as explained just
823above, except that indexes out of range cause an error. Examples: >
824 :let l = mylist[:3] " first four items
825 :let l = mylist[4:4] " List with one item
826 :let l = mylist[:] " shallow copy of a List
827
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000828Using expr8[expr1] or expr8[expr1a : expr1b] on a Funcref results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829
Bram Moolenaard8b02732005-01-14 21:48:43 +0000830
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000831expr8.name entry in a Dictionary *expr-entry*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000832
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000833If expr8 is a Dictionary and it is followed by a dot, then the following name
834will be used as a key in the Dictionary. This is just like: expr8[name].
Bram Moolenaard8b02732005-01-14 21:48:43 +0000835
836The name must consist of alphanumeric characters, just like a variable name,
837but it may start with a number. Curly braces cannot be used.
838
839There must not be white space before or after the dot.
840
841Examples: >
842 :let dict = {"one": 1, 2: "two"}
843 :echo dict.one
844 :echo dict .2
845
846Note that the dot is also used for String concatenation. To avoid confusion
847always put spaces around the dot for String concatenation.
848
849
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000850expr8(expr1, ...) Funcref function call
851
852When expr8 is a |Funcref| type variable, invoke the function it refers to.
853
854
855
856 *expr9*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857number
858------
859number number constant *expr-number*
860
861Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
862
863
864string *expr-string* *E114*
865------
866"string" string constant *expr-quote*
867
868Note that double quotes are used.
869
870A string constant accepts these special characters:
871\... three-digit octal number (e.g., "\316")
872\.. two-digit octal number (must be followed by non-digit)
873\. one-digit octal number (must be followed by non-digit)
874\x.. byte specified with two hex numbers (e.g., "\x1f")
875\x. byte specified with one hex number (must be followed by non-hex char)
876\X.. same as \x..
877\X. same as \x.
878\u.... character specified with up to 4 hex numbers, stored according to the
879 current value of 'encoding' (e.g., "\u02a4")
880\U.... same as \u....
881\b backspace <BS>
882\e escape <Esc>
883\f formfeed <FF>
884\n newline <NL>
885\r return <CR>
886\t tab <Tab>
887\\ backslash
888\" double quote
889\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W.
890
891Note that "\000" and "\x00" force the end of the string.
892
893
894literal-string *literal-string* *E115*
895---------------
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000896'string' string constant *expr-'*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898Note that single quotes are used.
899
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000900This string is taken as it is. No backslashes are removed or have a special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000901meaning. The only exception is that two quotes stand for one quote.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000902
903Single quoted strings are useful for patterns, so that backslashes do not need
904to be doubled. These two commands are equivalent: >
905 if a =~ "\\s*"
906 if a =~ '\s*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
908
909option *expr-option* *E112* *E113*
910------
911&option option value, local value if possible
912&g:option global option value
913&l:option local option value
914
915Examples: >
916 echo "tabstop is " . &tabstop
917 if &insertmode
918
919Any option name can be used here. See |options|. When using the local value
920and there is no buffer-local or window-local value, the global value is used
921anyway.
922
923
924register *expr-register*
925--------
926@r contents of register 'r'
927
928The result is the contents of the named register, as a single string.
929Newlines are inserted where required. To get the contents of the unnamed
930register use @" or @@. The '=' register can not be used here. See
931|registers| for an explanation of the available registers.
932
933
934nesting *expr-nesting* *E110*
935-------
936(expr1) nested expression
937
938
939environment variable *expr-env*
940--------------------
941$VAR environment variable
942
943The String value of any environment variable. When it is not defined, the
944result is an empty string.
945 *expr-env-expand*
946Note that there is a difference between using $VAR directly and using
947expand("$VAR"). Using it directly will only expand environment variables that
948are known inside the current Vim session. Using expand() will first try using
949the environment variables known inside the current Vim session. If that
950fails, a shell will be used to expand the variable. This can be slow, but it
951does expand all variables that the shell knows about. Example: >
952 :echo $version
953 :echo expand("$version")
954The first one probably doesn't echo anything, the second echoes the $version
955variable (if your shell supports it).
956
957
958internal variable *expr-variable*
959-----------------
960variable internal variable
961See below |internal-variables|.
962
963
964function call *expr-function* *E116* *E117* *E118* *E119* *E120*
965-------------
966function(expr1, ...) function call
967See below |functions|.
968
969
970==============================================================================
9713. Internal variable *internal-variables* *E121*
972 *E461*
973An internal variable name can be made up of letters, digits and '_'. But it
974cannot start with a digit. It's also possible to use curly braces, see
975|curly-braces-names|.
976
977An internal variable is created with the ":let" command |:let|.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000978An internal variable is explicitly destroyed with the ":unlet" command
979|:unlet|.
980Using a name that is not an internal variable or refers to a variable that has
981been destroyed results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
983There are several name spaces for variables. Which one is to be used is
984specified by what is prepended:
985
986 (nothing) In a function: local to a function; otherwise: global
987|buffer-variable| b: Local to the current buffer.
988|window-variable| w: Local to the current window.
989|global-variable| g: Global.
990|local-variable| l: Local to a function.
991|script-variable| s: Local to a |:source|'ed Vim script.
992|function-argument| a: Function argument (only inside a function).
993|vim-variable| v: Global, predefined by Vim.
994
Bram Moolenaar8f999f12005-01-25 22:12:55 +0000995The scope name by itself can be used as a Dictionary. For example, to delete
996all script-local variables: >
997 :for k in keys(s:)
998 : unlet s:[k]
999 :endfor
1000<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001 *buffer-variable* *b:var*
1002A variable name that is preceded with "b:" is local to the current buffer.
1003Thus you can have several "b:foo" variables, one for each buffer.
1004This kind of variable is deleted when the buffer is wiped out or deleted with
1005|:bdelete|.
1006
1007One local buffer variable is predefined:
1008 *b:changedtick-variable* *changetick*
1009b:changedtick The total number of changes to the current buffer. It is
1010 incremented for each change. An undo command is also a change
1011 in this case. This can be used to perform an action only when
1012 the buffer has changed. Example: >
1013 :if my_changedtick != b:changedtick
1014 : let my_changedtick = b:changedtick
1015 : call My_Update()
1016 :endif
1017<
1018 *window-variable* *w:var*
1019A variable name that is preceded with "w:" is local to the current window. It
1020is deleted when the window is closed.
1021
1022 *global-variable* *g:var*
1023Inside functions global variables are accessed with "g:". Omitting this will
1024access a variable local to a function. But "g:" can also be used in any other
1025place if you like.
1026
1027 *local-variable* *l:var*
1028Inside functions local variables are accessed without prepending anything.
1029But you can also prepend "l:" if you like.
1030
1031 *script-variable* *s:var*
1032In a Vim script variables starting with "s:" can be used. They cannot be
1033accessed from outside of the scripts, thus are local to the script.
1034
1035They can be used in:
1036- commands executed while the script is sourced
1037- functions defined in the script
1038- autocommands defined in the script
1039- functions and autocommands defined in functions and autocommands which were
1040 defined in the script (recursively)
1041- user defined commands defined in the script
1042Thus not in:
1043- other scripts sourced from this one
1044- mappings
1045- etc.
1046
1047script variables can be used to avoid conflicts with global variable names.
1048Take this example:
1049
1050 let s:counter = 0
1051 function MyCounter()
1052 let s:counter = s:counter + 1
1053 echo s:counter
1054 endfunction
1055 command Tick call MyCounter()
1056
1057You can now invoke "Tick" from any script, and the "s:counter" variable in
1058that script will not be changed, only the "s:counter" in the script where
1059"Tick" was defined is used.
1060
1061Another example that does the same: >
1062
1063 let s:counter = 0
1064 command Tick let s:counter = s:counter + 1 | echo s:counter
1065
1066When calling a function and invoking a user-defined command, the context for
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001067script variables is set to the script where the function or command was
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068defined.
1069
1070The script variables are also available when a function is defined inside a
1071function that is defined in a script. Example: >
1072
1073 let s:counter = 0
1074 function StartCounting(incr)
1075 if a:incr
1076 function MyCounter()
1077 let s:counter = s:counter + 1
1078 endfunction
1079 else
1080 function MyCounter()
1081 let s:counter = s:counter - 1
1082 endfunction
1083 endif
1084 endfunction
1085
1086This defines the MyCounter() function either for counting up or counting down
1087when calling StartCounting(). It doesn't matter from where StartCounting() is
1088called, the s:counter variable will be accessible in MyCounter().
1089
1090When the same script is sourced again it will use the same script variables.
1091They will remain valid as long as Vim is running. This can be used to
1092maintain a counter: >
1093
1094 if !exists("s:counter")
1095 let s:counter = 1
1096 echo "script executed for the first time"
1097 else
1098 let s:counter = s:counter + 1
1099 echo "script executed " . s:counter . " times now"
1100 endif
1101
1102Note that this means that filetype plugins don't get a different set of script
1103variables for each buffer. Use local buffer variables instead |b:var|.
1104
1105
1106Predefined Vim variables: *vim-variable* *v:var*
1107
1108 *v:charconvert_from* *charconvert_from-variable*
1109v:charconvert_from
1110 The name of the character encoding of a file to be converted.
1111 Only valid while evaluating the 'charconvert' option.
1112
1113 *v:charconvert_to* *charconvert_to-variable*
1114v:charconvert_to
1115 The name of the character encoding of a file after conversion.
1116 Only valid while evaluating the 'charconvert' option.
1117
1118 *v:cmdarg* *cmdarg-variable*
1119v:cmdarg This variable is used for two purposes:
1120 1. The extra arguments given to a file read/write command.
1121 Currently these are "++enc=" and "++ff=". This variable is
1122 set before an autocommand event for a file read/write
1123 command is triggered. There is a leading space to make it
1124 possible to append this variable directly after the
1125 read/write command. Note: The "+cmd" argument isn't
1126 included here, because it will be executed anyway.
1127 2. When printing a PostScript file with ":hardcopy" this is
1128 the argument for the ":hardcopy" command. This can be used
1129 in 'printexpr'.
1130
1131 *v:cmdbang* *cmdbang-variable*
1132v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1133 was used the value is 1, otherwise it is 0. Note that this
1134 can only be used in autocommands. For user commands |<bang>|
1135 can be used.
1136
1137 *v:count* *count-variable*
1138v:count The count given for the last Normal mode command. Can be used
1139 to get the count before a mapping. Read-only. Example: >
1140 :map _x :<C-U>echo "the count is " . v:count<CR>
1141< Note: The <C-U> is required to remove the line range that you
1142 get when typing ':' after a count.
1143 "count" also works, for backwards compatibility.
1144
1145 *v:count1* *count1-variable*
1146v:count1 Just like "v:count", but defaults to one when no count is
1147 used.
1148
1149 *v:ctype* *ctype-variable*
1150v:ctype The current locale setting for characters of the runtime
1151 environment. This allows Vim scripts to be aware of the
1152 current locale encoding. Technical: it's the value of
1153 LC_CTYPE. When not using a locale the value is "C".
1154 This variable can not be set directly, use the |:language|
1155 command.
1156 See |multi-lang|.
1157
1158 *v:dying* *dying-variable*
1159v:dying Normally zero. When a deadly signal is caught it's set to
1160 one. When multiple signals are caught the number increases.
1161 Can be used in an autocommand to check if Vim didn't
1162 terminate normally. {only works on Unix}
1163 Example: >
1164 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
1165<
1166 *v:errmsg* *errmsg-variable*
1167v:errmsg Last given error message. It's allowed to set this variable.
1168 Example: >
1169 :let v:errmsg = ""
1170 :silent! next
1171 :if v:errmsg != ""
1172 : ... handle error
1173< "errmsg" also works, for backwards compatibility.
1174
1175 *v:exception* *exception-variable*
1176v:exception The value of the exception most recently caught and not
1177 finished. See also |v:throwpoint| and |throw-variables|.
1178 Example: >
1179 :try
1180 : throw "oops"
1181 :catch /.*/
1182 : echo "caught" v:exception
1183 :endtry
1184< Output: "caught oops".
1185
1186 *v:fname_in* *fname_in-variable*
1187v:fname_in The name of the input file. Only valid while evaluating:
1188 option used for ~
1189 'charconvert' file to be converted
1190 'diffexpr' original file
1191 'patchexpr' original file
1192 'printexpr' file to be printed
1193
1194 *v:fname_out* *fname_out-variable*
1195v:fname_out The name of the output file. Only valid while
1196 evaluating:
1197 option used for ~
1198 'charconvert' resulting converted file (*)
1199 'diffexpr' output of diff
1200 'patchexpr' resulting patched file
1201 (*) When doing conversion for a write command (e.g., ":w
1202 file") it will be equal to v:fname_in. When doing conversion
1203 for a read command (e.g., ":e file") it will be a temporary
1204 file and different from v:fname_in.
1205
1206 *v:fname_new* *fname_new-variable*
1207v:fname_new The name of the new version of the file. Only valid while
1208 evaluating 'diffexpr'.
1209
1210 *v:fname_diff* *fname_diff-variable*
1211v:fname_diff The name of the diff (patch) file. Only valid while
1212 evaluating 'patchexpr'.
1213
1214 *v:folddashes* *folddashes-variable*
1215v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
1216 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001217 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218
1219 *v:foldlevel* *foldlevel-variable*
1220v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001221 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222
1223 *v:foldend* *foldend-variable*
1224v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001225 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226
1227 *v:foldstart* *foldstart-variable*
1228v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001229 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230
Bram Moolenaar843ee412004-06-30 16:16:41 +00001231 *v:insertmode* *insertmode-variable*
1232v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
1233 events. Values:
1234 i Insert mode
1235 r Replace mode
1236 v Virtual Replace mode
1237
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001238 *v:key* *key-variable*
1239v:key Key of the current item of a Dictionary. Only valid while
1240 evaluating the expression used with |map()| and |filter()|.
1241 Read-only.
1242
Bram Moolenaar071d4272004-06-13 20:20:40 +00001243 *v:lang* *lang-variable*
1244v:lang The current locale setting for messages of the runtime
1245 environment. This allows Vim scripts to be aware of the
1246 current language. Technical: it's the value of LC_MESSAGES.
1247 The value is system dependent.
1248 This variable can not be set directly, use the |:language|
1249 command.
1250 It can be different from |v:ctype| when messages are desired
1251 in a different language than what is used for character
1252 encoding. See |multi-lang|.
1253
1254 *v:lc_time* *lc_time-variable*
1255v:lc_time The current locale setting for time messages of the runtime
1256 environment. This allows Vim scripts to be aware of the
1257 current language. Technical: it's the value of LC_TIME.
1258 This variable can not be set directly, use the |:language|
1259 command. See |multi-lang|.
1260
1261 *v:lnum* *lnum-variable*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001262v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr'
1263 expressions. Only valid while one of these expressions is
1264 being evaluated. Read-only when in the |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265
1266 *v:prevcount* *prevcount-variable*
1267v:prevcount The count given for the last but one Normal mode command.
1268 This is the v:count value of the previous command. Useful if
1269 you want to cancel Visual mode and then use the count. >
1270 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
1271< Read-only.
1272
1273 *v:progname* *progname-variable*
1274v:progname Contains the name (with path removed) with which Vim was
1275 invoked. Allows you to do special initialisations for "view",
1276 "evim" etc., or any other name you might symlink to Vim.
1277 Read-only.
1278
1279 *v:register* *register-variable*
1280v:register The name of the register supplied to the last normal mode
1281 command. Empty if none were supplied. |getreg()| |setreg()|
1282
1283 *v:servername* *servername-variable*
1284v:servername The resulting registered |x11-clientserver| name if any.
1285 Read-only.
1286
1287 *v:shell_error* *shell_error-variable*
1288v:shell_error Result of the last shell command. When non-zero, the last
1289 shell command had an error. When zero, there was no problem.
1290 This only works when the shell returns the error code to Vim.
1291 The value -1 is often used when the command could not be
1292 executed. Read-only.
1293 Example: >
1294 :!mv foo bar
1295 :if v:shell_error
1296 : echo 'could not rename "foo" to "bar"!'
1297 :endif
1298< "shell_error" also works, for backwards compatibility.
1299
1300 *v:statusmsg* *statusmsg-variable*
1301v:statusmsg Last given status message. It's allowed to set this variable.
1302
1303 *v:termresponse* *termresponse-variable*
1304v:termresponse The escape sequence returned by the terminal for the |t_RV|
1305 termcap entry. It is set when Vim receives an escape sequence
1306 that starts with ESC [ or CSI and ends in a 'c', with only
1307 digits, ';' and '.' in between.
1308 When this option is set, the TermResponse autocommand event is
1309 fired, so that you can react to the response from the
1310 terminal.
1311 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
1312 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
1313 patch level (since this was introduced in patch 95, it's
1314 always 95 or bigger). Pc is always zero.
1315 {only when compiled with |+termresponse| feature}
1316
1317 *v:this_session* *this_session-variable*
1318v:this_session Full filename of the last loaded or saved session file. See
1319 |:mksession|. It is allowed to set this variable. When no
1320 session file has been saved, this variable is empty.
1321 "this_session" also works, for backwards compatibility.
1322
1323 *v:throwpoint* *throwpoint-variable*
1324v:throwpoint The point where the exception most recently caught and not
1325 finished was thrown. Not set when commands are typed. See
1326 also |v:exception| and |throw-variables|.
1327 Example: >
1328 :try
1329 : throw "oops"
1330 :catch /.*/
1331 : echo "Exception from" v:throwpoint
1332 :endtry
1333< Output: "Exception from test.vim, line 2"
1334
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001335 *v:val* *val-variable*
1336v:val Value of the current item of a List or Dictionary. Only valid
1337 while evaluating the expression used with |map()| and
1338 |filter()|. Read-only.
1339
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340 *v:version* *version-variable*
1341v:version Version number of Vim: Major version number times 100 plus
1342 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
1343 is 501. Read-only. "version" also works, for backwards
1344 compatibility.
1345 Use |has()| to check if a certain patch was included, e.g.: >
1346 if has("patch123")
1347< Note that patch numbers are specific to the version, thus both
1348 version 5.0 and 5.1 may have a patch 123, but these are
1349 completely different.
1350
1351 *v:warningmsg* *warningmsg-variable*
1352v:warningmsg Last given warning message. It's allowed to set this variable.
1353
1354==============================================================================
13554. Builtin Functions *functions*
1356
1357See |function-list| for a list grouped by what the function is used for.
1358
1359(Use CTRL-] on the function name to jump to the full explanation)
1360
1361USAGE RESULT DESCRIPTION ~
1362
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001363add( {list}, {item}) List append {item} to List {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001364append( {lnum}, {string}) Number append {string} below line {lnum}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001365append( {lnum}, {list}) Number append lines {list} below line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366argc() Number number of files in the argument list
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001367argidx() Number current index in the argument list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368argv( {nr}) String {nr} entry of the argument list
1369browse( {save}, {title}, {initdir}, {default})
1370 String put up a file requester
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001371browsedir( {title}, {initdir}) String put up a directory requester
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372bufexists( {expr}) Number TRUE if buffer {expr} exists
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001373buflisted( {expr}) Number TRUE if buffer {expr} is listed
1374bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375bufname( {expr}) String Name of the buffer {expr}
1376bufnr( {expr}) Number Number of the buffer {expr}
1377bufwinnr( {expr}) Number window number of buffer {expr}
1378byte2line( {byte}) Number line number at byte count {byte}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001379byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001380call( {func}, {arglist} [, {dict}])
1381 any call {func} with arguments {arglist}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382char2nr( {expr}) Number ASCII value of first char in {expr}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001383cindent( {lnum}) Number C indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384col( {expr}) Number column nr of cursor or mark
1385confirm( {msg} [, {choices} [, {default} [, {type}]]])
1386 Number number of choice picked by user
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001387copy( {expr}) any make a shallow copy of {expr}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001388count( {list}, {expr} [, {start} [, {ic}]])
1389 Number count how many {expr} are in {list}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390cscope_connection( [{num} , {dbpath} [, {prepend}]])
1391 Number checks existence of cscope connection
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001392cursor( {lnum}, {col}) Number position cursor at {lnum}, {col}
1393deepcopy( {expr}) any make a full copy of {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394delete( {fname}) Number delete file {fname}
1395did_filetype() Number TRUE if FileType autocommand event used
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001396diff_filler( {lnum}) Number diff filler lines about {lnum}
1397diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
Bram Moolenaar13065c42005-01-08 16:08:21 +00001398empty( {expr}) Number TRUE if {expr} is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399escape( {string}, {chars}) String escape {chars} in {string} with '\'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001400eval( {string}) any evaluate {string} into its value
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001401eventhandler( ) Number TRUE if inside an event handler
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402executable( {expr}) Number 1 if executable {expr} exists
1403exists( {expr}) Number TRUE if {expr} exists
1404expand( {expr}) String expand special keywords in {expr}
1405filereadable( {file}) Number TRUE if {file} is a readable file
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001406filter( {expr}, {string}) List/Dict remove items from {expr} where
1407 {string} is 0
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001408finddir( {name}[, {path}[, {count}]])
1409 String Find directory {name} in {path}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001410findfile( {name}[, {path}[, {count}]])
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001411 String Find file {name} in {path}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412filewritable( {file}) Number TRUE if {file} is a writable file
1413fnamemodify( {fname}, {mods}) String modify file name
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001414foldclosed( {lnum}) Number first line of fold at {lnum} if closed
1415foldclosedend( {lnum}) Number last line of fold at {lnum} if closed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416foldlevel( {lnum}) Number fold level at {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001417foldtext( ) String line displayed for closed fold
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418foreground( ) Number bring the Vim window to the foreground
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001419function( {name}) Funcref reference to function {name}
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001420get( {list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001421get( {dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001422getchar( [expr]) Number get one character from the user
1423getcharmod( ) Number modifiers for the last typed character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424getbufvar( {expr}, {varname}) variable {varname} in buffer {expr}
1425getcmdline() String return the current command-line
1426getcmdpos() Number return cursor position in command-line
1427getcwd() String the current working directory
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001428getfperm( {fname}) String file permissions of file {fname}
1429getfsize( {fname}) Number size in bytes of file {fname}
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001430getfontname( [{name}]) String name of font being used
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431getftime( {fname}) Number last modification time of file
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001432getftype( {fname}) String description of type of file {fname}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001433getline( {lnum}) String line {lnum} of current buffer
1434getline( {lnum}, {end}) List lines {lnum} to {end} of current buffer
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001435getreg( [{regname}]) String contents of register
1436getregtype( [{regname}]) String type of register
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437getwinposx() Number X coord in pixels of GUI Vim window
1438getwinposy() Number Y coord in pixels of GUI Vim window
1439getwinvar( {nr}, {varname}) variable {varname} in window {nr}
1440glob( {expr}) String expand file wildcards in {expr}
1441globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path}
1442has( {feature}) Number TRUE if feature {feature} supported
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001443has_key( {dict}, {key}) Number TRUE if {dict} has entry {key}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001444hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists
1445histadd( {history},{item}) String add an item to a history
1446histdel( {history} [, {item}]) String remove an item from a history
1447histget( {history} [, {index}]) String get the item {index} from a history
1448histnr( {history}) Number highest index of a history
1449hlexists( {name}) Number TRUE if highlight group {name} exists
1450hlID( {name}) Number syntax ID of highlight group {name}
1451hostname() String name of the machine Vim is running on
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001452iconv( {expr}, {from}, {to}) String convert encoding of {expr}
1453indent( {lnum}) Number indent of line {lnum}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001454index( {list}, {expr} [, {start} [, {ic}]])
1455 Number index in {list} where {expr} appears
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456input( {prompt} [, {text}]) String get input from the user
1457inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001458inputrestore() Number restore typeahead
1459inputsave() Number save and clear typeahead
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460inputsecret( {prompt} [, {text}]) String like input() but hiding the text
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001461insert( {list}, {item} [, {idx}]) List insert {item} in {list} [before {idx}]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462isdirectory( {directory}) Number TRUE if {directory} is a directory
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00001463islocked( {expr}) Number TRUE if {expr} is locked
Bram Moolenaar677ee682005-01-27 14:41:15 +00001464items( {dict}) List List of key-value pairs in {dict}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001465join( {list} [, {sep}]) String join {list} items into one String
Bram Moolenaard8b02732005-01-14 21:48:43 +00001466keys( {dict}) List List of keys in {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001467len( {expr}) Number the length of {expr}
1468libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number
1470line( {expr}) Number line nr of cursor, last line or mark
1471line2byte( {lnum}) Number byte count of line {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001472lispindent( {lnum}) Number Lisp indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473localtime() Number current time
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001474map( {expr}, {string}) List/Dict change each item in {expr} to {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
1476mapcheck( {name}[, {mode}]) String check for mappings matching {name}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001477match( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 Number position where {pat} matches in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001479matchend( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 Number position where {pat} ends in {expr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001481matchlist( {expr}, {pat}[, {start}[, {count}]])
1482 List match and submatches of {pat} in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001483matchstr( {expr}, {pat}[, {start}[, {count}]])
1484 String {count}'th match of {pat} in {expr}
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001485max({list}) Number maximum value of items in {list}
1486min({list}) Number minumum value of items in {list}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001487mkdir({name} [, {path} [, {prot}]])
1488 Number create directory {name}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001489mode() String current editing mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum}
1491nr2char( {expr}) String single char with ASCII value {expr}
1492prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001493range( {expr} [, {max} [, {stride}]])
1494 List items from {expr} to {max}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001495readfile({fname} [, {binary} [, {max}]])
1496 List get list of lines from file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497remote_expr( {server}, {string} [, {idvar}])
1498 String send expression
1499remote_foreground( {server}) Number bring Vim server to the foreground
1500remote_peek( {serverid} [, {retvar}])
1501 Number check for reply string
1502remote_read( {serverid}) String read reply string
1503remote_send( {server}, {string} [, {idvar}])
1504 String send key sequence
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001505remove( {list}, {idx} [, {end}]) any remove items {idx}-{end} from {list}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001506remove( {dict}, {key}) any remove entry {key} from {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001507rename( {from}, {to}) Number rename (move) file from {from} to {to}
1508repeat( {expr}, {count}) String repeat {expr} {count} times
1509resolve( {filename}) String get filename a shortcut points to
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001510reverse( {list}) List reverse {list} in-place
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001511search( {pattern} [, {flags}]) Number search for {pattern}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001513 Number search for other end of start/end pair
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514server2client( {clientid}, {string})
1515 Number send reply string
1516serverlist() String get a list of available servers
1517setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val}
1518setcmdpos( {pos}) Number set cursor position in command-line
1519setline( {lnum}, {line}) Number set line {lnum} to {line}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001520setreg( {n}, {v}[, {opt}]) Number set register to value and type
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001522simplify( {filename}) String simplify filename as much as possible
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001523sort( {list} [, {func}]) List sort {list}, using {func} to compare
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001524split( {expr} [, {pat}]) List make List from {pat} separated {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525strftime( {format}[, {time}]) String time in specified format
Bram Moolenaar8f999f12005-01-25 22:12:55 +00001526stridx( {haystack}, {needle}[, {start}])
1527 Number index of {needle} in {haystack}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001528string( {expr}) String String representation of {expr} value
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529strlen( {expr}) Number length of the String {expr}
1530strpart( {src}, {start}[, {len}])
1531 String {len} characters of {src} at {start}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001532strridx( {haystack}, {needle} [, {start}])
1533 Number last index of {needle} in {haystack}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534strtrans( {expr}) String translate string to make it printable
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001535submatch( {nr}) String specific match in ":substitute"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536substitute( {expr}, {pat}, {sub}, {flags})
1537 String all {pat} in {expr} replaced with {sub}
Bram Moolenaar47136d72004-10-12 20:02:24 +00001538synID( {lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539synIDattr( {synID}, {what} [, {mode}])
1540 String attribute {what} of syntax ID {synID}
1541synIDtrans( {synID}) Number translated syntax ID of {synID}
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001542system( {expr} [, {input}]) String output of shell command/filter {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543tempname() String name for a temporary file
1544tolower( {expr}) String the String {expr} switched to lowercase
1545toupper( {expr}) String the String {expr} switched to uppercase
Bram Moolenaar8299df92004-07-10 09:47:34 +00001546tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr}
1547 to chars in {tostr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548type( {name}) Number type of variable {name}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001549values( {dict}) List List of values in {dict}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550virtcol( {expr}) Number screen column of cursor or mark
1551visualmode( [expr]) String last visual mode used
1552winbufnr( {nr}) Number buffer number of window {nr}
1553wincol() Number window column of the cursor
1554winheight( {nr}) Number height of window {nr}
1555winline() Number window line of the cursor
1556winnr() Number number of current window
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001557winrestcmd() String returns command to restore window sizes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558winwidth( {nr}) Number width of window {nr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001559writefile({list}, {fname} [, {binary}])
1560 Number write list of lines to file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001562add({list}, {expr}) *add()*
1563 Append the item {expr} to List {list}. Returns the resulting
1564 List. Examples: >
1565 :let alist = add([1, 2, 3], item)
1566 :call add(mylist, "woodstock")
1567< Note that when {expr} is a List it is appended as a single
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001568 item. Use |extend()| to concatenate Lists.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001569 Use |insert()| to add an item at another position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001571
1572append({lnum}, {expr}) *append()*
Bram Moolenaar748bf032005-02-02 23:04:36 +00001573 When {expr} is a List: Append each item of the List as a text
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001574 line below line {lnum} in the current buffer.
Bram Moolenaar748bf032005-02-02 23:04:36 +00001575 Otherwise append {expr} as one text line below line {lnum} in
1576 the current buffer.
1577 {lnum} can be zero to insert a line before the first one.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001578 Returns 1 for failure ({lnum} out of range or out of memory),
1579 0 for success. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001580 :let failed = append(line('$'), "# THE END")
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001581 :let failed = append(0, ["Chapter 1", "the beginning"])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001582<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 *argc()*
1584argc() The result is the number of files in the argument list of the
1585 current window. See |arglist|.
1586
1587 *argidx()*
1588argidx() The result is the current index in the argument list. 0 is
1589 the first file. argc() - 1 is the last one. See |arglist|.
1590
1591 *argv()*
1592argv({nr}) The result is the {nr}th file in the argument list of the
1593 current window. See |arglist|. "argv(0)" is the first one.
1594 Example: >
1595 :let i = 0
1596 :while i < argc()
1597 : let f = escape(argv(i), '. ')
1598 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
1599 : let i = i + 1
1600 :endwhile
1601<
1602 *browse()*
1603browse({save}, {title}, {initdir}, {default})
1604 Put up a file requester. This only works when "has("browse")"
1605 returns non-zero (only in some GUI versions).
1606 The input fields are:
1607 {save} when non-zero, select file to write
1608 {title} title for the requester
1609 {initdir} directory to start browsing in
1610 {default} default file name
1611 When the "Cancel" button is hit, something went wrong, or
1612 browsing is not possible, an empty string is returned.
1613
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001614 *browsedir()*
1615browsedir({title}, {initdir})
1616 Put up a directory requester. This only works when
1617 "has("browse")" returns non-zero (only in some GUI versions).
1618 On systems where a directory browser is not supported a file
1619 browser is used. In that case: select a file in the directory
1620 to be used.
1621 The input fields are:
1622 {title} title for the requester
1623 {initdir} directory to start browsing in
1624 When the "Cancel" button is hit, something went wrong, or
1625 browsing is not possible, an empty string is returned.
1626
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627bufexists({expr}) *bufexists()*
1628 The result is a Number, which is non-zero if a buffer called
1629 {expr} exists.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001630 If the {expr} argument is a number, buffer numbers are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631 If the {expr} argument is a string it must match a buffer name
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001632 exactly. The name can be:
1633 - Relative to the current directory.
1634 - A full path.
1635 - The name of a buffer with 'filetype' set to "nofile".
1636 - A URL name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 Unlisted buffers will be found.
1638 Note that help files are listed by their short name in the
1639 output of |:buffers|, but bufexists() requires using their
1640 long name to be able to find them.
1641 Use "bufexists(0)" to test for the existence of an alternate
1642 file name.
1643 *buffer_exists()*
1644 Obsolete name: buffer_exists().
1645
1646buflisted({expr}) *buflisted()*
1647 The result is a Number, which is non-zero if a buffer called
1648 {expr} exists and is listed (has the 'buflisted' option set).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001649 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651bufloaded({expr}) *bufloaded()*
1652 The result is a Number, which is non-zero if a buffer called
1653 {expr} exists and is loaded (shown in a window or hidden).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001654 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655
1656bufname({expr}) *bufname()*
1657 The result is the name of a buffer, as it is displayed by the
1658 ":ls" command.
1659 If {expr} is a Number, that buffer number's name is given.
1660 Number zero is the alternate buffer for the current window.
1661 If {expr} is a String, it is used as a |file-pattern| to match
1662 with the buffer names. This is always done like 'magic' is
1663 set and 'cpoptions' is empty. When there is more than one
1664 match an empty string is returned.
1665 "" or "%" can be used for the current buffer, "#" for the
1666 alternate buffer.
1667 A full match is preferred, otherwise a match at the start, end
1668 or middle of the buffer name is accepted.
1669 Listed buffers are found first. If there is a single match
1670 with a listed buffer, that one is returned. Next unlisted
1671 buffers are searched for.
1672 If the {expr} is a String, but you want to use it as a buffer
1673 number, force it to be a Number by adding zero to it: >
1674 :echo bufname("3" + 0)
1675< If the buffer doesn't exist, or doesn't have a name, an empty
1676 string is returned. >
1677 bufname("#") alternate buffer name
1678 bufname(3) name of buffer 3
1679 bufname("%") name of current buffer
1680 bufname("file2") name of buffer where "file2" matches.
1681< *buffer_name()*
1682 Obsolete name: buffer_name().
1683
1684 *bufnr()*
1685bufnr({expr}) The result is the number of a buffer, as it is displayed by
1686 the ":ls" command. For the use of {expr}, see |bufname()|
1687 above. If the buffer doesn't exist, -1 is returned.
1688 bufnr("$") is the last buffer: >
1689 :let last_buffer = bufnr("$")
1690< The result is a Number, which is the highest buffer number
1691 of existing buffers. Note that not all buffers with a smaller
1692 number necessarily exist, because ":bwipeout" may have removed
1693 them. Use bufexists() to test for the existence of a buffer.
1694 *buffer_number()*
1695 Obsolete name: buffer_number().
1696 *last_buffer_nr()*
1697 Obsolete name for bufnr("$"): last_buffer_nr().
1698
1699bufwinnr({expr}) *bufwinnr()*
1700 The result is a Number, which is the number of the first
1701 window associated with buffer {expr}. For the use of {expr},
1702 see |bufname()| above. If buffer {expr} doesn't exist or
1703 there is no such window, -1 is returned. Example: >
1704
1705 echo "A window containing buffer 1 is " . (bufwinnr(1))
1706
1707< The number can be used with |CTRL-W_w| and ":wincmd w"
1708 |:wincmd|.
1709
1710
1711byte2line({byte}) *byte2line()*
1712 Return the line number that contains the character at byte
1713 count {byte} in the current buffer. This includes the
1714 end-of-line character, depending on the 'fileformat' option
1715 for the current buffer. The first character has byte count
1716 one.
1717 Also see |line2byte()|, |go| and |:goto|.
1718 {not available when compiled without the |+byte_offset|
1719 feature}
1720
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001721byteidx({expr}, {nr}) *byteidx()*
1722 Return byte index of the {nr}'th character in the string
1723 {expr}. Use zero for the first character, it returns zero.
1724 This function is only useful when there are multibyte
1725 characters, otherwise the returned value is equal to {nr}.
1726 Composing characters are counted as a separate character.
1727 Example : >
1728 echo matchstr(str, ".", byteidx(str, 3))
1729< will display the fourth character. Another way to do the
1730 same: >
1731 let s = strpart(str, byteidx(str, 3))
1732 echo strpart(s, 0, byteidx(s, 1))
1733< If there are less than {nr} characters -1 is returned.
1734 If there are exactly {nr} characters the length of the string
1735 is returned.
1736
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001737call({func}, {arglist} [, {dict}]) *call()* *E699*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001738 Call function {func} with the items in List {arglist} as
1739 arguments.
1740 {func} can either be a Funcref or the name of a function.
1741 a:firstline and a:lastline are set to the cursor line.
1742 Returns the return value of the called function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001743 {dict} is for functions with the "dict" attribute. It will be
1744 used to set the local variable "self". |Dictionary-function|
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001745
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746char2nr({expr}) *char2nr()*
1747 Return number value of the first char in {expr}. Examples: >
1748 char2nr(" ") returns 32
1749 char2nr("ABC") returns 65
1750< The current 'encoding' is used. Example for "utf-8": >
1751 char2nr("á") returns 225
1752 char2nr("á"[0]) returns 195
1753
1754cindent({lnum}) *cindent()*
1755 Get the amount of indent for line {lnum} according the C
1756 indenting rules, as with 'cindent'.
1757 The indent is counted in spaces, the value of 'tabstop' is
1758 relevant. {lnum} is used just like in |getline()|.
1759 When {lnum} is invalid or Vim was not compiled the |+cindent|
1760 feature, -1 is returned.
1761
1762 *col()*
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001763col({expr}) The result is a Number, which is the byte index of the column
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 position given with {expr}. The accepted positions are:
1765 . the cursor position
1766 $ the end of the cursor line (the result is the
1767 number of characters in the cursor line plus one)
1768 'x position of mark x (if the mark is not set, 0 is
1769 returned)
1770 For the screen column position use |virtcol()|.
1771 Note that only marks in the current file can be used.
1772 Examples: >
1773 col(".") column of cursor
1774 col("$") length of cursor line plus one
1775 col("'t") column of mark t
1776 col("'" . markname) column of mark markname
1777< The first column is 1. 0 is returned for an error.
1778 For the cursor position, when 'virtualedit' is active, the
1779 column is one higher if the cursor is after the end of the
1780 line. This can be used to obtain the column in Insert mode: >
1781 :imap <F2> <C-O>:let save_ve = &ve<CR>
1782 \<C-O>:set ve=all<CR>
1783 \<C-O>:echo col(".") . "\n" <Bar>
1784 \let &ve = save_ve<CR>
1785<
1786 *confirm()*
1787confirm({msg} [, {choices} [, {default} [, {type}]]])
1788 Confirm() offers the user a dialog, from which a choice can be
1789 made. It returns the number of the choice. For the first
1790 choice this is 1.
1791 Note: confirm() is only supported when compiled with dialog
1792 support, see |+dialog_con| and |+dialog_gui|.
1793 {msg} is displayed in a |dialog| with {choices} as the
1794 alternatives. When {choices} is missing or empty, "&OK" is
1795 used (and translated).
1796 {msg} is a String, use '\n' to include a newline. Only on
1797 some systems the string is wrapped when it doesn't fit.
1798 {choices} is a String, with the individual choices separated
1799 by '\n', e.g. >
1800 confirm("Save changes?", "&Yes\n&No\n&Cancel")
1801< The letter after the '&' is the shortcut key for that choice.
1802 Thus you can type 'c' to select "Cancel". The shortcut does
1803 not need to be the first letter: >
1804 confirm("file has been modified", "&Save\nSave &All")
1805< For the console, the first letter of each choice is used as
1806 the default shortcut key.
1807 The optional {default} argument is the number of the choice
1808 that is made if the user hits <CR>. Use 1 to make the first
1809 choice the default one. Use 0 to not set a default. If
1810 {default} is omitted, 1 is used.
1811 The optional {type} argument gives the type of dialog. This
1812 is only used for the icon of the Win32 GUI. It can be one of
1813 these values: "Error", "Question", "Info", "Warning" or
1814 "Generic". Only the first character is relevant. When {type}
1815 is omitted, "Generic" is used.
1816 If the user aborts the dialog by pressing <Esc>, CTRL-C,
1817 or another valid interrupt key, confirm() returns 0.
1818
1819 An example: >
1820 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
1821 :if choice == 0
1822 : echo "make up your mind!"
1823 :elseif choice == 3
1824 : echo "tasteful"
1825 :else
1826 : echo "I prefer bananas myself."
1827 :endif
1828< In a GUI dialog, buttons are used. The layout of the buttons
1829 depends on the 'v' flag in 'guioptions'. If it is included,
1830 the buttons are always put vertically. Otherwise, confirm()
1831 tries to put the buttons in one horizontal line. If they
1832 don't fit, a vertical layout is used anyway. For some systems
1833 the horizontal layout is always used.
1834
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001835 *copy()*
1836copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
1837 different from using {expr} directly.
1838 When {expr} is a List a shallow copy is created. This means
1839 that the original List can be changed without changing the
1840 copy, and vise versa. But the items are identical, thus
1841 changing an item changes the contents of both Lists. Also see
1842 |deepcopy()|.
1843
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001844count({comp}, {expr} [, {ic} [, {start}]]) *count()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001845 Return the number of times an item with value {expr} appears
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001846 in List or Dictionary {comp}.
1847 If {start} is given then start with the item with this index.
1848 {start} can only be used with a List.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001849 When {ic} is given and it's non-zero then case is ignored.
1850
1851
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 *cscope_connection()*
1853cscope_connection([{num} , {dbpath} [, {prepend}]])
1854 Checks for the existence of a |cscope| connection. If no
1855 parameters are specified, then the function returns:
1856 0, if cscope was not available (not compiled in), or
1857 if there are no cscope connections;
1858 1, if there is at least one cscope connection.
1859
1860 If parameters are specified, then the value of {num}
1861 determines how existence of a cscope connection is checked:
1862
1863 {num} Description of existence check
1864 ----- ------------------------------
1865 0 Same as no parameters (e.g., "cscope_connection()").
1866 1 Ignore {prepend}, and use partial string matches for
1867 {dbpath}.
1868 2 Ignore {prepend}, and use exact string matches for
1869 {dbpath}.
1870 3 Use {prepend}, use partial string matches for both
1871 {dbpath} and {prepend}.
1872 4 Use {prepend}, use exact string matches for both
1873 {dbpath} and {prepend}.
1874
1875 Note: All string comparisons are case sensitive!
1876
1877 Examples. Suppose we had the following (from ":cs show"): >
1878
1879 # pid database name prepend path
1880 0 27664 cscope.out /usr/local
1881<
1882 Invocation Return Val ~
1883 ---------- ---------- >
1884 cscope_connection() 1
1885 cscope_connection(1, "out") 1
1886 cscope_connection(2, "out") 0
1887 cscope_connection(3, "out") 0
1888 cscope_connection(3, "out", "local") 1
1889 cscope_connection(4, "out") 0
1890 cscope_connection(4, "out", "local") 0
1891 cscope_connection(4, "cscope.out", "/usr/local") 1
1892<
1893cursor({lnum}, {col}) *cursor()*
1894 Positions the cursor at the column {col} in the line {lnum}.
1895 Does not change the jumplist.
1896 If {lnum} is greater than the number of lines in the buffer,
1897 the cursor will be positioned at the last line in the buffer.
1898 If {lnum} is zero, the cursor will stay in the current line.
1899 If {col} is greater than the number of characters in the line,
1900 the cursor will be positioned at the last character in the
1901 line.
1902 If {col} is zero, the cursor will stay in the current column.
1903
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001904
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001905deepcopy({expr}[, {noref}]) *deepcopy()* *E698*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001906 Make a copy of {expr}. For Numbers and Strings this isn't
1907 different from using {expr} directly.
1908 When {expr} is a List a full copy is created. This means
1909 that the original List can be changed without changing the
1910 copy, and vise versa. When an item is a List, a copy for it
1911 is made, recursively. Thus changing an item in the copy does
1912 not change the contents of the original List.
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001913 When {noref} is omitted or zero a contained List or Dictionary
1914 is only copied once. All references point to this single
1915 copy. With {noref} set to 1 every occurrence of a List or
1916 Dictionary results in a new copy. This also means that a
1917 cyclic reference causes deepcopy() to fail.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001918 *E724*
1919 Nesting is possible up to 100 levels. When there is an item
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001920 that refers back to a higher level making a deep copy with
1921 {noref} set to 1 will fail.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001922 Also see |copy()|.
1923
1924delete({fname}) *delete()*
1925 Deletes the file by the name {fname}. The result is a Number,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 which is 0 if the file was deleted successfully, and non-zero
1927 when the deletion failed.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001928 Use |remove()| to delete an item from a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929
1930 *did_filetype()*
1931did_filetype() Returns non-zero when autocommands are being executed and the
1932 FileType event has been triggered at least once. Can be used
1933 to avoid triggering the FileType event again in the scripts
1934 that detect the file type. |FileType|
1935 When editing another file, the counter is reset, thus this
1936 really checks if the FileType event has been triggered for the
1937 current buffer. This allows an autocommand that starts
1938 editing another buffer to set 'filetype' and load a syntax
1939 file.
1940
Bram Moolenaar47136d72004-10-12 20:02:24 +00001941diff_filler({lnum}) *diff_filler()*
1942 Returns the number of filler lines above line {lnum}.
1943 These are the lines that were inserted at this point in
1944 another diff'ed window. These filler lines are shown in the
1945 display but don't exist in the buffer.
1946 {lnum} is used like with |getline()|. Thus "." is the current
1947 line, "'m" mark m, etc.
1948 Returns 0 if the current window is not in diff mode.
1949
1950diff_hlID({lnum}, {col}) *diff_hlID()*
1951 Returns the highlight ID for diff mode at line {lnum} column
1952 {col} (byte index). When the current line does not have a
1953 diff change zero is returned.
1954 {lnum} is used like with |getline()|. Thus "." is the current
1955 line, "'m" mark m, etc.
1956 {col} is 1 for the leftmost column, {lnum} is 1 for the first
1957 line.
1958 The highlight ID can be used with |synIDattr()| to obtain
1959 syntax information about the highlighting.
1960
Bram Moolenaar13065c42005-01-08 16:08:21 +00001961empty({expr}) *empty()*
1962 Return the Number 1 if {expr} is empty, zero otherwise.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001963 A List or Dictionary is empty when it does not have any items.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001964 A Number is empty when its value is zero.
1965 For a long List this is much faster then comparing the length
1966 with zero.
1967
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968escape({string}, {chars}) *escape()*
1969 Escape the characters in {chars} that occur in {string} with a
1970 backslash. Example: >
1971 :echo escape('c:\program files\vim', ' \')
1972< results in: >
1973 c:\\program\ files\\vim
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001974
1975< *eval()*
1976eval({string}) Evaluate {string} and return the result. Especially useful to
1977 turn the result of |string()| back into the original value.
1978 This works for Numbers, Strings and composites of them.
1979 Also works for Funcrefs that refer to existing functions.
1980
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981eventhandler() *eventhandler()*
1982 Returns 1 when inside an event handler. That is that Vim got
1983 interrupted while waiting for the user to type a character,
1984 e.g., when dropping a file on Vim. This means interactive
1985 commands cannot be used. Otherwise zero is returned.
1986
1987executable({expr}) *executable()*
1988 This function checks if an executable with the name {expr}
1989 exists. {expr} must be the name of the program without any
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001990 arguments.
1991 executable() uses the value of $PATH and/or the normal
1992 searchpath for programs. *PATHEXT*
1993 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
1994 optionally be included. Then the extensions in $PATHEXT are
1995 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
1996 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
1997 used. A dot by itself can be used in $PATHEXT to try using
1998 the name without an extension. When 'shell' looks like a
1999 Unix shell, then the name is also tried without adding an
2000 extension.
2001 On MS-DOS and MS-Windows it only checks if the file exists and
2002 is not a directory, not if it's really executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 The result is a Number:
2004 1 exists
2005 0 does not exist
2006 -1 not implemented on this system
2007
2008 *exists()*
2009exists({expr}) The result is a Number, which is non-zero if {expr} is
2010 defined, zero otherwise. The {expr} argument is a string,
2011 which contains one of these:
2012 &option-name Vim option (only checks if it exists,
2013 not if it really works)
2014 +option-name Vim option that works.
2015 $ENVNAME environment variable (could also be
2016 done by comparing with an empty
2017 string)
2018 *funcname built-in function (see |functions|)
2019 or user defined function (see
2020 |user-functions|).
2021 varname internal variable (see
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002022 |internal-variables|). Also works
2023 for |curly-braces-names|, Dictionary
2024 entries, List items, etc. Beware that
2025 this may cause functions to be
2026 invoked cause an error message for an
2027 invalid expression.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 :cmdname Ex command: built-in command, user
2029 command or command modifier |:command|.
2030 Returns:
2031 1 for match with start of a command
2032 2 full match with a command
2033 3 matches several user commands
2034 To check for a supported command
2035 always check the return value to be 2.
2036 #event autocommand defined for this event
2037 #event#pattern autocommand defined for this event and
2038 pattern (the pattern is taken
2039 literally and compared to the
2040 autocommand patterns character by
2041 character)
2042 For checking for a supported feature use |has()|.
2043
2044 Examples: >
2045 exists("&shortname")
2046 exists("$HOSTNAME")
2047 exists("*strftime")
2048 exists("*s:MyFunc")
2049 exists("bufcount")
2050 exists(":Make")
2051 exists("#CursorHold");
2052 exists("#BufReadPre#*.gz")
2053< There must be no space between the symbol (&/$/*/#) and the
2054 name.
2055 Note that the argument must be a string, not the name of the
2056 variable itself! For example: >
2057 exists(bufcount)
2058< This doesn't check for existence of the "bufcount" variable,
2059 but gets the contents of "bufcount", and checks if that
2060 exists.
2061
2062expand({expr} [, {flag}]) *expand()*
2063 Expand wildcards and the following special keywords in {expr}.
2064 The result is a String.
2065
2066 When there are several matches, they are separated by <NL>
2067 characters. [Note: in version 5.0 a space was used, which
2068 caused problems when a file name contains a space]
2069
2070 If the expansion fails, the result is an empty string. A name
2071 for a non-existing file is not included.
2072
2073 When {expr} starts with '%', '#' or '<', the expansion is done
2074 like for the |cmdline-special| variables with their associated
2075 modifiers. Here is a short overview:
2076
2077 % current file name
2078 # alternate file name
2079 #n alternate file name n
2080 <cfile> file name under the cursor
2081 <afile> autocmd file name
2082 <abuf> autocmd buffer number (as a String!)
2083 <amatch> autocmd matched name
2084 <sfile> sourced script file name
2085 <cword> word under the cursor
2086 <cWORD> WORD under the cursor
2087 <client> the {clientid} of the last received
2088 message |server2client()|
2089 Modifiers:
2090 :p expand to full path
2091 :h head (last path component removed)
2092 :t tail (last path component only)
2093 :r root (one extension removed)
2094 :e extension only
2095
2096 Example: >
2097 :let &tags = expand("%:p:h") . "/tags"
2098< Note that when expanding a string that starts with '%', '#' or
2099 '<', any following text is ignored. This does NOT work: >
2100 :let doesntwork = expand("%:h.bak")
2101< Use this: >
2102 :let doeswork = expand("%:h") . ".bak"
2103< Also note that expanding "<cfile>" and others only returns the
2104 referenced file name without further expansion. If "<cfile>"
2105 is "~/.cshrc", you need to do another expand() to have the
2106 "~/" expanded into the path of the home directory: >
2107 :echo expand(expand("<cfile>"))
2108<
2109 There cannot be white space between the variables and the
2110 following modifier. The |fnamemodify()| function can be used
2111 to modify normal file names.
2112
2113 When using '%' or '#', and the current or alternate file name
2114 is not defined, an empty string is used. Using "%:p" in a
2115 buffer with no name, results in the current directory, with a
2116 '/' added.
2117
2118 When {expr} does not start with '%', '#' or '<', it is
2119 expanded like a file name is expanded on the command line.
2120 'suffixes' and 'wildignore' are used, unless the optional
2121 {flag} argument is given and it is non-zero. Names for
2122 non-existing files are included.
2123
2124 Expand() can also be used to expand variables and environment
2125 variables that are only known in a shell. But this can be
2126 slow, because a shell must be started. See |expr-env-expand|.
2127 The expanded variable is still handled like a list of file
2128 names. When an environment variable cannot be expanded, it is
2129 left unchanged. Thus ":echo expand('$FOOBAR')" results in
2130 "$FOOBAR".
2131
2132 See |glob()| for finding existing files. See |system()| for
2133 getting the raw output of an external command.
2134
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002135extend({expr1}, {expr2} [, {expr3}]) *extend()*
2136 {expr1} and {expr2} must be both Lists or both Dictionaries.
2137
2138 If they are Lists: Append {expr2} to {expr1}.
2139 If {expr3} is given insert the items of {expr2} before item
2140 {expr3} in {expr1}. When {expr3} is zero insert before the
2141 first item. When {expr3} is equal to len({expr1}) then
2142 {expr2} is appended.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002143 Examples: >
2144 :echo sort(extend(mylist, [7, 5]))
2145 :call extend(mylist, [2, 3], 1)
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002146< Use |add()| to concatenate one item to a list. To concatenate
2147 two lists into a new list use the + operator: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002148 :let newlist = [1, 2, 3] + [4, 5]
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002149<
2150 If they are Dictionaries:
2151 Add all entries from {expr2} to {expr1}.
2152 If a key exists in both {expr1} and {expr2} then {expr3} is
2153 used to decide what to do:
2154 {expr3} = "keep": keep the value of {expr1}
2155 {expr3} = "force": use the value of {expr2}
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00002156 {expr3} = "error": give an error message *E737*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002157 When {expr3} is omitted then "force" is assumed.
2158
2159 {expr1} is changed when {expr2} is not empty. If necessary
2160 make a copy of {expr1} first.
2161 {expr2} remains unchanged.
2162 Returns {expr1}.
2163
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002164
Bram Moolenaar071d4272004-06-13 20:20:40 +00002165filereadable({file}) *filereadable()*
2166 The result is a Number, which is TRUE when a file with the
2167 name {file} exists, and can be read. If {file} doesn't exist,
2168 or is a directory, the result is FALSE. {file} is any
2169 expression, which is used as a String.
2170 *file_readable()*
2171 Obsolete name: file_readable().
2172
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002173
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002174filter({expr}, {string}) *filter()*
2175 {expr} must be a List or a Dictionary.
2176 For each item in {expr} evaluate {string} and when the result
2177 is zero remove the item from the List or Dictionary.
2178 Inside {string} |v:val| has the value of the current item.
2179 For a Dictionary |v:key| has the key of the current item.
2180 Examples: >
2181 :call filter(mylist, 'v:val !~ "OLD"')
2182< Removes the items where "OLD" appears. >
2183 :call filter(mydict, 'v:key >= 8')
2184< Removes the items with a key below 8. >
2185 :call filter(var, 0)
Bram Moolenaard8b02732005-01-14 21:48:43 +00002186< Removes all the items, thus clears the List or Dictionary.
2187
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002188 Note that {string} is the result of expression and is then
2189 used as an expression again. Often it is good to use a
2190 |literal-string| to avoid having to double backslashes.
2191
2192 The operation is done in-place. If you want a List or
2193 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002194 :let l = filter(copy(mylist), '& =~ "KEEP"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002195
2196< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002197
2198
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002199finddir({name}[, {path}[, {count}]]) *finddir()*
2200 Find directory {name} in {path}.
2201 If {path} is omitted or empty then 'path' is used.
2202 If the optional {count} is given, find {count}'s occurrence of
2203 {name} in {path}.
2204 This is quite similar to the ex-command |:find|.
2205 When the found directory is below the current directory a
2206 relative path is returned. Otherwise a full path is returned.
2207 Example: >
2208 :echo findfile("tags.vim", ".;")
2209< Searches from the current directory upwards until it finds
2210 the file "tags.vim".
2211 {only available when compiled with the +file_in_path feature}
2212
2213findfile({name}[, {path}[, {count}]]) *findfile()*
2214 Just like |finddir()|, but find a file instead of a directory.
2215
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216filewritable({file}) *filewritable()*
2217 The result is a Number, which is 1 when a file with the
2218 name {file} exists, and can be written. If {file} doesn't
2219 exist, or is not writable, the result is 0. If (file) is a
2220 directory, and we can write to it, the result is 2.
2221
2222fnamemodify({fname}, {mods}) *fnamemodify()*
2223 Modify file name {fname} according to {mods}. {mods} is a
2224 string of characters like it is used for file names on the
2225 command line. See |filename-modifiers|.
2226 Example: >
2227 :echo fnamemodify("main.c", ":p:h")
2228< results in: >
2229 /home/mool/vim/vim/src
2230< Note: Environment variables and "~" don't work in {fname}, use
2231 |expand()| first then.
2232
2233foldclosed({lnum}) *foldclosed()*
2234 The result is a Number. If the line {lnum} is in a closed
2235 fold, the result is the number of the first line in that fold.
2236 If the line {lnum} is not in a closed fold, -1 is returned.
2237
2238foldclosedend({lnum}) *foldclosedend()*
2239 The result is a Number. If the line {lnum} is in a closed
2240 fold, the result is the number of the last line in that fold.
2241 If the line {lnum} is not in a closed fold, -1 is returned.
2242
2243foldlevel({lnum}) *foldlevel()*
2244 The result is a Number, which is the foldlevel of line {lnum}
2245 in the current buffer. For nested folds the deepest level is
2246 returned. If there is no fold at line {lnum}, zero is
2247 returned. It doesn't matter if the folds are open or closed.
2248 When used while updating folds (from 'foldexpr') -1 is
2249 returned for lines where folds are still to be updated and the
2250 foldlevel is unknown. As a special case the level of the
2251 previous line is usually available.
2252
2253 *foldtext()*
2254foldtext() Returns a String, to be displayed for a closed fold. This is
2255 the default function used for the 'foldtext' option and should
2256 only be called from evaluating 'foldtext'. It uses the
2257 |v:foldstart|, |v:foldend| and |v:folddashes| variables.
2258 The returned string looks like this: >
2259 +-- 45 lines: abcdef
2260< The number of dashes depends on the foldlevel. The "45" is
2261 the number of lines in the fold. "abcdef" is the text in the
2262 first non-blank line of the fold. Leading white space, "//"
2263 or "/*" and the text from the 'foldmarker' and 'commentstring'
2264 options is removed.
2265 {not available when compiled without the |+folding| feature}
2266
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002267foldtextresult({lnum}) *foldtextresult()*
2268 Returns the text that is displayed for the closed fold at line
2269 {lnum}. Evaluates 'foldtext' in the appropriate context.
2270 When there is no closed fold at {lnum} an empty string is
2271 returned.
2272 {lnum} is used like with |getline()|. Thus "." is the current
2273 line, "'m" mark m, etc.
2274 Useful when exporting folded text, e.g., to HTML.
2275 {not available when compiled without the |+folding| feature}
2276
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 *foreground()*
2278foreground() Move the Vim window to the foreground. Useful when sent from
2279 a client to a Vim server. |remote_send()|
2280 On Win32 systems this might not work, the OS does not always
2281 allow a window to bring itself to the foreground. Use
2282 |remote_foreground()| instead.
2283 {only in the Win32, Athena, Motif and GTK GUI versions and the
2284 Win32 console version}
2285
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002286
Bram Moolenaar13065c42005-01-08 16:08:21 +00002287function({name}) *function()* *E700*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002288 Return a Funcref variable that refers to function {name}.
2289 {name} can be a user defined function or an internal function.
2290
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002291
Bram Moolenaar677ee682005-01-27 14:41:15 +00002292get({list}, {idx} [, {default}]) *get()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002293 Get item {idx} from List {list}. When this item is not
2294 available return {default}. Return zero when {default} is
2295 omitted.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002296get({dict}, {key} [, {default}])
2297 Get item with key {key} from Dictionary {dict}. When this
2298 item is not available return {default}. Return zero when
2299 {default} is omitted.
2300
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002301
2302getbufvar({expr}, {varname}) *getbufvar()*
2303 The result is the value of option or local buffer variable
2304 {varname} in buffer {expr}. Note that the name without "b:"
2305 must be used.
2306 This also works for a global or local window option, but it
2307 doesn't work for a global or local window variable.
2308 For the use of {expr}, see |bufname()| above.
2309 When the buffer or variable doesn't exist an empty string is
2310 returned, there is no error message.
2311 Examples: >
2312 :let bufmodified = getbufvar(1, "&mod")
2313 :echo "todo myvar = " . getbufvar("todo", "myvar")
2314<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315getchar([expr]) *getchar()*
2316 Get a single character from the user. If it is an 8-bit
2317 character, the result is a number. Otherwise a String is
2318 returned with the encoded character. For a special key it's a
2319 sequence of bytes starting with 0x80 (decimal: 128).
2320 If [expr] is omitted, wait until a character is available.
2321 If [expr] is 0, only get a character when one is available.
2322 If [expr] is 1, only check if a character is available, it is
2323 not consumed. If a normal character is
2324 available, it is returned, otherwise a
2325 non-zero value is returned.
2326 If a normal character available, it is returned as a Number.
2327 Use nr2char() to convert it to a String.
2328 The returned value is zero if no character is available.
2329 The returned value is a string of characters for special keys
2330 and when a modifier (shift, control, alt) was used.
2331 There is no prompt, you will somehow have to make clear to the
2332 user that a character has to be typed.
2333 There is no mapping for the character.
2334 Key codes are replaced, thus when the user presses the <Del>
2335 key you get the code for the <Del> key, not the raw character
2336 sequence. Examples: >
2337 getchar() == "\<Del>"
2338 getchar() == "\<S-Left>"
2339< This example redefines "f" to ignore case: >
2340 :nmap f :call FindChar()<CR>
2341 :function FindChar()
2342 : let c = nr2char(getchar())
2343 : while col('.') < col('$') - 1
2344 : normal l
2345 : if getline('.')[col('.') - 1] ==? c
2346 : break
2347 : endif
2348 : endwhile
2349 :endfunction
2350
2351getcharmod() *getcharmod()*
2352 The result is a Number which is the state of the modifiers for
2353 the last obtained character with getchar() or in another way.
2354 These values are added together:
2355 2 shift
2356 4 control
2357 8 alt (meta)
2358 16 mouse double click
2359 32 mouse triple click
2360 64 mouse quadruple click
2361 128 Macintosh only: command
2362 Only the modifiers that have not been included in the
2363 character itself are obtained. Thus Shift-a results in "A"
2364 with no modifier.
2365
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366getcmdline() *getcmdline()*
2367 Return the current command-line. Only works when the command
2368 line is being edited, thus requires use of |c_CTRL-\_e| or
2369 |c_CTRL-R_=|.
2370 Example: >
2371 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
2372< Also see |getcmdpos()| and |setcmdpos()|.
2373
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002374getcmdpos() *getcmdpos()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 Return the position of the cursor in the command line as a
2376 byte count. The first column is 1.
2377 Only works when editing the command line, thus requires use of
2378 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
2379 Also see |setcmdpos()| and |getcmdline()|.
2380
2381 *getcwd()*
2382getcwd() The result is a String, which is the name of the current
2383 working directory.
2384
2385getfsize({fname}) *getfsize()*
2386 The result is a Number, which is the size in bytes of the
2387 given file {fname}.
2388 If {fname} is a directory, 0 is returned.
2389 If the file {fname} can't be found, -1 is returned.
2390
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002391getfontname([{name}]) *getfontname()*
2392 Without an argument returns the name of the normal font being
2393 used. Like what is used for the Normal highlight group
2394 |hl-Normal|.
2395 With an argument a check is done whether {name} is a valid
2396 font name. If not then an empty string is returned.
2397 Otherwise the actual font name is returned, or {name} if the
2398 GUI does not support obtaining the real name.
2399 Only works when the GUI is running, thus not you your vimrc or
2400 Note that the GTK 2 GUI accepts any font name, thus checking
2401 for a valid name does not work.
2402 gvimrc file. Use the |GUIEnter| autocommand to use this
2403 function just after the GUI has started.
2404
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002405getfperm({fname}) *getfperm()*
2406 The result is a String, which is the read, write, and execute
2407 permissions of the given file {fname}.
2408 If {fname} does not exist or its directory cannot be read, an
2409 empty string is returned.
2410 The result is of the form "rwxrwxrwx", where each group of
2411 "rwx" flags represent, in turn, the permissions of the owner
2412 of the file, the group the file belongs to, and other users.
2413 If a user does not have a given permission the flag for this
2414 is replaced with the string "-". Example: >
2415 :echo getfperm("/etc/passwd")
2416< This will hopefully (from a security point of view) display
2417 the string "rw-r--r--" or even "rw-------".
2418
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419getftime({fname}) *getftime()*
2420 The result is a Number, which is the last modification time of
2421 the given file {fname}. The value is measured as seconds
2422 since 1st Jan 1970, and may be passed to strftime(). See also
2423 |localtime()| and |strftime()|.
2424 If the file {fname} can't be found -1 is returned.
2425
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002426getftype({fname}) *getftype()*
2427 The result is a String, which is a description of the kind of
2428 file of the given file {fname}.
2429 If {fname} does not exist an empty string is returned.
2430 Here is a table over different kinds of files and their
2431 results:
2432 Normal file "file"
2433 Directory "dir"
2434 Symbolic link "link"
2435 Block device "bdev"
2436 Character device "cdev"
2437 Socket "socket"
2438 FIFO "fifo"
2439 All other "other"
2440 Example: >
2441 getftype("/home")
2442< Note that a type such as "link" will only be returned on
2443 systems that support it. On some systems only "dir" and
2444 "file" are returned.
2445
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 *getline()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002447getline({lnum} [, {end}])
2448 Without {end} the result is a String, which is line {lnum}
2449 from the current buffer. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 getline(1)
2451< When {lnum} is a String that doesn't start with a
2452 digit, line() is called to translate the String into a Number.
2453 To get the line under the cursor: >
2454 getline(".")
2455< When {lnum} is smaller than 1 or bigger than the number of
2456 lines in the buffer, an empty string is returned.
2457
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002458 When {end} is given the result is a List where each item is a
2459 line from the current buffer in the range {lnum} to {end},
2460 including line {end}.
2461 {end} is used in the same way as {lnum}.
2462 Non-existing lines are silently omitted.
2463 When {end} is before {lnum} an error is given.
2464 Example: >
2465 :let start = line('.')
2466 :let end = search("^$") - 1
2467 :let lines = getline(start, end)
2468
2469
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470getreg([{regname}]) *getreg()*
2471 The result is a String, which is the contents of register
2472 {regname}. Example: >
2473 :let cliptext = getreg('*')
2474< getreg('=') returns the last evaluated value of the expression
2475 register. (For use in maps).
2476 If {regname} is not specified, |v:register| is used.
2477
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002478
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479getregtype([{regname}]) *getregtype()*
2480 The result is a String, which is type of register {regname}.
2481 The value will be one of:
2482 "v" for |characterwise| text
2483 "V" for |linewise| text
2484 "<CTRL-V>{width}" for |blockwise-visual| text
2485 0 for an empty or unknown register
2486 <CTRL-V> is one character with value 0x16.
2487 If {regname} is not specified, |v:register| is used.
2488
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002489
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 *getwinposx()*
2491getwinposx() The result is a Number, which is the X coordinate in pixels of
2492 the left hand side of the GUI Vim window. The result will be
2493 -1 if the information is not available.
2494
2495 *getwinposy()*
2496getwinposy() The result is a Number, which is the Y coordinate in pixels of
2497 the top of the GUI Vim window. The result will be -1 if the
2498 information is not available.
2499
2500getwinvar({nr}, {varname}) *getwinvar()*
2501 The result is the value of option or local window variable
2502 {varname} in window {nr}.
2503 This also works for a global or local buffer option, but it
2504 doesn't work for a global or local buffer variable.
2505 Note that the name without "w:" must be used.
2506 Examples: >
2507 :let list_is_on = getwinvar(2, '&list')
2508 :echo "myvar = " . getwinvar(1, 'myvar')
2509<
2510 *glob()*
2511glob({expr}) Expand the file wildcards in {expr}. The result is a String.
2512 When there are several matches, they are separated by <NL>
2513 characters.
2514 If the expansion fails, the result is an empty string.
2515 A name for a non-existing file is not included.
2516
2517 For most systems backticks can be used to get files names from
2518 any external command. Example: >
2519 :let tagfiles = glob("`find . -name tags -print`")
2520 :let &tags = substitute(tagfiles, "\n", ",", "g")
2521< The result of the program inside the backticks should be one
2522 item per line. Spaces inside an item are allowed.
2523
2524 See |expand()| for expanding special Vim variables. See
2525 |system()| for getting the raw output of an external command.
2526
2527globpath({path}, {expr}) *globpath()*
2528 Perform glob() on all directories in {path} and concatenate
2529 the results. Example: >
2530 :echo globpath(&rtp, "syntax/c.vim")
2531< {path} is a comma-separated list of directory names. Each
2532 directory name is prepended to {expr} and expanded like with
2533 glob(). A path separator is inserted when needed.
2534 To add a comma inside a directory name escape it with a
2535 backslash. Note that on MS-Windows a directory may have a
2536 trailing backslash, remove it if you put a comma after it.
2537 If the expansion fails for one of the directories, there is no
2538 error message.
2539 The 'wildignore' option applies: Names matching one of the
2540 patterns in 'wildignore' will be skipped.
2541
2542 *has()*
2543has({feature}) The result is a Number, which is 1 if the feature {feature} is
2544 supported, zero otherwise. The {feature} argument is a
2545 string. See |feature-list| below.
2546 Also see |exists()|.
2547
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002548
2549has_key({dict}, {key}) *has_key()*
2550 The result is a Number, which is 1 if Dictionary {dict} has an
2551 entry with key {key}. Zero otherwise.
2552
2553
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554hasmapto({what} [, {mode}]) *hasmapto()*
2555 The result is a Number, which is 1 if there is a mapping that
2556 contains {what} in somewhere in the rhs (what it is mapped to)
2557 and this mapping exists in one of the modes indicated by
2558 {mode}.
2559 Both the global mappings and the mappings local to the current
2560 buffer are checked for a match.
2561 If no matching mapping is found 0 is returned.
2562 The following characters are recognized in {mode}:
2563 n Normal mode
2564 v Visual mode
2565 o Operator-pending mode
2566 i Insert mode
2567 l Language-Argument ("r", "f", "t", etc.)
2568 c Command-line mode
2569 When {mode} is omitted, "nvo" is used.
2570
2571 This function is useful to check if a mapping already exists
2572 to a function in a Vim script. Example: >
2573 :if !hasmapto('\ABCdoit')
2574 : map <Leader>d \ABCdoit
2575 :endif
2576< This installs the mapping to "\ABCdoit" only if there isn't
2577 already a mapping to "\ABCdoit".
2578
2579histadd({history}, {item}) *histadd()*
2580 Add the String {item} to the history {history} which can be
2581 one of: *hist-names*
2582 "cmd" or ":" command line history
2583 "search" or "/" search pattern history
2584 "expr" or "=" typed expression history
2585 "input" or "@" input line history
2586 If {item} does already exist in the history, it will be
2587 shifted to become the newest entry.
2588 The result is a Number: 1 if the operation was successful,
2589 otherwise 0 is returned.
2590
2591 Example: >
2592 :call histadd("input", strftime("%Y %b %d"))
2593 :let date=input("Enter date: ")
2594< This function is not available in the |sandbox|.
2595
2596histdel({history} [, {item}]) *histdel()*
2597 Clear {history}, ie. delete all its entries. See |hist-names|
2598 for the possible values of {history}.
2599
2600 If the parameter {item} is given as String, this is seen
2601 as regular expression. All entries matching that expression
2602 will be removed from the history (if there are any).
2603 Upper/lowercase must match, unless "\c" is used |/\c|.
2604 If {item} is a Number, it will be interpreted as index, see
2605 |:history-indexing|. The respective entry will be removed
2606 if it exists.
2607
2608 The result is a Number: 1 for a successful operation,
2609 otherwise 0 is returned.
2610
2611 Examples:
2612 Clear expression register history: >
2613 :call histdel("expr")
2614<
2615 Remove all entries starting with "*" from the search history: >
2616 :call histdel("/", '^\*')
2617<
2618 The following three are equivalent: >
2619 :call histdel("search", histnr("search"))
2620 :call histdel("search", -1)
2621 :call histdel("search", '^'.histget("search", -1).'$')
2622<
2623 To delete the last search pattern and use the last-but-one for
2624 the "n" command and 'hlsearch': >
2625 :call histdel("search", -1)
2626 :let @/ = histget("search", -1)
2627
2628histget({history} [, {index}]) *histget()*
2629 The result is a String, the entry with Number {index} from
2630 {history}. See |hist-names| for the possible values of
2631 {history}, and |:history-indexing| for {index}. If there is
2632 no such entry, an empty String is returned. When {index} is
2633 omitted, the most recent item from the history is used.
2634
2635 Examples:
2636 Redo the second last search from history. >
2637 :execute '/' . histget("search", -2)
2638
2639< Define an Ex command ":H {num}" that supports re-execution of
2640 the {num}th entry from the output of |:history|. >
2641 :command -nargs=1 H execute histget("cmd", 0+<args>)
2642<
2643histnr({history}) *histnr()*
2644 The result is the Number of the current entry in {history}.
2645 See |hist-names| for the possible values of {history}.
2646 If an error occurred, -1 is returned.
2647
2648 Example: >
2649 :let inp_index = histnr("expr")
2650<
2651hlexists({name}) *hlexists()*
2652 The result is a Number, which is non-zero if a highlight group
2653 called {name} exists. This is when the group has been
2654 defined in some way. Not necessarily when highlighting has
2655 been defined for it, it may also have been used for a syntax
2656 item.
2657 *highlight_exists()*
2658 Obsolete name: highlight_exists().
2659
2660 *hlID()*
2661hlID({name}) The result is a Number, which is the ID of the highlight group
2662 with name {name}. When the highlight group doesn't exist,
2663 zero is returned.
2664 This can be used to retrieve information about the highlight
2665 group. For example, to get the background color of the
2666 "Comment" group: >
2667 :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
2668< *highlightID()*
2669 Obsolete name: highlightID().
2670
2671hostname() *hostname()*
2672 The result is a String, which is the name of the machine on
2673 which Vim is currently running. Machine names greater than
2674 256 characters long are truncated.
2675
2676iconv({expr}, {from}, {to}) *iconv()*
2677 The result is a String, which is the text {expr} converted
2678 from encoding {from} to encoding {to}.
2679 When the conversion fails an empty string is returned.
2680 The encoding names are whatever the iconv() library function
2681 can accept, see ":!man 3 iconv".
2682 Most conversions require Vim to be compiled with the |+iconv|
2683 feature. Otherwise only UTF-8 to latin1 conversion and back
2684 can be done.
2685 This can be used to display messages with special characters,
2686 no matter what 'encoding' is set to. Write the message in
2687 UTF-8 and use: >
2688 echo iconv(utf8_str, "utf-8", &enc)
2689< Note that Vim uses UTF-8 for all Unicode encodings, conversion
2690 from/to UCS-2 is automatically changed to use UTF-8. You
2691 cannot use UCS-2 in a string anyway, because of the NUL bytes.
2692 {only available when compiled with the +multi_byte feature}
2693
2694 *indent()*
2695indent({lnum}) The result is a Number, which is indent of line {lnum} in the
2696 current buffer. The indent is counted in spaces, the value
2697 of 'tabstop' is relevant. {lnum} is used just like in
2698 |getline()|.
2699 When {lnum} is invalid -1 is returned.
2700
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002701
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002702index({list}, {expr} [, {start} [, {ic}]]) *index()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002703 Return the lowest index in List {list} where the item has a
2704 value equal to {expr}.
Bram Moolenaar748bf032005-02-02 23:04:36 +00002705 If {start} is given then start looking at the item with index
2706 {start} (may be negative for an item relative to the end).
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002707 When {ic} is given and it is non-zero, ignore case. Otherwise
2708 case must match.
2709 -1 is returned when {expr} is not found in {list}.
2710 Example: >
2711 :let idx = index(words, "the")
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002712 :if index(numbers, 123) >= 0
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002713
2714
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715input({prompt} [, {text}]) *input()*
2716 The result is a String, which is whatever the user typed on
2717 the command-line. The parameter is either a prompt string, or
2718 a blank string (for no prompt). A '\n' can be used in the
2719 prompt to start a new line. The highlighting set with
2720 |:echohl| is used for the prompt. The input is entered just
2721 like a command-line, with the same editing commands and
2722 mappings. There is a separate history for lines typed for
2723 input().
2724 If the optional {text} is present, this is used for the
2725 default reply, as if the user typed this.
2726 NOTE: This must not be used in a startup file, for the
2727 versions that only run in GUI mode (e.g., the Win32 GUI).
2728 Note: When input() is called from within a mapping it will
2729 consume remaining characters from that mapping, because a
2730 mapping is handled like the characters were typed.
2731 Use |inputsave()| before input() and |inputrestore()|
2732 after input() to avoid that. Another solution is to avoid
2733 that further characters follow in the mapping, e.g., by using
2734 |:execute| or |:normal|.
2735
2736 Example: >
2737 :if input("Coffee or beer? ") == "beer"
2738 : echo "Cheers!"
2739 :endif
2740< Example with default text: >
2741 :let color = input("Color? ", "white")
2742< Example with a mapping: >
2743 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
2744 :function GetFoo()
2745 : call inputsave()
2746 : let g:Foo = input("enter search pattern: ")
2747 : call inputrestore()
2748 :endfunction
2749
2750inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
2751 Like input(), but when the GUI is running and text dialogs are
2752 supported, a dialog window pops up to input the text.
2753 Example: >
2754 :let n = inputdialog("value for shiftwidth", &sw)
2755 :if n != ""
2756 : let &sw = n
2757 :endif
2758< When the dialog is cancelled {cancelreturn} is returned. When
2759 omitted an empty string is returned.
2760 Hitting <Enter> works like pressing the OK button. Hitting
2761 <Esc> works like pressing the Cancel button.
2762
2763inputrestore() *inputrestore()*
2764 Restore typeahead that was saved with a previous inputsave().
2765 Should be called the same number of times inputsave() is
2766 called. Calling it more often is harmless though.
2767 Returns 1 when there is nothing to restore, 0 otherwise.
2768
2769inputsave() *inputsave()*
2770 Preserve typeahead (also from mappings) and clear it, so that
2771 a following prompt gets input from the user. Should be
2772 followed by a matching inputrestore() after the prompt. Can
2773 be used several times, in which case there must be just as
2774 many inputrestore() calls.
2775 Returns 1 when out of memory, 0 otherwise.
2776
2777inputsecret({prompt} [, {text}]) *inputsecret()*
2778 This function acts much like the |input()| function with but
2779 two exceptions:
2780 a) the user's response will be displayed as a sequence of
2781 asterisks ("*") thereby keeping the entry secret, and
2782 b) the user's response will not be recorded on the input
2783 |history| stack.
2784 The result is a String, which is whatever the user actually
2785 typed on the command-line in response to the issued prompt.
2786
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002787insert({list}, {item} [, {idx}]) *insert()*
2788 Insert {item} at the start of List {list}.
2789 If {idx} is specified insert {item} before the item with index
2790 {idx}. If {idx} is zero it goes before the first item, just
2791 like omitting {idx}. A negative {idx} is also possible, see
2792 |list-index|. -1 inserts just before the last item.
2793 Returns the resulting List. Examples: >
2794 :let mylist = insert([2, 3, 5], 1)
2795 :call insert(mylist, 4, -1)
2796 :call insert(mylist, 6, len(mylist))
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002797< The last example can be done simpler with |add()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002798 Note that when {item} is a List it is inserted as a single
2799 item. Use |extend()| to concatenate Lists.
2800
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801isdirectory({directory}) *isdirectory()*
2802 The result is a Number, which is non-zero when a directory
2803 with the name {directory} exists. If {directory} doesn't
2804 exist, or isn't a directory, the result is FALSE. {directory}
2805 is any expression, which is used as a String.
2806
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002807islocked({expr}) *islocked()*
2808 The result is a Number, which is non-zero when {expr} is the
2809 name of a locked variable.
2810 {expr} must be the name of a variable, List item or Dictionary
2811 entry, not the variable itself! Example: >
2812 :let alist = [0, ['a', 'b'], 2, 3]
2813 :lockvar 1 alist
2814 :echo islocked('alist') " 1
2815 :echo islocked('alist[1]') " 0
2816
2817< When {expr} is a variable that does not exist you get an error
2818 message. Use |exists()| to check for existance.
2819
Bram Moolenaar677ee682005-01-27 14:41:15 +00002820items({dict}) *items()*
2821 Return a List with all the key-value pairs of {dict}. Each
2822 List item is a list with two items: the key of a {dict} entry
2823 and the value of this entry. The List is in arbitrary order.
2824
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002825
2826join({list} [, {sep}]) *join()*
2827 Join the items in {list} together into one String.
2828 When {sep} is specified it is put in between the items. If
2829 {sep} is omitted a single space is used.
2830 Note that {sep} is not added at the end. You might want to
2831 add it there too: >
2832 let lines = join(mylist, "\n") . "\n"
2833< String items are used as-is. Lists and Dictionaries are
2834 converted into a string like with |string()|.
2835 The opposite function is |split()|.
2836
Bram Moolenaard8b02732005-01-14 21:48:43 +00002837keys({dict}) *keys()*
2838 Return a List with all the keys of {dict}. The List is in
2839 arbitrary order.
2840
Bram Moolenaar13065c42005-01-08 16:08:21 +00002841 *len()* *E701*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002842len({expr}) The result is a Number, which is the length of the argument.
2843 When {expr} is a String or a Number the length in bytes is
2844 used, as with |strlen()|.
2845 When {expr} is a List the number of items in the List is
2846 returned.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002847 When {expr} is a Dictionary the number of entries in the
2848 Dictionary is returned.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002849 Otherwise an error is given.
2850
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 *libcall()* *E364* *E368*
2852libcall({libname}, {funcname}, {argument})
2853 Call function {funcname} in the run-time library {libname}
2854 with single argument {argument}.
2855 This is useful to call functions in a library that you
2856 especially made to be used with Vim. Since only one argument
2857 is possible, calling standard library functions is rather
2858 limited.
2859 The result is the String returned by the function. If the
2860 function returns NULL, this will appear as an empty string ""
2861 to Vim.
2862 If the function returns a number, use libcallnr()!
2863 If {argument} is a number, it is passed to the function as an
2864 int; if {argument} is a string, it is passed as a
2865 null-terminated string.
2866 This function will fail in |restricted-mode|.
2867
2868 libcall() allows you to write your own 'plug-in' extensions to
2869 Vim without having to recompile the program. It is NOT a
2870 means to call system functions! If you try to do so Vim will
2871 very probably crash.
2872
2873 For Win32, the functions you write must be placed in a DLL
2874 and use the normal C calling convention (NOT Pascal which is
2875 used in Windows System DLLs). The function must take exactly
2876 one parameter, either a character pointer or a long integer,
2877 and must return a character pointer or NULL. The character
2878 pointer returned must point to memory that will remain valid
2879 after the function has returned (e.g. in static data in the
2880 DLL). If it points to allocated memory, that memory will
2881 leak away. Using a static buffer in the function should work,
2882 it's then freed when the DLL is unloaded.
2883
2884 WARNING: If the function returns a non-valid pointer, Vim may
2885 crash! This also happens if the function returns a number,
2886 because Vim thinks it's a pointer.
2887 For Win32 systems, {libname} should be the filename of the DLL
2888 without the ".DLL" suffix. A full path is only required if
2889 the DLL is not in the usual places.
2890 For Unix: When compiling your own plugins, remember that the
2891 object code must be compiled as position-independent ('PIC').
2892 {only in Win32 on some Unix versions, when the |+libcall|
2893 feature is present}
2894 Examples: >
2895 :echo libcall("libc.so", "getenv", "HOME")
2896 :echo libcallnr("/usr/lib/libc.so", "getpid", "")
2897<
2898 *libcallnr()*
2899libcallnr({libname}, {funcname}, {argument})
2900 Just like libcall(), but used for a function that returns an
2901 int instead of a string.
2902 {only in Win32 on some Unix versions, when the |+libcall|
2903 feature is present}
2904 Example (not very useful...): >
2905 :call libcallnr("libc.so", "printf", "Hello World!\n")
2906 :call libcallnr("libc.so", "sleep", 10)
2907<
2908 *line()*
2909line({expr}) The result is a Number, which is the line number of the file
2910 position given with {expr}. The accepted positions are:
2911 . the cursor position
2912 $ the last line in the current buffer
2913 'x position of mark x (if the mark is not set, 0 is
2914 returned)
2915 Note that only marks in the current file can be used.
2916 Examples: >
2917 line(".") line number of the cursor
2918 line("'t") line number of mark t
2919 line("'" . marker) line number of mark marker
2920< *last-position-jump*
2921 This autocommand jumps to the last known position in a file
2922 just after opening it, if the '" mark is set: >
2923 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002924
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925line2byte({lnum}) *line2byte()*
2926 Return the byte count from the start of the buffer for line
2927 {lnum}. This includes the end-of-line character, depending on
2928 the 'fileformat' option for the current buffer. The first
2929 line returns 1.
2930 This can also be used to get the byte count for the line just
2931 below the last line: >
2932 line2byte(line("$") + 1)
2933< This is the file size plus one.
2934 When {lnum} is invalid, or the |+byte_offset| feature has been
2935 disabled at compile time, -1 is returned.
2936 Also see |byte2line()|, |go| and |:goto|.
2937
2938lispindent({lnum}) *lispindent()*
2939 Get the amount of indent for line {lnum} according the lisp
2940 indenting rules, as with 'lisp'.
2941 The indent is counted in spaces, the value of 'tabstop' is
2942 relevant. {lnum} is used just like in |getline()|.
2943 When {lnum} is invalid or Vim was not compiled the
2944 |+lispindent| feature, -1 is returned.
2945
2946localtime() *localtime()*
2947 Return the current time, measured as seconds since 1st Jan
2948 1970. See also |strftime()| and |getftime()|.
2949
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002950
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002951map({expr}, {string}) *map()*
2952 {expr} must be a List or a Dictionary.
2953 Replace each item in {expr} with the result of evaluating
2954 {string}.
2955 Inside {string} |v:val| has the value of the current item.
2956 For a Dictionary |v:key| has the key of the current item.
2957 Example: >
2958 :call map(mylist, '"> " . v:val . " <"')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002959< This puts "> " before and " <" after each item in "mylist".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002960
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002961 Note that {string} is the result of an expression and is then
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002962 used as an expression again. Often it is good to use a
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002963 |literal-string| to avoid having to double backslashes. You
2964 still have to double ' quotes
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002965
2966 The operation is done in-place. If you want a List or
2967 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002968 :let tlist = map(copy(mylist), ' & . "\t"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002969
2970< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002971
2972
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973maparg({name}[, {mode}]) *maparg()*
2974 Return the rhs of mapping {name} in mode {mode}. When there
2975 is no mapping for {name}, an empty String is returned.
2976 These characters can be used for {mode}:
2977 "n" Normal
2978 "v" Visual
2979 "o" Operator-pending
2980 "i" Insert
2981 "c" Cmd-line
2982 "l" langmap |language-mapping|
2983 "" Normal, Visual and Operator-pending
2984 When {mode} is omitted, the modes from "" are used.
2985 The {name} can have special key names, like in the ":map"
2986 command. The returned String has special characters
2987 translated like in the output of the ":map" command listing.
2988 The mappings local to the current buffer are checked first,
2989 then the global mappings.
2990
2991mapcheck({name}[, {mode}]) *mapcheck()*
2992 Check if there is a mapping that matches with {name} in mode
2993 {mode}. See |maparg()| for {mode} and special names in
2994 {name}.
2995 A match happens with a mapping that starts with {name} and
2996 with a mapping which is equal to the start of {name}.
2997
2998 matches mapping "a" "ab" "abc" ~
2999 mapcheck("a") yes yes yes
3000 mapcheck("abc") yes yes yes
3001 mapcheck("ax") yes no no
3002 mapcheck("b") no no no
3003
3004 The difference with maparg() is that mapcheck() finds a
3005 mapping that matches with {name}, while maparg() only finds a
3006 mapping for {name} exactly.
3007 When there is no mapping that starts with {name}, an empty
3008 String is returned. If there is one, the rhs of that mapping
3009 is returned. If there are several mappings that start with
3010 {name}, the rhs of one of them is returned.
3011 The mappings local to the current buffer are checked first,
3012 then the global mappings.
3013 This function can be used to check if a mapping can be added
3014 without being ambiguous. Example: >
3015 :if mapcheck("_vv") == ""
3016 : map _vv :set guifont=7x13<CR>
3017 :endif
3018< This avoids adding the "_vv" mapping when there already is a
3019 mapping for "_v" or for "_vvv".
3020
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003021match({expr}, {pat}[, {start}[, {count}]]) *match()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003022 When {expr} is a List then this returns the index of the first
3023 item where {pat} matches. Each item is used as a String,
3024 Lists and Dictionaries are used as echoed.
3025 Otherwise, {expr} is used as a String. The result is a
3026 Number, which gives the index (byte offset) in {expr} where
3027 {pat} matches.
3028 A match at the first character or List item returns zero.
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003029 If there is no match -1 is returned.
3030 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003031 :echo match("testing", "ing") " results in 4
3032 :echo match([1, 'x'], '\a') " results in 2
3033< See |string-match| for how {pat} is used.
3034
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003035 When {count} is given use the {count}'th match. When a match
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003036 is found in a String the search for the next one starts on
3037 character further. Thus this example results in 1: >
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003038 echo match("testing", "..", 0, 2)
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003039< In a List the search continues in the next item.
3040
3041 If {start} is given, the search starts from byte index
3042 {start} in a String or item {start} in a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 The result, however, is still the index counted from the
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003044 first character/item. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 :echo match("testing", "ing", 2)
3046< result is again "4". >
3047 :echo match("testing", "ing", 4)
3048< result is again "4". >
3049 :echo match("testing", "t", 2)
3050< result is "3".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003051 For a String, if {start} < 0, it will be set to 0. For a list
3052 the index is counted from the end.
3053 If {start} is out of range (> strlen({expr} for a String or
3054 > len({expr} for a List) -1 is returned.
3055
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 See |pattern| for the patterns that are accepted.
3057 The 'ignorecase' option is used to set the ignore-caseness of
3058 the pattern. 'smartcase' is NOT used. The matching is always
3059 done like 'magic' is set and 'cpoptions' is empty.
3060
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003061matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 Same as match(), but return the index of first character after
3063 the match. Example: >
3064 :echo matchend("testing", "ing")
3065< results in "7".
3066 The {start}, if given, has the same meaning as for match(). >
3067 :echo matchend("testing", "ing", 2)
3068< results in "7". >
3069 :echo matchend("testing", "ing", 5)
3070< result is "-1".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003071 When {expr} is a List the result is equal to match().
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003073matchlist({expr}, {pat}[, {start}[, {count}]]) *matchlist()*
3074 Same as match(), but return a List. The first item in the
3075 list is the matched string, same as what matchstr() would
3076 return. Following items are submatches, like "\1", "\2", etc.
3077 in |:substitute|.
3078 When there is no match an empty list is returned.
3079
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003080matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 Same as match(), but return the matched string. Example: >
3082 :echo matchstr("testing", "ing")
3083< results in "ing".
3084 When there is no match "" is returned.
3085 The {start}, if given, has the same meaning as for match(). >
3086 :echo matchstr("testing", "ing", 2)
3087< results in "ing". >
3088 :echo matchstr("testing", "ing", 5)
3089< result is "".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003090 When {expr} is a List then the matching item is returned.
3091 The type isn't changed, it's not necessarily a String.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003093 *max()*
3094max({list}) Return the maximum value of all items in {list}.
3095 If {list} is not a list or one of the items in {list} cannot
3096 be used as a Number this results in an error.
3097 An empty List results in zero.
3098
3099 *min()*
3100min({list}) Return the minumum value of all items in {list}.
3101 If {list} is not a list or one of the items in {list} cannot
3102 be used as a Number this results in an error.
3103 An empty List results in zero.
3104
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003105 *mkdir()* *E749*
3106mkdir({name} [, {path} [, {prot}]])
3107 Create directory {name}.
3108 If {path} is "p" then intermediate directories are created as
3109 necessary. Otherwise it must be "".
3110 If {prot} is given it is used to set the protection bits of
3111 the new directory. The default is 0755 (rwxr-xr-x: r/w for
3112 the user readable for others). Use 0700 to make it unreadable
3113 for others.
3114 This function is not available in the |sandbox|.
3115 Not available on all systems. To check use: >
3116 :if exists("*mkdir")
3117<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 *mode()*
3119mode() Return a string that indicates the current mode:
3120 n Normal
3121 v Visual by character
3122 V Visual by line
3123 CTRL-V Visual blockwise
3124 s Select by character
3125 S Select by line
3126 CTRL-S Select blockwise
3127 i Insert
3128 R Replace
3129 c Command-line
3130 r Hit-enter prompt
3131 This is useful in the 'statusline' option. In most other
3132 places it always returns "c" or "n".
3133
3134nextnonblank({lnum}) *nextnonblank()*
3135 Return the line number of the first line at or below {lnum}
3136 that is not blank. Example: >
3137 if getline(nextnonblank(1)) =~ "Java"
3138< When {lnum} is invalid or there is no non-blank line at or
3139 below it, zero is returned.
3140 See also |prevnonblank()|.
3141
3142nr2char({expr}) *nr2char()*
3143 Return a string with a single character, which has the number
3144 value {expr}. Examples: >
3145 nr2char(64) returns "@"
3146 nr2char(32) returns " "
3147< The current 'encoding' is used. Example for "utf-8": >
3148 nr2char(300) returns I with bow character
3149< Note that a NUL character in the file is specified with
3150 nr2char(10), because NULs are represented with newline
3151 characters. nr2char(0) is a real NUL and terminates the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003152 string, thus results in an empty string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153
3154prevnonblank({lnum}) *prevnonblank()*
3155 Return the line number of the first line at or above {lnum}
3156 that is not blank. Example: >
3157 let ind = indent(prevnonblank(v:lnum - 1))
3158< When {lnum} is invalid or there is no non-blank line at or
3159 above it, zero is returned.
3160 Also see |nextnonblank()|.
3161
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003162 *E726* *E727*
Bram Moolenaard8b02732005-01-14 21:48:43 +00003163range({expr} [, {max} [, {stride}]]) *range()*
3164 Returns a List with Numbers:
3165 - If only {expr} is specified: [0, 1, ..., {expr} - 1]
3166 - If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
3167 - If {stride} is specified: [{expr}, {expr} + {stride}, ...,
3168 {max}] (increasing {expr} with {stride} each time, not
3169 producing a value past {max}).
3170 Examples: >
3171 range(4) " [0, 1, 2, 3]
3172 range(2, 4) " [2, 3, 4]
3173 range(2, 9, 3) " [2, 5, 8]
3174 range(2, -2, -1) " [2, 1, 0, -1, -2]
3175<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003176 *readfile()*
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003177readfile({fname} [, {binary} [, {max}]])
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003178 Read file {fname} and return a List, each line of the file as
3179 an item. Lines broken at NL characters. Macintosh files
3180 separated with CR will result in a single long line (unless a
3181 NL appears somewhere).
3182 When {binary} is equal to "b" binary mode is used:
3183 - When the last line ends in a NL an extra empty list item is
3184 added.
3185 - No CR characters are removed.
3186 Otherwise:
3187 - CR characters that appear before a NL are removed.
3188 - Whether the last line ends in a NL or not does not matter.
3189 All NUL characters are replaced with a NL character.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003190 When {max} is given this specifies the maximum number of lines
3191 to be read. Useful if you only want to check the first ten
3192 lines of a file: >
3193 :for line in readfile(fname, '', 10)
3194 : if line =~ 'Date' | echo line | endif
3195 :endfor
3196< When {max} is zero or negative the result is an empty list.
3197 Note that without {max} the whole file is read into memory.
3198 Also note that there is no recognition of encoding. Read a
3199 file into a buffer if you need to.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003200 When the file can't be opened an error message is given and
3201 the result is an empty list.
3202 Also see |writefile()|.
3203
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 *remote_expr()* *E449*
3205remote_expr({server}, {string} [, {idvar}])
3206 Send the {string} to {server}. The string is sent as an
3207 expression and the result is returned after evaluation.
3208 If {idvar} is present, it is taken as the name of a
3209 variable and a {serverid} for later use with
3210 remote_read() is stored there.
3211 See also |clientserver| |RemoteReply|.
3212 This function is not available in the |sandbox|.
3213 {only available when compiled with the |+clientserver| feature}
3214 Note: Any errors will cause a local error message to be issued
3215 and the result will be the empty string.
3216 Examples: >
3217 :echo remote_expr("gvim", "2+2")
3218 :echo remote_expr("gvim1", "b:current_syntax")
3219<
3220
3221remote_foreground({server}) *remote_foreground()*
3222 Move the Vim server with the name {server} to the foreground.
3223 This works like: >
3224 remote_expr({server}, "foreground()")
3225< Except that on Win32 systems the client does the work, to work
3226 around the problem that the OS doesn't always allow the server
3227 to bring itself to the foreground.
3228 This function is not available in the |sandbox|.
3229 {only in the Win32, Athena, Motif and GTK GUI versions and the
3230 Win32 console version}
3231
3232
3233remote_peek({serverid} [, {retvar}]) *remote_peek()*
3234 Returns a positive number if there are available strings
3235 from {serverid}. Copies any reply string into the variable
3236 {retvar} if specified. {retvar} must be a string with the
3237 name of a variable.
3238 Returns zero if none are available.
3239 Returns -1 if something is wrong.
3240 See also |clientserver|.
3241 This function is not available in the |sandbox|.
3242 {only available when compiled with the |+clientserver| feature}
3243 Examples: >
3244 :let repl = ""
3245 :echo "PEEK: ".remote_peek(id, "repl").": ".repl
3246
3247remote_read({serverid}) *remote_read()*
3248 Return the oldest available reply from {serverid} and consume
3249 it. It blocks until a reply is available.
3250 See also |clientserver|.
3251 This function is not available in the |sandbox|.
3252 {only available when compiled with the |+clientserver| feature}
3253 Example: >
3254 :echo remote_read(id)
3255<
3256 *remote_send()* *E241*
3257remote_send({server}, {string} [, {idvar}])
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003258 Send the {string} to {server}. The string is sent as input
3259 keys and the function returns immediately. At the Vim server
3260 the keys are not mapped |:map|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 If {idvar} is present, it is taken as the name of a
3262 variable and a {serverid} for later use with
3263 remote_read() is stored there.
3264 See also |clientserver| |RemoteReply|.
3265 This function is not available in the |sandbox|.
3266 {only available when compiled with the |+clientserver| feature}
3267 Note: Any errors will be reported in the server and may mess
3268 up the display.
3269 Examples: >
3270 :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
3271 \ remote_read(serverid)
3272
3273 :autocmd NONE RemoteReply *
3274 \ echo remote_read(expand("<amatch>"))
3275 :echo remote_send("gvim", ":sleep 10 | echo ".
3276 \ 'server2client(expand("<client>"), "HELLO")<CR>')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003277<
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003278remove({list}, {idx} [, {end}]) *remove()*
3279 Without {end}: Remove the item at {idx} from List {list} and
3280 return it.
3281 With {end}: Remove items from {idx} to {end} (inclusive) and
3282 return a list with these items. When {idx} points to the same
3283 item as {end} a list with one item is returned. When {end}
3284 points to an item before {idx} this is an error.
3285 See |list-index| for possible values of {idx} and {end}.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003286 Example: >
3287 :echo "last item: " . remove(mylist, -1)
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003288 :call remove(mylist, 0, 9)
Bram Moolenaard8b02732005-01-14 21:48:43 +00003289remove({dict}, {key})
3290 Remove the entry from {dict} with key {key}. Example: >
3291 :echo "removed " . remove(dict, "one")
3292< If there is no {key} in {dict} this is an error.
3293
3294 Use |delete()| to remove a file.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003295
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296rename({from}, {to}) *rename()*
3297 Rename the file by the name {from} to the name {to}. This
3298 should also work to move files across file systems. The
3299 result is a Number, which is 0 if the file was renamed
3300 successfully, and non-zero when the renaming failed.
3301 This function is not available in the |sandbox|.
3302
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003303repeat({expr}, {count}) *repeat()*
3304 Repeat {expr} {count} times and return the concatenated
3305 result. Example: >
3306 :let seperator = repeat('-', 80)
3307< When {count} is zero or negative the result is empty.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003308 When {expr} is a List the result is {expr} concatenated
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003309 {count} times. Example: >
3310 :let longlist = repeat(['a', 'b'], 3)
3311< Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003312
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003313
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314resolve({filename}) *resolve()* *E655*
3315 On MS-Windows, when {filename} is a shortcut (a .lnk file),
3316 returns the path the shortcut points to in a simplified form.
3317 On Unix, repeat resolving symbolic links in all path
3318 components of {filename} and return the simplified result.
3319 To cope with link cycles, resolving of symbolic links is
3320 stopped after 100 iterations.
3321 On other systems, return the simplified {filename}.
3322 The simplification step is done as by |simplify()|.
3323 resolve() keeps a leading path component specifying the
3324 current directory (provided the result is still a relative
3325 path name) and also keeps a trailing path separator.
3326
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003327 *reverse()*
3328reverse({list}) Reverse the order of items in {list} in-place. Returns
3329 {list}.
3330 If you want a list to remain unmodified make a copy first: >
3331 :let revlist = reverse(copy(mylist))
3332
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333search({pattern} [, {flags}]) *search()*
3334 Search for regexp pattern {pattern}. The search starts at the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003335 cursor position (you can use |cursor()| to set it).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 {flags} is a String, which can contain these character flags:
3337 'b' search backward instead of forward
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003338 'n' do Not move the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 'w' wrap around the end of the file
3340 'W' don't wrap around the end of the file
3341 If neither 'w' or 'W' is given, the 'wrapscan' option applies.
3342
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003343 When a match has been found its line number is returned.
3344 The cursor will be positioned at the match, unless the 'n'
3345 flag is used).
3346 If there is no match a 0 is returned and the cursor doesn't
3347 move. No error message is given.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348
3349 Example (goes over all files in the argument list): >
3350 :let n = 1
3351 :while n <= argc() " loop over all files in arglist
3352 : exe "argument " . n
3353 : " start at the last char in the file and wrap for the
3354 : " first search to find match at start of file
3355 : normal G$
3356 : let flags = "w"
3357 : while search("foo", flags) > 0
3358 : s/foo/bar/g
3359 : let flags = "W"
3360 : endwhile
3361 : update " write the file if modified
3362 : let n = n + 1
3363 :endwhile
3364<
3365 *searchpair()*
3366searchpair({start}, {middle}, {end} [, {flags} [, {skip}]])
3367 Search for the match of a nested start-end pair. This can be
3368 used to find the "endif" that matches an "if", while other
3369 if/endif pairs in between are ignored.
3370 The search starts at the cursor. If a match is found, the
3371 cursor is positioned at it and the line number is returned.
3372 If no match is found 0 or -1 is returned and the cursor
3373 doesn't move. No error message is given.
3374
3375 {start}, {middle} and {end} are patterns, see |pattern|. They
3376 must not contain \( \) pairs. Use of \%( \) is allowed. When
3377 {middle} is not empty, it is found when searching from either
3378 direction, but only when not in a nested start-end pair. A
3379 typical use is: >
3380 searchpair('\<if\>', '\<else\>', '\<endif\>')
3381< By leaving {middle} empty the "else" is skipped.
3382
3383 {flags} are used like with |search()|. Additionally:
3384 'n' do Not move the cursor
3385 'r' Repeat until no more matches found; will find the
3386 outer pair
3387 'm' return number of Matches instead of line number with
3388 the match; will only be > 1 when 'r' is used.
3389
3390 When a match for {start}, {middle} or {end} is found, the
3391 {skip} expression is evaluated with the cursor positioned on
3392 the start of the match. It should return non-zero if this
3393 match is to be skipped. E.g., because it is inside a comment
3394 or a string.
3395 When {skip} is omitted or empty, every match is accepted.
3396 When evaluating {skip} causes an error the search is aborted
3397 and -1 returned.
3398
3399 The value of 'ignorecase' is used. 'magic' is ignored, the
3400 patterns are used like it's on.
3401
3402 The search starts exactly at the cursor. A match with
3403 {start}, {middle} or {end} at the next character, in the
3404 direction of searching, is the first one found. Example: >
3405 if 1
3406 if 2
3407 endif 2
3408 endif 1
3409< When starting at the "if 2", with the cursor on the "i", and
3410 searching forwards, the "endif 2" is found. When starting on
3411 the character just before the "if 2", the "endif 1" will be
3412 found. That's because the "if 2" will be found first, and
3413 then this is considered to be a nested if/endif from "if 2" to
3414 "endif 2".
3415 When searching backwards and {end} is more than one character,
3416 it may be useful to put "\zs" at the end of the pattern, so
3417 that when the cursor is inside a match with the end it finds
3418 the matching start.
3419
3420 Example, to find the "endif" command in a Vim script: >
3421
3422 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
3423 \ 'getline(".") =~ "^\\s*\""')
3424
3425< The cursor must be at or after the "if" for which a match is
3426 to be found. Note that single-quote strings are used to avoid
3427 having to double the backslashes. The skip expression only
3428 catches comments at the start of a line, not after a command.
3429 Also, a word "en" or "if" halfway a line is considered a
3430 match.
3431 Another example, to search for the matching "{" of a "}": >
3432
3433 :echo searchpair('{', '', '}', 'bW')
3434
3435< This works when the cursor is at or before the "}" for which a
3436 match is to be found. To reject matches that syntax
3437 highlighting recognized as strings: >
3438
3439 :echo searchpair('{', '', '}', 'bW',
3440 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
3441<
3442server2client( {clientid}, {string}) *server2client()*
3443 Send a reply string to {clientid}. The most recent {clientid}
3444 that sent a string can be retrieved with expand("<client>").
3445 {only available when compiled with the |+clientserver| feature}
3446 Note:
3447 This id has to be stored before the next command can be
3448 received. Ie. before returning from the received command and
3449 before calling any commands that waits for input.
3450 See also |clientserver|.
3451 Example: >
3452 :echo server2client(expand("<client>"), "HELLO")
3453<
3454serverlist() *serverlist()*
3455 Return a list of available server names, one per line.
3456 When there are no servers or the information is not available
3457 an empty string is returned. See also |clientserver|.
3458 {only available when compiled with the |+clientserver| feature}
3459 Example: >
3460 :echo serverlist()
3461<
3462setbufvar({expr}, {varname}, {val}) *setbufvar()*
3463 Set option or local variable {varname} in buffer {expr} to
3464 {val}.
3465 This also works for a global or local window option, but it
3466 doesn't work for a global or local window variable.
3467 For a local window option the global value is unchanged.
3468 For the use of {expr}, see |bufname()| above.
3469 Note that the variable name without "b:" must be used.
3470 Examples: >
3471 :call setbufvar(1, "&mod", 1)
3472 :call setbufvar("todo", "myvar", "foobar")
3473< This function is not available in the |sandbox|.
3474
3475setcmdpos({pos}) *setcmdpos()*
3476 Set the cursor position in the command line to byte position
3477 {pos}. The first position is 1.
3478 Use |getcmdpos()| to obtain the current position.
3479 Only works while editing the command line, thus you must use
Bram Moolenaard8b02732005-01-14 21:48:43 +00003480 |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
3481 |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
3482 set after the command line is set to the expression. For
3483 |c_CTRL-R_=| it is set after evaluating the expression but
3484 before inserting the resulting text.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 When the number is too big the cursor is put at the end of the
3486 line. A number smaller than one has undefined results.
3487 Returns 0 when successful, 1 when not editing the command
3488 line.
3489
3490setline({lnum}, {line}) *setline()*
3491 Set line {lnum} of the current buffer to {line}. If this
3492 succeeds, 0 is returned. If this fails (most likely because
3493 {lnum} is invalid) 1 is returned. Example: >
3494 :call setline(5, strftime("%c"))
3495< Note: The '[ and '] marks are not set.
3496
3497 *setreg()*
3498setreg({regname}, {value} [,{options}])
3499 Set the register {regname} to {value}.
3500 If {options} contains "a" or {regname} is upper case,
3501 then the value is appended.
3502 {options} can also contains a register type specification:
3503 "c" or "v" |characterwise| mode
3504 "l" or "V" |linewise| mode
3505 "b" or "<CTRL-V>" |blockwise-visual| mode
3506 If a number immediately follows "b" or "<CTRL-V>" then this is
3507 used as the width of the selection - if it is not specified
3508 then the width of the block is set to the number of characters
3509 in the longest line (counting a <TAB> as 1 character).
3510
3511 If {options} contains no register settings, then the default
3512 is to use character mode unless {value} ends in a <NL>.
3513 Setting the '=' register is not possible.
3514 Returns zero for success, non-zero for failure.
3515
3516 Examples: >
3517 :call setreg(v:register, @*)
3518 :call setreg('*', @%, 'ac')
3519 :call setreg('a', "1\n2\n3", 'b5')
3520
3521< This example shows using the functions to save and restore a
3522 register. >
3523 :let var_a = getreg('a')
3524 :let var_amode = getregtype('a')
3525 ....
3526 :call setreg('a', var_a, var_amode)
3527
3528< You can also change the type of a register by appending
3529 nothing: >
3530 :call setreg('a', '', 'al')
3531
3532setwinvar({nr}, {varname}, {val}) *setwinvar()*
3533 Set option or local variable {varname} in window {nr} to
3534 {val}.
3535 This also works for a global or local buffer option, but it
3536 doesn't work for a global or local buffer variable.
3537 For a local buffer option the global value is unchanged.
3538 Note that the variable name without "w:" must be used.
3539 Examples: >
3540 :call setwinvar(1, "&list", 0)
3541 :call setwinvar(2, "myvar", "foobar")
3542< This function is not available in the |sandbox|.
3543
3544simplify({filename}) *simplify()*
3545 Simplify the file name as much as possible without changing
3546 the meaning. Shortcuts (on MS-Windows) or symbolic links (on
3547 Unix) are not resolved. If the first path component in
3548 {filename} designates the current directory, this will be
3549 valid for the result as well. A trailing path separator is
3550 not removed either.
3551 Example: >
3552 simplify("./dir/.././/file/") == "./file/"
3553< Note: The combination "dir/.." is only removed if "dir" is
3554 a searchable directory or does not exist. On Unix, it is also
3555 removed when "dir" is a symbolic link within the same
3556 directory. In order to resolve all the involved symbolic
3557 links before simplifying the path name, use |resolve()|.
3558
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003559
Bram Moolenaar13065c42005-01-08 16:08:21 +00003560sort({list} [, {func}]) *sort()* *E702*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003561 Sort the items in {list} in-place. Returns {list}. If you
3562 want a list to remain unmodified make a copy first: >
3563 :let sortedlist = sort(copy(mylist))
3564< Uses the string representation of each item to sort on.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003565 Numbers sort after Strings, Lists after Numbers.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003566 When {func} is given and it is one then case is ignored.
3567 When {func} is a Funcref or a function name, this function is
3568 called to compare items. The function is invoked with two
3569 items as argument and must return zero if they are equal, 1 if
3570 the first one sorts after the second one, -1 if the first one
3571 sorts before the second one. Example: >
3572 func MyCompare(i1, i2)
3573 return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
3574 endfunc
3575 let sortedlist = sort(mylist, "MyCompare")
3576
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003577split({expr} [, {pattern}]) *split()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003578 Make a List out of {expr}. When {pattern} is omitted each
3579 white-separated sequence of characters becomes an item.
3580 Otherwise the string is split where {pattern} matches,
3581 removing the matched characters. Empty strings are omitted.
3582 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003583 :let words = split(getline('.'), '\W\+')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003584< Since empty strings are not added the "\+" isn't required but
3585 it makes the function work a bit faster.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003586 The opposite function is |join()|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003587
3588
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589strftime({format} [, {time}]) *strftime()*
3590 The result is a String, which is a formatted date and time, as
3591 specified by the {format} string. The given {time} is used,
3592 or the current time if no time is given. The accepted
3593 {format} depends on your system, thus this is not portable!
3594 See the manual page of the C function strftime() for the
3595 format. The maximum length of the result is 80 characters.
3596 See also |localtime()| and |getftime()|.
3597 The language can be changed with the |:language| command.
3598 Examples: >
3599 :echo strftime("%c") Sun Apr 27 11:49:23 1997
3600 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
3601 :echo strftime("%y%m%d %T") 970427 11:53:55
3602 :echo strftime("%H:%M") 11:55
3603 :echo strftime("%c", getftime("file.c"))
3604 Show mod time of file.c.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003605< Not available on all systems. To check use: >
3606 :if exists("*strftime")
3607
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003608stridx({haystack}, {needle} [, {start}]) *stridx()*
3609 The result is a Number, which gives the byte index in
3610 {haystack} of the first occurrence of the String {needle}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003611 If {start} is specified, the search starts at index {start}.
3612 This can be used to find a second match: >
3613 :let comma1 = stridx(line, ",")
3614 :let comma2 = stridx(line, ",", comma1 + 1)
3615< The search is done case-sensitive.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003616 For pattern searches use |match()|.
3617 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003618 See also |strridx()|.
3619 Examples: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620 :echo stridx("An Example", "Example") 3
3621 :echo stridx("Starting point", "Start") 0
3622 :echo stridx("Starting point", "start") -1
3623<
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003624 *string()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003625string({expr}) Return {expr} converted to a String. If {expr} is a Number,
3626 String or a composition of them, then the result can be parsed
3627 back with |eval()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003628 {expr} type result ~
Bram Moolenaard8b02732005-01-14 21:48:43 +00003629 String 'string'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003630 Number 123
Bram Moolenaard8b02732005-01-14 21:48:43 +00003631 Funcref function('name')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003632 List [item, item]
Bram Moolenaard8b02732005-01-14 21:48:43 +00003633 Note that in String values the ' character is doubled.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003634
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 *strlen()*
3636strlen({expr}) The result is a Number, which is the length of the String
3637 {expr} in bytes. If you want to count the number of
3638 multi-byte characters use something like this: >
3639
3640 :let len = strlen(substitute(str, ".", "x", "g"))
3641
3642< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003643 If the argument is a Number it is first converted to a String.
3644 For other types an error is given.
3645 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646
3647strpart({src}, {start}[, {len}]) *strpart()*
3648 The result is a String, which is part of {src}, starting from
3649 byte {start}, with the length {len}.
3650 When non-existing bytes are included, this doesn't result in
3651 an error, the bytes are simply omitted.
3652 If {len} is missing, the copy continues from {start} till the
3653 end of the {src}. >
3654 strpart("abcdefg", 3, 2) == "de"
3655 strpart("abcdefg", -2, 4) == "ab"
3656 strpart("abcdefg", 5, 4) == "fg"
3657 strpart("abcdefg", 3) == "defg"
3658< Note: To get the first character, {start} must be 0. For
3659 example, to get three bytes under and after the cursor: >
3660 strpart(getline(line(".")), col(".") - 1, 3)
3661<
Bram Moolenaar677ee682005-01-27 14:41:15 +00003662strridx({haystack}, {needle} [, {start}]) *strridx()*
3663 The result is a Number, which gives the byte index in
3664 {haystack} of the last occurrence of the String {needle}.
3665 When {start} is specified, matches beyond this index are
3666 ignored. This can be used to find a match before a previous
3667 match: >
3668 :let lastcomma = strridx(line, ",")
3669 :let comma2 = strridx(line, ",", lastcomma - 1)
3670< The search is done case-sensitive.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003671 For pattern searches use |match()|.
3672 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003673 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 See also |stridx()|. Examples: >
3675 :echo strridx("an angry armadillo", "an") 3
3676<
3677strtrans({expr}) *strtrans()*
3678 The result is a String, which is {expr} with all unprintable
3679 characters translated into printable characters |'isprint'|.
3680 Like they are shown in a window. Example: >
3681 echo strtrans(@a)
3682< This displays a newline in register a as "^@" instead of
3683 starting a new line.
3684
3685submatch({nr}) *submatch()*
3686 Only for an expression in a |:substitute| command. Returns
3687 the {nr}'th submatch of the matched text. When {nr} is 0
3688 the whole matched text is returned.
3689 Example: >
3690 :s/\d\+/\=submatch(0) + 1/
3691< This finds the first number in the line and adds one to it.
3692 A line break is included as a newline character.
3693
3694substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
3695 The result is a String, which is a copy of {expr}, in which
3696 the first match of {pat} is replaced with {sub}. This works
3697 like the ":substitute" command (without any flags). But the
3698 matching with {pat} is always done like the 'magic' option is
3699 set and 'cpoptions' is empty (to make scripts portable).
3700 See |string-match| for how {pat} is used.
3701 And a "~" in {sub} is not replaced with the previous {sub}.
3702 Note that some codes in {sub} have a special meaning
3703 |sub-replace-special|. For example, to replace something with
3704 "\n" (two characters), use "\\\\n" or '\\n'.
3705 When {pat} does not match in {expr}, {expr} is returned
3706 unmodified.
3707 When {flags} is "g", all matches of {pat} in {expr} are
3708 replaced. Otherwise {flags} should be "".
3709 Example: >
3710 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
3711< This removes the last component of the 'path' option. >
3712 :echo substitute("testing", ".*", "\\U\\0", "")
3713< results in "TESTING".
3714
Bram Moolenaar47136d72004-10-12 20:02:24 +00003715synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00003717 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 The syntax ID can be used with |synIDattr()| and
3719 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00003720 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 line.
3722 When {trans} is non-zero, transparent items are reduced to the
3723 item that they reveal. This is useful when wanting to know
3724 the effective color. When {trans} is zero, the transparent
3725 item is returned. This is useful when wanting to know which
3726 syntax item is effective (e.g. inside parens).
3727 Warning: This function can be very slow. Best speed is
3728 obtained by going through the file in forward direction.
3729
3730 Example (echoes the name of the syntax item under the cursor): >
3731 :echo synIDattr(synID(line("."), col("."), 1), "name")
3732<
3733synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
3734 The result is a String, which is the {what} attribute of
3735 syntax ID {synID}. This can be used to obtain information
3736 about a syntax item.
3737 {mode} can be "gui", "cterm" or "term", to get the attributes
3738 for that mode. When {mode} is omitted, or an invalid value is
3739 used, the attributes for the currently active highlighting are
3740 used (GUI, cterm or term).
3741 Use synIDtrans() to follow linked highlight groups.
3742 {what} result
3743 "name" the name of the syntax item
3744 "fg" foreground color (GUI: color name used to set
3745 the color, cterm: color number as a string,
3746 term: empty string)
3747 "bg" background color (like "fg")
3748 "fg#" like "fg", but for the GUI and the GUI is
3749 running the name in "#RRGGBB" form
3750 "bg#" like "fg#" for "bg"
3751 "bold" "1" if bold
3752 "italic" "1" if italic
3753 "reverse" "1" if reverse
3754 "inverse" "1" if inverse (= reverse)
3755 "underline" "1" if underlined
3756
3757 Example (echoes the color of the syntax item under the
3758 cursor): >
3759 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
3760<
3761synIDtrans({synID}) *synIDtrans()*
3762 The result is a Number, which is the translated syntax ID of
3763 {synID}. This is the syntax group ID of what is being used to
3764 highlight the character. Highlight links given with
3765 ":highlight link" are followed.
3766
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003767system({expr} [, {input}]) *system()* *E677*
3768 Get the output of the shell command {expr}.
3769 When {input} is given, this string is written to a file and
3770 passed as stdin to the command. The string is written as-is,
3771 you need to take care of using the correct line separators
3772 yourself.
3773 Note: newlines in {expr} may cause the command to fail. The
3774 characters in 'shellquote' and 'shellxquote' may also cause
3775 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776 This is not to be used for interactive commands.
3777 The result is a String. Example: >
3778
3779 :let files = system("ls")
3780
3781< To make the result more system-independent, the shell output
3782 is filtered to replace <CR> with <NL> for Macintosh, and
3783 <CR><NL> with <NL> for DOS-like systems.
3784 The command executed is constructed using several options:
3785 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
3786 ({tmp} is an automatically generated file name).
3787 For Unix and OS/2 braces are put around {expr} to allow for
3788 concatenated commands.
3789
3790 The resulting error code can be found in |v:shell_error|.
3791 This function will fail in |restricted-mode|.
3792 Unlike ":!cmd" there is no automatic check for changed files.
3793 Use |:checktime| to force a check.
3794
3795tempname() *tempname()* *temp-file-name*
3796 The result is a String, which is the name of a file that
3797 doesn't exist. It can be used for a temporary file. The name
3798 is different for at least 26 consecutive calls. Example: >
3799 :let tmpfile = tempname()
3800 :exe "redir > " . tmpfile
3801< For Unix, the file will be in a private directory (only
3802 accessible by the current user) to avoid security problems
3803 (e.g., a symlink attack or other people reading your file).
3804 When Vim exits the directory and all files in it are deleted.
3805 For MS-Windows forward slashes are used when the 'shellslash'
3806 option is set or when 'shellcmdflag' starts with '-'.
3807
3808tolower({expr}) *tolower()*
3809 The result is a copy of the String given, with all uppercase
3810 characters turned into lowercase (just like applying |gu| to
3811 the string).
3812
3813toupper({expr}) *toupper()*
3814 The result is a copy of the String given, with all lowercase
3815 characters turned into uppercase (just like applying |gU| to
3816 the string).
3817
Bram Moolenaar8299df92004-07-10 09:47:34 +00003818tr({src}, {fromstr}, {tostr}) *tr()*
3819 The result is a copy of the {src} string with all characters
3820 which appear in {fromstr} replaced by the character in that
3821 position in the {tostr} string. Thus the first character in
3822 {fromstr} is translated into the first character in {tostr}
3823 and so on. Exactly like the unix "tr" command.
3824 This code also deals with multibyte characters properly.
3825
3826 Examples: >
3827 echo tr("hello there", "ht", "HT")
3828< returns "Hello THere" >
3829 echo tr("<blob>", "<>", "{}")
3830< returns "{blob}"
3831
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003832 *type()*
3833type({expr}) The result is a Number, depending on the type of {expr}:
Bram Moolenaar748bf032005-02-02 23:04:36 +00003834 Number: 0
3835 String: 1
3836 Funcref: 2
3837 List: 3
3838 Dictionary: 4
3839 To avoid the magic numbers it should be used this way: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003840 :if type(myvar) == type(0)
3841 :if type(myvar) == type("")
3842 :if type(myvar) == type(function("tr"))
3843 :if type(myvar) == type([])
Bram Moolenaar748bf032005-02-02 23:04:36 +00003844 :if type(myvar) == type({})
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845
Bram Moolenaar677ee682005-01-27 14:41:15 +00003846values({dict}) *values()*
3847 Return a List with all the values of {dict}. The List is in
3848 arbitrary order.
3849
3850
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851virtcol({expr}) *virtcol()*
3852 The result is a Number, which is the screen column of the file
3853 position given with {expr}. That is, the last screen position
3854 occupied by the character at that position, when the screen
3855 would be of unlimited width. When there is a <Tab> at the
3856 position, the returned Number will be the column at the end of
3857 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
3858 set to 8, it returns 8.
3859 For the byte position use |col()|.
3860 When Virtual editing is active in the current mode, a position
3861 beyond the end of the line can be returned. |'virtualedit'|
3862 The accepted positions are:
3863 . the cursor position
3864 $ the end of the cursor line (the result is the
3865 number of displayed characters in the cursor line
3866 plus one)
3867 'x position of mark x (if the mark is not set, 0 is
3868 returned)
3869 Note that only marks in the current file can be used.
3870 Examples: >
3871 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
3872 virtcol("$") with text "foo^Lbar", returns 9
3873 virtcol("'t") with text " there", with 't at 'h', returns 6
3874< The first column is 1. 0 is returned for an error.
3875
3876visualmode([expr]) *visualmode()*
3877 The result is a String, which describes the last Visual mode
3878 used. Initially it returns an empty string, but once Visual
3879 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
3880 single CTRL-V character) for character-wise, line-wise, or
3881 block-wise Visual mode respectively.
3882 Example: >
3883 :exe "normal " . visualmode()
3884< This enters the same Visual mode as before. It is also useful
3885 in scripts if you wish to act differently depending on the
3886 Visual mode that was used.
3887
3888 If an expression is supplied that results in a non-zero number
3889 or a non-empty string, then the Visual mode will be cleared
3890 and the old value is returned. Note that " " and "0" are also
3891 non-empty strings, thus cause the mode to be cleared.
3892
3893 *winbufnr()*
3894winbufnr({nr}) The result is a Number, which is the number of the buffer
3895 associated with window {nr}. When {nr} is zero, the number of
3896 the buffer in the current window is returned. When window
3897 {nr} doesn't exist, -1 is returned.
3898 Example: >
3899 :echo "The file in the current window is " . bufname(winbufnr(0))
3900<
3901 *wincol()*
3902wincol() The result is a Number, which is the virtual column of the
3903 cursor in the window. This is counting screen cells from the
3904 left side of the window. The leftmost column is one.
3905
3906winheight({nr}) *winheight()*
3907 The result is a Number, which is the height of window {nr}.
3908 When {nr} is zero, the height of the current window is
3909 returned. When window {nr} doesn't exist, -1 is returned.
3910 An existing window always has a height of zero or more.
3911 Examples: >
3912 :echo "The current window has " . winheight(0) . " lines."
3913<
3914 *winline()*
3915winline() The result is a Number, which is the screen line of the cursor
3916 in the window. This is counting screen lines from the top of
3917 the window. The first line is one.
3918
3919 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003920winnr([{arg}]) The result is a Number, which is the number of the current
3921 window. The top window has number 1.
3922 When the optional argument is "$", the number of the
3923 last window is returnd (the window count).
3924 When the optional argument is "#", the number of the last
3925 accessed window is returned (where |CTRL-W_p| goes to).
3926 If there is no previous window 0 is returned.
3927 The number can be used with |CTRL-W_w| and ":wincmd w"
3928 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929
3930 *winrestcmd()*
3931winrestcmd() Returns a sequence of |:resize| commands that should restore
3932 the current window sizes. Only works properly when no windows
3933 are opened or closed and the current window is unchanged.
3934 Example: >
3935 :let cmd = winrestcmd()
3936 :call MessWithWindowSizes()
3937 :exe cmd
3938
3939winwidth({nr}) *winwidth()*
3940 The result is a Number, which is the width of window {nr}.
3941 When {nr} is zero, the width of the current window is
3942 returned. When window {nr} doesn't exist, -1 is returned.
3943 An existing window always has a width of zero or more.
3944 Examples: >
3945 :echo "The current window has " . winwidth(0) . " columns."
3946 :if winwidth(0) <= 50
3947 : exe "normal 50\<C-W>|"
3948 :endif
3949<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003950 *writefile()*
3951writefile({list}, {fname} [, {binary}])
3952 Write List {list} to file {fname}. Each list item is
3953 separated with a NL. Each list item must be a String or
3954 Number.
3955 When {binary} is equal to "b" binary mode is used: There will
3956 not be a NL after the last list item. An empty item at the
3957 end does cause the last line in the file to end in a NL.
3958 All NL characters are replaced with a NUL character.
3959 Inserting CR characters needs to be done before passing {list}
3960 to writefile().
3961 An existing file is overwritten, if possible.
3962 When the write fails -1 is returned, otherwise 0. There is an
3963 error message if the file can't be created or when writing
3964 fails.
3965 Also see |readfile()|.
3966 To copy a file byte for byte: >
3967 :let fl = readfile("foo", "b")
3968 :call writefile(fl, "foocopy", "b")
3969<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970
3971 *feature-list*
3972There are three types of features:
39731. Features that are only supported when they have been enabled when Vim
3974 was compiled |+feature-list|. Example: >
3975 :if has("cindent")
39762. Features that are only supported when certain conditions have been met.
3977 Example: >
3978 :if has("gui_running")
3979< *has-patch*
39803. Included patches. First check |v:version| for the version of Vim.
3981 Then the "patch123" feature means that patch 123 has been included for
3982 this version. Example (checking version 6.2.148 or later): >
3983 :if v:version > 602 || v:version == 602 && has("patch148")
3984
3985all_builtin_terms Compiled with all builtin terminals enabled.
3986amiga Amiga version of Vim.
3987arabic Compiled with Arabic support |Arabic|.
3988arp Compiled with ARP support (Amiga).
3989autocmd Compiled with autocommands support.
3990balloon_eval Compiled with |balloon-eval| support.
3991beos BeOS version of Vim.
3992browse Compiled with |:browse| support, and browse() will
3993 work.
3994builtin_terms Compiled with some builtin terminals.
3995byte_offset Compiled with support for 'o' in 'statusline'
3996cindent Compiled with 'cindent' support.
3997clientserver Compiled with remote invocation support |clientserver|.
3998clipboard Compiled with 'clipboard' support.
3999cmdline_compl Compiled with |cmdline-completion| support.
4000cmdline_hist Compiled with |cmdline-history| support.
4001cmdline_info Compiled with 'showcmd' and 'ruler' support.
4002comments Compiled with |'comments'| support.
4003cryptv Compiled with encryption support |encryption|.
4004cscope Compiled with |cscope| support.
4005compatible Compiled to be very Vi compatible.
4006debug Compiled with "DEBUG" defined.
4007dialog_con Compiled with console dialog support.
4008dialog_gui Compiled with GUI dialog support.
4009diff Compiled with |vimdiff| and 'diff' support.
4010digraphs Compiled with support for digraphs.
4011dnd Compiled with support for the "~ register |quote_~|.
4012dos32 32 bits DOS (DJGPP) version of Vim.
4013dos16 16 bits DOS version of Vim.
4014ebcdic Compiled on a machine with ebcdic character set.
4015emacs_tags Compiled with support for Emacs tags.
4016eval Compiled with expression evaluation support. Always
4017 true, of course!
4018ex_extra Compiled with extra Ex commands |+ex_extra|.
4019extra_search Compiled with support for |'incsearch'| and
4020 |'hlsearch'|
4021farsi Compiled with Farsi support |farsi|.
4022file_in_path Compiled with support for |gf| and |<cfile>|
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004023filterpipe When 'shelltemp' is off pipes are used for shell
4024 read/write/filter commands
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025find_in_path Compiled with support for include file searches
4026 |+find_in_path|.
4027fname_case Case in file names matters (for Amiga, MS-DOS, and
4028 Windows this is not present).
4029folding Compiled with |folding| support.
4030footer Compiled with GUI footer support. |gui-footer|
4031fork Compiled to use fork()/exec() instead of system().
4032gettext Compiled with message translation |multi-lang|
4033gui Compiled with GUI enabled.
4034gui_athena Compiled with Athena GUI.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004035gui_beos Compiled with BeOS GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036gui_gtk Compiled with GTK+ GUI (any version).
4037gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00004038gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039gui_mac Compiled with Macintosh GUI.
4040gui_motif Compiled with Motif GUI.
4041gui_photon Compiled with Photon GUI.
4042gui_win32 Compiled with MS Windows Win32 GUI.
4043gui_win32s idem, and Win32s system being used (Windows 3.1)
4044gui_running Vim is running in the GUI, or it will start soon.
4045hangul_input Compiled with Hangul input support. |hangul|
4046iconv Can use iconv() for conversion.
4047insert_expand Compiled with support for CTRL-X expansion commands in
4048 Insert mode.
4049jumplist Compiled with |jumplist| support.
4050keymap Compiled with 'keymap' support.
4051langmap Compiled with 'langmap' support.
4052libcall Compiled with |libcall()| support.
4053linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
4054 support.
4055lispindent Compiled with support for lisp indenting.
4056listcmds Compiled with commands for the buffer list |:files|
4057 and the argument list |arglist|.
4058localmap Compiled with local mappings and abbr. |:map-local|
4059mac Macintosh version of Vim.
4060macunix Macintosh version of Vim, using Unix files (OS-X).
4061menu Compiled with support for |:menu|.
4062mksession Compiled with support for |:mksession|.
4063modify_fname Compiled with file name modifiers. |filename-modifiers|
4064mouse Compiled with support mouse.
4065mouseshape Compiled with support for 'mouseshape'.
4066mouse_dec Compiled with support for Dec terminal mouse.
4067mouse_gpm Compiled with support for gpm (Linux console mouse)
4068mouse_netterm Compiled with support for netterm mouse.
4069mouse_pterm Compiled with support for qnx pterm mouse.
4070mouse_xterm Compiled with support for xterm mouse.
4071multi_byte Compiled with support for editing Korean et al.
4072multi_byte_ime Compiled with support for IME input method.
4073multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004074mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00004076netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077ole Compiled with OLE automation support for Win32.
4078os2 OS/2 version of Vim.
4079osfiletype Compiled with support for osfiletypes |+osfiletype|
4080path_extra Compiled with up/downwards search in 'path' and 'tags'
4081perl Compiled with Perl interface.
4082postscript Compiled with PostScript file printing.
4083printer Compiled with |:hardcopy| support.
4084python Compiled with Python interface.
4085qnx QNX version of Vim.
4086quickfix Compiled with |quickfix| support.
4087rightleft Compiled with 'rightleft' support.
4088ruby Compiled with Ruby interface |ruby|.
4089scrollbind Compiled with 'scrollbind' support.
4090showcmd Compiled with 'showcmd' support.
4091signs Compiled with |:sign| support.
4092smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004093sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094statusline Compiled with support for 'statusline', 'rulerformat'
4095 and special formats of 'titlestring' and 'iconstring'.
4096sun_workshop Compiled with support for Sun |workshop|.
4097syntax Compiled with syntax highlighting support.
4098syntax_items There are active syntax highlighting items for the
4099 current buffer.
4100system Compiled to use system() instead of fork()/exec().
4101tag_binary Compiled with binary searching in tags files
4102 |tag-binary-search|.
4103tag_old_static Compiled with support for old static tags
4104 |tag-old-static|.
4105tag_any_white Compiled with support for any white characters in tags
4106 files |tag-any-white|.
4107tcl Compiled with Tcl interface.
4108terminfo Compiled with terminfo instead of termcap.
4109termresponse Compiled with support for |t_RV| and |v:termresponse|.
4110textobjects Compiled with support for |text-objects|.
4111tgetent Compiled with tgetent support, able to use a termcap
4112 or terminfo file.
4113title Compiled with window title support |'title'|.
4114toolbar Compiled with support for |gui-toolbar|.
4115unix Unix version of Vim.
4116user_commands User-defined commands.
4117viminfo Compiled with viminfo support.
4118vim_starting True while initial source'ing takes place.
4119vertsplit Compiled with vertically split windows |:vsplit|.
4120virtualedit Compiled with 'virtualedit' option.
4121visual Compiled with Visual mode.
4122visualextra Compiled with extra Visual mode commands.
4123 |blockwise-operators|.
4124vms VMS version of Vim.
4125vreplace Compiled with |gR| and |gr| commands.
4126wildignore Compiled with 'wildignore' option.
4127wildmenu Compiled with 'wildmenu' option.
4128windows Compiled with support for more than one window.
4129winaltkeys Compiled with 'winaltkeys' option.
4130win16 Win16 version of Vim (MS-Windows 3.1).
4131win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
4132win64 Win64 version of Vim (MS-Windows 64 bit).
4133win32unix Win32 version of Vim, using Unix files (Cygwin)
4134win95 Win32 version for MS-Windows 95/98/ME.
4135writebackup Compiled with 'writebackup' default on.
4136xfontset Compiled with X fontset support |xfontset|.
4137xim Compiled with X input method support |xim|.
4138xsmp Compiled with X session management support.
4139xsmp_interact Compiled with interactive X session management support.
4140xterm_clipboard Compiled with support for xterm clipboard.
4141xterm_save Compiled with support for saving and restoring the
4142 xterm screen.
4143x11 Compiled with X11 support.
4144
4145 *string-match*
4146Matching a pattern in a String
4147
4148A regexp pattern as explained at |pattern| is normally used to find a match in
4149the buffer lines. When a pattern is used to find a match in a String, almost
4150everything works in the same way. The difference is that a String is handled
4151like it is one line. When it contains a "\n" character, this is not seen as a
4152line break for the pattern. It can be matched with a "\n" in the pattern, or
4153with ".". Example: >
4154 :let a = "aaaa\nxxxx"
4155 :echo matchstr(a, "..\n..")
4156 aa
4157 xx
4158 :echo matchstr(a, "a.x")
4159 a
4160 x
4161
4162Don't forget that "^" will only match at the first character of the String and
4163"$" at the last character of the string. They don't match after or before a
4164"\n".
4165
4166==============================================================================
41675. Defining functions *user-functions*
4168
4169New functions can be defined. These can be called just like builtin
4170functions. The function executes a sequence of Ex commands. Normal mode
4171commands can be executed with the |:normal| command.
4172
4173The function name must start with an uppercase letter, to avoid confusion with
4174builtin functions. To prevent from using the same name in different scripts
4175avoid obvious, short names. A good habit is to start the function name with
4176the name of the script, e.g., "HTMLcolor()".
4177
4178It's also possible to use curly braces, see |curly-braces-names|.
4179
4180 *local-function*
4181A function local to a script must start with "s:". A local script function
4182can only be called from within the script and from functions, user commands
4183and autocommands defined in the script. It is also possible to call the
4184function from a mappings defined in the script, but then |<SID>| must be used
4185instead of "s:" when the mapping is expanded outside of the script.
4186
4187 *:fu* *:function* *E128* *E129* *E123*
4188:fu[nction] List all functions and their arguments.
4189
4190:fu[nction] {name} List function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004191 {name} can also be a Dictionary entry that is a
4192 Funcref: >
4193 :function dict.init
4194< *E124* *E125*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004195:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196 Define a new function by the name {name}. The name
4197 must be made of alphanumeric characters and '_', and
4198 must start with a capital or "s:" (see above).
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004199
4200 {name} can also be a Dictionary entry that is a
4201 Funcref: >
4202 :function dict.init(arg)
4203< "dict" must be an existing dictionary. The entry
4204 "init" is added if it didn't exist yet. Otherwise [!]
4205 is required to overwrite an existing function. The
4206 result is a |Funcref| to a numbered function. The
4207 function can only be used with a |Funcref| and will be
4208 deleted if there are no more references to it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 *E127* *E122*
4210 When a function by this name already exists and [!] is
4211 not used an error message is given. When [!] is used,
4212 an existing function is silently replaced. Unless it
4213 is currently being executed, that is an error.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004214
4215 For the {arguments} see |function-argument|.
4216
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 *a:firstline* *a:lastline*
4218 When the [range] argument is added, the function is
4219 expected to take care of a range itself. The range is
4220 passed as "a:firstline" and "a:lastline". If [range]
4221 is excluded, ":{range}call" will call the function for
4222 each line in the range, with the cursor on the start
4223 of each line. See |function-range-example|.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004224
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225 When the [abort] argument is added, the function will
4226 abort as soon as an error is detected.
4227 The last used search pattern and the redo command "."
4228 will not be changed by the function.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004229
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004230 When the [dict] argument is added, the function must
4231 be invoked through an entry in a Dictionary. The
4232 local variable "self" will then be set to the
4233 dictionary. See |Dictionary-function|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004234
4235 *:endf* *:endfunction* *E126* *E193*
4236:endf[unction] The end of a function definition. Must be on a line
4237 by its own, without other commands.
4238
4239 *:delf* *:delfunction* *E130* *E131*
4240:delf[unction] {name} Delete function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004241 {name} can also be a Dictionary entry that is a
4242 Funcref: >
4243 :delfunc dict.init
4244< This will remove the "init" entry from "dict". The
4245 function is deleted if there are no more references to
4246 it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 *:retu* *:return* *E133*
4248:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
4249 evaluated and returned as the result of the function.
4250 If "[expr]" is not given, the number 0 is returned.
4251 When a function ends without an explicit ":return",
4252 the number 0 is returned.
4253 Note that there is no check for unreachable lines,
4254 thus there is no warning if commands follow ":return".
4255
4256 If the ":return" is used after a |:try| but before the
4257 matching |:finally| (if present), the commands
4258 following the ":finally" up to the matching |:endtry|
4259 are executed first. This process applies to all
4260 nested ":try"s inside the function. The function
4261 returns at the outermost ":endtry".
4262
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004263 *function-argument* *a:var*
4264An argument can be defined by giving its name. In the function this can then
4265be used as "a:name" ("a:" for argument).
4266 *a:0* *a:1* *a:000* *E740*
4267Up to 20 arguments can be given, separated by commas. After the named
4268arguments an argument "..." can be specified, which means that more arguments
4269may optionally be following. In the function the extra arguments can be used
4270as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004271can be 0). "a:000" is set to a List that contains these arguments. Note that
4272"a:1" is the same as "a:000[0]".
4273 *E742*
4274The a: scope and the variables in it cannot be changed, they are fixed.
4275However, if a List or Dictionary is used, you can changes their contents.
4276Thus you can pass a List to a function and have the function add an item to
4277it. If you want to make sure the function cannot change a List or Dictionary
4278use |:lockvar|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004280When not using "...", the number of arguments in a function call must be equal
4281to the number of named arguments. When using "...", the number of arguments
4282may be larger.
4283
4284It is also possible to define a function without any arguments. You must
4285still supply the () then. The body of the function follows in the next lines,
4286until the matching |:endfunction|. It is allowed to define another function
4287inside a function body.
4288
4289 *local-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290Inside a function variables can be used. These are local variables, which
4291will disappear when the function returns. Global variables need to be
4292accessed with "g:".
4293
4294Example: >
4295 :function Table(title, ...)
4296 : echohl Title
4297 : echo a:title
4298 : echohl None
Bram Moolenaar677ee682005-01-27 14:41:15 +00004299 : echo a:0 . " items:"
4300 : for s in a:000
4301 : echon ' ' . s
4302 : endfor
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 :endfunction
4304
4305This function can then be called with: >
Bram Moolenaar677ee682005-01-27 14:41:15 +00004306 call Table("Table", "line1", "line2")
4307 call Table("Empty Table")
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308
4309To return more than one value, pass the name of a global variable: >
4310 :function Compute(n1, n2, divname)
4311 : if a:n2 == 0
4312 : return "fail"
4313 : endif
4314 : let g:{a:divname} = a:n1 / a:n2
4315 : return "ok"
4316 :endfunction
4317
4318This function can then be called with: >
4319 :let success = Compute(13, 1324, "div")
4320 :if success == "ok"
4321 : echo div
4322 :endif
4323
4324An alternative is to return a command that can be executed. This also works
4325with local variables in a calling function. Example: >
4326 :function Foo()
4327 : execute Bar()
4328 : echo "line " . lnum . " column " . col
4329 :endfunction
4330
4331 :function Bar()
4332 : return "let lnum = " . line(".") . " | let col = " . col(".")
4333 :endfunction
4334
4335The names "lnum" and "col" could also be passed as argument to Bar(), to allow
4336the caller to set the names.
4337
4338 *:cal* *:call* *E107*
4339:[range]cal[l] {name}([arguments])
4340 Call a function. The name of the function and its arguments
4341 are as specified with |:function|. Up to 20 arguments can be
4342 used.
4343 Without a range and for functions that accept a range, the
4344 function is called once. When a range is given the cursor is
4345 positioned at the start of the first line before executing the
4346 function.
4347 When a range is given and the function doesn't handle it
4348 itself, the function is executed for each line in the range,
4349 with the cursor in the first column of that line. The cursor
4350 is left at the last line (possibly moved by the last function
4351 call). The arguments are re-evaluated for each line. Thus
4352 this works:
4353 *function-range-example* >
4354 :function Mynumber(arg)
4355 : echo line(".") . " " . a:arg
4356 :endfunction
4357 :1,5call Mynumber(getline("."))
4358<
4359 The "a:firstline" and "a:lastline" are defined anyway, they
4360 can be used to do something different at the start or end of
4361 the range.
4362
4363 Example of a function that handles the range itself: >
4364
4365 :function Cont() range
4366 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
4367 :endfunction
4368 :4,8call Cont()
4369<
4370 This function inserts the continuation character "\" in front
4371 of all the lines in the range, except the first one.
4372
4373 *E132*
4374The recursiveness of user functions is restricted with the |'maxfuncdepth'|
4375option.
4376
Bram Moolenaar7c626922005-02-07 22:01:03 +00004377
4378AUTOMATICALLY LOADING FUNCTIONS ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 *autoload-functions*
4380When using many or large functions, it's possible to automatically define them
Bram Moolenaar7c626922005-02-07 22:01:03 +00004381only when they are used. There are two methods: with an autocommand and with
4382the "autoload" directory in 'runtimepath'.
4383
4384
4385Using an autocommand ~
4386
4387The autocommand is useful if you have a plugin that is a long Vim script file.
4388You can define the autocommand and quickly quit the script with |:finish|.
4389That makes Vim startup faster. The autocommand should then load the same file
4390again, setting a variable to skip the |:finish| command.
4391
4392Use the FuncUndefined autocommand event with a pattern that matches the
4393function(s) to be defined. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394
4395 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
4396
4397The file "~/vim/bufnetfuncs.vim" should then define functions that start with
4398"BufNet". Also see |FuncUndefined|.
4399
Bram Moolenaar7c626922005-02-07 22:01:03 +00004400
4401Using an autoload script ~
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004402 *autoload* *E746*
Bram Moolenaar7c626922005-02-07 22:01:03 +00004403Using a script in the "autoload" directory is simpler, but requires using
4404exactly the right file name. A function that can be autoloaded has a name
4405like this: >
4406
4407 :call filename:funcname()
4408
4409When such a function is called, and it is not defined yet, Vim will search the
4410"autoload" directories in 'runtimepath' for a script file called
4411"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
4412then define the function like this: >
4413
4414 function filename:funcname()
4415 echo "Done!"
4416 endfunction
4417
4418The file name and the name used before the colon in the function must match
4419exactly, and the defined function must have the name exactly as it will be
4420called.
4421
4422It is possible to use subdirectories. Every colon in the function name works
4423like a path separator. Thus when calling a function: >
4424
4425 :call foo:bar:func()
4426
4427Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
4428
4429The name before the first colon must be at least two characters long,
4430otherwise it looks like a scope, such as "s:".
4431
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004432This also works when reading a variable that has not been set yet: >
4433
4434 :let l = foo:bar:lvar
4435
4436When assigning a value to such a variable nothing special happens. This can
4437be used to pass settings to the autoload script before it's loaded: >
4438
4439 :let foo:bar:toggle = 1
4440 :call foo:bar:func()
4441
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004442Note that when you make a mistake and call a function that is supposed to be
4443defined in an autoload script, but the script doesn't actually define the
4444function, the script will be sourced every time you try to call the function.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004445And you will get an error message every time.
4446
4447Also note that if you have two script files, and one calls a function in the
4448other and vise versa, before the used function is defined, it won't work.
4449Avoid using the autoload functionality at the toplevel.
Bram Moolenaar7c626922005-02-07 22:01:03 +00004450
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451==============================================================================
44526. Curly braces names *curly-braces-names*
4453
4454Wherever you can use a variable, you can use a "curly braces name" variable.
4455This is a regular variable name with one or more expressions wrapped in braces
4456{} like this: >
4457 my_{adjective}_variable
4458
4459When Vim encounters this, it evaluates the expression inside the braces, puts
4460that in place of the expression, and re-interprets the whole as a variable
4461name. So in the above example, if the variable "adjective" was set to
4462"noisy", then the reference would be to "my_noisy_variable", whereas if
4463"adjective" was set to "quiet", then it would be to "my_quiet_variable".
4464
4465One application for this is to create a set of variables governed by an option
4466value. For example, the statement >
4467 echo my_{&background}_message
4468
4469would output the contents of "my_dark_message" or "my_light_message" depending
4470on the current value of 'background'.
4471
4472You can use multiple brace pairs: >
4473 echo my_{adverb}_{adjective}_message
4474..or even nest them: >
4475 echo my_{ad{end_of_word}}_message
4476where "end_of_word" is either "verb" or "jective".
4477
4478However, the expression inside the braces must evaluate to a valid single
4479variable name. e.g. this is invalid: >
4480 :let foo='a + b'
4481 :echo c{foo}d
4482.. since the result of expansion is "ca + bd", which is not a variable name.
4483
4484 *curly-braces-function-names*
4485You can call and define functions by an evaluated name in a similar way.
4486Example: >
4487 :let func_end='whizz'
4488 :call my_func_{func_end}(parameter)
4489
4490This would call the function "my_func_whizz(parameter)".
4491
4492==============================================================================
44937. Commands *expression-commands*
4494
4495:let {var-name} = {expr1} *:let* *E18*
4496 Set internal variable {var-name} to the result of the
4497 expression {expr1}. The variable will get the type
4498 from the {expr}. If {var-name} didn't exist yet, it
4499 is created.
4500
Bram Moolenaar13065c42005-01-08 16:08:21 +00004501:let {var-name}[{idx}] = {expr1} *E689*
4502 Set a list item to the result of the expression
4503 {expr1}. {var-name} must refer to a list and {idx}
4504 must be a valid index in that list. For nested list
4505 the index can be repeated.
4506 This cannot be used to add an item to a list.
4507
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004508 *E711* *E719*
4509:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004510 Set a sequence of items in a List to the result of the
4511 expression {expr1}, which must be a list with the
4512 correct number of items.
4513 {idx1} can be omitted, zero is used instead.
4514 {idx2} can be omitted, meaning the end of the list.
4515 When the selected range of items is partly past the
4516 end of the list, items will be added.
4517
Bram Moolenaar748bf032005-02-02 23:04:36 +00004518 *:let+=* *:let-=* *:let.=* *E734*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004519:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
4520:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
4521:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
4522 These fail if {var} was not set yet and when the type
4523 of {var} and {expr1} don't fit the operator.
4524
4525
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526:let ${env-name} = {expr1} *:let-environment* *:let-$*
4527 Set environment variable {env-name} to the result of
4528 the expression {expr1}. The type is always String.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004529:let ${env-name} .= {expr1}
4530 Append {expr1} to the environment variable {env-name}.
4531 If the environment variable didn't exist yet this
4532 works like "=".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533
4534:let @{reg-name} = {expr1} *:let-register* *:let-@*
4535 Write the result of the expression {expr1} in register
4536 {reg-name}. {reg-name} must be a single letter, and
4537 must be the name of a writable register (see
4538 |registers|). "@@" can be used for the unnamed
4539 register, "@/" for the search pattern.
4540 If the result of {expr1} ends in a <CR> or <NL>, the
4541 register will be linewise, otherwise it will be set to
4542 characterwise.
4543 This can be used to clear the last search pattern: >
4544 :let @/ = ""
4545< This is different from searching for an empty string,
4546 that would match everywhere.
4547
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004548:let @{reg-name} .= {expr1}
4549 Append {expr1} to register {reg-name}. If the
4550 register was empty it's like setting it to {expr1}.
4551
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552:let &{option-name} = {expr1} *:let-option* *:let-star*
4553 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004554 expression {expr1}. A String or Number value is
4555 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 For an option local to a window or buffer the effect
4557 is just like using the |:set| command: both the local
4558 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004559 Example: >
4560 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004562:let &{option-name} .= {expr1}
4563 For a string option: Append {expr1} to the value.
4564 Does not insert a comma like |:set+=|.
4565
4566:let &{option-name} += {expr1}
4567:let &{option-name} -= {expr1}
4568 For a number or boolean option: Add or subtract
4569 {expr1}.
4570
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571:let &l:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004572:let &l:{option-name} .= {expr1}
4573:let &l:{option-name} += {expr1}
4574:let &l:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575 Like above, but only set the local value of an option
4576 (if there is one). Works like |:setlocal|.
4577
4578:let &g:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004579:let &g:{option-name} .= {expr1}
4580:let &g:{option-name} += {expr1}
4581:let &g:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 Like above, but only set the global value of an option
4583 (if there is one). Works like |:setglobal|.
4584
Bram Moolenaar13065c42005-01-08 16:08:21 +00004585:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004586 {expr1} must evaluate to a List. The first item in
4587 the list is assigned to {name1}, the second item to
4588 {name2}, etc.
4589 The number of names must match the number of items in
4590 the List.
4591 Each name can be one of the items of the ":let"
4592 command as mentioned above.
4593 Example: >
4594 :let [s, item] = GetItem(s)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004595< Detail: {expr1} is evaluated first, then the
4596 assignments are done in sequence. This matters if
4597 {name2} depends on {name1}. Example: >
4598 :let x = [0, 1]
4599 :let i = 0
4600 :let [i, x[i]] = [1, 2]
4601 :echo x
4602< The result is [0, 2].
4603
4604:let [{name1}, {name2}, ...] .= {expr1}
4605:let [{name1}, {name2}, ...] += {expr1}
4606:let [{name1}, {name2}, ...] -= {expr1}
4607 Like above, but append/add/subtract the value for each
4608 List item.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004609
4610:let [{name}, ..., ; {lastname}] = {expr1}
Bram Moolenaar677ee682005-01-27 14:41:15 +00004611 Like |:let-unpack| above, but the List may have more
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004612 items than there are names. A list of the remaining
4613 items is assigned to {lastname}. If there are no
4614 remaining items {lastname} is set to an empty list.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004615 Example: >
4616 :let [a, b; rest] = ["aval", "bval", 3, 4]
4617<
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004618:let [{name}, ..., ; {lastname}] .= {expr1}
4619:let [{name}, ..., ; {lastname}] += {expr1}
4620:let [{name}, ..., ; {lastname}] -= {expr1}
4621 Like above, but append/add/subtract the value for each
4622 List item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 *E106*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004624:let {var-name} .. List the value of variable {var-name}. Multiple
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00004625 variable names may be given. Special names recognized
4626 here: *E738*
4627 g: global variables.
4628 b: local buffer variables.
4629 w: local window variables.
4630 v: Vim variables.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00004632:let List the values of all variables. The type of the
4633 variable is indicated before the value:
4634 <nothing> String
4635 # Number
4636 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004638
4639:unl[et][!] {name} ... *:unlet* *:unl* *E108*
4640 Remove the internal variable {name}. Several variable
4641 names can be given, they are all removed. The name
4642 may also be a List or Dictionary item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 With [!] no error message is given for non-existing
4644 variables.
Bram Moolenaar9cd15162005-01-16 22:02:49 +00004645 One or more items from a List can be removed: >
4646 :unlet list[3] " remove fourth item
4647 :unlet list[3:] " remove fourth item to last
4648< One item from a Dictionary can be removed at a time: >
4649 :unlet dict['two']
4650 :unlet dict.two
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004652:lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv*
4653 Lock the internal variable {name}. Locking means that
4654 it can no longer be changed (until it is unlocked).
4655 A locked variable can be deleted: >
4656 :lockvar v
4657 :let v = 'asdf' " fails!
4658 :unlet v
4659< *E741*
4660 If you try to change a locked variable you get an
4661 error message: "E741: Value of {name} is locked"
4662
4663 [depth] is relevant when locking a List or Dictionary.
4664 It specifies how deep the locking goes:
4665 1 Lock the List or Dictionary itself,
4666 cannot add or remove items, but can
4667 still change their values.
4668 2 Also lock the values, cannot change
4669 the items. If an item is a List or
4670 Dictionary, cannot add or remove
4671 items, but can still change the
4672 values.
4673 3 Like 2 but for the List/Dictionary in
4674 the List/Dictionary, one level deeper.
4675 The default [depth] is 2, thus when {name} is a List
4676 or Dictionary the values cannot be changed.
4677 *E743*
4678 For unlimited depth use [!] and omit [depth].
4679 However, there is a maximum depth of 100 to catch
4680 loops.
4681
4682 Note that when two variables refer to the same List
4683 and you lock one of them, the List will also be locked
4684 when used through the other variable. Example: >
4685 :let l = [0, 1, 2, 3]
4686 :let cl = l
4687 :lockvar l
4688 :let cl[1] = 99 " won't work!
4689< You may want to make a copy of a list to avoid this.
4690 See |deepcopy()|.
4691
4692
4693:unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo*
4694 Unlock the internal variable {name}. Does the
4695 opposite of |:lockvar|.
4696
4697
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
4699:en[dif] Execute the commands until the next matching ":else"
4700 or ":endif" if {expr1} evaluates to non-zero.
4701
4702 From Vim version 4.5 until 5.0, every Ex command in
4703 between the ":if" and ":endif" is ignored. These two
4704 commands were just to allow for future expansions in a
4705 backwards compatible way. Nesting was allowed. Note
4706 that any ":else" or ":elseif" was ignored, the "else"
4707 part was not executed either.
4708
4709 You can use this to remain compatible with older
4710 versions: >
4711 :if version >= 500
4712 : version-5-specific-commands
4713 :endif
4714< The commands still need to be parsed to find the
4715 "endif". Sometimes an older Vim has a problem with a
4716 new command. For example, ":silent" is recognized as
4717 a ":substitute" command. In that case ":execute" can
4718 avoid problems: >
4719 :if version >= 600
4720 : execute "silent 1,$delete"
4721 :endif
4722<
4723 NOTE: The ":append" and ":insert" commands don't work
4724 properly in between ":if" and ":endif".
4725
4726 *:else* *:el* *E581* *E583*
4727:el[se] Execute the commands until the next matching ":else"
4728 or ":endif" if they previously were not being
4729 executed.
4730
4731 *:elseif* *:elsei* *E582* *E584*
4732:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
4733 is no extra ":endif".
4734
4735:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004736 *E170* *E585* *E588* *E733*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737:endw[hile] Repeat the commands between ":while" and ":endwhile",
4738 as long as {expr1} evaluates to non-zero.
4739 When an error is detected from a command inside the
4740 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00004741 Example: >
4742 :let lnum = 1
4743 :while lnum <= line("$")
4744 :call FixLine(lnum)
4745 :let lnum = lnum + 1
4746 :endwhile
4747<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00004749 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004751:for {var} in {list} *:for* *E690* *E732*
Bram Moolenaar12805862005-01-05 22:16:17 +00004752:endfo[r] *:endfo* *:endfor*
4753 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00004754 each item in {list}. Variable {var} is set to the
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004755 value of each item.
4756 When an error is detected for a command inside the
Bram Moolenaar12805862005-01-05 22:16:17 +00004757 loop, execution continues after the "endfor".
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004758 Changing {list} affects what items are used. Make a
4759 copy if this is unwanted: >
4760 :for item in copy(mylist)
4761< When not making a copy, Vim stores a reference to the
4762 next item in the list, before executing the commands
4763 with the current item. Thus the current item can be
4764 removed without effect. Removing any later item means
4765 it will not be found. Thus the following example
4766 works (an inefficient way to make a list empty): >
4767 :for item in mylist
Bram Moolenaar12805862005-01-05 22:16:17 +00004768 :call remove(mylist, 0)
4769 :endfor
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004770< Note that reordering the list (e.g., with sort() or
4771 reverse()) may have unexpected effects.
4772 Note that the type of each list item should be
Bram Moolenaar12805862005-01-05 22:16:17 +00004773 identical to avoid errors for the type of {var}
4774 changing. Unlet the variable at the end of the loop
4775 to allow multiple item types.
4776
4777:for {var} in {string}
4778:endfo[r] Like ":for" above, but use each character in {string}
4779 as a list item.
4780 Composing characters are used as separate characters.
4781 A Number is first converted to a String.
4782
4783:for [{var1}, {var2}, ...] in {listlist}
4784:endfo[r]
4785 Like ":for" above, but each item in {listlist} must be
4786 a list, of which each item is assigned to {var1},
4787 {var2}, etc. Example: >
4788 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
4789 :echo getline(lnum)[col]
4790 :endfor
4791<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00004793:con[tinue] When used inside a ":while" or ":for" loop, jumps back
4794 to the start of the loop.
4795 If it is used after a |:try| inside the loop but
4796 before the matching |:finally| (if present), the
4797 commands following the ":finally" up to the matching
4798 |:endtry| are executed first. This process applies to
4799 all nested ":try"s inside the loop. The outermost
4800 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801
4802 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00004803:brea[k] When used inside a ":while" or ":for" loop, skips to
4804 the command after the matching ":endwhile" or
4805 ":endfor".
4806 If it is used after a |:try| inside the loop but
4807 before the matching |:finally| (if present), the
4808 commands following the ":finally" up to the matching
4809 |:endtry| are executed first. This process applies to
4810 all nested ":try"s inside the loop. The outermost
4811 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
4813:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
4814:endt[ry] Change the error handling for the commands between
4815 ":try" and ":endtry" including everything being
4816 executed across ":source" commands, function calls,
4817 or autocommand invocations.
4818
4819 When an error or interrupt is detected and there is
4820 a |:finally| command following, execution continues
4821 after the ":finally". Otherwise, or when the
4822 ":endtry" is reached thereafter, the next
4823 (dynamically) surrounding ":try" is checked for
4824 a corresponding ":finally" etc. Then the script
4825 processing is terminated. (Whether a function
4826 definition has an "abort" argument does not matter.)
4827 Example: >
4828 :try | edit too much | finally | echo "cleanup" | endtry
4829 :echo "impossible" " not reached, script terminated above
4830<
4831 Moreover, an error or interrupt (dynamically) inside
4832 ":try" and ":endtry" is converted to an exception. It
4833 can be caught as if it were thrown by a |:throw|
4834 command (see |:catch|). In this case, the script
4835 processing is not terminated.
4836
4837 The value "Vim:Interrupt" is used for an interrupt
4838 exception. An error in a Vim command is converted
4839 to a value of the form "Vim({command}):{errmsg}",
4840 other errors are converted to a value of the form
4841 "Vim:{errmsg}". {command} is the full command name,
4842 and {errmsg} is the message that is displayed if the
4843 error exception is not caught, always beginning with
4844 the error number.
4845 Examples: >
4846 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
4847 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
4848<
4849 *:cat* *:catch* *E603* *E604* *E605*
4850:cat[ch] /{pattern}/ The following commands until the next ":catch",
4851 |:finally|, or |:endtry| that belongs to the same
4852 |:try| as the ":catch" are executed when an exception
4853 matching {pattern} is being thrown and has not yet
4854 been caught by a previous ":catch". Otherwise, these
4855 commands are skipped.
4856 When {pattern} is omitted all errors are caught.
4857 Examples: >
4858 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
4859 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
4860 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
4861 :catch /^Vim(write):/ " catch all errors in :write
4862 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
4863 :catch /my-exception/ " catch user exception
4864 :catch /.*/ " catch everything
4865 :catch " same as /.*/
4866<
4867 Another character can be used instead of / around the
4868 {pattern}, so long as it does not have a special
4869 meaning (e.g., '|' or '"') and doesn't occur inside
4870 {pattern}.
4871 NOTE: It is not reliable to ":catch" the TEXT of
4872 an error message because it may vary in different
4873 locales.
4874
4875 *:fina* *:finally* *E606* *E607*
4876:fina[lly] The following commands until the matching |:endtry|
4877 are executed whenever the part between the matching
4878 |:try| and the ":finally" is left: either by falling
4879 through to the ":finally" or by a |:continue|,
4880 |:break|, |:finish|, or |:return|, or by an error or
4881 interrupt or exception (see |:throw|).
4882
4883 *:th* *:throw* *E608*
4884:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
4885 If the ":throw" is used after a |:try| but before the
4886 first corresponding |:catch|, commands are skipped
4887 until the first ":catch" matching {expr1} is reached.
4888 If there is no such ":catch" or if the ":throw" is
4889 used after a ":catch" but before the |:finally|, the
4890 commands following the ":finally" (if present) up to
4891 the matching |:endtry| are executed. If the ":throw"
4892 is after the ":finally", commands up to the ":endtry"
4893 are skipped. At the ":endtry", this process applies
4894 again for the next dynamically surrounding ":try"
4895 (which may be found in a calling function or sourcing
4896 script), until a matching ":catch" has been found.
4897 If the exception is not caught, the command processing
4898 is terminated.
4899 Example: >
4900 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
4901<
4902
4903 *:ec* *:echo*
4904:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
4905 first {expr1} starts on a new line.
4906 Also see |:comment|.
4907 Use "\n" to start a new line. Use "\r" to move the
4908 cursor to the first column.
4909 Uses the highlighting set by the |:echohl| command.
4910 Cannot be followed by a comment.
4911 Example: >
4912 :echo "the value of 'shell' is" &shell
4913< A later redraw may make the message disappear again.
4914 To avoid that a command from before the ":echo" causes
4915 a redraw afterwards (redraws are often postponed until
4916 you type something), force a redraw with the |:redraw|
4917 command. Example: >
4918 :new | redraw | echo "there is a new window"
4919<
4920 *:echon*
4921:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
4922 |:comment|.
4923 Uses the highlighting set by the |:echohl| command.
4924 Cannot be followed by a comment.
4925 Example: >
4926 :echon "the value of 'shell' is " &shell
4927<
4928 Note the difference between using ":echo", which is a
4929 Vim command, and ":!echo", which is an external shell
4930 command: >
4931 :!echo % --> filename
4932< The arguments of ":!" are expanded, see |:_%|. >
4933 :!echo "%" --> filename or "filename"
4934< Like the previous example. Whether you see the double
4935 quotes or not depends on your 'shell'. >
4936 :echo % --> nothing
4937< The '%' is an illegal character in an expression. >
4938 :echo "%" --> %
4939< This just echoes the '%' character. >
4940 :echo expand("%") --> filename
4941< This calls the expand() function to expand the '%'.
4942
4943 *:echoh* *:echohl*
4944:echoh[l] {name} Use the highlight group {name} for the following
4945 |:echo|, |:echon| and |:echomsg| commands. Also used
4946 for the |input()| prompt. Example: >
4947 :echohl WarningMsg | echo "Don't panic!" | echohl None
4948< Don't forget to set the group back to "None",
4949 otherwise all following echo's will be highlighted.
4950
4951 *:echom* *:echomsg*
4952:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
4953 message in the |message-history|.
4954 Spaces are placed between the arguments as with the
4955 |:echo| command. But unprintable characters are
4956 displayed, not interpreted.
4957 Uses the highlighting set by the |:echohl| command.
4958 Example: >
4959 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
4960<
4961 *:echoe* *:echoerr*
4962:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
4963 message in the |message-history|. When used in a
4964 script or function the line number will be added.
4965 Spaces are placed between the arguments as with the
4966 :echo command. When used inside a try conditional,
4967 the message is raised as an error exception instead
4968 (see |try-echoerr|).
4969 Example: >
4970 :echoerr "This script just failed!"
4971< If you just want a highlighted message use |:echohl|.
4972 And to get a beep: >
4973 :exe "normal \<Esc>"
4974<
4975 *:exe* *:execute*
4976:exe[cute] {expr1} .. Executes the string that results from the evaluation
4977 of {expr1} as an Ex command. Multiple arguments are
4978 concatenated, with a space in between. {expr1} is
4979 used as the processed command, command line editing
4980 keys are not recognized.
4981 Cannot be followed by a comment.
4982 Examples: >
4983 :execute "buffer " nextbuf
4984 :execute "normal " count . "w"
4985<
4986 ":execute" can be used to append a command to commands
4987 that don't accept a '|'. Example: >
4988 :execute '!ls' | echo "theend"
4989
4990< ":execute" is also a nice way to avoid having to type
4991 control characters in a Vim script for a ":normal"
4992 command: >
4993 :execute "normal ixxx\<Esc>"
4994< This has an <Esc> character, see |expr-string|.
4995
4996 Note: The executed string may be any command-line, but
Bram Moolenaard8b02732005-01-14 21:48:43 +00004997 you cannot start or end a "while", "for" or "if"
4998 command. Thus this is illegal: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 :execute 'while i > 5'
5000 :execute 'echo "test" | break'
5001<
5002 It is allowed to have a "while" or "if" command
5003 completely in the executed string: >
5004 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
5005<
5006
5007 *:comment*
5008 ":execute", ":echo" and ":echon" cannot be followed by
5009 a comment directly, because they see the '"' as the
5010 start of a string. But, you can use '|' followed by a
5011 comment. Example: >
5012 :echo "foo" | "this is a comment
5013
5014==============================================================================
50158. Exception handling *exception-handling*
5016
5017The Vim script language comprises an exception handling feature. This section
5018explains how it can be used in a Vim script.
5019
5020Exceptions may be raised by Vim on an error or on interrupt, see
5021|catch-errors| and |catch-interrupt|. You can also explicitly throw an
5022exception by using the ":throw" command, see |throw-catch|.
5023
5024
5025TRY CONDITIONALS *try-conditionals*
5026
5027Exceptions can be caught or can cause cleanup code to be executed. You can
5028use a try conditional to specify catch clauses (that catch exceptions) and/or
5029a finally clause (to be executed for cleanup).
5030 A try conditional begins with a |:try| command and ends at the matching
5031|:endtry| command. In between, you can use a |:catch| command to start
5032a catch clause, or a |:finally| command to start a finally clause. There may
5033be none or multiple catch clauses, but there is at most one finally clause,
5034which must not be followed by any catch clauses. The lines before the catch
5035clauses and the finally clause is called a try block. >
5036
5037 :try
5038 : ...
5039 : ... TRY BLOCK
5040 : ...
5041 :catch /{pattern}/
5042 : ...
5043 : ... CATCH CLAUSE
5044 : ...
5045 :catch /{pattern}/
5046 : ...
5047 : ... CATCH CLAUSE
5048 : ...
5049 :finally
5050 : ...
5051 : ... FINALLY CLAUSE
5052 : ...
5053 :endtry
5054
5055The try conditional allows to watch code for exceptions and to take the
5056appropriate actions. Exceptions from the try block may be caught. Exceptions
5057from the try block and also the catch clauses may cause cleanup actions.
5058 When no exception is thrown during execution of the try block, the control
5059is transferred to the finally clause, if present. After its execution, the
5060script continues with the line following the ":endtry".
5061 When an exception occurs during execution of the try block, the remaining
5062lines in the try block are skipped. The exception is matched against the
5063patterns specified as arguments to the ":catch" commands. The catch clause
5064after the first matching ":catch" is taken, other catch clauses are not
5065executed. The catch clause ends when the next ":catch", ":finally", or
5066":endtry" command is reached - whatever is first. Then, the finally clause
5067(if present) is executed. When the ":endtry" is reached, the script execution
5068continues in the following line as usual.
5069 When an exception that does not match any of the patterns specified by the
5070":catch" commands is thrown in the try block, the exception is not caught by
5071that try conditional and none of the catch clauses is executed. Only the
5072finally clause, if present, is taken. The exception pends during execution of
5073the finally clause. It is resumed at the ":endtry", so that commands after
5074the ":endtry" are not executed and the exception might be caught elsewhere,
5075see |try-nesting|.
5076 When during execution of a catch clause another exception is thrown, the
5077remaining lines in that catch clause are not executed. The new exception is
5078not matched against the patterns in any of the ":catch" commands of the same
5079try conditional and none of its catch clauses is taken. If there is, however,
5080a finally clause, it is executed, and the exception pends during its
5081execution. The commands following the ":endtry" are not executed. The new
5082exception might, however, be caught elsewhere, see |try-nesting|.
5083 When during execution of the finally clause (if present) an exception is
5084thrown, the remaining lines in the finally clause are skipped. If the finally
5085clause has been taken because of an exception from the try block or one of the
5086catch clauses, the original (pending) exception is discarded. The commands
5087following the ":endtry" are not executed, and the exception from the finally
5088clause is propagated and can be caught elsewhere, see |try-nesting|.
5089
5090The finally clause is also executed, when a ":break" or ":continue" for
5091a ":while" loop enclosing the complete try conditional is executed from the
5092try block or a catch clause. Or when a ":return" or ":finish" is executed
5093from the try block or a catch clause of a try conditional in a function or
5094sourced script, respectively. The ":break", ":continue", ":return", or
5095":finish" pends during execution of the finally clause and is resumed when the
5096":endtry" is reached. It is, however, discarded when an exception is thrown
5097from the finally clause.
5098 When a ":break" or ":continue" for a ":while" loop enclosing the complete
5099try conditional or when a ":return" or ":finish" is encountered in the finally
5100clause, the rest of the finally clause is skipped, and the ":break",
5101":continue", ":return" or ":finish" is executed as usual. If the finally
5102clause has been taken because of an exception or an earlier ":break",
5103":continue", ":return", or ":finish" from the try block or a catch clause,
5104this pending exception or command is discarded.
5105
5106For examples see |throw-catch| and |try-finally|.
5107
5108
5109NESTING OF TRY CONDITIONALS *try-nesting*
5110
5111Try conditionals can be nested arbitrarily. That is, a complete try
5112conditional can be put into the try block, a catch clause, or the finally
5113clause of another try conditional. If the inner try conditional does not
5114catch an exception thrown in its try block or throws a new exception from one
5115of its catch clauses or its finally clause, the outer try conditional is
5116checked according to the rules above. If the inner try conditional is in the
5117try block of the outer try conditional, its catch clauses are checked, but
5118otherwise only the finally clause is executed. It does not matter for
5119nesting, whether the inner try conditional is directly contained in the outer
5120one, or whether the outer one sources a script or calls a function containing
5121the inner try conditional.
5122
5123When none of the active try conditionals catches an exception, just their
5124finally clauses are executed. Thereafter, the script processing terminates.
5125An error message is displayed in case of an uncaught exception explicitly
5126thrown by a ":throw" command. For uncaught error and interrupt exceptions
5127implicitly raised by Vim, the error message(s) or interrupt message are shown
5128as usual.
5129
5130For examples see |throw-catch|.
5131
5132
5133EXAMINING EXCEPTION HANDLING CODE *except-examine*
5134
5135Exception handling code can get tricky. If you are in doubt what happens, set
5136'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
5137script file. Then you see when an exception is thrown, discarded, caught, or
5138finished. When using a verbosity level of at least 14, things pending in
5139a finally clause are also shown. This information is also given in debug mode
5140(see |debug-scripts|).
5141
5142
5143THROWING AND CATCHING EXCEPTIONS *throw-catch*
5144
5145You can throw any number or string as an exception. Use the |:throw| command
5146and pass the value to be thrown as argument: >
5147 :throw 4711
5148 :throw "string"
5149< *throw-expression*
5150You can also specify an expression argument. The expression is then evaluated
5151first, and the result is thrown: >
5152 :throw 4705 + strlen("string")
5153 :throw strpart("strings", 0, 6)
5154
5155An exception might be thrown during evaluation of the argument of the ":throw"
5156command. Unless it is caught there, the expression evaluation is abandoned.
5157The ":throw" command then does not throw a new exception.
5158 Example: >
5159
5160 :function! Foo(arg)
5161 : try
5162 : throw a:arg
5163 : catch /foo/
5164 : endtry
5165 : return 1
5166 :endfunction
5167 :
5168 :function! Bar()
5169 : echo "in Bar"
5170 : return 4710
5171 :endfunction
5172 :
5173 :throw Foo("arrgh") + Bar()
5174
5175This throws "arrgh", and "in Bar" is not displayed since Bar() is not
5176executed. >
5177 :throw Foo("foo") + Bar()
5178however displays "in Bar" and throws 4711.
5179
5180Any other command that takes an expression as argument might also be
5181abandoned by an (uncaught) exception during the expression evaluation. The
5182exception is then propagated to the caller of the command.
5183 Example: >
5184
5185 :if Foo("arrgh")
5186 : echo "then"
5187 :else
5188 : echo "else"
5189 :endif
5190
5191Here neither of "then" or "else" is displayed.
5192
5193 *catch-order*
5194Exceptions can be caught by a try conditional with one or more |:catch|
5195commands, see |try-conditionals|. The values to be caught by each ":catch"
5196command can be specified as a pattern argument. The subsequent catch clause
5197gets executed when a matching exception is caught.
5198 Example: >
5199
5200 :function! Foo(value)
5201 : try
5202 : throw a:value
5203 : catch /^\d\+$/
5204 : echo "Number thrown"
5205 : catch /.*/
5206 : echo "String thrown"
5207 : endtry
5208 :endfunction
5209 :
5210 :call Foo(0x1267)
5211 :call Foo('string')
5212
5213The first call to Foo() displays "Number thrown", the second "String thrown".
5214An exception is matched against the ":catch" commands in the order they are
5215specified. Only the first match counts. So you should place the more
5216specific ":catch" first. The following order does not make sense: >
5217
5218 : catch /.*/
5219 : echo "String thrown"
5220 : catch /^\d\+$/
5221 : echo "Number thrown"
5222
5223The first ":catch" here matches always, so that the second catch clause is
5224never taken.
5225
5226 *throw-variables*
5227If you catch an exception by a general pattern, you may access the exact value
5228in the variable |v:exception|: >
5229
5230 : catch /^\d\+$/
5231 : echo "Number thrown. Value is" v:exception
5232
5233You may also be interested where an exception was thrown. This is stored in
5234|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
5235exception most recently caught as long it is not finished.
5236 Example: >
5237
5238 :function! Caught()
5239 : if v:exception != ""
5240 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
5241 : else
5242 : echo 'Nothing caught'
5243 : endif
5244 :endfunction
5245 :
5246 :function! Foo()
5247 : try
5248 : try
5249 : try
5250 : throw 4711
5251 : finally
5252 : call Caught()
5253 : endtry
5254 : catch /.*/
5255 : call Caught()
5256 : throw "oops"
5257 : endtry
5258 : catch /.*/
5259 : call Caught()
5260 : finally
5261 : call Caught()
5262 : endtry
5263 :endfunction
5264 :
5265 :call Foo()
5266
5267This displays >
5268
5269 Nothing caught
5270 Caught "4711" in function Foo, line 4
5271 Caught "oops" in function Foo, line 10
5272 Nothing caught
5273
5274A practical example: The following command ":LineNumber" displays the line
5275number in the script or function where it has been used: >
5276
5277 :function! LineNumber()
5278 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
5279 :endfunction
5280 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
5281<
5282 *try-nested*
5283An exception that is not caught by a try conditional can be caught by
5284a surrounding try conditional: >
5285
5286 :try
5287 : try
5288 : throw "foo"
5289 : catch /foobar/
5290 : echo "foobar"
5291 : finally
5292 : echo "inner finally"
5293 : endtry
5294 :catch /foo/
5295 : echo "foo"
5296 :endtry
5297
5298The inner try conditional does not catch the exception, just its finally
5299clause is executed. The exception is then caught by the outer try
5300conditional. The example displays "inner finally" and then "foo".
5301
5302 *throw-from-catch*
5303You can catch an exception and throw a new one to be caught elsewhere from the
5304catch clause: >
5305
5306 :function! Foo()
5307 : throw "foo"
5308 :endfunction
5309 :
5310 :function! Bar()
5311 : try
5312 : call Foo()
5313 : catch /foo/
5314 : echo "Caught foo, throw bar"
5315 : throw "bar"
5316 : endtry
5317 :endfunction
5318 :
5319 :try
5320 : call Bar()
5321 :catch /.*/
5322 : echo "Caught" v:exception
5323 :endtry
5324
5325This displays "Caught foo, throw bar" and then "Caught bar".
5326
5327 *rethrow*
5328There is no real rethrow in the Vim script language, but you may throw
5329"v:exception" instead: >
5330
5331 :function! Bar()
5332 : try
5333 : call Foo()
5334 : catch /.*/
5335 : echo "Rethrow" v:exception
5336 : throw v:exception
5337 : endtry
5338 :endfunction
5339< *try-echoerr*
5340Note that this method cannot be used to "rethrow" Vim error or interrupt
5341exceptions, because it is not possible to fake Vim internal exceptions.
5342Trying so causes an error exception. You should throw your own exception
5343denoting the situation. If you want to cause a Vim error exception containing
5344the original error exception value, you can use the |:echoerr| command: >
5345
5346 :try
5347 : try
5348 : asdf
5349 : catch /.*/
5350 : echoerr v:exception
5351 : endtry
5352 :catch /.*/
5353 : echo v:exception
5354 :endtry
5355
5356This code displays
5357
5358 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
5359
5360
5361CLEANUP CODE *try-finally*
5362
5363Scripts often change global settings and restore them at their end. If the
5364user however interrupts the script by pressing CTRL-C, the settings remain in
5365an inconsistent state. The same may happen to you in the development phase of
5366a script when an error occurs or you explicitly throw an exception without
5367catching it. You can solve these problems by using a try conditional with
5368a finally clause for restoring the settings. Its execution is guaranteed on
5369normal control flow, on error, on an explicit ":throw", and on interrupt.
5370(Note that errors and interrupts from inside the try conditional are converted
5371to exceptions. When not caught, they terminate the script after the finally
5372clause has been executed.)
5373Example: >
5374
5375 :try
5376 : let s:saved_ts = &ts
5377 : set ts=17
5378 :
5379 : " Do the hard work here.
5380 :
5381 :finally
5382 : let &ts = s:saved_ts
5383 : unlet s:saved_ts
5384 :endtry
5385
5386This method should be used locally whenever a function or part of a script
5387changes global settings which need to be restored on failure or normal exit of
5388that function or script part.
5389
5390 *break-finally*
5391Cleanup code works also when the try block or a catch clause is left by
5392a ":continue", ":break", ":return", or ":finish".
5393 Example: >
5394
5395 :let first = 1
5396 :while 1
5397 : try
5398 : if first
5399 : echo "first"
5400 : let first = 0
5401 : continue
5402 : else
5403 : throw "second"
5404 : endif
5405 : catch /.*/
5406 : echo v:exception
5407 : break
5408 : finally
5409 : echo "cleanup"
5410 : endtry
5411 : echo "still in while"
5412 :endwhile
5413 :echo "end"
5414
5415This displays "first", "cleanup", "second", "cleanup", and "end". >
5416
5417 :function! Foo()
5418 : try
5419 : return 4711
5420 : finally
5421 : echo "cleanup\n"
5422 : endtry
5423 : echo "Foo still active"
5424 :endfunction
5425 :
5426 :echo Foo() "returned by Foo"
5427
5428This displays "cleanup" and "4711 returned by Foo". You don't need to add an
5429extra ":return" in the finally clause. (Above all, this would override the
5430return value.)
5431
5432 *except-from-finally*
5433Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
5434a finally clause is possible, but not recommended since it abandons the
5435cleanup actions for the try conditional. But, of course, interrupt and error
5436exceptions might get raised from a finally clause.
5437 Example where an error in the finally clause stops an interrupt from
5438working correctly: >
5439
5440 :try
5441 : try
5442 : echo "Press CTRL-C for interrupt"
5443 : while 1
5444 : endwhile
5445 : finally
5446 : unlet novar
5447 : endtry
5448 :catch /novar/
5449 :endtry
5450 :echo "Script still running"
5451 :sleep 1
5452
5453If you need to put commands that could fail into a finally clause, you should
5454think about catching or ignoring the errors in these commands, see
5455|catch-errors| and |ignore-errors|.
5456
5457
5458CATCHING ERRORS *catch-errors*
5459
5460If you want to catch specific errors, you just have to put the code to be
5461watched in a try block and add a catch clause for the error message. The
5462presence of the try conditional causes all errors to be converted to an
5463exception. No message is displayed and |v:errmsg| is not set then. To find
5464the right pattern for the ":catch" command, you have to know how the format of
5465the error exception is.
5466 Error exceptions have the following format: >
5467
5468 Vim({cmdname}):{errmsg}
5469or >
5470 Vim:{errmsg}
5471
5472{cmdname} is the name of the command that failed; the second form is used when
5473the command name is not known. {errmsg} is the error message usually produced
5474when the error occurs outside try conditionals. It always begins with
5475a capital "E", followed by a two or three-digit error number, a colon, and
5476a space.
5477
5478Examples:
5479
5480The command >
5481 :unlet novar
5482normally produces the error message >
5483 E108: No such variable: "novar"
5484which is converted inside try conditionals to an exception >
5485 Vim(unlet):E108: No such variable: "novar"
5486
5487The command >
5488 :dwim
5489normally produces the error message >
5490 E492: Not an editor command: dwim
5491which is converted inside try conditionals to an exception >
5492 Vim:E492: Not an editor command: dwim
5493
5494You can catch all ":unlet" errors by a >
5495 :catch /^Vim(unlet):/
5496or all errors for misspelled command names by a >
5497 :catch /^Vim:E492:/
5498
5499Some error messages may be produced by different commands: >
5500 :function nofunc
5501and >
5502 :delfunction nofunc
5503both produce the error message >
5504 E128: Function name must start with a capital: nofunc
5505which is converted inside try conditionals to an exception >
5506 Vim(function):E128: Function name must start with a capital: nofunc
5507or >
5508 Vim(delfunction):E128: Function name must start with a capital: nofunc
5509respectively. You can catch the error by its number independently on the
5510command that caused it if you use the following pattern: >
5511 :catch /^Vim(\a\+):E128:/
5512
5513Some commands like >
5514 :let x = novar
5515produce multiple error messages, here: >
5516 E121: Undefined variable: novar
5517 E15: Invalid expression: novar
5518Only the first is used for the exception value, since it is the most specific
5519one (see |except-several-errors|). So you can catch it by >
5520 :catch /^Vim(\a\+):E121:/
5521
5522You can catch all errors related to the name "nofunc" by >
5523 :catch /\<nofunc\>/
5524
5525You can catch all Vim errors in the ":write" and ":read" commands by >
5526 :catch /^Vim(\(write\|read\)):E\d\+:/
5527
5528You can catch all Vim errors by the pattern >
5529 :catch /^Vim\((\a\+)\)\=:E\d\+:/
5530<
5531 *catch-text*
5532NOTE: You should never catch the error message text itself: >
5533 :catch /No such variable/
5534only works in the english locale, but not when the user has selected
5535a different language by the |:language| command. It is however helpful to
5536cite the message text in a comment: >
5537 :catch /^Vim(\a\+):E108:/ " No such variable
5538
5539
5540IGNORING ERRORS *ignore-errors*
5541
5542You can ignore errors in a specific Vim command by catching them locally: >
5543
5544 :try
5545 : write
5546 :catch
5547 :endtry
5548
5549But you are strongly recommended NOT to use this simple form, since it could
5550catch more than you want. With the ":write" command, some autocommands could
5551be executed and cause errors not related to writing, for instance: >
5552
5553 :au BufWritePre * unlet novar
5554
5555There could even be such errors you are not responsible for as a script
5556writer: a user of your script might have defined such autocommands. You would
5557then hide the error from the user.
5558 It is much better to use >
5559
5560 :try
5561 : write
5562 :catch /^Vim(write):/
5563 :endtry
5564
5565which only catches real write errors. So catch only what you'd like to ignore
5566intentionally.
5567
5568For a single command that does not cause execution of autocommands, you could
5569even suppress the conversion of errors to exceptions by the ":silent!"
5570command: >
5571 :silent! nunmap k
5572This works also when a try conditional is active.
5573
5574
5575CATCHING INTERRUPTS *catch-interrupt*
5576
5577When there are active try conditionals, an interrupt (CTRL-C) is converted to
5578the exception "Vim:Interrupt". You can catch it like every exception. The
5579script is not terminated, then.
5580 Example: >
5581
5582 :function! TASK1()
5583 : sleep 10
5584 :endfunction
5585
5586 :function! TASK2()
5587 : sleep 20
5588 :endfunction
5589
5590 :while 1
5591 : let command = input("Type a command: ")
5592 : try
5593 : if command == ""
5594 : continue
5595 : elseif command == "END"
5596 : break
5597 : elseif command == "TASK1"
5598 : call TASK1()
5599 : elseif command == "TASK2"
5600 : call TASK2()
5601 : else
5602 : echo "\nIllegal command:" command
5603 : continue
5604 : endif
5605 : catch /^Vim:Interrupt$/
5606 : echo "\nCommand interrupted"
5607 : " Caught the interrupt. Continue with next prompt.
5608 : endtry
5609 :endwhile
5610
5611You can interrupt a task here by pressing CTRL-C; the script then asks for
5612a new command. If you press CTRL-C at the prompt, the script is terminated.
5613
5614For testing what happens when CTRL-C would be pressed on a specific line in
5615your script, use the debug mode and execute the |>quit| or |>interrupt|
5616command on that line. See |debug-scripts|.
5617
5618
5619CATCHING ALL *catch-all*
5620
5621The commands >
5622
5623 :catch /.*/
5624 :catch //
5625 :catch
5626
5627catch everything, error exceptions, interrupt exceptions and exceptions
5628explicitly thrown by the |:throw| command. This is useful at the top level of
5629a script in order to catch unexpected things.
5630 Example: >
5631
5632 :try
5633 :
5634 : " do the hard work here
5635 :
5636 :catch /MyException/
5637 :
5638 : " handle known problem
5639 :
5640 :catch /^Vim:Interrupt$/
5641 : echo "Script interrupted"
5642 :catch /.*/
5643 : echo "Internal error (" . v:exception . ")"
5644 : echo " - occurred at " . v:throwpoint
5645 :endtry
5646 :" end of script
5647
5648Note: Catching all might catch more things than you want. Thus, you are
5649strongly encouraged to catch only for problems that you can really handle by
5650specifying a pattern argument to the ":catch".
5651 Example: Catching all could make it nearly impossible to interrupt a script
5652by pressing CTRL-C: >
5653
5654 :while 1
5655 : try
5656 : sleep 1
5657 : catch
5658 : endtry
5659 :endwhile
5660
5661
5662EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
5663
5664Exceptions may be used during execution of autocommands. Example: >
5665
5666 :autocmd User x try
5667 :autocmd User x throw "Oops!"
5668 :autocmd User x catch
5669 :autocmd User x echo v:exception
5670 :autocmd User x endtry
5671 :autocmd User x throw "Arrgh!"
5672 :autocmd User x echo "Should not be displayed"
5673 :
5674 :try
5675 : doautocmd User x
5676 :catch
5677 : echo v:exception
5678 :endtry
5679
5680This displays "Oops!" and "Arrgh!".
5681
5682 *except-autocmd-Pre*
5683For some commands, autocommands get executed before the main action of the
5684command takes place. If an exception is thrown and not caught in the sequence
5685of autocommands, the sequence and the command that caused its execution are
5686abandoned and the exception is propagated to the caller of the command.
5687 Example: >
5688
5689 :autocmd BufWritePre * throw "FAIL"
5690 :autocmd BufWritePre * echo "Should not be displayed"
5691 :
5692 :try
5693 : write
5694 :catch
5695 : echo "Caught:" v:exception "from" v:throwpoint
5696 :endtry
5697
5698Here, the ":write" command does not write the file currently being edited (as
5699you can see by checking 'modified'), since the exception from the BufWritePre
5700autocommand abandons the ":write". The exception is then caught and the
5701script displays: >
5702
5703 Caught: FAIL from BufWrite Auto commands for "*"
5704<
5705 *except-autocmd-Post*
5706For some commands, autocommands get executed after the main action of the
5707command has taken place. If this main action fails and the command is inside
5708an active try conditional, the autocommands are skipped and an error exception
5709is thrown that can be caught by the caller of the command.
5710 Example: >
5711
5712 :autocmd BufWritePost * echo "File successfully written!"
5713 :
5714 :try
5715 : write /i/m/p/o/s/s/i/b/l/e
5716 :catch
5717 : echo v:exception
5718 :endtry
5719
5720This just displays: >
5721
5722 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
5723
5724If you really need to execute the autocommands even when the main action
5725fails, trigger the event from the catch clause.
5726 Example: >
5727
5728 :autocmd BufWritePre * set noreadonly
5729 :autocmd BufWritePost * set readonly
5730 :
5731 :try
5732 : write /i/m/p/o/s/s/i/b/l/e
5733 :catch
5734 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
5735 :endtry
5736<
5737You can also use ":silent!": >
5738
5739 :let x = "ok"
5740 :let v:errmsg = ""
5741 :autocmd BufWritePost * if v:errmsg != ""
5742 :autocmd BufWritePost * let x = "after fail"
5743 :autocmd BufWritePost * endif
5744 :try
5745 : silent! write /i/m/p/o/s/s/i/b/l/e
5746 :catch
5747 :endtry
5748 :echo x
5749
5750This displays "after fail".
5751
5752If the main action of the command does not fail, exceptions from the
5753autocommands will be catchable by the caller of the command: >
5754
5755 :autocmd BufWritePost * throw ":-("
5756 :autocmd BufWritePost * echo "Should not be displayed"
5757 :
5758 :try
5759 : write
5760 :catch
5761 : echo v:exception
5762 :endtry
5763<
5764 *except-autocmd-Cmd*
5765For some commands, the normal action can be replaced by a sequence of
5766autocommands. Exceptions from that sequence will be catchable by the caller
5767of the command.
5768 Example: For the ":write" command, the caller cannot know whether the file
5769had actually been written when the exception occurred. You need to tell it in
5770some way. >
5771
5772 :if !exists("cnt")
5773 : let cnt = 0
5774 :
5775 : autocmd BufWriteCmd * if &modified
5776 : autocmd BufWriteCmd * let cnt = cnt + 1
5777 : autocmd BufWriteCmd * if cnt % 3 == 2
5778 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5779 : autocmd BufWriteCmd * endif
5780 : autocmd BufWriteCmd * write | set nomodified
5781 : autocmd BufWriteCmd * if cnt % 3 == 0
5782 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5783 : autocmd BufWriteCmd * endif
5784 : autocmd BufWriteCmd * echo "File successfully written!"
5785 : autocmd BufWriteCmd * endif
5786 :endif
5787 :
5788 :try
5789 : write
5790 :catch /^BufWriteCmdError$/
5791 : if &modified
5792 : echo "Error on writing (file contents not changed)"
5793 : else
5794 : echo "Error after writing"
5795 : endif
5796 :catch /^Vim(write):/
5797 : echo "Error on writing"
5798 :endtry
5799
5800When this script is sourced several times after making changes, it displays
5801first >
5802 File successfully written!
5803then >
5804 Error on writing (file contents not changed)
5805then >
5806 Error after writing
5807etc.
5808
5809 *except-autocmd-ill*
5810You cannot spread a try conditional over autocommands for different events.
5811The following code is ill-formed: >
5812
5813 :autocmd BufWritePre * try
5814 :
5815 :autocmd BufWritePost * catch
5816 :autocmd BufWritePost * echo v:exception
5817 :autocmd BufWritePost * endtry
5818 :
5819 :write
5820
5821
5822EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
5823
5824Some programming languages allow to use hierarchies of exception classes or to
5825pass additional information with the object of an exception class. You can do
5826similar things in Vim.
5827 In order to throw an exception from a hierarchy, just throw the complete
5828class name with the components separated by a colon, for instance throw the
5829string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
5830 When you want to pass additional information with your exception class, add
5831it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
5832for an error when writing "myfile".
5833 With the appropriate patterns in the ":catch" command, you can catch for
5834base classes or derived classes of your hierarchy. Additional information in
5835parentheses can be cut out from |v:exception| with the ":substitute" command.
5836 Example: >
5837
5838 :function! CheckRange(a, func)
5839 : if a:a < 0
5840 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
5841 : endif
5842 :endfunction
5843 :
5844 :function! Add(a, b)
5845 : call CheckRange(a:a, "Add")
5846 : call CheckRange(a:b, "Add")
5847 : let c = a:a + a:b
5848 : if c < 0
5849 : throw "EXCEPT:MATHERR:OVERFLOW"
5850 : endif
5851 : return c
5852 :endfunction
5853 :
5854 :function! Div(a, b)
5855 : call CheckRange(a:a, "Div")
5856 : call CheckRange(a:b, "Div")
5857 : if (a:b == 0)
5858 : throw "EXCEPT:MATHERR:ZERODIV"
5859 : endif
5860 : return a:a / a:b
5861 :endfunction
5862 :
5863 :function! Write(file)
5864 : try
5865 : execute "write" a:file
5866 : catch /^Vim(write):/
5867 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
5868 : endtry
5869 :endfunction
5870 :
5871 :try
5872 :
5873 : " something with arithmetics and I/O
5874 :
5875 :catch /^EXCEPT:MATHERR:RANGE/
5876 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
5877 : echo "Range error in" function
5878 :
5879 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
5880 : echo "Math error"
5881 :
5882 :catch /^EXCEPT:IO/
5883 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
5884 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
5885 : if file !~ '^/'
5886 : let file = dir . "/" . file
5887 : endif
5888 : echo 'I/O error for "' . file . '"'
5889 :
5890 :catch /^EXCEPT/
5891 : echo "Unspecified error"
5892 :
5893 :endtry
5894
5895The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
5896a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
5897exceptions with the "Vim" prefix; they are reserved for Vim.
5898 Vim error exceptions are parameterized with the name of the command that
5899failed, if known. See |catch-errors|.
5900
5901
5902PECULIARITIES
5903 *except-compat*
5904The exception handling concept requires that the command sequence causing the
5905exception is aborted immediately and control is transferred to finally clauses
5906and/or a catch clause.
5907
5908In the Vim script language there are cases where scripts and functions
5909continue after an error: in functions without the "abort" flag or in a command
5910after ":silent!", control flow goes to the following line, and outside
5911functions, control flow goes to the line following the outermost ":endwhile"
5912or ":endif". On the other hand, errors should be catchable as exceptions
5913(thus, requiring the immediate abortion).
5914
5915This problem has been solved by converting errors to exceptions and using
5916immediate abortion (if not suppressed by ":silent!") only when a try
5917conditional is active. This is no restriction since an (error) exception can
5918be caught only from an active try conditional. If you want an immediate
5919termination without catching the error, just use a try conditional without
5920catch clause. (You can cause cleanup code being executed before termination
5921by specifying a finally clause.)
5922
5923When no try conditional is active, the usual abortion and continuation
5924behavior is used instead of immediate abortion. This ensures compatibility of
5925scripts written for Vim 6.1 and earlier.
5926
5927However, when sourcing an existing script that does not use exception handling
5928commands (or when calling one of its functions) from inside an active try
5929conditional of a new script, you might change the control flow of the existing
5930script on error. You get the immediate abortion on error and can catch the
5931error in the new script. If however the sourced script suppresses error
5932messages by using the ":silent!" command (checking for errors by testing
5933|v:errmsg| if appropriate), its execution path is not changed. The error is
5934not converted to an exception. (See |:silent|.) So the only remaining cause
5935where this happens is for scripts that don't care about errors and produce
5936error messages. You probably won't want to use such code from your new
5937scripts.
5938
5939 *except-syntax-err*
5940Syntax errors in the exception handling commands are never caught by any of
5941the ":catch" commands of the try conditional they belong to. Its finally
5942clauses, however, is executed.
5943 Example: >
5944
5945 :try
5946 : try
5947 : throw 4711
5948 : catch /\(/
5949 : echo "in catch with syntax error"
5950 : catch
5951 : echo "inner catch-all"
5952 : finally
5953 : echo "inner finally"
5954 : endtry
5955 :catch
5956 : echo 'outer catch-all caught "' . v:exception . '"'
5957 : finally
5958 : echo "outer finally"
5959 :endtry
5960
5961This displays: >
5962 inner finally
5963 outer catch-all caught "Vim(catch):E54: Unmatched \("
5964 outer finally
5965The original exception is discarded and an error exception is raised, instead.
5966
5967 *except-single-line*
5968The ":try", ":catch", ":finally", and ":endtry" commands can be put on
5969a single line, but then syntax errors may make it difficult to recognize the
5970"catch" line, thus you better avoid this.
5971 Example: >
5972 :try | unlet! foo # | catch | endtry
5973raises an error exception for the trailing characters after the ":unlet!"
5974argument, but does not see the ":catch" and ":endtry" commands, so that the
5975error exception is discarded and the "E488: Trailing characters" message gets
5976displayed.
5977
5978 *except-several-errors*
5979When several errors appear in a single command, the first error message is
5980usually the most specific one and therefor converted to the error exception.
5981 Example: >
5982 echo novar
5983causes >
5984 E121: Undefined variable: novar
5985 E15: Invalid expression: novar
5986The value of the error exception inside try conditionals is: >
5987 Vim(echo):E121: Undefined variable: novar
5988< *except-syntax-error*
5989But when a syntax error is detected after a normal error in the same command,
5990the syntax error is used for the exception being thrown.
5991 Example: >
5992 unlet novar #
5993causes >
5994 E108: No such variable: "novar"
5995 E488: Trailing characters
5996The value of the error exception inside try conditionals is: >
5997 Vim(unlet):E488: Trailing characters
5998This is done because the syntax error might change the execution path in a way
5999not intended by the user. Example: >
6000 try
6001 try | unlet novar # | catch | echo v:exception | endtry
6002 catch /.*/
6003 echo "outer catch:" v:exception
6004 endtry
6005This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
6006a "E600: Missing :endtry" error message is given, see |except-single-line|.
6007
6008==============================================================================
60099. Examples *eval-examples*
6010
6011Printing in Hex ~
6012>
6013 :" The function Nr2Hex() returns the Hex string of a number.
6014 :func Nr2Hex(nr)
6015 : let n = a:nr
6016 : let r = ""
6017 : while n
6018 : let r = '0123456789ABCDEF'[n % 16] . r
6019 : let n = n / 16
6020 : endwhile
6021 : return r
6022 :endfunc
6023
6024 :" The function String2Hex() converts each character in a string to a two
6025 :" character Hex string.
6026 :func String2Hex(str)
6027 : let out = ''
6028 : let ix = 0
6029 : while ix < strlen(a:str)
6030 : let out = out . Nr2Hex(char2nr(a:str[ix]))
6031 : let ix = ix + 1
6032 : endwhile
6033 : return out
6034 :endfunc
6035
6036Example of its use: >
6037 :echo Nr2Hex(32)
6038result: "20" >
6039 :echo String2Hex("32")
6040result: "3332"
6041
6042
6043Sorting lines (by Robert Webb) ~
6044
6045Here is a Vim script to sort lines. Highlight the lines in Vim and type
6046":Sort". This doesn't call any external programs so it'll work on any
6047platform. The function Sort() actually takes the name of a comparison
6048function as its argument, like qsort() does in C. So you could supply it
6049with different comparison functions in order to sort according to date etc.
6050>
6051 :" Function for use with Sort(), to compare two strings.
6052 :func! Strcmp(str1, str2)
6053 : if (a:str1 < a:str2)
6054 : return -1
6055 : elseif (a:str1 > a:str2)
6056 : return 1
6057 : else
6058 : return 0
6059 : endif
6060 :endfunction
6061
6062 :" Sort lines. SortR() is called recursively.
6063 :func! SortR(start, end, cmp)
6064 : if (a:start >= a:end)
6065 : return
6066 : endif
6067 : let partition = a:start - 1
6068 : let middle = partition
6069 : let partStr = getline((a:start + a:end) / 2)
6070 : let i = a:start
6071 : while (i <= a:end)
6072 : let str = getline(i)
6073 : exec "let result = " . a:cmp . "(str, partStr)"
6074 : if (result <= 0)
6075 : " Need to put it before the partition. Swap lines i and partition.
6076 : let partition = partition + 1
6077 : if (result == 0)
6078 : let middle = partition
6079 : endif
6080 : if (i != partition)
6081 : let str2 = getline(partition)
6082 : call setline(i, str2)
6083 : call setline(partition, str)
6084 : endif
6085 : endif
6086 : let i = i + 1
6087 : endwhile
6088
6089 : " Now we have a pointer to the "middle" element, as far as partitioning
6090 : " goes, which could be anywhere before the partition. Make sure it is at
6091 : " the end of the partition.
6092 : if (middle != partition)
6093 : let str = getline(middle)
6094 : let str2 = getline(partition)
6095 : call setline(middle, str2)
6096 : call setline(partition, str)
6097 : endif
6098 : call SortR(a:start, partition - 1, a:cmp)
6099 : call SortR(partition + 1, a:end, a:cmp)
6100 :endfunc
6101
6102 :" To Sort a range of lines, pass the range to Sort() along with the name of a
6103 :" function that will compare two lines.
6104 :func! Sort(cmp) range
6105 : call SortR(a:firstline, a:lastline, a:cmp)
6106 :endfunc
6107
6108 :" :Sort takes a range of lines and sorts them.
6109 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
6110<
6111 *sscanf*
6112There is no sscanf() function in Vim. If you need to extract parts from a
6113line, you can use matchstr() and substitute() to do it. This example shows
6114how to get the file name, line number and column number out of a line like
6115"foobar.txt, 123, 45". >
6116 :" Set up the match bit
6117 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
6118 :"get the part matching the whole expression
6119 :let l = matchstr(line, mx)
6120 :"get each item out of the match
6121 :let file = substitute(l, mx, '\1', '')
6122 :let lnum = substitute(l, mx, '\2', '')
6123 :let col = substitute(l, mx, '\3', '')
6124
6125The input is in the variable "line", the results in the variables "file",
6126"lnum" and "col". (idea from Michael Geddes)
6127
6128==============================================================================
612910. No +eval feature *no-eval-feature*
6130
6131When the |+eval| feature was disabled at compile time, none of the expression
6132evaluation commands are available. To prevent this from causing Vim scripts
6133to generate all kinds of errors, the ":if" and ":endif" commands are still
6134recognized, though the argument of the ":if" and everything between the ":if"
6135and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
6136only if the commands are at the start of the line. The ":else" command is not
6137recognized.
6138
6139Example of how to avoid executing commands when the |+eval| feature is
6140missing: >
6141
6142 :if 1
6143 : echo "Expression evaluation is compiled in"
6144 :else
6145 : echo "You will _never_ see this message"
6146 :endif
6147
6148==============================================================================
614911. The sandbox *eval-sandbox* *sandbox* *E48*
6150
6151The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
6152options are evaluated in a sandbox. This means that you are protected from
6153these expressions having nasty side effects. This gives some safety for when
6154these options are set from a modeline. It is also used when the command from
6155a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006156The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157
6158These items are not allowed in the sandbox:
6159 - changing the buffer text
6160 - defining or changing mapping, autocommands, functions, user commands
6161 - setting certain options (see |option-summary|)
6162 - executing a shell command
6163 - reading or writing a file
6164 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006165This is not guaranteed 100% secure, but it should block most attacks.
6166
6167 *:san* *:sandbox*
6168:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
6169 option that may have been set from a modeline, e.g.
6170 'foldexpr'.
6171
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172
6173 vim:tw=78:ts=8:ft=help:norl: