blob: 8ff4bac0679694cdc17a9cc17d491d97ac28ae38 [file] [log] [blame]
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00001*eval.txt* For Vim version 7.0aa. Last change: 2005 Mar 17
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Expression evaluation *expression* *expr* *E15* *eval*
8
9Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|.
10
11Note: Expression evaluation can be disabled at compile time. If this has been
Bram Moolenaare2cc9702005-03-15 22:43:58 +000012done, the features in this document are not available. See |+eval| and
Bram Moolenaard8b02732005-01-14 21:48:43 +000013|no-eval-feature|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000014
Bram Moolenaar13065c42005-01-08 16:08:21 +0000151. Variables |variables|
16 1.1 Variable types
Bram Moolenaar9588a0f2005-01-08 21:45:39 +000017 1.2 Function references |Funcref|
Bram Moolenaar7c626922005-02-07 22:01:03 +000018 1.3 Lists |Lists|
Bram Moolenaard8b02732005-01-14 21:48:43 +000019 1.4 Dictionaries |Dictionaries|
20 1.5 More about variables |more-variables|
Bram Moolenaar13065c42005-01-08 16:08:21 +0000212. Expression syntax |expression-syntax|
223. Internal variable |internal-variables|
234. Builtin Functions |functions|
245. Defining functions |user-functions|
256. Curly braces names |curly-braces-names|
267. Commands |expression-commands|
278. Exception handling |exception-handling|
289. Examples |eval-examples|
2910. No +eval feature |no-eval-feature|
3011. The sandbox |eval-sandbox|
Bram Moolenaar071d4272004-06-13 20:20:40 +000031
32{Vi does not have any of these commands}
33
34==============================================================================
351. Variables *variables*
36
Bram Moolenaar13065c42005-01-08 16:08:21 +0000371.1 Variable types ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +000038 *E712*
Bram Moolenaar13065c42005-01-08 16:08:21 +000039There are four types of variables:
Bram Moolenaar071d4272004-06-13 20:20:40 +000040
Bram Moolenaard8b02732005-01-14 21:48:43 +000041Number A 32 bit signed number.
42 Examples: -123 0x10 0177
43
44String A NUL terminated string of 8-bit unsigned characters (bytes).
45 Examples: "ab\txx\"--" 'x-z''a,c'
46
47Funcref A reference to a function |Funcref|.
48 Example: function("strlen")
49
50List An ordered sequence of items |List|.
51 Example: [1, 2, ['a', 'b']]
Bram Moolenaar071d4272004-06-13 20:20:40 +000052
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000053The Number and String types are converted automatically, depending on how they
54are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +000055
56Conversion from a Number to a String is by making the ASCII representation of
57the Number. Examples: >
58 Number 123 --> String "123"
59 Number 0 --> String "0"
60 Number -1 --> String "-1"
61
62Conversion from a String to a Number is done by converting the first digits
63to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If
64the String doesn't start with digits, the result is zero. Examples: >
65 String "456" --> Number 456
66 String "6bar" --> Number 6
67 String "foo" --> Number 0
68 String "0xf1" --> Number 241
69 String "0100" --> Number 64
70 String "-8" --> Number -8
71 String "+8" --> Number 0
72
73To force conversion from String to Number, add zero to it: >
74 :echo "0100" + 0
75
76For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
77
78Note that in the command >
79 :if "foo"
80"foo" is converted to 0, which means FALSE. To test for a non-empty string,
81use strlen(): >
82 :if strlen("foo")
Bram Moolenaar748bf032005-02-02 23:04:36 +000083< *E745* *E728* *E703* *E729* *E730* *E731*
84List, Dictionary and Funcref types are not automatically converted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000085
Bram Moolenaar13065c42005-01-08 16:08:21 +000086 *E706*
87You will get an error if you try to change the type of a variable. You need
88to |:unlet| it first to avoid this error. String and Number are considered
Bram Moolenaard8b02732005-01-14 21:48:43 +000089equivalent though. Consider this sequence of commands: >
Bram Moolenaar13065c42005-01-08 16:08:21 +000090 :let l = "string"
Bram Moolenaar9588a0f2005-01-08 21:45:39 +000091 :let l = 44 " changes type from String to Number
Bram Moolenaar13065c42005-01-08 16:08:21 +000092 :let l = [1, 2, 3] " error!
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000093
Bram Moolenaar13065c42005-01-08 16:08:21 +000094
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000951.2 Function references ~
Bram Moolenaar748bf032005-02-02 23:04:36 +000096 *Funcref* *E695* *E718*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000097A Funcref variable is obtained with the |function()| function. It can be used
Bram Moolenaar3a3a7232005-01-17 22:16:15 +000098in an expression in the place of a function name, before the parenthesis
99around the arguments, to invoke the function it refers to. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000100
101 :let Fn = function("MyFunc")
102 :echo Fn()
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000103< *E704* *E705* *E707*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000104A Funcref variable must start with a capital, "s:", "w:" or "b:". You cannot
105have both a Funcref variable and a function with the same name.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000106
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000107A special case is defining a function and directly assigning its Funcref to a
108Dictionary entry. Example: >
109 :function dict.init() dict
110 : let self.val = 0
111 :endfunction
112
113The key of the Dictionary can start with a lower case letter. The actual
114function name is not used here. Also see |numbered-function|.
115
116A Funcref can also be used with the |:call| command: >
117 :call Fn()
118 :call dict.init()
Bram Moolenaar13065c42005-01-08 16:08:21 +0000119
120The name of the referenced function can be obtained with |string()|. >
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000121 :let func = string(Fn)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000122
123You can use |call()| to invoke a Funcref and use a list variable for the
124arguments: >
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000125 :let r = call(Fn, mylist)
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000126
127
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001281.3 Lists ~
Bram Moolenaar7c626922005-02-07 22:01:03 +0000129 *List* *Lists* *E686*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000130A List is an ordered sequence of items. An item can be of any type. Items
131can be accessed by their index number. Items can be added and removed at any
132position in the sequence.
133
Bram Moolenaar13065c42005-01-08 16:08:21 +0000134
135List creation ~
136 *E696* *E697*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000137A List is created with a comma separated list of items in square brackets.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000138Examples: >
139 :let mylist = [1, two, 3, "four"]
140 :let emptylist = []
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000141
142An item can be any expression. Using a List for an item creates a
Bram Moolenaar13065c42005-01-08 16:08:21 +0000143nested List: >
144 :let nestlist = [[11, 12], [21, 22], [31, 32]]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000145
146An extra comma after the last item is ignored.
147
Bram Moolenaar13065c42005-01-08 16:08:21 +0000148
149List index ~
150 *list-index* *E684*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000151An item in the List can be accessed by putting the index in square brackets
Bram Moolenaar13065c42005-01-08 16:08:21 +0000152after the List. Indexes are zero-based, thus the first item has index zero. >
153 :let item = mylist[0] " get the first item: 1
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000154 :let item = mylist[2] " get the third item: 3
Bram Moolenaar13065c42005-01-08 16:08:21 +0000155
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000156When the resulting item is a list this can be repeated: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000157 :let item = nestlist[0][1] " get the first list, second item: 12
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000158<
Bram Moolenaar13065c42005-01-08 16:08:21 +0000159A negative index is counted from the end. Index -1 refers to the last item in
160the List, -2 to the last but one item, etc. >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000161 :let last = mylist[-1] " get the last item: "four"
162
Bram Moolenaar13065c42005-01-08 16:08:21 +0000163To avoid an error for an invalid index use the |get()| function. When an item
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000164is not available it returns zero or the default value you specify: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000165 :echo get(mylist, idx)
166 :echo get(mylist, idx, "NONE")
167
168
169List concatenation ~
170
171Two lists can be concatenated with the "+" operator: >
172 :let longlist = mylist + [5, 6]
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000173 :let mylist += [7, 8]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000174
175To prepend or append an item turn the item into a list by putting [] around
176it. To change a list in-place see |list-modification| below.
177
178
179Sublist ~
180
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000181A part of the List can be obtained by specifying the first and last index,
182separated by a colon in square brackets: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000183 :let shortlist = mylist[2:-1] " get List [3, "four"]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000184
185Omitting the first index is similar to zero. Omitting the last index is
186similar to -1. The difference is that there is no error if the items are not
187available. >
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000188 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
189 :let shortlist = mylist[2:2] " List with one item: [3]
190 :let otherlist = mylist[:] " make a copy of the List
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000191
Bram Moolenaard8b02732005-01-14 21:48:43 +0000192The second index can be just before the first index. In that case the result
193is an empty list. If the second index is lower, this results in an error. >
194 :echo mylist[2:1] " result: []
195 :echo mylist[2:0] " error!
196
Bram 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 Moolenaare2cc9702005-03-15 22:43:58 +0000448 :call filter(dict 'v:val =~ "x"')
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000449This 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
Bram Moolenaar05159a02005-02-26 23:04:13 +0000964function call *expr-function* *E116* *E118* *E119* *E120*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965-------------
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
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001108 *v:beval_col* *beval_col-variable*
1109v:beval_col The number of the column, over which the mouse pointer is.
1110 This is the byte index in the |v:beval_lnum| line.
1111 Only valid while evaluating the 'balloonexpr' option.
1112
1113 *v:beval_bufnr* *beval_bufnr-variable*
1114v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
1115 valid while evaluating the 'balloonexpr' option.
1116
1117 *v:beval_lnum* *beval_lnum-variable*
1118v:beval_lnum The number of the line, over which the mouse pointer is. Only
1119 valid while evaluating the 'balloonexpr' option.
1120
1121 *v:beval_text* *beval_text-variable*
1122v:beval_text The text under or after the mouse pointer. Usually a word as it is
1123 useful for debugging a C program. 'iskeyword' applies, but a
1124 dot and "->" before the position is included. When on a ']'
1125 the text before it is used, including the matching '[' and
1126 word before it. When on a Visual area within one line the
1127 highlighted text is used.
1128 Only valid while evaluating the 'balloonexpr' option.
1129
1130 *v:beval_winnr* *beval_winnr-variable*
1131v:beval_winnr The number of the window, over which the mouse pointer is. Only
1132 valid while evaluating the 'balloonexpr' option.
1133
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 *v:charconvert_from* *charconvert_from-variable*
1135v:charconvert_from
1136 The name of the character encoding of a file to be converted.
1137 Only valid while evaluating the 'charconvert' option.
1138
1139 *v:charconvert_to* *charconvert_to-variable*
1140v:charconvert_to
1141 The name of the character encoding of a file after conversion.
1142 Only valid while evaluating the 'charconvert' option.
1143
1144 *v:cmdarg* *cmdarg-variable*
1145v:cmdarg This variable is used for two purposes:
1146 1. The extra arguments given to a file read/write command.
1147 Currently these are "++enc=" and "++ff=". This variable is
1148 set before an autocommand event for a file read/write
1149 command is triggered. There is a leading space to make it
1150 possible to append this variable directly after the
1151 read/write command. Note: The "+cmd" argument isn't
1152 included here, because it will be executed anyway.
1153 2. When printing a PostScript file with ":hardcopy" this is
1154 the argument for the ":hardcopy" command. This can be used
1155 in 'printexpr'.
1156
1157 *v:cmdbang* *cmdbang-variable*
1158v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1159 was used the value is 1, otherwise it is 0. Note that this
1160 can only be used in autocommands. For user commands |<bang>|
1161 can be used.
1162
1163 *v:count* *count-variable*
1164v:count The count given for the last Normal mode command. Can be used
1165 to get the count before a mapping. Read-only. Example: >
1166 :map _x :<C-U>echo "the count is " . v:count<CR>
1167< Note: The <C-U> is required to remove the line range that you
1168 get when typing ':' after a count.
1169 "count" also works, for backwards compatibility.
1170
1171 *v:count1* *count1-variable*
1172v:count1 Just like "v:count", but defaults to one when no count is
1173 used.
1174
1175 *v:ctype* *ctype-variable*
1176v:ctype The current locale setting for characters of the runtime
1177 environment. This allows Vim scripts to be aware of the
1178 current locale encoding. Technical: it's the value of
1179 LC_CTYPE. When not using a locale the value is "C".
1180 This variable can not be set directly, use the |:language|
1181 command.
1182 See |multi-lang|.
1183
1184 *v:dying* *dying-variable*
1185v:dying Normally zero. When a deadly signal is caught it's set to
1186 one. When multiple signals are caught the number increases.
1187 Can be used in an autocommand to check if Vim didn't
1188 terminate normally. {only works on Unix}
1189 Example: >
1190 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
1191<
1192 *v:errmsg* *errmsg-variable*
1193v:errmsg Last given error message. It's allowed to set this variable.
1194 Example: >
1195 :let v:errmsg = ""
1196 :silent! next
1197 :if v:errmsg != ""
1198 : ... handle error
1199< "errmsg" also works, for backwards compatibility.
1200
1201 *v:exception* *exception-variable*
1202v:exception The value of the exception most recently caught and not
1203 finished. See also |v:throwpoint| and |throw-variables|.
1204 Example: >
1205 :try
1206 : throw "oops"
1207 :catch /.*/
1208 : echo "caught" v:exception
1209 :endtry
1210< Output: "caught oops".
1211
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001212 *v:fcs_reason* *fcs_reason-variable*
1213v:fcs_reason The reason why the |FileChangedShell| event was triggered.
1214 Can be used in an autocommand to decide what to do and/or what
1215 to set v:fcs_choice to. Possible values:
1216 deleted file no longer exists
1217 conflict file contents, mode or timestamp was
1218 changed and buffer is modified
1219 changed file contents has changed
1220 mode mode of file changed
1221 time only file timestamp changed
1222
1223 *v:fcs_choice* *fcs_choice-variable*
1224v:fcs_choice What should happen after a |FileChangedShell| event was
1225 triggered. Can be used in an autocommand to tell Vim what to
1226 do with the affected buffer:
1227 reload Reload the buffer (does not work if
1228 the file was deleted).
1229 ask Ask the user what to do, as if there
1230 was no autocommand. Except that when
1231 only the timestamp changed nothing
1232 will happen.
1233 <empty> Nothing, the autocommand should do
1234 everything that needs to be done.
1235 The default is empty. If another (invalid) value is used then
1236 Vim behaves like it is empty, there is no warning message.
1237
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 *v:fname_in* *fname_in-variable*
1239v:fname_in The name of the input file. Only valid while evaluating:
1240 option used for ~
1241 'charconvert' file to be converted
1242 'diffexpr' original file
1243 'patchexpr' original file
1244 'printexpr' file to be printed
1245
1246 *v:fname_out* *fname_out-variable*
1247v:fname_out The name of the output file. Only valid while
1248 evaluating:
1249 option used for ~
1250 'charconvert' resulting converted file (*)
1251 'diffexpr' output of diff
1252 'patchexpr' resulting patched file
1253 (*) When doing conversion for a write command (e.g., ":w
1254 file") it will be equal to v:fname_in. When doing conversion
1255 for a read command (e.g., ":e file") it will be a temporary
1256 file and different from v:fname_in.
1257
1258 *v:fname_new* *fname_new-variable*
1259v:fname_new The name of the new version of the file. Only valid while
1260 evaluating 'diffexpr'.
1261
1262 *v:fname_diff* *fname_diff-variable*
1263v:fname_diff The name of the diff (patch) file. Only valid while
1264 evaluating 'patchexpr'.
1265
1266 *v:folddashes* *folddashes-variable*
1267v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
1268 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001269 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001270
1271 *v:foldlevel* *foldlevel-variable*
1272v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001273 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274
1275 *v:foldend* *foldend-variable*
1276v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001277 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278
1279 *v:foldstart* *foldstart-variable*
1280v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001281 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282
Bram Moolenaar843ee412004-06-30 16:16:41 +00001283 *v:insertmode* *insertmode-variable*
1284v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
1285 events. Values:
1286 i Insert mode
1287 r Replace mode
1288 v Virtual Replace mode
1289
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001290 *v:key* *key-variable*
1291v:key Key of the current item of a Dictionary. Only valid while
1292 evaluating the expression used with |map()| and |filter()|.
1293 Read-only.
1294
Bram Moolenaar071d4272004-06-13 20:20:40 +00001295 *v:lang* *lang-variable*
1296v:lang The current locale setting for messages of the runtime
1297 environment. This allows Vim scripts to be aware of the
1298 current language. Technical: it's the value of LC_MESSAGES.
1299 The value is system dependent.
1300 This variable can not be set directly, use the |:language|
1301 command.
1302 It can be different from |v:ctype| when messages are desired
1303 in a different language than what is used for character
1304 encoding. See |multi-lang|.
1305
1306 *v:lc_time* *lc_time-variable*
1307v:lc_time The current locale setting for time messages of the runtime
1308 environment. This allows Vim scripts to be aware of the
1309 current language. Technical: it's the value of LC_TIME.
1310 This variable can not be set directly, use the |:language|
1311 command. See |multi-lang|.
1312
1313 *v:lnum* *lnum-variable*
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001314v:lnum Line number for the 'foldexpr' |fold-expr| and 'indentexpr'
1315 expressions. Only valid while one of these expressions is
1316 being evaluated. Read-only when in the |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317
1318 *v:prevcount* *prevcount-variable*
1319v:prevcount The count given for the last but one Normal mode command.
1320 This is the v:count value of the previous command. Useful if
1321 you want to cancel Visual mode and then use the count. >
1322 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
1323< Read-only.
1324
Bram Moolenaar05159a02005-02-26 23:04:13 +00001325 *v:profiling* *profiling-variable*
1326v:profiling Normally zero. Set to one after using ":profile start".
1327 See |profiling|.
1328
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 *v:progname* *progname-variable*
1330v:progname Contains the name (with path removed) with which Vim was
1331 invoked. Allows you to do special initialisations for "view",
1332 "evim" etc., or any other name you might symlink to Vim.
1333 Read-only.
1334
1335 *v:register* *register-variable*
1336v:register The name of the register supplied to the last normal mode
1337 command. Empty if none were supplied. |getreg()| |setreg()|
1338
1339 *v:servername* *servername-variable*
1340v:servername The resulting registered |x11-clientserver| name if any.
1341 Read-only.
1342
1343 *v:shell_error* *shell_error-variable*
1344v:shell_error Result of the last shell command. When non-zero, the last
1345 shell command had an error. When zero, there was no problem.
1346 This only works when the shell returns the error code to Vim.
1347 The value -1 is often used when the command could not be
1348 executed. Read-only.
1349 Example: >
1350 :!mv foo bar
1351 :if v:shell_error
1352 : echo 'could not rename "foo" to "bar"!'
1353 :endif
1354< "shell_error" also works, for backwards compatibility.
1355
1356 *v:statusmsg* *statusmsg-variable*
1357v:statusmsg Last given status message. It's allowed to set this variable.
1358
1359 *v:termresponse* *termresponse-variable*
1360v:termresponse The escape sequence returned by the terminal for the |t_RV|
1361 termcap entry. It is set when Vim receives an escape sequence
1362 that starts with ESC [ or CSI and ends in a 'c', with only
1363 digits, ';' and '.' in between.
1364 When this option is set, the TermResponse autocommand event is
1365 fired, so that you can react to the response from the
1366 terminal.
1367 The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
1368 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
1369 patch level (since this was introduced in patch 95, it's
1370 always 95 or bigger). Pc is always zero.
1371 {only when compiled with |+termresponse| feature}
1372
1373 *v:this_session* *this_session-variable*
1374v:this_session Full filename of the last loaded or saved session file. See
1375 |:mksession|. It is allowed to set this variable. When no
1376 session file has been saved, this variable is empty.
1377 "this_session" also works, for backwards compatibility.
1378
1379 *v:throwpoint* *throwpoint-variable*
1380v:throwpoint The point where the exception most recently caught and not
1381 finished was thrown. Not set when commands are typed. See
1382 also |v:exception| and |throw-variables|.
1383 Example: >
1384 :try
1385 : throw "oops"
1386 :catch /.*/
1387 : echo "Exception from" v:throwpoint
1388 :endtry
1389< Output: "Exception from test.vim, line 2"
1390
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001391 *v:val* *val-variable*
1392v:val Value of the current item of a List or Dictionary. Only valid
1393 while evaluating the expression used with |map()| and
1394 |filter()|. Read-only.
1395
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396 *v:version* *version-variable*
1397v:version Version number of Vim: Major version number times 100 plus
1398 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
1399 is 501. Read-only. "version" also works, for backwards
1400 compatibility.
1401 Use |has()| to check if a certain patch was included, e.g.: >
1402 if has("patch123")
1403< Note that patch numbers are specific to the version, thus both
1404 version 5.0 and 5.1 may have a patch 123, but these are
1405 completely different.
1406
1407 *v:warningmsg* *warningmsg-variable*
1408v:warningmsg Last given warning message. It's allowed to set this variable.
1409
1410==============================================================================
14114. Builtin Functions *functions*
1412
1413See |function-list| for a list grouped by what the function is used for.
1414
1415(Use CTRL-] on the function name to jump to the full explanation)
1416
1417USAGE RESULT DESCRIPTION ~
1418
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001419add( {list}, {item}) List append {item} to List {list}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001420append( {lnum}, {string}) Number append {string} below line {lnum}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001421append( {lnum}, {list}) Number append lines {list} below line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422argc() Number number of files in the argument list
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001423argidx() Number current index in the argument list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424argv( {nr}) String {nr} entry of the argument list
1425browse( {save}, {title}, {initdir}, {default})
1426 String put up a file requester
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001427browsedir( {title}, {initdir}) String put up a directory requester
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428bufexists( {expr}) Number TRUE if buffer {expr} exists
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001429buflisted( {expr}) Number TRUE if buffer {expr} is listed
1430bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431bufname( {expr}) String Name of the buffer {expr}
1432bufnr( {expr}) Number Number of the buffer {expr}
1433bufwinnr( {expr}) Number window number of buffer {expr}
1434byte2line( {byte}) Number line number at byte count {byte}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001435byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001436call( {func}, {arglist} [, {dict}])
1437 any call {func} with arguments {arglist}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438char2nr( {expr}) Number ASCII value of first char in {expr}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001439cindent( {lnum}) Number C indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440col( {expr}) Number column nr of cursor or mark
1441confirm( {msg} [, {choices} [, {default} [, {type}]]])
1442 Number number of choice picked by user
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001443copy( {expr}) any make a shallow copy of {expr}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001444count( {list}, {expr} [, {start} [, {ic}]])
1445 Number count how many {expr} are in {list}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446cscope_connection( [{num} , {dbpath} [, {prepend}]])
1447 Number checks existence of cscope connection
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001448cursor( {lnum}, {col}) Number position cursor at {lnum}, {col}
1449deepcopy( {expr}) any make a full copy of {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450delete( {fname}) Number delete file {fname}
1451did_filetype() Number TRUE if FileType autocommand event used
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001452diff_filler( {lnum}) Number diff filler lines about {lnum}
1453diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
Bram Moolenaar13065c42005-01-08 16:08:21 +00001454empty( {expr}) Number TRUE if {expr} is empty
Bram Moolenaar05159a02005-02-26 23:04:13 +00001455errorlist() List list of quickfix items
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456escape( {string}, {chars}) String escape {chars} in {string} with '\'
Bram Moolenaare2cc9702005-03-15 22:43:58 +00001457eval( {string}) any evaluate {string} into its value
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001458eventhandler( ) Number TRUE if inside an event handler
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459executable( {expr}) Number 1 if executable {expr} exists
1460exists( {expr}) Number TRUE if {expr} exists
1461expand( {expr}) String expand special keywords in {expr}
1462filereadable( {file}) Number TRUE if {file} is a readable file
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001463filter( {expr}, {string}) List/Dict remove items from {expr} where
1464 {string} is 0
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001465finddir( {name}[, {path}[, {count}]])
1466 String Find directory {name} in {path}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001467findfile( {name}[, {path}[, {count}]])
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001468 String Find file {name} in {path}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469filewritable( {file}) Number TRUE if {file} is a writable file
1470fnamemodify( {fname}, {mods}) String modify file name
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001471foldclosed( {lnum}) Number first line of fold at {lnum} if closed
1472foldclosedend( {lnum}) Number last line of fold at {lnum} if closed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473foldlevel( {lnum}) Number fold level at {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001474foldtext( ) String line displayed for closed fold
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475foreground( ) Number bring the Vim window to the foreground
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001476function( {name}) Funcref reference to function {name}
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001477get( {list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001478get( {dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001479getchar( [expr]) Number get one character from the user
1480getcharmod( ) Number modifiers for the last typed character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481getbufvar( {expr}, {varname}) variable {varname} in buffer {expr}
1482getcmdline() String return the current command-line
1483getcmdpos() Number return cursor position in command-line
1484getcwd() String the current working directory
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001485getfperm( {fname}) String file permissions of file {fname}
1486getfsize( {fname}) Number size in bytes of file {fname}
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001487getfontname( [{name}]) String name of font being used
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488getftime( {fname}) Number last modification time of file
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00001489getftype( {fname}) String description of type of file {fname}
Bram Moolenaar7c626922005-02-07 22:01:03 +00001490getline( {lnum}) String line {lnum} of current buffer
1491getline( {lnum}, {end}) List lines {lnum} to {end} of current buffer
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001492getreg( [{regname}]) String contents of register
1493getregtype( [{regname}]) String type of register
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494getwinposx() Number X coord in pixels of GUI Vim window
1495getwinposy() Number Y coord in pixels of GUI Vim window
1496getwinvar( {nr}, {varname}) variable {varname} in window {nr}
1497glob( {expr}) String expand file wildcards in {expr}
1498globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path}
1499has( {feature}) Number TRUE if feature {feature} supported
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001500has_key( {dict}, {key}) Number TRUE if {dict} has entry {key}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists
1502histadd( {history},{item}) String add an item to a history
1503histdel( {history} [, {item}]) String remove an item from a history
1504histget( {history} [, {index}]) String get the item {index} from a history
1505histnr( {history}) Number highest index of a history
1506hlexists( {name}) Number TRUE if highlight group {name} exists
1507hlID( {name}) Number syntax ID of highlight group {name}
1508hostname() String name of the machine Vim is running on
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001509iconv( {expr}, {from}, {to}) String convert encoding of {expr}
1510indent( {lnum}) Number indent of line {lnum}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001511index( {list}, {expr} [, {start} [, {ic}]])
1512 Number index in {list} where {expr} appears
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513input( {prompt} [, {text}]) String get input from the user
1514inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001515inputrestore() Number restore typeahead
1516inputsave() Number save and clear typeahead
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517inputsecret( {prompt} [, {text}]) String like input() but hiding the text
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001518insert( {list}, {item} [, {idx}]) List insert {item} in {list} [before {idx}]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519isdirectory( {directory}) Number TRUE if {directory} is a directory
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00001520islocked( {expr}) Number TRUE if {expr} is locked
Bram Moolenaar677ee682005-01-27 14:41:15 +00001521items( {dict}) List List of key-value pairs in {dict}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001522join( {list} [, {sep}]) String join {list} items into one String
Bram Moolenaard8b02732005-01-14 21:48:43 +00001523keys( {dict}) List List of keys in {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001524len( {expr}) Number the length of {expr}
1525libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number
1527line( {expr}) Number line nr of cursor, last line or mark
1528line2byte( {lnum}) Number byte count of line {lnum}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001529lispindent( {lnum}) Number Lisp indent for line {lnum}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530localtime() Number current time
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001531map( {expr}, {string}) List/Dict change each item in {expr} to {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
1533mapcheck( {name}[, {mode}]) String check for mappings matching {name}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001534match( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535 Number position where {pat} matches in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001536matchend( {expr}, {pat}[, {start}[, {count}]])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 Number position where {pat} ends in {expr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001538matchlist( {expr}, {pat}[, {start}[, {count}]])
1539 List match and submatches of {pat} in {expr}
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00001540matchstr( {expr}, {pat}[, {start}[, {count}]])
1541 String {count}'th match of {pat} in {expr}
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001542max({list}) Number maximum value of items in {list}
1543min({list}) Number minumum value of items in {list}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001544mkdir({name} [, {path} [, {prot}]])
1545 Number create directory {name}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001546mode() String current editing mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum}
1548nr2char( {expr}) String single char with ASCII value {expr}
1549prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001550range( {expr} [, {max} [, {stride}]])
1551 List items from {expr} to {max}
Bram Moolenaar26a60b42005-02-22 08:49:11 +00001552readfile({fname} [, {binary} [, {max}]])
1553 List get list of lines from file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554remote_expr( {server}, {string} [, {idvar}])
1555 String send expression
1556remote_foreground( {server}) Number bring Vim server to the foreground
1557remote_peek( {serverid} [, {retvar}])
1558 Number check for reply string
1559remote_read( {serverid}) String read reply string
1560remote_send( {server}, {string} [, {idvar}])
1561 String send key sequence
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001562remove( {list}, {idx} [, {end}]) any remove items {idx}-{end} from {list}
Bram Moolenaard8b02732005-01-14 21:48:43 +00001563remove( {dict}, {key}) any remove entry {key} from {dict}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001564rename( {from}, {to}) Number rename (move) file from {from} to {to}
1565repeat( {expr}, {count}) String repeat {expr} {count} times
1566resolve( {filename}) String get filename a shortcut points to
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001567reverse( {list}) List reverse {list} in-place
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001568search( {pattern} [, {flags}]) Number search for {pattern}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001570 Number search for other end of start/end pair
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571server2client( {clientid}, {string})
1572 Number send reply string
1573serverlist() String get a list of available servers
1574setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val}
1575setcmdpos( {pos}) Number set cursor position in command-line
1576setline( {lnum}, {line}) Number set line {lnum} to {line}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001577setreg( {n}, {v}[, {opt}]) Number set register to value and type
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val}
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001579simplify( {filename}) String simplify filename as much as possible
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001580sort( {list} [, {func}]) List sort {list}, using {func} to compare
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001581split( {expr} [, {pat}]) List make List from {pat} separated {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582strftime( {format}[, {time}]) String time in specified format
Bram Moolenaar8f999f12005-01-25 22:12:55 +00001583stridx( {haystack}, {needle}[, {start}])
1584 Number index of {needle} in {haystack}
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00001585string( {expr}) String String representation of {expr} value
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586strlen( {expr}) Number length of the String {expr}
1587strpart( {src}, {start}[, {len}])
1588 String {len} characters of {src} at {start}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001589strridx( {haystack}, {needle} [, {start}])
1590 Number last index of {needle} in {haystack}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591strtrans( {expr}) String translate string to make it printable
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001592submatch( {nr}) String specific match in ":substitute"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593substitute( {expr}, {pat}, {sub}, {flags})
1594 String all {pat} in {expr} replaced with {sub}
Bram Moolenaar47136d72004-10-12 20:02:24 +00001595synID( {lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596synIDattr( {synID}, {what} [, {mode}])
1597 String attribute {what} of syntax ID {synID}
1598synIDtrans( {synID}) Number translated syntax ID of {synID}
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001599system( {expr} [, {input}]) String output of shell command/filter {expr}
Bram Moolenaare2cc9702005-03-15 22:43:58 +00001600taglist({expr}) List list of tags matching {expr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601tempname() String name for a temporary file
1602tolower( {expr}) String the String {expr} switched to lowercase
1603toupper( {expr}) String the String {expr} switched to uppercase
Bram Moolenaar8299df92004-07-10 09:47:34 +00001604tr( {src}, {fromstr}, {tostr}) String translate chars of {src} in {fromstr}
1605 to chars in {tostr}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606type( {name}) Number type of variable {name}
Bram Moolenaar677ee682005-01-27 14:41:15 +00001607values( {dict}) List List of values in {dict}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608virtcol( {expr}) Number screen column of cursor or mark
1609visualmode( [expr]) String last visual mode used
1610winbufnr( {nr}) Number buffer number of window {nr}
1611wincol() Number window column of the cursor
1612winheight( {nr}) Number height of window {nr}
1613winline() Number window line of the cursor
1614winnr() Number number of current window
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001615winrestcmd() String returns command to restore window sizes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616winwidth( {nr}) Number width of window {nr}
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001617writefile({list}, {fname} [, {binary}])
1618 Number write list of lines to file {fname}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001620add({list}, {expr}) *add()*
1621 Append the item {expr} to List {list}. Returns the resulting
1622 List. Examples: >
1623 :let alist = add([1, 2, 3], item)
1624 :call add(mylist, "woodstock")
1625< Note that when {expr} is a List it is appended as a single
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001626 item. Use |extend()| to concatenate Lists.
Bram Moolenaar13065c42005-01-08 16:08:21 +00001627 Use |insert()| to add an item at another position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001629
1630append({lnum}, {expr}) *append()*
Bram Moolenaar748bf032005-02-02 23:04:36 +00001631 When {expr} is a List: Append each item of the List as a text
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001632 line below line {lnum} in the current buffer.
Bram Moolenaar748bf032005-02-02 23:04:36 +00001633 Otherwise append {expr} as one text line below line {lnum} in
1634 the current buffer.
1635 {lnum} can be zero to insert a line before the first one.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001636 Returns 1 for failure ({lnum} out of range or out of memory),
1637 0 for success. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001638 :let failed = append(line('$'), "# THE END")
Bram Moolenaara14de3d2005-01-07 21:48:26 +00001639 :let failed = append(0, ["Chapter 1", "the beginning"])
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001640<
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 *argc()*
1642argc() The result is the number of files in the argument list of the
1643 current window. See |arglist|.
1644
1645 *argidx()*
1646argidx() The result is the current index in the argument list. 0 is
1647 the first file. argc() - 1 is the last one. See |arglist|.
1648
1649 *argv()*
1650argv({nr}) The result is the {nr}th file in the argument list of the
1651 current window. See |arglist|. "argv(0)" is the first one.
1652 Example: >
1653 :let i = 0
1654 :while i < argc()
1655 : let f = escape(argv(i), '. ')
1656 : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
1657 : let i = i + 1
1658 :endwhile
1659<
1660 *browse()*
1661browse({save}, {title}, {initdir}, {default})
1662 Put up a file requester. This only works when "has("browse")"
1663 returns non-zero (only in some GUI versions).
1664 The input fields are:
1665 {save} when non-zero, select file to write
1666 {title} title for the requester
1667 {initdir} directory to start browsing in
1668 {default} default file name
1669 When the "Cancel" button is hit, something went wrong, or
1670 browsing is not possible, an empty string is returned.
1671
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00001672 *browsedir()*
1673browsedir({title}, {initdir})
1674 Put up a directory requester. This only works when
1675 "has("browse")" returns non-zero (only in some GUI versions).
1676 On systems where a directory browser is not supported a file
1677 browser is used. In that case: select a file in the directory
1678 to be used.
1679 The input fields are:
1680 {title} title for the requester
1681 {initdir} directory to start browsing in
1682 When the "Cancel" button is hit, something went wrong, or
1683 browsing is not possible, an empty string is returned.
1684
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685bufexists({expr}) *bufexists()*
1686 The result is a Number, which is non-zero if a buffer called
1687 {expr} exists.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001688 If the {expr} argument is a number, buffer numbers are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 If the {expr} argument is a string it must match a buffer name
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001690 exactly. The name can be:
1691 - Relative to the current directory.
1692 - A full path.
1693 - The name of a buffer with 'filetype' set to "nofile".
1694 - A URL name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695 Unlisted buffers will be found.
1696 Note that help files are listed by their short name in the
1697 output of |:buffers|, but bufexists() requires using their
1698 long name to be able to find them.
1699 Use "bufexists(0)" to test for the existence of an alternate
1700 file name.
1701 *buffer_exists()*
1702 Obsolete name: buffer_exists().
1703
1704buflisted({expr}) *buflisted()*
1705 The result is a Number, which is non-zero if a buffer called
1706 {expr} exists and is listed (has the 'buflisted' option set).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001707 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708
1709bufloaded({expr}) *bufloaded()*
1710 The result is a Number, which is non-zero if a buffer called
1711 {expr} exists and is loaded (shown in a window or hidden).
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001712 The {expr} argument is used like with |bufexists()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713
1714bufname({expr}) *bufname()*
1715 The result is the name of a buffer, as it is displayed by the
1716 ":ls" command.
1717 If {expr} is a Number, that buffer number's name is given.
1718 Number zero is the alternate buffer for the current window.
1719 If {expr} is a String, it is used as a |file-pattern| to match
1720 with the buffer names. This is always done like 'magic' is
1721 set and 'cpoptions' is empty. When there is more than one
1722 match an empty string is returned.
1723 "" or "%" can be used for the current buffer, "#" for the
1724 alternate buffer.
1725 A full match is preferred, otherwise a match at the start, end
1726 or middle of the buffer name is accepted.
1727 Listed buffers are found first. If there is a single match
1728 with a listed buffer, that one is returned. Next unlisted
1729 buffers are searched for.
1730 If the {expr} is a String, but you want to use it as a buffer
1731 number, force it to be a Number by adding zero to it: >
1732 :echo bufname("3" + 0)
1733< If the buffer doesn't exist, or doesn't have a name, an empty
1734 string is returned. >
1735 bufname("#") alternate buffer name
1736 bufname(3) name of buffer 3
1737 bufname("%") name of current buffer
1738 bufname("file2") name of buffer where "file2" matches.
1739< *buffer_name()*
1740 Obsolete name: buffer_name().
1741
1742 *bufnr()*
1743bufnr({expr}) The result is the number of a buffer, as it is displayed by
1744 the ":ls" command. For the use of {expr}, see |bufname()|
1745 above. If the buffer doesn't exist, -1 is returned.
1746 bufnr("$") is the last buffer: >
1747 :let last_buffer = bufnr("$")
1748< The result is a Number, which is the highest buffer number
1749 of existing buffers. Note that not all buffers with a smaller
1750 number necessarily exist, because ":bwipeout" may have removed
1751 them. Use bufexists() to test for the existence of a buffer.
1752 *buffer_number()*
1753 Obsolete name: buffer_number().
1754 *last_buffer_nr()*
1755 Obsolete name for bufnr("$"): last_buffer_nr().
1756
1757bufwinnr({expr}) *bufwinnr()*
1758 The result is a Number, which is the number of the first
1759 window associated with buffer {expr}. For the use of {expr},
1760 see |bufname()| above. If buffer {expr} doesn't exist or
1761 there is no such window, -1 is returned. Example: >
1762
1763 echo "A window containing buffer 1 is " . (bufwinnr(1))
1764
1765< The number can be used with |CTRL-W_w| and ":wincmd w"
1766 |:wincmd|.
1767
1768
1769byte2line({byte}) *byte2line()*
1770 Return the line number that contains the character at byte
1771 count {byte} in the current buffer. This includes the
1772 end-of-line character, depending on the 'fileformat' option
1773 for the current buffer. The first character has byte count
1774 one.
1775 Also see |line2byte()|, |go| and |:goto|.
1776 {not available when compiled without the |+byte_offset|
1777 feature}
1778
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001779byteidx({expr}, {nr}) *byteidx()*
1780 Return byte index of the {nr}'th character in the string
1781 {expr}. Use zero for the first character, it returns zero.
1782 This function is only useful when there are multibyte
1783 characters, otherwise the returned value is equal to {nr}.
1784 Composing characters are counted as a separate character.
1785 Example : >
1786 echo matchstr(str, ".", byteidx(str, 3))
1787< will display the fourth character. Another way to do the
1788 same: >
1789 let s = strpart(str, byteidx(str, 3))
1790 echo strpart(s, 0, byteidx(s, 1))
1791< If there are less than {nr} characters -1 is returned.
1792 If there are exactly {nr} characters the length of the string
1793 is returned.
1794
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001795call({func}, {arglist} [, {dict}]) *call()* *E699*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001796 Call function {func} with the items in List {arglist} as
1797 arguments.
1798 {func} can either be a Funcref or the name of a function.
1799 a:firstline and a:lastline are set to the cursor line.
1800 Returns the return value of the called function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001801 {dict} is for functions with the "dict" attribute. It will be
1802 used to set the local variable "self". |Dictionary-function|
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001803
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804char2nr({expr}) *char2nr()*
1805 Return number value of the first char in {expr}. Examples: >
1806 char2nr(" ") returns 32
1807 char2nr("ABC") returns 65
1808< The current 'encoding' is used. Example for "utf-8": >
1809 char2nr("á") returns 225
1810 char2nr("á"[0]) returns 195
1811
1812cindent({lnum}) *cindent()*
1813 Get the amount of indent for line {lnum} according the C
1814 indenting rules, as with 'cindent'.
1815 The indent is counted in spaces, the value of 'tabstop' is
1816 relevant. {lnum} is used just like in |getline()|.
1817 When {lnum} is invalid or Vim was not compiled the |+cindent|
1818 feature, -1 is returned.
1819
1820 *col()*
Bram Moolenaarc0197e22004-09-13 20:26:32 +00001821col({expr}) The result is a Number, which is the byte index of the column
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 position given with {expr}. The accepted positions are:
1823 . the cursor position
1824 $ the end of the cursor line (the result is the
1825 number of characters in the cursor line plus one)
1826 'x position of mark x (if the mark is not set, 0 is
1827 returned)
1828 For the screen column position use |virtcol()|.
1829 Note that only marks in the current file can be used.
1830 Examples: >
1831 col(".") column of cursor
1832 col("$") length of cursor line plus one
1833 col("'t") column of mark t
1834 col("'" . markname) column of mark markname
1835< The first column is 1. 0 is returned for an error.
1836 For the cursor position, when 'virtualedit' is active, the
1837 column is one higher if the cursor is after the end of the
1838 line. This can be used to obtain the column in Insert mode: >
1839 :imap <F2> <C-O>:let save_ve = &ve<CR>
1840 \<C-O>:set ve=all<CR>
1841 \<C-O>:echo col(".") . "\n" <Bar>
1842 \let &ve = save_ve<CR>
1843<
1844 *confirm()*
1845confirm({msg} [, {choices} [, {default} [, {type}]]])
1846 Confirm() offers the user a dialog, from which a choice can be
1847 made. It returns the number of the choice. For the first
1848 choice this is 1.
1849 Note: confirm() is only supported when compiled with dialog
1850 support, see |+dialog_con| and |+dialog_gui|.
1851 {msg} is displayed in a |dialog| with {choices} as the
1852 alternatives. When {choices} is missing or empty, "&OK" is
1853 used (and translated).
1854 {msg} is a String, use '\n' to include a newline. Only on
1855 some systems the string is wrapped when it doesn't fit.
1856 {choices} is a String, with the individual choices separated
1857 by '\n', e.g. >
1858 confirm("Save changes?", "&Yes\n&No\n&Cancel")
1859< The letter after the '&' is the shortcut key for that choice.
1860 Thus you can type 'c' to select "Cancel". The shortcut does
1861 not need to be the first letter: >
1862 confirm("file has been modified", "&Save\nSave &All")
1863< For the console, the first letter of each choice is used as
1864 the default shortcut key.
1865 The optional {default} argument is the number of the choice
1866 that is made if the user hits <CR>. Use 1 to make the first
1867 choice the default one. Use 0 to not set a default. If
1868 {default} is omitted, 1 is used.
1869 The optional {type} argument gives the type of dialog. This
1870 is only used for the icon of the Win32 GUI. It can be one of
1871 these values: "Error", "Question", "Info", "Warning" or
1872 "Generic". Only the first character is relevant. When {type}
1873 is omitted, "Generic" is used.
1874 If the user aborts the dialog by pressing <Esc>, CTRL-C,
1875 or another valid interrupt key, confirm() returns 0.
1876
1877 An example: >
1878 :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
1879 :if choice == 0
1880 : echo "make up your mind!"
1881 :elseif choice == 3
1882 : echo "tasteful"
1883 :else
1884 : echo "I prefer bananas myself."
1885 :endif
1886< In a GUI dialog, buttons are used. The layout of the buttons
1887 depends on the 'v' flag in 'guioptions'. If it is included,
1888 the buttons are always put vertically. Otherwise, confirm()
1889 tries to put the buttons in one horizontal line. If they
1890 don't fit, a vertical layout is used anyway. For some systems
1891 the horizontal layout is always used.
1892
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001893 *copy()*
1894copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
1895 different from using {expr} directly.
1896 When {expr} is a List a shallow copy is created. This means
1897 that the original List can be changed without changing the
1898 copy, and vise versa. But the items are identical, thus
1899 changing an item changes the contents of both Lists. Also see
1900 |deepcopy()|.
1901
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001902count({comp}, {expr} [, {ic} [, {start}]]) *count()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001903 Return the number of times an item with value {expr} appears
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001904 in List or Dictionary {comp}.
1905 If {start} is given then start with the item with this index.
1906 {start} can only be used with a List.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001907 When {ic} is given and it's non-zero then case is ignored.
1908
1909
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 *cscope_connection()*
1911cscope_connection([{num} , {dbpath} [, {prepend}]])
1912 Checks for the existence of a |cscope| connection. If no
1913 parameters are specified, then the function returns:
1914 0, if cscope was not available (not compiled in), or
1915 if there are no cscope connections;
1916 1, if there is at least one cscope connection.
1917
1918 If parameters are specified, then the value of {num}
1919 determines how existence of a cscope connection is checked:
1920
1921 {num} Description of existence check
1922 ----- ------------------------------
1923 0 Same as no parameters (e.g., "cscope_connection()").
1924 1 Ignore {prepend}, and use partial string matches for
1925 {dbpath}.
1926 2 Ignore {prepend}, and use exact string matches for
1927 {dbpath}.
1928 3 Use {prepend}, use partial string matches for both
1929 {dbpath} and {prepend}.
1930 4 Use {prepend}, use exact string matches for both
1931 {dbpath} and {prepend}.
1932
1933 Note: All string comparisons are case sensitive!
1934
1935 Examples. Suppose we had the following (from ":cs show"): >
1936
1937 # pid database name prepend path
1938 0 27664 cscope.out /usr/local
1939<
1940 Invocation Return Val ~
1941 ---------- ---------- >
1942 cscope_connection() 1
1943 cscope_connection(1, "out") 1
1944 cscope_connection(2, "out") 0
1945 cscope_connection(3, "out") 0
1946 cscope_connection(3, "out", "local") 1
1947 cscope_connection(4, "out") 0
1948 cscope_connection(4, "out", "local") 0
1949 cscope_connection(4, "cscope.out", "/usr/local") 1
1950<
1951cursor({lnum}, {col}) *cursor()*
1952 Positions the cursor at the column {col} in the line {lnum}.
1953 Does not change the jumplist.
1954 If {lnum} is greater than the number of lines in the buffer,
1955 the cursor will be positioned at the last line in the buffer.
1956 If {lnum} is zero, the cursor will stay in the current line.
1957 If {col} is greater than the number of characters in the line,
1958 the cursor will be positioned at the last character in the
1959 line.
1960 If {col} is zero, the cursor will stay in the current column.
1961
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001962
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001963deepcopy({expr}[, {noref}]) *deepcopy()* *E698*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001964 Make a copy of {expr}. For Numbers and Strings this isn't
1965 different from using {expr} directly.
1966 When {expr} is a List a full copy is created. This means
1967 that the original List can be changed without changing the
1968 copy, and vise versa. When an item is a List, a copy for it
1969 is made, recursively. Thus changing an item in the copy does
1970 not change the contents of the original List.
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001971 When {noref} is omitted or zero a contained List or Dictionary
1972 is only copied once. All references point to this single
1973 copy. With {noref} set to 1 every occurrence of a List or
1974 Dictionary results in a new copy. This also means that a
1975 cyclic reference causes deepcopy() to fail.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001976 *E724*
1977 Nesting is possible up to 100 levels. When there is an item
Bram Moolenaar4399ef42005-02-12 14:29:27 +00001978 that refers back to a higher level making a deep copy with
1979 {noref} set to 1 will fail.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001980 Also see |copy()|.
1981
1982delete({fname}) *delete()*
1983 Deletes the file by the name {fname}. The result is a Number,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 which is 0 if the file was deleted successfully, and non-zero
1985 when the deletion failed.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001986 Use |remove()| to delete an item from a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987
1988 *did_filetype()*
1989did_filetype() Returns non-zero when autocommands are being executed and the
1990 FileType event has been triggered at least once. Can be used
1991 to avoid triggering the FileType event again in the scripts
1992 that detect the file type. |FileType|
1993 When editing another file, the counter is reset, thus this
1994 really checks if the FileType event has been triggered for the
1995 current buffer. This allows an autocommand that starts
1996 editing another buffer to set 'filetype' and load a syntax
1997 file.
1998
Bram Moolenaar47136d72004-10-12 20:02:24 +00001999diff_filler({lnum}) *diff_filler()*
2000 Returns the number of filler lines above line {lnum}.
2001 These are the lines that were inserted at this point in
2002 another diff'ed window. These filler lines are shown in the
2003 display but don't exist in the buffer.
2004 {lnum} is used like with |getline()|. Thus "." is the current
2005 line, "'m" mark m, etc.
2006 Returns 0 if the current window is not in diff mode.
2007
2008diff_hlID({lnum}, {col}) *diff_hlID()*
2009 Returns the highlight ID for diff mode at line {lnum} column
2010 {col} (byte index). When the current line does not have a
2011 diff change zero is returned.
2012 {lnum} is used like with |getline()|. Thus "." is the current
2013 line, "'m" mark m, etc.
2014 {col} is 1 for the leftmost column, {lnum} is 1 for the first
2015 line.
2016 The highlight ID can be used with |synIDattr()| to obtain
2017 syntax information about the highlighting.
2018
Bram Moolenaar13065c42005-01-08 16:08:21 +00002019empty({expr}) *empty()*
2020 Return the Number 1 if {expr} is empty, zero otherwise.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002021 A List or Dictionary is empty when it does not have any items.
Bram Moolenaar13065c42005-01-08 16:08:21 +00002022 A Number is empty when its value is zero.
2023 For a long List this is much faster then comparing the length
2024 with zero.
2025
Bram Moolenaar05159a02005-02-26 23:04:13 +00002026errorlist() *errorlist()*
2027 Returns a list with all the current quickfix errors. Each
2028 list item is a dictionary with these entries:
2029 bufnr number of buffer that has the file name, use
2030 bufname() to get the name
2031 lnum line number in the buffer (first line is 1)
2032 col column number (first column is 1)
2033 vcol non-zero: column number is visual column
2034 zero: column number is byte index
2035 nr error number
2036 text description of the error
2037 type type of the error, 'E', '1', etc.
2038 valid non-zero: recognized error message
2039
2040 Useful application: Find pattern matches in multiple files and
2041 do something with them: >
2042 :vimgrep /theword/jg *.c
2043 :for d in errorlist()
2044 : echo bufname(d.bufnr) ':' d.lnum '=' d.text
2045 :endfor
2046
2047
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048escape({string}, {chars}) *escape()*
2049 Escape the characters in {chars} that occur in {string} with a
2050 backslash. Example: >
2051 :echo escape('c:\program files\vim', ' \')
2052< results in: >
2053 c:\\program\ files\\vim
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002054
2055< *eval()*
2056eval({string}) Evaluate {string} and return the result. Especially useful to
2057 turn the result of |string()| back into the original value.
2058 This works for Numbers, Strings and composites of them.
2059 Also works for Funcrefs that refer to existing functions.
2060
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061eventhandler() *eventhandler()*
2062 Returns 1 when inside an event handler. That is that Vim got
2063 interrupted while waiting for the user to type a character,
2064 e.g., when dropping a file on Vim. This means interactive
2065 commands cannot be used. Otherwise zero is returned.
2066
2067executable({expr}) *executable()*
2068 This function checks if an executable with the name {expr}
2069 exists. {expr} must be the name of the program without any
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002070 arguments.
2071 executable() uses the value of $PATH and/or the normal
2072 searchpath for programs. *PATHEXT*
2073 On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
2074 optionally be included. Then the extensions in $PATHEXT are
2075 tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
2076 found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
2077 used. A dot by itself can be used in $PATHEXT to try using
2078 the name without an extension. When 'shell' looks like a
2079 Unix shell, then the name is also tried without adding an
2080 extension.
2081 On MS-DOS and MS-Windows it only checks if the file exists and
2082 is not a directory, not if it's really executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 The result is a Number:
2084 1 exists
2085 0 does not exist
2086 -1 not implemented on this system
2087
2088 *exists()*
2089exists({expr}) The result is a Number, which is non-zero if {expr} is
2090 defined, zero otherwise. The {expr} argument is a string,
2091 which contains one of these:
2092 &option-name Vim option (only checks if it exists,
2093 not if it really works)
2094 +option-name Vim option that works.
2095 $ENVNAME environment variable (could also be
2096 done by comparing with an empty
2097 string)
2098 *funcname built-in function (see |functions|)
2099 or user defined function (see
2100 |user-functions|).
2101 varname internal variable (see
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002102 |internal-variables|). Also works
2103 for |curly-braces-names|, Dictionary
2104 entries, List items, etc. Beware that
2105 this may cause functions to be
2106 invoked cause an error message for an
2107 invalid expression.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 :cmdname Ex command: built-in command, user
2109 command or command modifier |:command|.
2110 Returns:
2111 1 for match with start of a command
2112 2 full match with a command
2113 3 matches several user commands
2114 To check for a supported command
2115 always check the return value to be 2.
2116 #event autocommand defined for this event
2117 #event#pattern autocommand defined for this event and
2118 pattern (the pattern is taken
2119 literally and compared to the
2120 autocommand patterns character by
2121 character)
2122 For checking for a supported feature use |has()|.
2123
2124 Examples: >
2125 exists("&shortname")
2126 exists("$HOSTNAME")
2127 exists("*strftime")
2128 exists("*s:MyFunc")
2129 exists("bufcount")
2130 exists(":Make")
2131 exists("#CursorHold");
2132 exists("#BufReadPre#*.gz")
2133< There must be no space between the symbol (&/$/*/#) and the
2134 name.
2135 Note that the argument must be a string, not the name of the
2136 variable itself! For example: >
2137 exists(bufcount)
2138< This doesn't check for existence of the "bufcount" variable,
2139 but gets the contents of "bufcount", and checks if that
2140 exists.
2141
2142expand({expr} [, {flag}]) *expand()*
2143 Expand wildcards and the following special keywords in {expr}.
2144 The result is a String.
2145
2146 When there are several matches, they are separated by <NL>
2147 characters. [Note: in version 5.0 a space was used, which
2148 caused problems when a file name contains a space]
2149
2150 If the expansion fails, the result is an empty string. A name
2151 for a non-existing file is not included.
2152
2153 When {expr} starts with '%', '#' or '<', the expansion is done
2154 like for the |cmdline-special| variables with their associated
2155 modifiers. Here is a short overview:
2156
2157 % current file name
2158 # alternate file name
2159 #n alternate file name n
2160 <cfile> file name under the cursor
2161 <afile> autocmd file name
2162 <abuf> autocmd buffer number (as a String!)
2163 <amatch> autocmd matched name
2164 <sfile> sourced script file name
2165 <cword> word under the cursor
2166 <cWORD> WORD under the cursor
2167 <client> the {clientid} of the last received
2168 message |server2client()|
2169 Modifiers:
2170 :p expand to full path
2171 :h head (last path component removed)
2172 :t tail (last path component only)
2173 :r root (one extension removed)
2174 :e extension only
2175
2176 Example: >
2177 :let &tags = expand("%:p:h") . "/tags"
2178< Note that when expanding a string that starts with '%', '#' or
2179 '<', any following text is ignored. This does NOT work: >
2180 :let doesntwork = expand("%:h.bak")
2181< Use this: >
2182 :let doeswork = expand("%:h") . ".bak"
2183< Also note that expanding "<cfile>" and others only returns the
2184 referenced file name without further expansion. If "<cfile>"
2185 is "~/.cshrc", you need to do another expand() to have the
2186 "~/" expanded into the path of the home directory: >
2187 :echo expand(expand("<cfile>"))
2188<
2189 There cannot be white space between the variables and the
2190 following modifier. The |fnamemodify()| function can be used
2191 to modify normal file names.
2192
2193 When using '%' or '#', and the current or alternate file name
2194 is not defined, an empty string is used. Using "%:p" in a
2195 buffer with no name, results in the current directory, with a
2196 '/' added.
2197
2198 When {expr} does not start with '%', '#' or '<', it is
2199 expanded like a file name is expanded on the command line.
2200 'suffixes' and 'wildignore' are used, unless the optional
2201 {flag} argument is given and it is non-zero. Names for
2202 non-existing files are included.
2203
2204 Expand() can also be used to expand variables and environment
2205 variables that are only known in a shell. But this can be
2206 slow, because a shell must be started. See |expr-env-expand|.
2207 The expanded variable is still handled like a list of file
2208 names. When an environment variable cannot be expanded, it is
2209 left unchanged. Thus ":echo expand('$FOOBAR')" results in
2210 "$FOOBAR".
2211
2212 See |glob()| for finding existing files. See |system()| for
2213 getting the raw output of an external command.
2214
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002215extend({expr1}, {expr2} [, {expr3}]) *extend()*
2216 {expr1} and {expr2} must be both Lists or both Dictionaries.
2217
2218 If they are Lists: Append {expr2} to {expr1}.
2219 If {expr3} is given insert the items of {expr2} before item
2220 {expr3} in {expr1}. When {expr3} is zero insert before the
2221 first item. When {expr3} is equal to len({expr1}) then
2222 {expr2} is appended.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002223 Examples: >
2224 :echo sort(extend(mylist, [7, 5]))
2225 :call extend(mylist, [2, 3], 1)
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002226< Use |add()| to concatenate one item to a list. To concatenate
2227 two lists into a new list use the + operator: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002228 :let newlist = [1, 2, 3] + [4, 5]
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002229<
2230 If they are Dictionaries:
2231 Add all entries from {expr2} to {expr1}.
2232 If a key exists in both {expr1} and {expr2} then {expr3} is
2233 used to decide what to do:
2234 {expr3} = "keep": keep the value of {expr1}
2235 {expr3} = "force": use the value of {expr2}
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00002236 {expr3} = "error": give an error message *E737*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002237 When {expr3} is omitted then "force" is assumed.
2238
2239 {expr1} is changed when {expr2} is not empty. If necessary
2240 make a copy of {expr1} first.
2241 {expr2} remains unchanged.
2242 Returns {expr1}.
2243
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002244
Bram Moolenaar071d4272004-06-13 20:20:40 +00002245filereadable({file}) *filereadable()*
2246 The result is a Number, which is TRUE when a file with the
2247 name {file} exists, and can be read. If {file} doesn't exist,
2248 or is a directory, the result is FALSE. {file} is any
2249 expression, which is used as a String.
2250 *file_readable()*
2251 Obsolete name: file_readable().
2252
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002253
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002254filter({expr}, {string}) *filter()*
2255 {expr} must be a List or a Dictionary.
2256 For each item in {expr} evaluate {string} and when the result
2257 is zero remove the item from the List or Dictionary.
2258 Inside {string} |v:val| has the value of the current item.
2259 For a Dictionary |v:key| has the key of the current item.
2260 Examples: >
2261 :call filter(mylist, 'v:val !~ "OLD"')
2262< Removes the items where "OLD" appears. >
2263 :call filter(mydict, 'v:key >= 8')
2264< Removes the items with a key below 8. >
2265 :call filter(var, 0)
Bram Moolenaard8b02732005-01-14 21:48:43 +00002266< Removes all the items, thus clears the List or Dictionary.
2267
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002268 Note that {string} is the result of expression and is then
2269 used as an expression again. Often it is good to use a
2270 |literal-string| to avoid having to double backslashes.
2271
2272 The operation is done in-place. If you want a List or
2273 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00002274 :let l = filter(copy(mylist), '& =~ "KEEP"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002275
2276< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002277
2278
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00002279finddir({name}[, {path}[, {count}]]) *finddir()*
2280 Find directory {name} in {path}.
2281 If {path} is omitted or empty then 'path' is used.
2282 If the optional {count} is given, find {count}'s occurrence of
2283 {name} in {path}.
2284 This is quite similar to the ex-command |:find|.
2285 When the found directory is below the current directory a
2286 relative path is returned. Otherwise a full path is returned.
2287 Example: >
2288 :echo findfile("tags.vim", ".;")
2289< Searches from the current directory upwards until it finds
2290 the file "tags.vim".
2291 {only available when compiled with the +file_in_path feature}
2292
2293findfile({name}[, {path}[, {count}]]) *findfile()*
2294 Just like |finddir()|, but find a file instead of a directory.
2295
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296filewritable({file}) *filewritable()*
2297 The result is a Number, which is 1 when a file with the
2298 name {file} exists, and can be written. If {file} doesn't
2299 exist, or is not writable, the result is 0. If (file) is a
2300 directory, and we can write to it, the result is 2.
2301
2302fnamemodify({fname}, {mods}) *fnamemodify()*
2303 Modify file name {fname} according to {mods}. {mods} is a
2304 string of characters like it is used for file names on the
2305 command line. See |filename-modifiers|.
2306 Example: >
2307 :echo fnamemodify("main.c", ":p:h")
2308< results in: >
2309 /home/mool/vim/vim/src
2310< Note: Environment variables and "~" don't work in {fname}, use
2311 |expand()| first then.
2312
2313foldclosed({lnum}) *foldclosed()*
2314 The result is a Number. If the line {lnum} is in a closed
2315 fold, the result is the number of the first line in that fold.
2316 If the line {lnum} is not in a closed fold, -1 is returned.
2317
2318foldclosedend({lnum}) *foldclosedend()*
2319 The result is a Number. If the line {lnum} is in a closed
2320 fold, the result is the number of the last line in that fold.
2321 If the line {lnum} is not in a closed fold, -1 is returned.
2322
2323foldlevel({lnum}) *foldlevel()*
2324 The result is a Number, which is the foldlevel of line {lnum}
2325 in the current buffer. For nested folds the deepest level is
2326 returned. If there is no fold at line {lnum}, zero is
2327 returned. It doesn't matter if the folds are open or closed.
2328 When used while updating folds (from 'foldexpr') -1 is
2329 returned for lines where folds are still to be updated and the
2330 foldlevel is unknown. As a special case the level of the
2331 previous line is usually available.
2332
2333 *foldtext()*
2334foldtext() Returns a String, to be displayed for a closed fold. This is
2335 the default function used for the 'foldtext' option and should
2336 only be called from evaluating 'foldtext'. It uses the
2337 |v:foldstart|, |v:foldend| and |v:folddashes| variables.
2338 The returned string looks like this: >
2339 +-- 45 lines: abcdef
2340< The number of dashes depends on the foldlevel. The "45" is
2341 the number of lines in the fold. "abcdef" is the text in the
2342 first non-blank line of the fold. Leading white space, "//"
2343 or "/*" and the text from the 'foldmarker' and 'commentstring'
2344 options is removed.
2345 {not available when compiled without the |+folding| feature}
2346
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002347foldtextresult({lnum}) *foldtextresult()*
2348 Returns the text that is displayed for the closed fold at line
2349 {lnum}. Evaluates 'foldtext' in the appropriate context.
2350 When there is no closed fold at {lnum} an empty string is
2351 returned.
2352 {lnum} is used like with |getline()|. Thus "." is the current
2353 line, "'m" mark m, etc.
2354 Useful when exporting folded text, e.g., to HTML.
2355 {not available when compiled without the |+folding| feature}
2356
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 *foreground()*
2358foreground() Move the Vim window to the foreground. Useful when sent from
2359 a client to a Vim server. |remote_send()|
2360 On Win32 systems this might not work, the OS does not always
2361 allow a window to bring itself to the foreground. Use
2362 |remote_foreground()| instead.
2363 {only in the Win32, Athena, Motif and GTK GUI versions and the
2364 Win32 console version}
2365
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002366
Bram Moolenaar13065c42005-01-08 16:08:21 +00002367function({name}) *function()* *E700*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002368 Return a Funcref variable that refers to function {name}.
2369 {name} can be a user defined function or an internal function.
2370
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002371
Bram Moolenaar677ee682005-01-27 14:41:15 +00002372get({list}, {idx} [, {default}]) *get()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002373 Get item {idx} from List {list}. When this item is not
2374 available return {default}. Return zero when {default} is
2375 omitted.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002376get({dict}, {key} [, {default}])
2377 Get item with key {key} from Dictionary {dict}. When this
2378 item is not available return {default}. Return zero when
2379 {default} is omitted.
2380
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002381
2382getbufvar({expr}, {varname}) *getbufvar()*
2383 The result is the value of option or local buffer variable
2384 {varname} in buffer {expr}. Note that the name without "b:"
2385 must be used.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00002386 This also works for a global or buffer-local option, but it
2387 doesn't work for a global variable, window-local variable or
2388 window-local option.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002389 For the use of {expr}, see |bufname()| above.
2390 When the buffer or variable doesn't exist an empty string is
2391 returned, there is no error message.
2392 Examples: >
2393 :let bufmodified = getbufvar(1, "&mod")
2394 :echo "todo myvar = " . getbufvar("todo", "myvar")
2395<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396getchar([expr]) *getchar()*
2397 Get a single character from the user. If it is an 8-bit
2398 character, the result is a number. Otherwise a String is
2399 returned with the encoded character. For a special key it's a
2400 sequence of bytes starting with 0x80 (decimal: 128).
2401 If [expr] is omitted, wait until a character is available.
2402 If [expr] is 0, only get a character when one is available.
2403 If [expr] is 1, only check if a character is available, it is
2404 not consumed. If a normal character is
2405 available, it is returned, otherwise a
2406 non-zero value is returned.
2407 If a normal character available, it is returned as a Number.
2408 Use nr2char() to convert it to a String.
2409 The returned value is zero if no character is available.
2410 The returned value is a string of characters for special keys
2411 and when a modifier (shift, control, alt) was used.
2412 There is no prompt, you will somehow have to make clear to the
2413 user that a character has to be typed.
2414 There is no mapping for the character.
2415 Key codes are replaced, thus when the user presses the <Del>
2416 key you get the code for the <Del> key, not the raw character
2417 sequence. Examples: >
2418 getchar() == "\<Del>"
2419 getchar() == "\<S-Left>"
2420< This example redefines "f" to ignore case: >
2421 :nmap f :call FindChar()<CR>
2422 :function FindChar()
2423 : let c = nr2char(getchar())
2424 : while col('.') < col('$') - 1
2425 : normal l
2426 : if getline('.')[col('.') - 1] ==? c
2427 : break
2428 : endif
2429 : endwhile
2430 :endfunction
2431
2432getcharmod() *getcharmod()*
2433 The result is a Number which is the state of the modifiers for
2434 the last obtained character with getchar() or in another way.
2435 These values are added together:
2436 2 shift
2437 4 control
2438 8 alt (meta)
2439 16 mouse double click
2440 32 mouse triple click
2441 64 mouse quadruple click
2442 128 Macintosh only: command
2443 Only the modifiers that have not been included in the
2444 character itself are obtained. Thus Shift-a results in "A"
2445 with no modifier.
2446
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447getcmdline() *getcmdline()*
2448 Return the current command-line. Only works when the command
2449 line is being edited, thus requires use of |c_CTRL-\_e| or
2450 |c_CTRL-R_=|.
2451 Example: >
2452 :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
2453< Also see |getcmdpos()| and |setcmdpos()|.
2454
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002455getcmdpos() *getcmdpos()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 Return the position of the cursor in the command line as a
2457 byte count. The first column is 1.
2458 Only works when editing the command line, thus requires use of
2459 |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
2460 Also see |setcmdpos()| and |getcmdline()|.
2461
2462 *getcwd()*
2463getcwd() The result is a String, which is the name of the current
2464 working directory.
2465
2466getfsize({fname}) *getfsize()*
2467 The result is a Number, which is the size in bytes of the
2468 given file {fname}.
2469 If {fname} is a directory, 0 is returned.
2470 If the file {fname} can't be found, -1 is returned.
2471
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002472getfontname([{name}]) *getfontname()*
2473 Without an argument returns the name of the normal font being
2474 used. Like what is used for the Normal highlight group
2475 |hl-Normal|.
2476 With an argument a check is done whether {name} is a valid
2477 font name. If not then an empty string is returned.
2478 Otherwise the actual font name is returned, or {name} if the
2479 GUI does not support obtaining the real name.
2480 Only works when the GUI is running, thus not you your vimrc or
2481 Note that the GTK 2 GUI accepts any font name, thus checking
2482 for a valid name does not work.
2483 gvimrc file. Use the |GUIEnter| autocommand to use this
2484 function just after the GUI has started.
2485
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002486getfperm({fname}) *getfperm()*
2487 The result is a String, which is the read, write, and execute
2488 permissions of the given file {fname}.
2489 If {fname} does not exist or its directory cannot be read, an
2490 empty string is returned.
2491 The result is of the form "rwxrwxrwx", where each group of
2492 "rwx" flags represent, in turn, the permissions of the owner
2493 of the file, the group the file belongs to, and other users.
2494 If a user does not have a given permission the flag for this
2495 is replaced with the string "-". Example: >
2496 :echo getfperm("/etc/passwd")
2497< This will hopefully (from a security point of view) display
2498 the string "rw-r--r--" or even "rw-------".
Bram Moolenaare2cc9702005-03-15 22:43:58 +00002499
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500getftime({fname}) *getftime()*
2501 The result is a Number, which is the last modification time of
2502 the given file {fname}. The value is measured as seconds
2503 since 1st Jan 1970, and may be passed to strftime(). See also
2504 |localtime()| and |strftime()|.
2505 If the file {fname} can't be found -1 is returned.
2506
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002507getftype({fname}) *getftype()*
2508 The result is a String, which is a description of the kind of
2509 file of the given file {fname}.
2510 If {fname} does not exist an empty string is returned.
2511 Here is a table over different kinds of files and their
2512 results:
2513 Normal file "file"
2514 Directory "dir"
2515 Symbolic link "link"
2516 Block device "bdev"
2517 Character device "cdev"
2518 Socket "socket"
2519 FIFO "fifo"
2520 All other "other"
2521 Example: >
2522 getftype("/home")
2523< Note that a type such as "link" will only be returned on
2524 systems that support it. On some systems only "dir" and
2525 "file" are returned.
2526
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 *getline()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002528getline({lnum} [, {end}])
2529 Without {end} the result is a String, which is line {lnum}
2530 from the current buffer. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 getline(1)
2532< When {lnum} is a String that doesn't start with a
2533 digit, line() is called to translate the String into a Number.
2534 To get the line under the cursor: >
2535 getline(".")
2536< When {lnum} is smaller than 1 or bigger than the number of
2537 lines in the buffer, an empty string is returned.
2538
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002539 When {end} is given the result is a List where each item is a
2540 line from the current buffer in the range {lnum} to {end},
2541 including line {end}.
2542 {end} is used in the same way as {lnum}.
2543 Non-existing lines are silently omitted.
2544 When {end} is before {lnum} an error is given.
2545 Example: >
2546 :let start = line('.')
2547 :let end = search("^$") - 1
2548 :let lines = getline(start, end)
2549
2550
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551getreg([{regname}]) *getreg()*
2552 The result is a String, which is the contents of register
2553 {regname}. Example: >
2554 :let cliptext = getreg('*')
2555< getreg('=') returns the last evaluated value of the expression
2556 register. (For use in maps).
2557 If {regname} is not specified, |v:register| is used.
2558
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002559
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560getregtype([{regname}]) *getregtype()*
2561 The result is a String, which is type of register {regname}.
2562 The value will be one of:
2563 "v" for |characterwise| text
2564 "V" for |linewise| text
2565 "<CTRL-V>{width}" for |blockwise-visual| text
2566 0 for an empty or unknown register
2567 <CTRL-V> is one character with value 0x16.
2568 If {regname} is not specified, |v:register| is used.
2569
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002570
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 *getwinposx()*
2572getwinposx() The result is a Number, which is the X coordinate in pixels of
2573 the left hand side of the GUI Vim window. The result will be
2574 -1 if the information is not available.
2575
2576 *getwinposy()*
2577getwinposy() The result is a Number, which is the Y coordinate in pixels of
2578 the top of the GUI Vim window. The result will be -1 if the
2579 information is not available.
2580
2581getwinvar({nr}, {varname}) *getwinvar()*
2582 The result is the value of option or local window variable
2583 {varname} in window {nr}.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00002584 This also works for a global option, buffer-local option and
2585 window-local option, but it doesn't work for a global variable
2586 or buffer-local variable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 Note that the name without "w:" must be used.
2588 Examples: >
2589 :let list_is_on = getwinvar(2, '&list')
2590 :echo "myvar = " . getwinvar(1, 'myvar')
2591<
2592 *glob()*
2593glob({expr}) Expand the file wildcards in {expr}. The result is a String.
2594 When there are several matches, they are separated by <NL>
2595 characters.
2596 If the expansion fails, the result is an empty string.
2597 A name for a non-existing file is not included.
2598
2599 For most systems backticks can be used to get files names from
2600 any external command. Example: >
2601 :let tagfiles = glob("`find . -name tags -print`")
2602 :let &tags = substitute(tagfiles, "\n", ",", "g")
2603< The result of the program inside the backticks should be one
2604 item per line. Spaces inside an item are allowed.
2605
2606 See |expand()| for expanding special Vim variables. See
2607 |system()| for getting the raw output of an external command.
2608
2609globpath({path}, {expr}) *globpath()*
2610 Perform glob() on all directories in {path} and concatenate
2611 the results. Example: >
2612 :echo globpath(&rtp, "syntax/c.vim")
2613< {path} is a comma-separated list of directory names. Each
2614 directory name is prepended to {expr} and expanded like with
2615 glob(). A path separator is inserted when needed.
2616 To add a comma inside a directory name escape it with a
2617 backslash. Note that on MS-Windows a directory may have a
2618 trailing backslash, remove it if you put a comma after it.
2619 If the expansion fails for one of the directories, there is no
2620 error message.
2621 The 'wildignore' option applies: Names matching one of the
2622 patterns in 'wildignore' will be skipped.
2623
2624 *has()*
2625has({feature}) The result is a Number, which is 1 if the feature {feature} is
2626 supported, zero otherwise. The {feature} argument is a
2627 string. See |feature-list| below.
2628 Also see |exists()|.
2629
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002630
2631has_key({dict}, {key}) *has_key()*
2632 The result is a Number, which is 1 if Dictionary {dict} has an
2633 entry with key {key}. Zero otherwise.
2634
2635
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636hasmapto({what} [, {mode}]) *hasmapto()*
2637 The result is a Number, which is 1 if there is a mapping that
2638 contains {what} in somewhere in the rhs (what it is mapped to)
2639 and this mapping exists in one of the modes indicated by
2640 {mode}.
2641 Both the global mappings and the mappings local to the current
2642 buffer are checked for a match.
2643 If no matching mapping is found 0 is returned.
2644 The following characters are recognized in {mode}:
2645 n Normal mode
2646 v Visual mode
2647 o Operator-pending mode
2648 i Insert mode
2649 l Language-Argument ("r", "f", "t", etc.)
2650 c Command-line mode
2651 When {mode} is omitted, "nvo" is used.
2652
2653 This function is useful to check if a mapping already exists
2654 to a function in a Vim script. Example: >
2655 :if !hasmapto('\ABCdoit')
2656 : map <Leader>d \ABCdoit
2657 :endif
2658< This installs the mapping to "\ABCdoit" only if there isn't
2659 already a mapping to "\ABCdoit".
2660
2661histadd({history}, {item}) *histadd()*
2662 Add the String {item} to the history {history} which can be
2663 one of: *hist-names*
2664 "cmd" or ":" command line history
2665 "search" or "/" search pattern history
2666 "expr" or "=" typed expression history
2667 "input" or "@" input line history
2668 If {item} does already exist in the history, it will be
2669 shifted to become the newest entry.
2670 The result is a Number: 1 if the operation was successful,
2671 otherwise 0 is returned.
2672
2673 Example: >
2674 :call histadd("input", strftime("%Y %b %d"))
2675 :let date=input("Enter date: ")
2676< This function is not available in the |sandbox|.
2677
2678histdel({history} [, {item}]) *histdel()*
2679 Clear {history}, ie. delete all its entries. See |hist-names|
2680 for the possible values of {history}.
2681
2682 If the parameter {item} is given as String, this is seen
2683 as regular expression. All entries matching that expression
2684 will be removed from the history (if there are any).
2685 Upper/lowercase must match, unless "\c" is used |/\c|.
2686 If {item} is a Number, it will be interpreted as index, see
2687 |:history-indexing|. The respective entry will be removed
2688 if it exists.
2689
2690 The result is a Number: 1 for a successful operation,
2691 otherwise 0 is returned.
2692
2693 Examples:
2694 Clear expression register history: >
2695 :call histdel("expr")
2696<
2697 Remove all entries starting with "*" from the search history: >
2698 :call histdel("/", '^\*')
2699<
2700 The following three are equivalent: >
2701 :call histdel("search", histnr("search"))
2702 :call histdel("search", -1)
2703 :call histdel("search", '^'.histget("search", -1).'$')
2704<
2705 To delete the last search pattern and use the last-but-one for
2706 the "n" command and 'hlsearch': >
2707 :call histdel("search", -1)
2708 :let @/ = histget("search", -1)
2709
2710histget({history} [, {index}]) *histget()*
2711 The result is a String, the entry with Number {index} from
2712 {history}. See |hist-names| for the possible values of
2713 {history}, and |:history-indexing| for {index}. If there is
2714 no such entry, an empty String is returned. When {index} is
2715 omitted, the most recent item from the history is used.
2716
2717 Examples:
2718 Redo the second last search from history. >
2719 :execute '/' . histget("search", -2)
2720
2721< Define an Ex command ":H {num}" that supports re-execution of
2722 the {num}th entry from the output of |:history|. >
2723 :command -nargs=1 H execute histget("cmd", 0+<args>)
2724<
2725histnr({history}) *histnr()*
2726 The result is the Number of the current entry in {history}.
2727 See |hist-names| for the possible values of {history}.
2728 If an error occurred, -1 is returned.
2729
2730 Example: >
2731 :let inp_index = histnr("expr")
2732<
2733hlexists({name}) *hlexists()*
2734 The result is a Number, which is non-zero if a highlight group
2735 called {name} exists. This is when the group has been
2736 defined in some way. Not necessarily when highlighting has
2737 been defined for it, it may also have been used for a syntax
2738 item.
2739 *highlight_exists()*
2740 Obsolete name: highlight_exists().
2741
2742 *hlID()*
2743hlID({name}) The result is a Number, which is the ID of the highlight group
2744 with name {name}. When the highlight group doesn't exist,
2745 zero is returned.
2746 This can be used to retrieve information about the highlight
2747 group. For example, to get the background color of the
2748 "Comment" group: >
2749 :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
2750< *highlightID()*
2751 Obsolete name: highlightID().
2752
2753hostname() *hostname()*
2754 The result is a String, which is the name of the machine on
2755 which Vim is currently running. Machine names greater than
2756 256 characters long are truncated.
2757
2758iconv({expr}, {from}, {to}) *iconv()*
2759 The result is a String, which is the text {expr} converted
2760 from encoding {from} to encoding {to}.
2761 When the conversion fails an empty string is returned.
2762 The encoding names are whatever the iconv() library function
2763 can accept, see ":!man 3 iconv".
2764 Most conversions require Vim to be compiled with the |+iconv|
2765 feature. Otherwise only UTF-8 to latin1 conversion and back
2766 can be done.
2767 This can be used to display messages with special characters,
2768 no matter what 'encoding' is set to. Write the message in
2769 UTF-8 and use: >
2770 echo iconv(utf8_str, "utf-8", &enc)
2771< Note that Vim uses UTF-8 for all Unicode encodings, conversion
2772 from/to UCS-2 is automatically changed to use UTF-8. You
2773 cannot use UCS-2 in a string anyway, because of the NUL bytes.
2774 {only available when compiled with the +multi_byte feature}
2775
2776 *indent()*
2777indent({lnum}) The result is a Number, which is indent of line {lnum} in the
2778 current buffer. The indent is counted in spaces, the value
2779 of 'tabstop' is relevant. {lnum} is used just like in
2780 |getline()|.
2781 When {lnum} is invalid -1 is returned.
2782
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002783
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002784index({list}, {expr} [, {start} [, {ic}]]) *index()*
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002785 Return the lowest index in List {list} where the item has a
2786 value equal to {expr}.
Bram Moolenaar748bf032005-02-02 23:04:36 +00002787 If {start} is given then start looking at the item with index
2788 {start} (may be negative for an item relative to the end).
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002789 When {ic} is given and it is non-zero, ignore case. Otherwise
2790 case must match.
2791 -1 is returned when {expr} is not found in {list}.
2792 Example: >
2793 :let idx = index(words, "the")
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002794 :if index(numbers, 123) >= 0
Bram Moolenaarde8866b2005-01-06 23:24:37 +00002795
2796
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797input({prompt} [, {text}]) *input()*
2798 The result is a String, which is whatever the user typed on
2799 the command-line. The parameter is either a prompt string, or
2800 a blank string (for no prompt). A '\n' can be used in the
2801 prompt to start a new line. The highlighting set with
2802 |:echohl| is used for the prompt. The input is entered just
2803 like a command-line, with the same editing commands and
2804 mappings. There is a separate history for lines typed for
2805 input().
2806 If the optional {text} is present, this is used for the
2807 default reply, as if the user typed this.
2808 NOTE: This must not be used in a startup file, for the
2809 versions that only run in GUI mode (e.g., the Win32 GUI).
2810 Note: When input() is called from within a mapping it will
2811 consume remaining characters from that mapping, because a
2812 mapping is handled like the characters were typed.
2813 Use |inputsave()| before input() and |inputrestore()|
2814 after input() to avoid that. Another solution is to avoid
2815 that further characters follow in the mapping, e.g., by using
2816 |:execute| or |:normal|.
2817
2818 Example: >
2819 :if input("Coffee or beer? ") == "beer"
2820 : echo "Cheers!"
2821 :endif
2822< Example with default text: >
2823 :let color = input("Color? ", "white")
2824< Example with a mapping: >
2825 :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
2826 :function GetFoo()
2827 : call inputsave()
2828 : let g:Foo = input("enter search pattern: ")
2829 : call inputrestore()
2830 :endfunction
2831
2832inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()*
2833 Like input(), but when the GUI is running and text dialogs are
2834 supported, a dialog window pops up to input the text.
2835 Example: >
2836 :let n = inputdialog("value for shiftwidth", &sw)
2837 :if n != ""
2838 : let &sw = n
2839 :endif
2840< When the dialog is cancelled {cancelreturn} is returned. When
2841 omitted an empty string is returned.
2842 Hitting <Enter> works like pressing the OK button. Hitting
2843 <Esc> works like pressing the Cancel button.
2844
2845inputrestore() *inputrestore()*
2846 Restore typeahead that was saved with a previous inputsave().
2847 Should be called the same number of times inputsave() is
2848 called. Calling it more often is harmless though.
2849 Returns 1 when there is nothing to restore, 0 otherwise.
2850
2851inputsave() *inputsave()*
2852 Preserve typeahead (also from mappings) and clear it, so that
2853 a following prompt gets input from the user. Should be
2854 followed by a matching inputrestore() after the prompt. Can
2855 be used several times, in which case there must be just as
2856 many inputrestore() calls.
2857 Returns 1 when out of memory, 0 otherwise.
2858
2859inputsecret({prompt} [, {text}]) *inputsecret()*
2860 This function acts much like the |input()| function with but
2861 two exceptions:
2862 a) the user's response will be displayed as a sequence of
2863 asterisks ("*") thereby keeping the entry secret, and
2864 b) the user's response will not be recorded on the input
2865 |history| stack.
2866 The result is a String, which is whatever the user actually
2867 typed on the command-line in response to the issued prompt.
2868
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002869insert({list}, {item} [, {idx}]) *insert()*
2870 Insert {item} at the start of List {list}.
2871 If {idx} is specified insert {item} before the item with index
2872 {idx}. If {idx} is zero it goes before the first item, just
2873 like omitting {idx}. A negative {idx} is also possible, see
2874 |list-index|. -1 inserts just before the last item.
2875 Returns the resulting List. Examples: >
2876 :let mylist = insert([2, 3, 5], 1)
2877 :call insert(mylist, 4, -1)
2878 :call insert(mylist, 6, len(mylist))
Bram Moolenaara14de3d2005-01-07 21:48:26 +00002879< The last example can be done simpler with |add()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002880 Note that when {item} is a List it is inserted as a single
2881 item. Use |extend()| to concatenate Lists.
2882
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883isdirectory({directory}) *isdirectory()*
2884 The result is a Number, which is non-zero when a directory
2885 with the name {directory} exists. If {directory} doesn't
2886 exist, or isn't a directory, the result is FALSE. {directory}
2887 is any expression, which is used as a String.
2888
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002889islocked({expr}) *islocked()*
2890 The result is a Number, which is non-zero when {expr} is the
2891 name of a locked variable.
2892 {expr} must be the name of a variable, List item or Dictionary
2893 entry, not the variable itself! Example: >
2894 :let alist = [0, ['a', 'b'], 2, 3]
2895 :lockvar 1 alist
2896 :echo islocked('alist') " 1
2897 :echo islocked('alist[1]') " 0
2898
2899< When {expr} is a variable that does not exist you get an error
2900 message. Use |exists()| to check for existance.
2901
Bram Moolenaar677ee682005-01-27 14:41:15 +00002902items({dict}) *items()*
2903 Return a List with all the key-value pairs of {dict}. Each
2904 List item is a list with two items: the key of a {dict} entry
2905 and the value of this entry. The List is in arbitrary order.
2906
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00002907
2908join({list} [, {sep}]) *join()*
2909 Join the items in {list} together into one String.
2910 When {sep} is specified it is put in between the items. If
2911 {sep} is omitted a single space is used.
2912 Note that {sep} is not added at the end. You might want to
2913 add it there too: >
2914 let lines = join(mylist, "\n") . "\n"
2915< String items are used as-is. Lists and Dictionaries are
2916 converted into a string like with |string()|.
2917 The opposite function is |split()|.
2918
Bram Moolenaard8b02732005-01-14 21:48:43 +00002919keys({dict}) *keys()*
2920 Return a List with all the keys of {dict}. The List is in
2921 arbitrary order.
2922
Bram Moolenaar13065c42005-01-08 16:08:21 +00002923 *len()* *E701*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002924len({expr}) The result is a Number, which is the length of the argument.
2925 When {expr} is a String or a Number the length in bytes is
2926 used, as with |strlen()|.
2927 When {expr} is a List the number of items in the List is
2928 returned.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002929 When {expr} is a Dictionary the number of entries in the
2930 Dictionary is returned.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00002931 Otherwise an error is given.
2932
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 *libcall()* *E364* *E368*
2934libcall({libname}, {funcname}, {argument})
2935 Call function {funcname} in the run-time library {libname}
2936 with single argument {argument}.
2937 This is useful to call functions in a library that you
2938 especially made to be used with Vim. Since only one argument
2939 is possible, calling standard library functions is rather
2940 limited.
2941 The result is the String returned by the function. If the
2942 function returns NULL, this will appear as an empty string ""
2943 to Vim.
2944 If the function returns a number, use libcallnr()!
2945 If {argument} is a number, it is passed to the function as an
2946 int; if {argument} is a string, it is passed as a
2947 null-terminated string.
2948 This function will fail in |restricted-mode|.
2949
2950 libcall() allows you to write your own 'plug-in' extensions to
2951 Vim without having to recompile the program. It is NOT a
2952 means to call system functions! If you try to do so Vim will
2953 very probably crash.
2954
2955 For Win32, the functions you write must be placed in a DLL
2956 and use the normal C calling convention (NOT Pascal which is
2957 used in Windows System DLLs). The function must take exactly
2958 one parameter, either a character pointer or a long integer,
2959 and must return a character pointer or NULL. The character
2960 pointer returned must point to memory that will remain valid
2961 after the function has returned (e.g. in static data in the
2962 DLL). If it points to allocated memory, that memory will
2963 leak away. Using a static buffer in the function should work,
2964 it's then freed when the DLL is unloaded.
2965
2966 WARNING: If the function returns a non-valid pointer, Vim may
2967 crash! This also happens if the function returns a number,
2968 because Vim thinks it's a pointer.
2969 For Win32 systems, {libname} should be the filename of the DLL
2970 without the ".DLL" suffix. A full path is only required if
2971 the DLL is not in the usual places.
2972 For Unix: When compiling your own plugins, remember that the
2973 object code must be compiled as position-independent ('PIC').
2974 {only in Win32 on some Unix versions, when the |+libcall|
2975 feature is present}
2976 Examples: >
2977 :echo libcall("libc.so", "getenv", "HOME")
2978 :echo libcallnr("/usr/lib/libc.so", "getpid", "")
2979<
2980 *libcallnr()*
2981libcallnr({libname}, {funcname}, {argument})
2982 Just like libcall(), but used for a function that returns an
2983 int instead of a string.
2984 {only in Win32 on some Unix versions, when the |+libcall|
2985 feature is present}
2986 Example (not very useful...): >
2987 :call libcallnr("libc.so", "printf", "Hello World!\n")
2988 :call libcallnr("libc.so", "sleep", 10)
2989<
2990 *line()*
2991line({expr}) The result is a Number, which is the line number of the file
2992 position given with {expr}. The accepted positions are:
2993 . the cursor position
2994 $ the last line in the current buffer
2995 'x position of mark x (if the mark is not set, 0 is
2996 returned)
2997 Note that only marks in the current file can be used.
2998 Examples: >
2999 line(".") line number of the cursor
3000 line("'t") line number of mark t
3001 line("'" . marker) line number of mark marker
3002< *last-position-jump*
3003 This autocommand jumps to the last known position in a file
3004 just after opening it, if the '" mark is set: >
3005 :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003006
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007line2byte({lnum}) *line2byte()*
3008 Return the byte count from the start of the buffer for line
3009 {lnum}. This includes the end-of-line character, depending on
3010 the 'fileformat' option for the current buffer. The first
3011 line returns 1.
3012 This can also be used to get the byte count for the line just
3013 below the last line: >
3014 line2byte(line("$") + 1)
3015< This is the file size plus one.
3016 When {lnum} is invalid, or the |+byte_offset| feature has been
3017 disabled at compile time, -1 is returned.
3018 Also see |byte2line()|, |go| and |:goto|.
3019
3020lispindent({lnum}) *lispindent()*
3021 Get the amount of indent for line {lnum} according the lisp
3022 indenting rules, as with 'lisp'.
3023 The indent is counted in spaces, the value of 'tabstop' is
3024 relevant. {lnum} is used just like in |getline()|.
3025 When {lnum} is invalid or Vim was not compiled the
3026 |+lispindent| feature, -1 is returned.
3027
3028localtime() *localtime()*
3029 Return the current time, measured as seconds since 1st Jan
3030 1970. See also |strftime()| and |getftime()|.
3031
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003032
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003033map({expr}, {string}) *map()*
3034 {expr} must be a List or a Dictionary.
3035 Replace each item in {expr} with the result of evaluating
3036 {string}.
3037 Inside {string} |v:val| has the value of the current item.
3038 For a Dictionary |v:key| has the key of the current item.
3039 Example: >
3040 :call map(mylist, '"> " . v:val . " <"')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003041< This puts "> " before and " <" after each item in "mylist".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003042
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003043 Note that {string} is the result of an expression and is then
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003044 used as an expression again. Often it is good to use a
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003045 |literal-string| to avoid having to double backslashes. You
3046 still have to double ' quotes
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003047
3048 The operation is done in-place. If you want a List or
3049 Dictionary to remain unmodified make a copy first: >
Bram Moolenaard8b02732005-01-14 21:48:43 +00003050 :let tlist = map(copy(mylist), ' & . "\t"')
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00003051
3052< Returns {expr}, the List or Dictionary that was filtered.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003053
3054
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055maparg({name}[, {mode}]) *maparg()*
3056 Return the rhs of mapping {name} in mode {mode}. When there
3057 is no mapping for {name}, an empty String is returned.
3058 These characters can be used for {mode}:
3059 "n" Normal
3060 "v" Visual
3061 "o" Operator-pending
3062 "i" Insert
3063 "c" Cmd-line
3064 "l" langmap |language-mapping|
3065 "" Normal, Visual and Operator-pending
3066 When {mode} is omitted, the modes from "" are used.
3067 The {name} can have special key names, like in the ":map"
3068 command. The returned String has special characters
3069 translated like in the output of the ":map" command listing.
3070 The mappings local to the current buffer are checked first,
3071 then the global mappings.
3072
3073mapcheck({name}[, {mode}]) *mapcheck()*
3074 Check if there is a mapping that matches with {name} in mode
3075 {mode}. See |maparg()| for {mode} and special names in
3076 {name}.
3077 A match happens with a mapping that starts with {name} and
3078 with a mapping which is equal to the start of {name}.
3079
3080 matches mapping "a" "ab" "abc" ~
3081 mapcheck("a") yes yes yes
3082 mapcheck("abc") yes yes yes
3083 mapcheck("ax") yes no no
3084 mapcheck("b") no no no
3085
3086 The difference with maparg() is that mapcheck() finds a
3087 mapping that matches with {name}, while maparg() only finds a
3088 mapping for {name} exactly.
3089 When there is no mapping that starts with {name}, an empty
3090 String is returned. If there is one, the rhs of that mapping
3091 is returned. If there are several mappings that start with
3092 {name}, the rhs of one of them is returned.
3093 The mappings local to the current buffer are checked first,
3094 then the global mappings.
3095 This function can be used to check if a mapping can be added
3096 without being ambiguous. Example: >
3097 :if mapcheck("_vv") == ""
3098 : map _vv :set guifont=7x13<CR>
3099 :endif
3100< This avoids adding the "_vv" mapping when there already is a
3101 mapping for "_v" or for "_vvv".
3102
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003103match({expr}, {pat}[, {start}[, {count}]]) *match()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003104 When {expr} is a List then this returns the index of the first
3105 item where {pat} matches. Each item is used as a String,
3106 Lists and Dictionaries are used as echoed.
3107 Otherwise, {expr} is used as a String. The result is a
3108 Number, which gives the index (byte offset) in {expr} where
3109 {pat} matches.
3110 A match at the first character or List item returns zero.
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003111 If there is no match -1 is returned.
3112 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003113 :echo match("testing", "ing") " results in 4
3114 :echo match([1, 'x'], '\a') " results in 2
3115< See |string-match| for how {pat} is used.
Bram Moolenaar05159a02005-02-26 23:04:13 +00003116 *strpbrk()*
3117 Vim doesn't have a strpbrk() function. But you can do: >
3118 :let sepidx = match(line, '[.,;: \t]')
3119< *strcasestr()*
3120 Vim doesn't have a strcasestr() function. But you can add
3121 "\c" to the pattern to ignore case: >
3122 :let idx = match(haystack, '\cneedle')
3123<
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003124 When {count} is given use the {count}'th match. When a match
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003125 is found in a String the search for the next one starts on
3126 character further. Thus this example results in 1: >
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003127 echo match("testing", "..", 0, 2)
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003128< In a List the search continues in the next item.
3129
3130 If {start} is given, the search starts from byte index
3131 {start} in a String or item {start} in a List.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 The result, however, is still the index counted from the
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003133 first character/item. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 :echo match("testing", "ing", 2)
3135< result is again "4". >
3136 :echo match("testing", "ing", 4)
3137< result is again "4". >
3138 :echo match("testing", "t", 2)
3139< result is "3".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003140 For a String, if {start} < 0, it will be set to 0. For a list
3141 the index is counted from the end.
3142 If {start} is out of range (> strlen({expr} for a String or
3143 > len({expr} for a List) -1 is returned.
3144
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 See |pattern| for the patterns that are accepted.
3146 The 'ignorecase' option is used to set the ignore-caseness of
3147 the pattern. 'smartcase' is NOT used. The matching is always
3148 done like 'magic' is set and 'cpoptions' is empty.
3149
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003150matchend({expr}, {pat}[, {start}[, {count}]]) *matchend()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 Same as match(), but return the index of first character after
3152 the match. Example: >
3153 :echo matchend("testing", "ing")
3154< results in "7".
Bram Moolenaar05159a02005-02-26 23:04:13 +00003155 *strspn()* *strcspn()*
3156 Vim doesn't have a strspn() or strcspn() function, but you can
3157 do it with matchend(): >
3158 :let span = matchend(line, '[a-zA-Z]')
3159 :let span = matchend(line, '[^a-zA-Z]')
3160< Except that -1 is returned when there are no matches.
3161
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 The {start}, if given, has the same meaning as for match(). >
3163 :echo matchend("testing", "ing", 2)
3164< results in "7". >
3165 :echo matchend("testing", "ing", 5)
3166< result is "-1".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003167 When {expr} is a List the result is equal to match().
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003169matchlist({expr}, {pat}[, {start}[, {count}]]) *matchlist()*
3170 Same as match(), but return a List. The first item in the
3171 list is the matched string, same as what matchstr() would
3172 return. Following items are submatches, like "\1", "\2", etc.
3173 in |:substitute|.
3174 When there is no match an empty list is returned.
3175
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00003176matchstr({expr}, {pat}[, {start}[, {count}]]) *matchstr()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 Same as match(), but return the matched string. Example: >
3178 :echo matchstr("testing", "ing")
3179< results in "ing".
3180 When there is no match "" is returned.
3181 The {start}, if given, has the same meaning as for match(). >
3182 :echo matchstr("testing", "ing", 2)
3183< results in "ing". >
3184 :echo matchstr("testing", "ing", 5)
3185< result is "".
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003186 When {expr} is a List then the matching item is returned.
3187 The type isn't changed, it's not necessarily a String.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003189 *max()*
3190max({list}) Return the maximum value of all items in {list}.
3191 If {list} is not a list or one of the items in {list} cannot
3192 be used as a Number this results in an error.
3193 An empty List results in zero.
3194
3195 *min()*
3196min({list}) Return the minumum value of all items in {list}.
3197 If {list} is not a list or one of the items in {list} cannot
3198 be used as a Number this results in an error.
3199 An empty List results in zero.
3200
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003201 *mkdir()* *E749*
3202mkdir({name} [, {path} [, {prot}]])
3203 Create directory {name}.
3204 If {path} is "p" then intermediate directories are created as
3205 necessary. Otherwise it must be "".
3206 If {prot} is given it is used to set the protection bits of
3207 the new directory. The default is 0755 (rwxr-xr-x: r/w for
3208 the user readable for others). Use 0700 to make it unreadable
3209 for others.
3210 This function is not available in the |sandbox|.
3211 Not available on all systems. To check use: >
3212 :if exists("*mkdir")
3213<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 *mode()*
3215mode() Return a string that indicates the current mode:
3216 n Normal
3217 v Visual by character
3218 V Visual by line
3219 CTRL-V Visual blockwise
3220 s Select by character
3221 S Select by line
3222 CTRL-S Select blockwise
3223 i Insert
3224 R Replace
3225 c Command-line
3226 r Hit-enter prompt
3227 This is useful in the 'statusline' option. In most other
3228 places it always returns "c" or "n".
3229
3230nextnonblank({lnum}) *nextnonblank()*
3231 Return the line number of the first line at or below {lnum}
3232 that is not blank. Example: >
3233 if getline(nextnonblank(1)) =~ "Java"
3234< When {lnum} is invalid or there is no non-blank line at or
3235 below it, zero is returned.
3236 See also |prevnonblank()|.
3237
3238nr2char({expr}) *nr2char()*
3239 Return a string with a single character, which has the number
3240 value {expr}. Examples: >
3241 nr2char(64) returns "@"
3242 nr2char(32) returns " "
3243< The current 'encoding' is used. Example for "utf-8": >
3244 nr2char(300) returns I with bow character
3245< Note that a NUL character in the file is specified with
3246 nr2char(10), because NULs are represented with newline
3247 characters. nr2char(0) is a real NUL and terminates the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003248 string, thus results in an empty string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249
3250prevnonblank({lnum}) *prevnonblank()*
3251 Return the line number of the first line at or above {lnum}
3252 that is not blank. Example: >
3253 let ind = indent(prevnonblank(v:lnum - 1))
3254< When {lnum} is invalid or there is no non-blank line at or
3255 above it, zero is returned.
3256 Also see |nextnonblank()|.
3257
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003258 *E726* *E727*
Bram Moolenaard8b02732005-01-14 21:48:43 +00003259range({expr} [, {max} [, {stride}]]) *range()*
3260 Returns a List with Numbers:
3261 - If only {expr} is specified: [0, 1, ..., {expr} - 1]
3262 - If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
3263 - If {stride} is specified: [{expr}, {expr} + {stride}, ...,
3264 {max}] (increasing {expr} with {stride} each time, not
3265 producing a value past {max}).
3266 Examples: >
3267 range(4) " [0, 1, 2, 3]
3268 range(2, 4) " [2, 3, 4]
3269 range(2, 9, 3) " [2, 5, 8]
3270 range(2, -2, -1) " [2, 1, 0, -1, -2]
3271<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003272 *readfile()*
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003273readfile({fname} [, {binary} [, {max}]])
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003274 Read file {fname} and return a List, each line of the file as
3275 an item. Lines broken at NL characters. Macintosh files
3276 separated with CR will result in a single long line (unless a
3277 NL appears somewhere).
3278 When {binary} is equal to "b" binary mode is used:
3279 - When the last line ends in a NL an extra empty list item is
3280 added.
3281 - No CR characters are removed.
3282 Otherwise:
3283 - CR characters that appear before a NL are removed.
3284 - Whether the last line ends in a NL or not does not matter.
3285 All NUL characters are replaced with a NL character.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00003286 When {max} is given this specifies the maximum number of lines
3287 to be read. Useful if you only want to check the first ten
3288 lines of a file: >
3289 :for line in readfile(fname, '', 10)
3290 : if line =~ 'Date' | echo line | endif
3291 :endfor
3292< When {max} is zero or negative the result is an empty list.
3293 Note that without {max} the whole file is read into memory.
3294 Also note that there is no recognition of encoding. Read a
3295 file into a buffer if you need to.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00003296 When the file can't be opened an error message is given and
3297 the result is an empty list.
3298 Also see |writefile()|.
3299
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300 *remote_expr()* *E449*
3301remote_expr({server}, {string} [, {idvar}])
3302 Send the {string} to {server}. The string is sent as an
3303 expression and the result is returned after evaluation.
3304 If {idvar} is present, it is taken as the name of a
3305 variable and a {serverid} for later use with
3306 remote_read() is stored there.
3307 See also |clientserver| |RemoteReply|.
3308 This function is not available in the |sandbox|.
3309 {only available when compiled with the |+clientserver| feature}
3310 Note: Any errors will cause a local error message to be issued
3311 and the result will be the empty string.
3312 Examples: >
3313 :echo remote_expr("gvim", "2+2")
3314 :echo remote_expr("gvim1", "b:current_syntax")
3315<
3316
3317remote_foreground({server}) *remote_foreground()*
3318 Move the Vim server with the name {server} to the foreground.
3319 This works like: >
3320 remote_expr({server}, "foreground()")
3321< Except that on Win32 systems the client does the work, to work
3322 around the problem that the OS doesn't always allow the server
3323 to bring itself to the foreground.
3324 This function is not available in the |sandbox|.
3325 {only in the Win32, Athena, Motif and GTK GUI versions and the
3326 Win32 console version}
3327
3328
3329remote_peek({serverid} [, {retvar}]) *remote_peek()*
3330 Returns a positive number if there are available strings
3331 from {serverid}. Copies any reply string into the variable
3332 {retvar} if specified. {retvar} must be a string with the
3333 name of a variable.
3334 Returns zero if none are available.
3335 Returns -1 if something is wrong.
3336 See also |clientserver|.
3337 This function is not available in the |sandbox|.
3338 {only available when compiled with the |+clientserver| feature}
3339 Examples: >
3340 :let repl = ""
3341 :echo "PEEK: ".remote_peek(id, "repl").": ".repl
3342
3343remote_read({serverid}) *remote_read()*
3344 Return the oldest available reply from {serverid} and consume
3345 it. It blocks until a reply is available.
3346 See also |clientserver|.
3347 This function is not available in the |sandbox|.
3348 {only available when compiled with the |+clientserver| feature}
3349 Example: >
3350 :echo remote_read(id)
3351<
3352 *remote_send()* *E241*
3353remote_send({server}, {string} [, {idvar}])
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003354 Send the {string} to {server}. The string is sent as input
3355 keys and the function returns immediately. At the Vim server
3356 the keys are not mapped |:map|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 If {idvar} is present, it is taken as the name of a
3358 variable and a {serverid} for later use with
3359 remote_read() is stored there.
3360 See also |clientserver| |RemoteReply|.
3361 This function is not available in the |sandbox|.
3362 {only available when compiled with the |+clientserver| feature}
3363 Note: Any errors will be reported in the server and may mess
3364 up the display.
3365 Examples: >
3366 :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
3367 \ remote_read(serverid)
3368
3369 :autocmd NONE RemoteReply *
3370 \ echo remote_read(expand("<amatch>"))
3371 :echo remote_send("gvim", ":sleep 10 | echo ".
3372 \ 'server2client(expand("<client>"), "HELLO")<CR>')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003373<
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003374remove({list}, {idx} [, {end}]) *remove()*
3375 Without {end}: Remove the item at {idx} from List {list} and
3376 return it.
3377 With {end}: Remove items from {idx} to {end} (inclusive) and
3378 return a list with these items. When {idx} points to the same
3379 item as {end} a list with one item is returned. When {end}
3380 points to an item before {idx} this is an error.
3381 See |list-index| for possible values of {idx} and {end}.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003382 Example: >
3383 :echo "last item: " . remove(mylist, -1)
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003384 :call remove(mylist, 0, 9)
Bram Moolenaard8b02732005-01-14 21:48:43 +00003385remove({dict}, {key})
3386 Remove the entry from {dict} with key {key}. Example: >
3387 :echo "removed " . remove(dict, "one")
3388< If there is no {key} in {dict} this is an error.
3389
3390 Use |delete()| to remove a file.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003391
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392rename({from}, {to}) *rename()*
3393 Rename the file by the name {from} to the name {to}. This
3394 should also work to move files across file systems. The
3395 result is a Number, which is 0 if the file was renamed
3396 successfully, and non-zero when the renaming failed.
3397 This function is not available in the |sandbox|.
3398
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003399repeat({expr}, {count}) *repeat()*
3400 Repeat {expr} {count} times and return the concatenated
3401 result. Example: >
3402 :let seperator = repeat('-', 80)
3403< When {count} is zero or negative the result is empty.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003404 When {expr} is a List the result is {expr} concatenated
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003405 {count} times. Example: >
3406 :let longlist = repeat(['a', 'b'], 3)
3407< Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003408
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003409
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410resolve({filename}) *resolve()* *E655*
3411 On MS-Windows, when {filename} is a shortcut (a .lnk file),
3412 returns the path the shortcut points to in a simplified form.
3413 On Unix, repeat resolving symbolic links in all path
3414 components of {filename} and return the simplified result.
3415 To cope with link cycles, resolving of symbolic links is
3416 stopped after 100 iterations.
3417 On other systems, return the simplified {filename}.
3418 The simplification step is done as by |simplify()|.
3419 resolve() keeps a leading path component specifying the
3420 current directory (provided the result is still a relative
3421 path name) and also keeps a trailing path separator.
3422
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003423 *reverse()*
3424reverse({list}) Reverse the order of items in {list} in-place. Returns
3425 {list}.
3426 If you want a list to remain unmodified make a copy first: >
3427 :let revlist = reverse(copy(mylist))
3428
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429search({pattern} [, {flags}]) *search()*
3430 Search for regexp pattern {pattern}. The search starts at the
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00003431 cursor position (you can use |cursor()| to set it).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 {flags} is a String, which can contain these character flags:
3433 'b' search backward instead of forward
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003434 'n' do Not move the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435 'w' wrap around the end of the file
3436 'W' don't wrap around the end of the file
3437 If neither 'w' or 'W' is given, the 'wrapscan' option applies.
3438
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003439 When a match has been found its line number is returned.
3440 The cursor will be positioned at the match, unless the 'n'
3441 flag is used).
3442 If there is no match a 0 is returned and the cursor doesn't
3443 move. No error message is given.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444
3445 Example (goes over all files in the argument list): >
3446 :let n = 1
3447 :while n <= argc() " loop over all files in arglist
3448 : exe "argument " . n
3449 : " start at the last char in the file and wrap for the
3450 : " first search to find match at start of file
3451 : normal G$
3452 : let flags = "w"
3453 : while search("foo", flags) > 0
3454 : s/foo/bar/g
3455 : let flags = "W"
3456 : endwhile
3457 : update " write the file if modified
3458 : let n = n + 1
3459 :endwhile
3460<
3461 *searchpair()*
3462searchpair({start}, {middle}, {end} [, {flags} [, {skip}]])
3463 Search for the match of a nested start-end pair. This can be
3464 used to find the "endif" that matches an "if", while other
3465 if/endif pairs in between are ignored.
3466 The search starts at the cursor. If a match is found, the
3467 cursor is positioned at it and the line number is returned.
3468 If no match is found 0 or -1 is returned and the cursor
3469 doesn't move. No error message is given.
3470
3471 {start}, {middle} and {end} are patterns, see |pattern|. They
3472 must not contain \( \) pairs. Use of \%( \) is allowed. When
3473 {middle} is not empty, it is found when searching from either
3474 direction, but only when not in a nested start-end pair. A
3475 typical use is: >
3476 searchpair('\<if\>', '\<else\>', '\<endif\>')
3477< By leaving {middle} empty the "else" is skipped.
3478
3479 {flags} are used like with |search()|. Additionally:
3480 'n' do Not move the cursor
3481 'r' Repeat until no more matches found; will find the
3482 outer pair
3483 'm' return number of Matches instead of line number with
3484 the match; will only be > 1 when 'r' is used.
3485
3486 When a match for {start}, {middle} or {end} is found, the
3487 {skip} expression is evaluated with the cursor positioned on
3488 the start of the match. It should return non-zero if this
3489 match is to be skipped. E.g., because it is inside a comment
3490 or a string.
3491 When {skip} is omitted or empty, every match is accepted.
3492 When evaluating {skip} causes an error the search is aborted
3493 and -1 returned.
3494
3495 The value of 'ignorecase' is used. 'magic' is ignored, the
3496 patterns are used like it's on.
3497
3498 The search starts exactly at the cursor. A match with
3499 {start}, {middle} or {end} at the next character, in the
3500 direction of searching, is the first one found. Example: >
3501 if 1
3502 if 2
3503 endif 2
3504 endif 1
3505< When starting at the "if 2", with the cursor on the "i", and
3506 searching forwards, the "endif 2" is found. When starting on
3507 the character just before the "if 2", the "endif 1" will be
3508 found. That's because the "if 2" will be found first, and
3509 then this is considered to be a nested if/endif from "if 2" to
3510 "endif 2".
3511 When searching backwards and {end} is more than one character,
3512 it may be useful to put "\zs" at the end of the pattern, so
3513 that when the cursor is inside a match with the end it finds
3514 the matching start.
3515
3516 Example, to find the "endif" command in a Vim script: >
3517
3518 :echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
3519 \ 'getline(".") =~ "^\\s*\""')
3520
3521< The cursor must be at or after the "if" for which a match is
3522 to be found. Note that single-quote strings are used to avoid
3523 having to double the backslashes. The skip expression only
3524 catches comments at the start of a line, not after a command.
3525 Also, a word "en" or "if" halfway a line is considered a
3526 match.
3527 Another example, to search for the matching "{" of a "}": >
3528
3529 :echo searchpair('{', '', '}', 'bW')
3530
3531< This works when the cursor is at or before the "}" for which a
3532 match is to be found. To reject matches that syntax
3533 highlighting recognized as strings: >
3534
3535 :echo searchpair('{', '', '}', 'bW',
3536 \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
3537<
3538server2client( {clientid}, {string}) *server2client()*
3539 Send a reply string to {clientid}. The most recent {clientid}
3540 that sent a string can be retrieved with expand("<client>").
3541 {only available when compiled with the |+clientserver| feature}
3542 Note:
3543 This id has to be stored before the next command can be
3544 received. Ie. before returning from the received command and
3545 before calling any commands that waits for input.
3546 See also |clientserver|.
3547 Example: >
3548 :echo server2client(expand("<client>"), "HELLO")
3549<
3550serverlist() *serverlist()*
3551 Return a list of available server names, one per line.
3552 When there are no servers or the information is not available
3553 an empty string is returned. See also |clientserver|.
3554 {only available when compiled with the |+clientserver| feature}
3555 Example: >
3556 :echo serverlist()
3557<
3558setbufvar({expr}, {varname}, {val}) *setbufvar()*
3559 Set option or local variable {varname} in buffer {expr} to
3560 {val}.
3561 This also works for a global or local window option, but it
3562 doesn't work for a global or local window variable.
3563 For a local window option the global value is unchanged.
3564 For the use of {expr}, see |bufname()| above.
3565 Note that the variable name without "b:" must be used.
3566 Examples: >
3567 :call setbufvar(1, "&mod", 1)
3568 :call setbufvar("todo", "myvar", "foobar")
3569< This function is not available in the |sandbox|.
3570
3571setcmdpos({pos}) *setcmdpos()*
3572 Set the cursor position in the command line to byte position
3573 {pos}. The first position is 1.
3574 Use |getcmdpos()| to obtain the current position.
3575 Only works while editing the command line, thus you must use
Bram Moolenaard8b02732005-01-14 21:48:43 +00003576 |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
3577 |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
3578 set after the command line is set to the expression. For
3579 |c_CTRL-R_=| it is set after evaluating the expression but
3580 before inserting the resulting text.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 When the number is too big the cursor is put at the end of the
3582 line. A number smaller than one has undefined results.
3583 Returns 0 when successful, 1 when not editing the command
3584 line.
3585
3586setline({lnum}, {line}) *setline()*
3587 Set line {lnum} of the current buffer to {line}. If this
3588 succeeds, 0 is returned. If this fails (most likely because
3589 {lnum} is invalid) 1 is returned. Example: >
3590 :call setline(5, strftime("%c"))
3591< Note: The '[ and '] marks are not set.
3592
3593 *setreg()*
3594setreg({regname}, {value} [,{options}])
3595 Set the register {regname} to {value}.
3596 If {options} contains "a" or {regname} is upper case,
3597 then the value is appended.
3598 {options} can also contains a register type specification:
3599 "c" or "v" |characterwise| mode
3600 "l" or "V" |linewise| mode
3601 "b" or "<CTRL-V>" |blockwise-visual| mode
3602 If a number immediately follows "b" or "<CTRL-V>" then this is
3603 used as the width of the selection - if it is not specified
3604 then the width of the block is set to the number of characters
3605 in the longest line (counting a <TAB> as 1 character).
3606
3607 If {options} contains no register settings, then the default
3608 is to use character mode unless {value} ends in a <NL>.
3609 Setting the '=' register is not possible.
3610 Returns zero for success, non-zero for failure.
3611
3612 Examples: >
3613 :call setreg(v:register, @*)
3614 :call setreg('*', @%, 'ac')
3615 :call setreg('a', "1\n2\n3", 'b5')
3616
3617< This example shows using the functions to save and restore a
3618 register. >
3619 :let var_a = getreg('a')
3620 :let var_amode = getregtype('a')
3621 ....
3622 :call setreg('a', var_a, var_amode)
3623
3624< You can also change the type of a register by appending
3625 nothing: >
3626 :call setreg('a', '', 'al')
3627
3628setwinvar({nr}, {varname}, {val}) *setwinvar()*
3629 Set option or local variable {varname} in window {nr} to
3630 {val}.
3631 This also works for a global or local buffer option, but it
3632 doesn't work for a global or local buffer variable.
3633 For a local buffer option the global value is unchanged.
3634 Note that the variable name without "w:" must be used.
3635 Examples: >
3636 :call setwinvar(1, "&list", 0)
3637 :call setwinvar(2, "myvar", "foobar")
3638< This function is not available in the |sandbox|.
3639
3640simplify({filename}) *simplify()*
3641 Simplify the file name as much as possible without changing
3642 the meaning. Shortcuts (on MS-Windows) or symbolic links (on
3643 Unix) are not resolved. If the first path component in
3644 {filename} designates the current directory, this will be
3645 valid for the result as well. A trailing path separator is
3646 not removed either.
3647 Example: >
3648 simplify("./dir/.././/file/") == "./file/"
3649< Note: The combination "dir/.." is only removed if "dir" is
3650 a searchable directory or does not exist. On Unix, it is also
3651 removed when "dir" is a symbolic link within the same
3652 directory. In order to resolve all the involved symbolic
3653 links before simplifying the path name, use |resolve()|.
3654
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003655
Bram Moolenaar13065c42005-01-08 16:08:21 +00003656sort({list} [, {func}]) *sort()* *E702*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003657 Sort the items in {list} in-place. Returns {list}. If you
3658 want a list to remain unmodified make a copy first: >
3659 :let sortedlist = sort(copy(mylist))
3660< Uses the string representation of each item to sort on.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003661 Numbers sort after Strings, Lists after Numbers.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003662 When {func} is given and it is one then case is ignored.
3663 When {func} is a Funcref or a function name, this function is
3664 called to compare items. The function is invoked with two
3665 items as argument and must return zero if they are equal, 1 if
3666 the first one sorts after the second one, -1 if the first one
3667 sorts before the second one. Example: >
3668 func MyCompare(i1, i2)
3669 return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
3670 endfunc
3671 let sortedlist = sort(mylist, "MyCompare")
3672
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003673split({expr} [, {pattern}]) *split()*
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003674 Make a List out of {expr}. When {pattern} is omitted each
3675 white-separated sequence of characters becomes an item.
3676 Otherwise the string is split where {pattern} matches,
3677 removing the matched characters. Empty strings are omitted.
3678 Example: >
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003679 :let words = split(getline('.'), '\W\+')
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003680< Since empty strings are not added the "\+" isn't required but
3681 it makes the function work a bit faster.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003682 The opposite function is |join()|.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003683
3684
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685strftime({format} [, {time}]) *strftime()*
3686 The result is a String, which is a formatted date and time, as
3687 specified by the {format} string. The given {time} is used,
3688 or the current time if no time is given. The accepted
3689 {format} depends on your system, thus this is not portable!
3690 See the manual page of the C function strftime() for the
3691 format. The maximum length of the result is 80 characters.
3692 See also |localtime()| and |getftime()|.
3693 The language can be changed with the |:language| command.
3694 Examples: >
3695 :echo strftime("%c") Sun Apr 27 11:49:23 1997
3696 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
3697 :echo strftime("%y%m%d %T") 970427 11:53:55
3698 :echo strftime("%H:%M") 11:55
3699 :echo strftime("%c", getftime("file.c"))
3700 Show mod time of file.c.
Bram Moolenaara14de3d2005-01-07 21:48:26 +00003701< Not available on all systems. To check use: >
3702 :if exists("*strftime")
3703
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003704stridx({haystack}, {needle} [, {start}]) *stridx()*
3705 The result is a Number, which gives the byte index in
3706 {haystack} of the first occurrence of the String {needle}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003707 If {start} is specified, the search starts at index {start}.
3708 This can be used to find a second match: >
3709 :let comma1 = stridx(line, ",")
3710 :let comma2 = stridx(line, ",", comma1 + 1)
3711< The search is done case-sensitive.
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003712 For pattern searches use |match()|.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003713 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaar677ee682005-01-27 14:41:15 +00003714 See also |strridx()|.
3715 Examples: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 :echo stridx("An Example", "Example") 3
3717 :echo stridx("Starting point", "Start") 0
3718 :echo stridx("Starting point", "start") -1
Bram Moolenaar05159a02005-02-26 23:04:13 +00003719< *strstr()* *strchr()*
3720 stridx() works similar to the C function strstr(). When used
3721 with a single character it works similar to strchr().
3722
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003723 *string()*
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003724string({expr}) Return {expr} converted to a String. If {expr} is a Number,
3725 String or a composition of them, then the result can be parsed
3726 back with |eval()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003727 {expr} type result ~
Bram Moolenaard8b02732005-01-14 21:48:43 +00003728 String 'string'
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003729 Number 123
Bram Moolenaard8b02732005-01-14 21:48:43 +00003730 Funcref function('name')
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +00003731 List [item, item]
Bram Moolenaard8b02732005-01-14 21:48:43 +00003732 Note that in String values the ' character is doubled.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003733
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734 *strlen()*
3735strlen({expr}) The result is a Number, which is the length of the String
3736 {expr} in bytes. If you want to count the number of
3737 multi-byte characters use something like this: >
3738
3739 :let len = strlen(substitute(str, ".", "x", "g"))
3740
3741< Composing characters are not counted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003742 If the argument is a Number it is first converted to a String.
3743 For other types an error is given.
3744 Also see |len()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745
3746strpart({src}, {start}[, {len}]) *strpart()*
3747 The result is a String, which is part of {src}, starting from
3748 byte {start}, with the length {len}.
3749 When non-existing bytes are included, this doesn't result in
3750 an error, the bytes are simply omitted.
3751 If {len} is missing, the copy continues from {start} till the
3752 end of the {src}. >
3753 strpart("abcdefg", 3, 2) == "de"
3754 strpart("abcdefg", -2, 4) == "ab"
3755 strpart("abcdefg", 5, 4) == "fg"
3756 strpart("abcdefg", 3) == "defg"
3757< Note: To get the first character, {start} must be 0. For
3758 example, to get three bytes under and after the cursor: >
3759 strpart(getline(line(".")), col(".") - 1, 3)
3760<
Bram Moolenaar677ee682005-01-27 14:41:15 +00003761strridx({haystack}, {needle} [, {start}]) *strridx()*
3762 The result is a Number, which gives the byte index in
3763 {haystack} of the last occurrence of the String {needle}.
3764 When {start} is specified, matches beyond this index are
3765 ignored. This can be used to find a match before a previous
3766 match: >
3767 :let lastcomma = strridx(line, ",")
3768 :let comma2 = strridx(line, ",", lastcomma - 1)
3769< The search is done case-sensitive.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003770 For pattern searches use |match()|.
3771 -1 is returned if the {needle} does not occur in {haystack}.
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003772 If the {needle} is empty the length of {haystack} is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 See also |stridx()|. Examples: >
3774 :echo strridx("an angry armadillo", "an") 3
Bram Moolenaar05159a02005-02-26 23:04:13 +00003775< *strrchr()*
3776 When used with a single character it works similar to the C
3777 function strrchr().
3778
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779strtrans({expr}) *strtrans()*
3780 The result is a String, which is {expr} with all unprintable
3781 characters translated into printable characters |'isprint'|.
3782 Like they are shown in a window. Example: >
3783 echo strtrans(@a)
3784< This displays a newline in register a as "^@" instead of
3785 starting a new line.
3786
3787submatch({nr}) *submatch()*
3788 Only for an expression in a |:substitute| command. Returns
3789 the {nr}'th submatch of the matched text. When {nr} is 0
3790 the whole matched text is returned.
3791 Example: >
3792 :s/\d\+/\=submatch(0) + 1/
3793< This finds the first number in the line and adds one to it.
3794 A line break is included as a newline character.
3795
3796substitute({expr}, {pat}, {sub}, {flags}) *substitute()*
3797 The result is a String, which is a copy of {expr}, in which
3798 the first match of {pat} is replaced with {sub}. This works
3799 like the ":substitute" command (without any flags). But the
3800 matching with {pat} is always done like the 'magic' option is
3801 set and 'cpoptions' is empty (to make scripts portable).
3802 See |string-match| for how {pat} is used.
3803 And a "~" in {sub} is not replaced with the previous {sub}.
3804 Note that some codes in {sub} have a special meaning
3805 |sub-replace-special|. For example, to replace something with
3806 "\n" (two characters), use "\\\\n" or '\\n'.
3807 When {pat} does not match in {expr}, {expr} is returned
3808 unmodified.
3809 When {flags} is "g", all matches of {pat} in {expr} are
3810 replaced. Otherwise {flags} should be "".
3811 Example: >
3812 :let &path = substitute(&path, ",\\=[^,]*$", "", "")
3813< This removes the last component of the 'path' option. >
3814 :echo substitute("testing", ".*", "\\U\\0", "")
3815< results in "TESTING".
3816
Bram Moolenaar47136d72004-10-12 20:02:24 +00003817synID({lnum}, {col}, {trans}) *synID()*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 The result is a Number, which is the syntax ID at the position
Bram Moolenaar47136d72004-10-12 20:02:24 +00003819 {lnum} and {col} in the current window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 The syntax ID can be used with |synIDattr()| and
3821 |synIDtrans()| to obtain syntax information about text.
Bram Moolenaar47136d72004-10-12 20:02:24 +00003822 {col} is 1 for the leftmost column, {lnum} is 1 for the first
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 line.
3824 When {trans} is non-zero, transparent items are reduced to the
3825 item that they reveal. This is useful when wanting to know
3826 the effective color. When {trans} is zero, the transparent
3827 item is returned. This is useful when wanting to know which
3828 syntax item is effective (e.g. inside parens).
3829 Warning: This function can be very slow. Best speed is
3830 obtained by going through the file in forward direction.
3831
3832 Example (echoes the name of the syntax item under the cursor): >
3833 :echo synIDattr(synID(line("."), col("."), 1), "name")
3834<
3835synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
3836 The result is a String, which is the {what} attribute of
3837 syntax ID {synID}. This can be used to obtain information
3838 about a syntax item.
3839 {mode} can be "gui", "cterm" or "term", to get the attributes
3840 for that mode. When {mode} is omitted, or an invalid value is
3841 used, the attributes for the currently active highlighting are
3842 used (GUI, cterm or term).
3843 Use synIDtrans() to follow linked highlight groups.
3844 {what} result
3845 "name" the name of the syntax item
3846 "fg" foreground color (GUI: color name used to set
3847 the color, cterm: color number as a string,
3848 term: empty string)
3849 "bg" background color (like "fg")
3850 "fg#" like "fg", but for the GUI and the GUI is
3851 running the name in "#RRGGBB" form
3852 "bg#" like "fg#" for "bg"
3853 "bold" "1" if bold
3854 "italic" "1" if italic
3855 "reverse" "1" if reverse
3856 "inverse" "1" if inverse (= reverse)
3857 "underline" "1" if underlined
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003858 "undercurl" "1" if undercurled
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859
3860 Example (echoes the color of the syntax item under the
3861 cursor): >
3862 :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
3863<
3864synIDtrans({synID}) *synIDtrans()*
3865 The result is a Number, which is the translated syntax ID of
3866 {synID}. This is the syntax group ID of what is being used to
3867 highlight the character. Highlight links given with
3868 ":highlight link" are followed.
3869
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003870system({expr} [, {input}]) *system()* *E677*
3871 Get the output of the shell command {expr}.
3872 When {input} is given, this string is written to a file and
3873 passed as stdin to the command. The string is written as-is,
3874 you need to take care of using the correct line separators
Bram Moolenaar05159a02005-02-26 23:04:13 +00003875 yourself. Pipes are not used.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003876 Note: newlines in {expr} may cause the command to fail. The
3877 characters in 'shellquote' and 'shellxquote' may also cause
3878 trouble.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879 This is not to be used for interactive commands.
3880 The result is a String. Example: >
3881
3882 :let files = system("ls")
3883
3884< To make the result more system-independent, the shell output
3885 is filtered to replace <CR> with <NL> for Macintosh, and
3886 <CR><NL> with <NL> for DOS-like systems.
3887 The command executed is constructed using several options:
3888 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote'
3889 ({tmp} is an automatically generated file name).
3890 For Unix and OS/2 braces are put around {expr} to allow for
3891 concatenated commands.
3892
3893 The resulting error code can be found in |v:shell_error|.
3894 This function will fail in |restricted-mode|.
3895 Unlike ":!cmd" there is no automatic check for changed files.
3896 Use |:checktime| to force a check.
3897
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003898
3899taglist({expr}) *taglist()*
3900 Returns a list of tags matching the regular expression {expr}.
3901 Each list item is a dictionary with the following entries:
3902 name name of the tag.
3903 filename name of the file where the tag is
3904 defined.
3905 cmd Ex command used to locate the tag in
3906 the file.
3907 kind type of the tag. The value for this
3908 entry depends on the language specific
3909 kind values generated by the ctags
3910 tool.
3911 static a file specific tag. Refer to
3912 |static-tag| for more information.
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00003913 The "kind" entry is only available when using Exuberant ctags
3914 generated tags file. More entries may be present, depending
3915 on the content of the tags file: access, implementation,
3916 inherits and signature. Refer to the ctags documentation for
3917 information about these fields. For C code the fields
3918 "struct", "class" and "enum" may appear, they give the name of
3919 the entity the tag is contained in.
3920
3921 The ex-command 'cmd' can be either an ex search pattern, a
3922 line number or a line number followed by a byte number.
Bram Moolenaare2cc9702005-03-15 22:43:58 +00003923
3924 If there are no matching tags, then an empty list is returned.
3925
3926 To get an exact tag match, the anchors '^' and '$' should be
3927 used in {expr}. Refer to |tag-regexp| for more information
3928 about the tag search regular expression pattern.
3929
3930 Refer to |'tags'| for information about how the tags file is
3931 located by Vim. Refer to |tags-file-format| for the format of
3932 the tags file generated by the different ctags tools.
3933
3934
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935tempname() *tempname()* *temp-file-name*
3936 The result is a String, which is the name of a file that
3937 doesn't exist. It can be used for a temporary file. The name
3938 is different for at least 26 consecutive calls. Example: >
3939 :let tmpfile = tempname()
3940 :exe "redir > " . tmpfile
3941< For Unix, the file will be in a private directory (only
3942 accessible by the current user) to avoid security problems
3943 (e.g., a symlink attack or other people reading your file).
3944 When Vim exits the directory and all files in it are deleted.
3945 For MS-Windows forward slashes are used when the 'shellslash'
3946 option is set or when 'shellcmdflag' starts with '-'.
3947
3948tolower({expr}) *tolower()*
3949 The result is a copy of the String given, with all uppercase
3950 characters turned into lowercase (just like applying |gu| to
3951 the string).
3952
3953toupper({expr}) *toupper()*
3954 The result is a copy of the String given, with all lowercase
3955 characters turned into uppercase (just like applying |gU| to
3956 the string).
3957
Bram Moolenaar8299df92004-07-10 09:47:34 +00003958tr({src}, {fromstr}, {tostr}) *tr()*
3959 The result is a copy of the {src} string with all characters
3960 which appear in {fromstr} replaced by the character in that
3961 position in the {tostr} string. Thus the first character in
3962 {fromstr} is translated into the first character in {tostr}
3963 and so on. Exactly like the unix "tr" command.
3964 This code also deals with multibyte characters properly.
3965
3966 Examples: >
3967 echo tr("hello there", "ht", "HT")
3968< returns "Hello THere" >
3969 echo tr("<blob>", "<>", "{}")
3970< returns "{blob}"
3971
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003972 *type()*
3973type({expr}) The result is a Number, depending on the type of {expr}:
Bram Moolenaar748bf032005-02-02 23:04:36 +00003974 Number: 0
3975 String: 1
3976 Funcref: 2
3977 List: 3
3978 Dictionary: 4
3979 To avoid the magic numbers it should be used this way: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003980 :if type(myvar) == type(0)
3981 :if type(myvar) == type("")
3982 :if type(myvar) == type(function("tr"))
3983 :if type(myvar) == type([])
Bram Moolenaar748bf032005-02-02 23:04:36 +00003984 :if type(myvar) == type({})
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985
Bram Moolenaar677ee682005-01-27 14:41:15 +00003986values({dict}) *values()*
3987 Return a List with all the values of {dict}. The List is in
3988 arbitrary order.
3989
3990
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991virtcol({expr}) *virtcol()*
3992 The result is a Number, which is the screen column of the file
3993 position given with {expr}. That is, the last screen position
3994 occupied by the character at that position, when the screen
3995 would be of unlimited width. When there is a <Tab> at the
3996 position, the returned Number will be the column at the end of
3997 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
3998 set to 8, it returns 8.
3999 For the byte position use |col()|.
4000 When Virtual editing is active in the current mode, a position
4001 beyond the end of the line can be returned. |'virtualedit'|
4002 The accepted positions are:
4003 . the cursor position
4004 $ the end of the cursor line (the result is the
4005 number of displayed characters in the cursor line
4006 plus one)
4007 'x position of mark x (if the mark is not set, 0 is
4008 returned)
4009 Note that only marks in the current file can be used.
4010 Examples: >
4011 virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
4012 virtcol("$") with text "foo^Lbar", returns 9
4013 virtcol("'t") with text " there", with 't at 'h', returns 6
4014< The first column is 1. 0 is returned for an error.
4015
4016visualmode([expr]) *visualmode()*
4017 The result is a String, which describes the last Visual mode
4018 used. Initially it returns an empty string, but once Visual
4019 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
4020 single CTRL-V character) for character-wise, line-wise, or
4021 block-wise Visual mode respectively.
4022 Example: >
4023 :exe "normal " . visualmode()
4024< This enters the same Visual mode as before. It is also useful
4025 in scripts if you wish to act differently depending on the
4026 Visual mode that was used.
4027
4028 If an expression is supplied that results in a non-zero number
4029 or a non-empty string, then the Visual mode will be cleared
4030 and the old value is returned. Note that " " and "0" are also
4031 non-empty strings, thus cause the mode to be cleared.
4032
4033 *winbufnr()*
4034winbufnr({nr}) The result is a Number, which is the number of the buffer
4035 associated with window {nr}. When {nr} is zero, the number of
4036 the buffer in the current window is returned. When window
4037 {nr} doesn't exist, -1 is returned.
4038 Example: >
4039 :echo "The file in the current window is " . bufname(winbufnr(0))
4040<
4041 *wincol()*
4042wincol() The result is a Number, which is the virtual column of the
4043 cursor in the window. This is counting screen cells from the
4044 left side of the window. The leftmost column is one.
4045
4046winheight({nr}) *winheight()*
4047 The result is a Number, which is the height of window {nr}.
4048 When {nr} is zero, the height of the current window is
4049 returned. When window {nr} doesn't exist, -1 is returned.
4050 An existing window always has a height of zero or more.
4051 Examples: >
4052 :echo "The current window has " . winheight(0) . " lines."
4053<
4054 *winline()*
4055winline() The result is a Number, which is the screen line of the cursor
4056 in the window. This is counting screen lines from the top of
4057 the window. The first line is one.
4058
4059 *winnr()*
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004060winnr([{arg}]) The result is a Number, which is the number of the current
4061 window. The top window has number 1.
4062 When the optional argument is "$", the number of the
4063 last window is returnd (the window count).
4064 When the optional argument is "#", the number of the last
4065 accessed window is returned (where |CTRL-W_p| goes to).
4066 If there is no previous window 0 is returned.
4067 The number can be used with |CTRL-W_w| and ":wincmd w"
4068 |:wincmd|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069
4070 *winrestcmd()*
4071winrestcmd() Returns a sequence of |:resize| commands that should restore
4072 the current window sizes. Only works properly when no windows
4073 are opened or closed and the current window is unchanged.
4074 Example: >
4075 :let cmd = winrestcmd()
4076 :call MessWithWindowSizes()
4077 :exe cmd
4078
4079winwidth({nr}) *winwidth()*
4080 The result is a Number, which is the width of window {nr}.
4081 When {nr} is zero, the width of the current window is
4082 returned. When window {nr} doesn't exist, -1 is returned.
4083 An existing window always has a width of zero or more.
4084 Examples: >
4085 :echo "The current window has " . winwidth(0) . " columns."
4086 :if winwidth(0) <= 50
4087 : exe "normal 50\<C-W>|"
4088 :endif
4089<
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00004090 *writefile()*
4091writefile({list}, {fname} [, {binary}])
4092 Write List {list} to file {fname}. Each list item is
4093 separated with a NL. Each list item must be a String or
4094 Number.
4095 When {binary} is equal to "b" binary mode is used: There will
4096 not be a NL after the last list item. An empty item at the
4097 end does cause the last line in the file to end in a NL.
4098 All NL characters are replaced with a NUL character.
4099 Inserting CR characters needs to be done before passing {list}
4100 to writefile().
4101 An existing file is overwritten, if possible.
4102 When the write fails -1 is returned, otherwise 0. There is an
4103 error message if the file can't be created or when writing
4104 fails.
4105 Also see |readfile()|.
4106 To copy a file byte for byte: >
4107 :let fl = readfile("foo", "b")
4108 :call writefile(fl, "foocopy", "b")
4109<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110
4111 *feature-list*
4112There are three types of features:
41131. Features that are only supported when they have been enabled when Vim
4114 was compiled |+feature-list|. Example: >
4115 :if has("cindent")
41162. Features that are only supported when certain conditions have been met.
4117 Example: >
4118 :if has("gui_running")
4119< *has-patch*
41203. Included patches. First check |v:version| for the version of Vim.
4121 Then the "patch123" feature means that patch 123 has been included for
4122 this version. Example (checking version 6.2.148 or later): >
4123 :if v:version > 602 || v:version == 602 && has("patch148")
4124
4125all_builtin_terms Compiled with all builtin terminals enabled.
4126amiga Amiga version of Vim.
4127arabic Compiled with Arabic support |Arabic|.
4128arp Compiled with ARP support (Amiga).
4129autocmd Compiled with autocommands support.
4130balloon_eval Compiled with |balloon-eval| support.
4131beos BeOS version of Vim.
4132browse Compiled with |:browse| support, and browse() will
4133 work.
4134builtin_terms Compiled with some builtin terminals.
4135byte_offset Compiled with support for 'o' in 'statusline'
4136cindent Compiled with 'cindent' support.
4137clientserver Compiled with remote invocation support |clientserver|.
4138clipboard Compiled with 'clipboard' support.
4139cmdline_compl Compiled with |cmdline-completion| support.
4140cmdline_hist Compiled with |cmdline-history| support.
4141cmdline_info Compiled with 'showcmd' and 'ruler' support.
4142comments Compiled with |'comments'| support.
4143cryptv Compiled with encryption support |encryption|.
4144cscope Compiled with |cscope| support.
4145compatible Compiled to be very Vi compatible.
4146debug Compiled with "DEBUG" defined.
4147dialog_con Compiled with console dialog support.
4148dialog_gui Compiled with GUI dialog support.
4149diff Compiled with |vimdiff| and 'diff' support.
4150digraphs Compiled with support for digraphs.
4151dnd Compiled with support for the "~ register |quote_~|.
4152dos32 32 bits DOS (DJGPP) version of Vim.
4153dos16 16 bits DOS version of Vim.
4154ebcdic Compiled on a machine with ebcdic character set.
4155emacs_tags Compiled with support for Emacs tags.
4156eval Compiled with expression evaluation support. Always
4157 true, of course!
4158ex_extra Compiled with extra Ex commands |+ex_extra|.
4159extra_search Compiled with support for |'incsearch'| and
4160 |'hlsearch'|
4161farsi Compiled with Farsi support |farsi|.
4162file_in_path Compiled with support for |gf| and |<cfile>|
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004163filterpipe When 'shelltemp' is off pipes are used for shell
4164 read/write/filter commands
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165find_in_path Compiled with support for include file searches
4166 |+find_in_path|.
4167fname_case Case in file names matters (for Amiga, MS-DOS, and
4168 Windows this is not present).
4169folding Compiled with |folding| support.
4170footer Compiled with GUI footer support. |gui-footer|
4171fork Compiled to use fork()/exec() instead of system().
4172gettext Compiled with message translation |multi-lang|
4173gui Compiled with GUI enabled.
4174gui_athena Compiled with Athena GUI.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004175gui_beos Compiled with BeOS GUI.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176gui_gtk Compiled with GTK+ GUI (any version).
4177gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined).
Bram Moolenaar843ee412004-06-30 16:16:41 +00004178gui_kde Compiled with KDE GUI |KVim|
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179gui_mac Compiled with Macintosh GUI.
4180gui_motif Compiled with Motif GUI.
4181gui_photon Compiled with Photon GUI.
4182gui_win32 Compiled with MS Windows Win32 GUI.
4183gui_win32s idem, and Win32s system being used (Windows 3.1)
4184gui_running Vim is running in the GUI, or it will start soon.
4185hangul_input Compiled with Hangul input support. |hangul|
4186iconv Can use iconv() for conversion.
4187insert_expand Compiled with support for CTRL-X expansion commands in
4188 Insert mode.
4189jumplist Compiled with |jumplist| support.
4190keymap Compiled with 'keymap' support.
4191langmap Compiled with 'langmap' support.
4192libcall Compiled with |libcall()| support.
4193linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
4194 support.
4195lispindent Compiled with support for lisp indenting.
4196listcmds Compiled with commands for the buffer list |:files|
4197 and the argument list |arglist|.
4198localmap Compiled with local mappings and abbr. |:map-local|
4199mac Macintosh version of Vim.
4200macunix Macintosh version of Vim, using Unix files (OS-X).
4201menu Compiled with support for |:menu|.
4202mksession Compiled with support for |:mksession|.
4203modify_fname Compiled with file name modifiers. |filename-modifiers|
4204mouse Compiled with support mouse.
4205mouseshape Compiled with support for 'mouseshape'.
4206mouse_dec Compiled with support for Dec terminal mouse.
4207mouse_gpm Compiled with support for gpm (Linux console mouse)
4208mouse_netterm Compiled with support for netterm mouse.
4209mouse_pterm Compiled with support for qnx pterm mouse.
4210mouse_xterm Compiled with support for xterm mouse.
4211multi_byte Compiled with support for editing Korean et al.
4212multi_byte_ime Compiled with support for IME input method.
4213multi_lang Compiled with support for multiple languages.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004214mzscheme Compiled with MzScheme interface |mzscheme|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215netbeans_intg Compiled with support for |netbeans|.
Bram Moolenaar009b2592004-10-24 19:18:58 +00004216netbeans_enabled Compiled with support for |netbeans| and it's used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217ole Compiled with OLE automation support for Win32.
4218os2 OS/2 version of Vim.
4219osfiletype Compiled with support for osfiletypes |+osfiletype|
4220path_extra Compiled with up/downwards search in 'path' and 'tags'
4221perl Compiled with Perl interface.
4222postscript Compiled with PostScript file printing.
4223printer Compiled with |:hardcopy| support.
Bram Moolenaar05159a02005-02-26 23:04:13 +00004224profile Compiled with |:profile| support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225python Compiled with Python interface.
4226qnx QNX version of Vim.
4227quickfix Compiled with |quickfix| support.
4228rightleft Compiled with 'rightleft' support.
4229ruby Compiled with Ruby interface |ruby|.
4230scrollbind Compiled with 'scrollbind' support.
4231showcmd Compiled with 'showcmd' support.
4232signs Compiled with |:sign| support.
4233smartindent Compiled with 'smartindent' support.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004234sniff Compiled with SNiFF interface support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235statusline Compiled with support for 'statusline', 'rulerformat'
4236 and special formats of 'titlestring' and 'iconstring'.
4237sun_workshop Compiled with support for Sun |workshop|.
4238syntax Compiled with syntax highlighting support.
4239syntax_items There are active syntax highlighting items for the
4240 current buffer.
4241system Compiled to use system() instead of fork()/exec().
4242tag_binary Compiled with binary searching in tags files
4243 |tag-binary-search|.
4244tag_old_static Compiled with support for old static tags
4245 |tag-old-static|.
4246tag_any_white Compiled with support for any white characters in tags
4247 files |tag-any-white|.
4248tcl Compiled with Tcl interface.
4249terminfo Compiled with terminfo instead of termcap.
4250termresponse Compiled with support for |t_RV| and |v:termresponse|.
4251textobjects Compiled with support for |text-objects|.
4252tgetent Compiled with tgetent support, able to use a termcap
4253 or terminfo file.
4254title Compiled with window title support |'title'|.
4255toolbar Compiled with support for |gui-toolbar|.
4256unix Unix version of Vim.
4257user_commands User-defined commands.
4258viminfo Compiled with viminfo support.
4259vim_starting True while initial source'ing takes place.
4260vertsplit Compiled with vertically split windows |:vsplit|.
4261virtualedit Compiled with 'virtualedit' option.
4262visual Compiled with Visual mode.
4263visualextra Compiled with extra Visual mode commands.
4264 |blockwise-operators|.
4265vms VMS version of Vim.
4266vreplace Compiled with |gR| and |gr| commands.
4267wildignore Compiled with 'wildignore' option.
4268wildmenu Compiled with 'wildmenu' option.
4269windows Compiled with support for more than one window.
4270winaltkeys Compiled with 'winaltkeys' option.
4271win16 Win16 version of Vim (MS-Windows 3.1).
4272win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP).
4273win64 Win64 version of Vim (MS-Windows 64 bit).
4274win32unix Win32 version of Vim, using Unix files (Cygwin)
4275win95 Win32 version for MS-Windows 95/98/ME.
4276writebackup Compiled with 'writebackup' default on.
4277xfontset Compiled with X fontset support |xfontset|.
4278xim Compiled with X input method support |xim|.
4279xsmp Compiled with X session management support.
4280xsmp_interact Compiled with interactive X session management support.
4281xterm_clipboard Compiled with support for xterm clipboard.
4282xterm_save Compiled with support for saving and restoring the
4283 xterm screen.
4284x11 Compiled with X11 support.
4285
4286 *string-match*
4287Matching a pattern in a String
4288
4289A regexp pattern as explained at |pattern| is normally used to find a match in
4290the buffer lines. When a pattern is used to find a match in a String, almost
4291everything works in the same way. The difference is that a String is handled
4292like it is one line. When it contains a "\n" character, this is not seen as a
4293line break for the pattern. It can be matched with a "\n" in the pattern, or
4294with ".". Example: >
4295 :let a = "aaaa\nxxxx"
4296 :echo matchstr(a, "..\n..")
4297 aa
4298 xx
4299 :echo matchstr(a, "a.x")
4300 a
4301 x
4302
4303Don't forget that "^" will only match at the first character of the String and
4304"$" at the last character of the string. They don't match after or before a
4305"\n".
4306
4307==============================================================================
43085. Defining functions *user-functions*
4309
4310New functions can be defined. These can be called just like builtin
4311functions. The function executes a sequence of Ex commands. Normal mode
4312commands can be executed with the |:normal| command.
4313
4314The function name must start with an uppercase letter, to avoid confusion with
4315builtin functions. To prevent from using the same name in different scripts
4316avoid obvious, short names. A good habit is to start the function name with
4317the name of the script, e.g., "HTMLcolor()".
4318
4319It's also possible to use curly braces, see |curly-braces-names|.
4320
4321 *local-function*
4322A function local to a script must start with "s:". A local script function
4323can only be called from within the script and from functions, user commands
4324and autocommands defined in the script. It is also possible to call the
4325function from a mappings defined in the script, but then |<SID>| must be used
4326instead of "s:" when the mapping is expanded outside of the script.
4327
4328 *:fu* *:function* *E128* *E129* *E123*
4329:fu[nction] List all functions and their arguments.
4330
4331:fu[nction] {name} List function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004332 {name} can also be a Dictionary entry that is a
4333 Funcref: >
4334 :function dict.init
4335< *E124* *E125*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004336:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 Define a new function by the name {name}. The name
4338 must be made of alphanumeric characters and '_', and
4339 must start with a capital or "s:" (see above).
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004340
4341 {name} can also be a Dictionary entry that is a
4342 Funcref: >
4343 :function dict.init(arg)
4344< "dict" must be an existing dictionary. The entry
4345 "init" is added if it didn't exist yet. Otherwise [!]
4346 is required to overwrite an existing function. The
4347 result is a |Funcref| to a numbered function. The
4348 function can only be used with a |Funcref| and will be
4349 deleted if there are no more references to it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350 *E127* *E122*
4351 When a function by this name already exists and [!] is
4352 not used an error message is given. When [!] is used,
4353 an existing function is silently replaced. Unless it
4354 is currently being executed, that is an error.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004355
4356 For the {arguments} see |function-argument|.
4357
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 *a:firstline* *a:lastline*
4359 When the [range] argument is added, the function is
4360 expected to take care of a range itself. The range is
4361 passed as "a:firstline" and "a:lastline". If [range]
4362 is excluded, ":{range}call" will call the function for
4363 each line in the range, with the cursor on the start
4364 of each line. See |function-range-example|.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004365
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 When the [abort] argument is added, the function will
4367 abort as soon as an error is detected.
4368 The last used search pattern and the redo command "."
4369 will not be changed by the function.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004370
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00004371 When the [dict] argument is added, the function must
4372 be invoked through an entry in a Dictionary. The
4373 local variable "self" will then be set to the
4374 dictionary. See |Dictionary-function|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375
4376 *:endf* *:endfunction* *E126* *E193*
4377:endf[unction] The end of a function definition. Must be on a line
4378 by its own, without other commands.
4379
4380 *:delf* *:delfunction* *E130* *E131*
4381:delf[unction] {name} Delete function {name}.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004382 {name} can also be a Dictionary entry that is a
4383 Funcref: >
4384 :delfunc dict.init
4385< This will remove the "init" entry from "dict". The
4386 function is deleted if there are no more references to
4387 it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388 *:retu* *:return* *E133*
4389:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
4390 evaluated and returned as the result of the function.
4391 If "[expr]" is not given, the number 0 is returned.
4392 When a function ends without an explicit ":return",
4393 the number 0 is returned.
4394 Note that there is no check for unreachable lines,
4395 thus there is no warning if commands follow ":return".
4396
4397 If the ":return" is used after a |:try| but before the
4398 matching |:finally| (if present), the commands
4399 following the ":finally" up to the matching |:endtry|
4400 are executed first. This process applies to all
4401 nested ":try"s inside the function. The function
4402 returns at the outermost ":endtry".
4403
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004404 *function-argument* *a:var*
4405An argument can be defined by giving its name. In the function this can then
4406be used as "a:name" ("a:" for argument).
4407 *a:0* *a:1* *a:000* *E740*
4408Up to 20 arguments can be given, separated by commas. After the named
4409arguments an argument "..." can be specified, which means that more arguments
4410may optionally be following. In the function the extra arguments can be used
4411as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004412can be 0). "a:000" is set to a List that contains these arguments. Note that
4413"a:1" is the same as "a:000[0]".
4414 *E742*
4415The a: scope and the variables in it cannot be changed, they are fixed.
4416However, if a List or Dictionary is used, you can changes their contents.
4417Thus you can pass a List to a function and have the function add an item to
4418it. If you want to make sure the function cannot change a List or Dictionary
4419use |:lockvar|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420
Bram Moolenaar8f999f12005-01-25 22:12:55 +00004421When not using "...", the number of arguments in a function call must be equal
4422to the number of named arguments. When using "...", the number of arguments
4423may be larger.
4424
4425It is also possible to define a function without any arguments. You must
4426still supply the () then. The body of the function follows in the next lines,
4427until the matching |:endfunction|. It is allowed to define another function
4428inside a function body.
4429
4430 *local-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431Inside a function variables can be used. These are local variables, which
4432will disappear when the function returns. Global variables need to be
4433accessed with "g:".
4434
4435Example: >
4436 :function Table(title, ...)
4437 : echohl Title
4438 : echo a:title
4439 : echohl None
Bram Moolenaar677ee682005-01-27 14:41:15 +00004440 : echo a:0 . " items:"
4441 : for s in a:000
4442 : echon ' ' . s
4443 : endfor
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 :endfunction
4445
4446This function can then be called with: >
Bram Moolenaar677ee682005-01-27 14:41:15 +00004447 call Table("Table", "line1", "line2")
4448 call Table("Empty Table")
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449
4450To return more than one value, pass the name of a global variable: >
4451 :function Compute(n1, n2, divname)
4452 : if a:n2 == 0
4453 : return "fail"
4454 : endif
4455 : let g:{a:divname} = a:n1 / a:n2
4456 : return "ok"
4457 :endfunction
4458
4459This function can then be called with: >
4460 :let success = Compute(13, 1324, "div")
4461 :if success == "ok"
4462 : echo div
4463 :endif
4464
4465An alternative is to return a command that can be executed. This also works
4466with local variables in a calling function. Example: >
4467 :function Foo()
4468 : execute Bar()
4469 : echo "line " . lnum . " column " . col
4470 :endfunction
4471
4472 :function Bar()
4473 : return "let lnum = " . line(".") . " | let col = " . col(".")
4474 :endfunction
4475
4476The names "lnum" and "col" could also be passed as argument to Bar(), to allow
4477the caller to set the names.
4478
4479 *:cal* *:call* *E107*
4480:[range]cal[l] {name}([arguments])
4481 Call a function. The name of the function and its arguments
4482 are as specified with |:function|. Up to 20 arguments can be
4483 used.
4484 Without a range and for functions that accept a range, the
4485 function is called once. When a range is given the cursor is
4486 positioned at the start of the first line before executing the
4487 function.
4488 When a range is given and the function doesn't handle it
4489 itself, the function is executed for each line in the range,
4490 with the cursor in the first column of that line. The cursor
4491 is left at the last line (possibly moved by the last function
4492 call). The arguments are re-evaluated for each line. Thus
4493 this works:
4494 *function-range-example* >
4495 :function Mynumber(arg)
4496 : echo line(".") . " " . a:arg
4497 :endfunction
4498 :1,5call Mynumber(getline("."))
4499<
4500 The "a:firstline" and "a:lastline" are defined anyway, they
4501 can be used to do something different at the start or end of
4502 the range.
4503
4504 Example of a function that handles the range itself: >
4505
4506 :function Cont() range
4507 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
4508 :endfunction
4509 :4,8call Cont()
4510<
4511 This function inserts the continuation character "\" in front
4512 of all the lines in the range, except the first one.
4513
4514 *E132*
4515The recursiveness of user functions is restricted with the |'maxfuncdepth'|
4516option.
4517
Bram Moolenaar7c626922005-02-07 22:01:03 +00004518
4519AUTOMATICALLY LOADING FUNCTIONS ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 *autoload-functions*
4521When using many or large functions, it's possible to automatically define them
Bram Moolenaar7c626922005-02-07 22:01:03 +00004522only when they are used. There are two methods: with an autocommand and with
4523the "autoload" directory in 'runtimepath'.
4524
4525
4526Using an autocommand ~
4527
Bram Moolenaar05159a02005-02-26 23:04:13 +00004528This is introduced in the user manual, section |41.14|.
4529
Bram Moolenaar7c626922005-02-07 22:01:03 +00004530The autocommand is useful if you have a plugin that is a long Vim script file.
4531You can define the autocommand and quickly quit the script with |:finish|.
4532That makes Vim startup faster. The autocommand should then load the same file
4533again, setting a variable to skip the |:finish| command.
4534
4535Use the FuncUndefined autocommand event with a pattern that matches the
4536function(s) to be defined. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537
4538 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
4539
4540The file "~/vim/bufnetfuncs.vim" should then define functions that start with
4541"BufNet". Also see |FuncUndefined|.
4542
Bram Moolenaar7c626922005-02-07 22:01:03 +00004543
4544Using an autoload script ~
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004545 *autoload* *E746*
Bram Moolenaar05159a02005-02-26 23:04:13 +00004546This is introduced in the user manual, section |41.15|.
4547
Bram Moolenaar7c626922005-02-07 22:01:03 +00004548Using a script in the "autoload" directory is simpler, but requires using
4549exactly the right file name. A function that can be autoloaded has a name
4550like this: >
4551
4552 :call filename:funcname()
4553
4554When such a function is called, and it is not defined yet, Vim will search the
4555"autoload" directories in 'runtimepath' for a script file called
4556"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
4557then define the function like this: >
4558
4559 function filename:funcname()
4560 echo "Done!"
4561 endfunction
4562
4563The file name and the name used before the colon in the function must match
4564exactly, and the defined function must have the name exactly as it will be
4565called.
4566
4567It is possible to use subdirectories. Every colon in the function name works
4568like a path separator. Thus when calling a function: >
4569
4570 :call foo:bar:func()
4571
4572Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
4573
4574The name before the first colon must be at least two characters long,
4575otherwise it looks like a scope, such as "s:".
4576
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004577This also works when reading a variable that has not been set yet: >
4578
4579 :let l = foo:bar:lvar
4580
4581When assigning a value to such a variable nothing special happens. This can
4582be used to pass settings to the autoload script before it's loaded: >
4583
4584 :let foo:bar:toggle = 1
4585 :call foo:bar:func()
4586
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004587Note that when you make a mistake and call a function that is supposed to be
4588defined in an autoload script, but the script doesn't actually define the
4589function, the script will be sourced every time you try to call the function.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00004590And you will get an error message every time.
4591
4592Also note that if you have two script files, and one calls a function in the
4593other and vise versa, before the used function is defined, it won't work.
4594Avoid using the autoload functionality at the toplevel.
Bram Moolenaar7c626922005-02-07 22:01:03 +00004595
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596==============================================================================
45976. Curly braces names *curly-braces-names*
4598
4599Wherever you can use a variable, you can use a "curly braces name" variable.
4600This is a regular variable name with one or more expressions wrapped in braces
4601{} like this: >
4602 my_{adjective}_variable
4603
4604When Vim encounters this, it evaluates the expression inside the braces, puts
4605that in place of the expression, and re-interprets the whole as a variable
4606name. So in the above example, if the variable "adjective" was set to
4607"noisy", then the reference would be to "my_noisy_variable", whereas if
4608"adjective" was set to "quiet", then it would be to "my_quiet_variable".
4609
4610One application for this is to create a set of variables governed by an option
4611value. For example, the statement >
4612 echo my_{&background}_message
4613
4614would output the contents of "my_dark_message" or "my_light_message" depending
4615on the current value of 'background'.
4616
4617You can use multiple brace pairs: >
4618 echo my_{adverb}_{adjective}_message
4619..or even nest them: >
4620 echo my_{ad{end_of_word}}_message
4621where "end_of_word" is either "verb" or "jective".
4622
4623However, the expression inside the braces must evaluate to a valid single
4624variable name. e.g. this is invalid: >
4625 :let foo='a + b'
4626 :echo c{foo}d
4627.. since the result of expansion is "ca + bd", which is not a variable name.
4628
4629 *curly-braces-function-names*
4630You can call and define functions by an evaluated name in a similar way.
4631Example: >
4632 :let func_end='whizz'
4633 :call my_func_{func_end}(parameter)
4634
4635This would call the function "my_func_whizz(parameter)".
4636
4637==============================================================================
46387. Commands *expression-commands*
4639
4640:let {var-name} = {expr1} *:let* *E18*
4641 Set internal variable {var-name} to the result of the
4642 expression {expr1}. The variable will get the type
4643 from the {expr}. If {var-name} didn't exist yet, it
4644 is created.
4645
Bram Moolenaar13065c42005-01-08 16:08:21 +00004646:let {var-name}[{idx}] = {expr1} *E689*
4647 Set a list item to the result of the expression
4648 {expr1}. {var-name} must refer to a list and {idx}
4649 must be a valid index in that list. For nested list
4650 the index can be repeated.
4651 This cannot be used to add an item to a list.
4652
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004653 *E711* *E719*
4654:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004655 Set a sequence of items in a List to the result of the
4656 expression {expr1}, which must be a list with the
4657 correct number of items.
4658 {idx1} can be omitted, zero is used instead.
4659 {idx2} can be omitted, meaning the end of the list.
4660 When the selected range of items is partly past the
4661 end of the list, items will be added.
4662
Bram Moolenaar748bf032005-02-02 23:04:36 +00004663 *:let+=* *:let-=* *:let.=* *E734*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004664:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
4665:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
4666:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
4667 These fail if {var} was not set yet and when the type
4668 of {var} and {expr1} don't fit the operator.
4669
4670
Bram Moolenaar071d4272004-06-13 20:20:40 +00004671:let ${env-name} = {expr1} *:let-environment* *:let-$*
4672 Set environment variable {env-name} to the result of
4673 the expression {expr1}. The type is always String.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004674:let ${env-name} .= {expr1}
4675 Append {expr1} to the environment variable {env-name}.
4676 If the environment variable didn't exist yet this
4677 works like "=".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678
4679:let @{reg-name} = {expr1} *:let-register* *:let-@*
4680 Write the result of the expression {expr1} in register
4681 {reg-name}. {reg-name} must be a single letter, and
4682 must be the name of a writable register (see
4683 |registers|). "@@" can be used for the unnamed
4684 register, "@/" for the search pattern.
4685 If the result of {expr1} ends in a <CR> or <NL>, the
4686 register will be linewise, otherwise it will be set to
4687 characterwise.
4688 This can be used to clear the last search pattern: >
4689 :let @/ = ""
4690< This is different from searching for an empty string,
4691 that would match everywhere.
4692
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004693:let @{reg-name} .= {expr1}
4694 Append {expr1} to register {reg-name}. If the
4695 register was empty it's like setting it to {expr1}.
4696
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697:let &{option-name} = {expr1} *:let-option* *:let-star*
4698 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004699 expression {expr1}. A String or Number value is
4700 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 For an option local to a window or buffer the effect
4702 is just like using the |:set| command: both the local
4703 value and the global value is changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004704 Example: >
4705 :let &path = &path . ',/usr/local/include'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004707:let &{option-name} .= {expr1}
4708 For a string option: Append {expr1} to the value.
4709 Does not insert a comma like |:set+=|.
4710
4711:let &{option-name} += {expr1}
4712:let &{option-name} -= {expr1}
4713 For a number or boolean option: Add or subtract
4714 {expr1}.
4715
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716:let &l:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004717:let &l:{option-name} .= {expr1}
4718:let &l:{option-name} += {expr1}
4719:let &l:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720 Like above, but only set the local value of an option
4721 (if there is one). Works like |:setlocal|.
4722
4723:let &g:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004724:let &g:{option-name} .= {expr1}
4725:let &g:{option-name} += {expr1}
4726:let &g:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 Like above, but only set the global value of an option
4728 (if there is one). Works like |:setglobal|.
4729
Bram Moolenaar13065c42005-01-08 16:08:21 +00004730:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004731 {expr1} must evaluate to a List. The first item in
4732 the list is assigned to {name1}, the second item to
4733 {name2}, etc.
4734 The number of names must match the number of items in
4735 the List.
4736 Each name can be one of the items of the ":let"
4737 command as mentioned above.
4738 Example: >
4739 :let [s, item] = GetItem(s)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004740< Detail: {expr1} is evaluated first, then the
4741 assignments are done in sequence. This matters if
4742 {name2} depends on {name1}. Example: >
4743 :let x = [0, 1]
4744 :let i = 0
4745 :let [i, x[i]] = [1, 2]
4746 :echo x
4747< The result is [0, 2].
4748
4749:let [{name1}, {name2}, ...] .= {expr1}
4750:let [{name1}, {name2}, ...] += {expr1}
4751:let [{name1}, {name2}, ...] -= {expr1}
4752 Like above, but append/add/subtract the value for each
4753 List item.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004754
4755:let [{name}, ..., ; {lastname}] = {expr1}
Bram Moolenaar677ee682005-01-27 14:41:15 +00004756 Like |:let-unpack| above, but the List may have more
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004757 items than there are names. A list of the remaining
4758 items is assigned to {lastname}. If there are no
4759 remaining items {lastname} is set to an empty list.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00004760 Example: >
4761 :let [a, b; rest] = ["aval", "bval", 3, 4]
4762<
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004763:let [{name}, ..., ; {lastname}] .= {expr1}
4764:let [{name}, ..., ; {lastname}] += {expr1}
4765:let [{name}, ..., ; {lastname}] -= {expr1}
4766 Like above, but append/add/subtract the value for each
4767 List item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 *E106*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004769:let {var-name} .. List the value of variable {var-name}. Multiple
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00004770 variable names may be given. Special names recognized
4771 here: *E738*
4772 g: global variables.
4773 b: local buffer variables.
4774 w: local window variables.
4775 v: Vim variables.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00004777:let List the values of all variables. The type of the
4778 variable is indicated before the value:
4779 <nothing> String
4780 # Number
4781 * Funcref
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004783
4784:unl[et][!] {name} ... *:unlet* *:unl* *E108*
4785 Remove the internal variable {name}. Several variable
4786 names can be given, they are all removed. The name
4787 may also be a List or Dictionary item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 With [!] no error message is given for non-existing
4789 variables.
Bram Moolenaar9cd15162005-01-16 22:02:49 +00004790 One or more items from a List can be removed: >
4791 :unlet list[3] " remove fourth item
4792 :unlet list[3:] " remove fourth item to last
4793< One item from a Dictionary can be removed at a time: >
4794 :unlet dict['two']
4795 :unlet dict.two
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00004797:lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv*
4798 Lock the internal variable {name}. Locking means that
4799 it can no longer be changed (until it is unlocked).
4800 A locked variable can be deleted: >
4801 :lockvar v
4802 :let v = 'asdf' " fails!
4803 :unlet v
4804< *E741*
4805 If you try to change a locked variable you get an
4806 error message: "E741: Value of {name} is locked"
4807
4808 [depth] is relevant when locking a List or Dictionary.
4809 It specifies how deep the locking goes:
4810 1 Lock the List or Dictionary itself,
4811 cannot add or remove items, but can
4812 still change their values.
4813 2 Also lock the values, cannot change
4814 the items. If an item is a List or
4815 Dictionary, cannot add or remove
4816 items, but can still change the
4817 values.
4818 3 Like 2 but for the List/Dictionary in
4819 the List/Dictionary, one level deeper.
4820 The default [depth] is 2, thus when {name} is a List
4821 or Dictionary the values cannot be changed.
4822 *E743*
4823 For unlimited depth use [!] and omit [depth].
4824 However, there is a maximum depth of 100 to catch
4825 loops.
4826
4827 Note that when two variables refer to the same List
4828 and you lock one of them, the List will also be locked
4829 when used through the other variable. Example: >
4830 :let l = [0, 1, 2, 3]
4831 :let cl = l
4832 :lockvar l
4833 :let cl[1] = 99 " won't work!
4834< You may want to make a copy of a list to avoid this.
4835 See |deepcopy()|.
4836
4837
4838:unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo*
4839 Unlock the internal variable {name}. Does the
4840 opposite of |:lockvar|.
4841
4842
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843:if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580*
4844:en[dif] Execute the commands until the next matching ":else"
4845 or ":endif" if {expr1} evaluates to non-zero.
4846
4847 From Vim version 4.5 until 5.0, every Ex command in
4848 between the ":if" and ":endif" is ignored. These two
4849 commands were just to allow for future expansions in a
4850 backwards compatible way. Nesting was allowed. Note
4851 that any ":else" or ":elseif" was ignored, the "else"
4852 part was not executed either.
4853
4854 You can use this to remain compatible with older
4855 versions: >
4856 :if version >= 500
4857 : version-5-specific-commands
4858 :endif
4859< The commands still need to be parsed to find the
4860 "endif". Sometimes an older Vim has a problem with a
4861 new command. For example, ":silent" is recognized as
4862 a ":substitute" command. In that case ":execute" can
4863 avoid problems: >
4864 :if version >= 600
4865 : execute "silent 1,$delete"
4866 :endif
4867<
4868 NOTE: The ":append" and ":insert" commands don't work
4869 properly in between ":if" and ":endif".
4870
4871 *:else* *:el* *E581* *E583*
4872:el[se] Execute the commands until the next matching ":else"
4873 or ":endif" if they previously were not being
4874 executed.
4875
4876 *:elseif* *:elsei* *E582* *E584*
4877:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
4878 is no extra ":endif".
4879
4880:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004881 *E170* *E585* *E588* *E733*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882:endw[hile] Repeat the commands between ":while" and ":endwhile",
4883 as long as {expr1} evaluates to non-zero.
4884 When an error is detected from a command inside the
4885 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00004886 Example: >
4887 :let lnum = 1
4888 :while lnum <= line("$")
4889 :call FixLine(lnum)
4890 :let lnum = lnum + 1
4891 :endwhile
4892<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00004894 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00004896:for {var} in {list} *:for* *E690* *E732*
Bram Moolenaar12805862005-01-05 22:16:17 +00004897:endfo[r] *:endfo* *:endfor*
4898 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00004899 each item in {list}. Variable {var} is set to the
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004900 value of each item.
4901 When an error is detected for a command inside the
Bram Moolenaar12805862005-01-05 22:16:17 +00004902 loop, execution continues after the "endfor".
Bram Moolenaarde8866b2005-01-06 23:24:37 +00004903 Changing {list} affects what items are used. Make a
4904 copy if this is unwanted: >
4905 :for item in copy(mylist)
4906< When not making a copy, Vim stores a reference to the
4907 next item in the list, before executing the commands
4908 with the current item. Thus the current item can be
4909 removed without effect. Removing any later item means
4910 it will not be found. Thus the following example
4911 works (an inefficient way to make a list empty): >
4912 :for item in mylist
Bram Moolenaar12805862005-01-05 22:16:17 +00004913 :call remove(mylist, 0)
4914 :endfor
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00004915< Note that reordering the list (e.g., with sort() or
4916 reverse()) may have unexpected effects.
4917 Note that the type of each list item should be
Bram Moolenaar12805862005-01-05 22:16:17 +00004918 identical to avoid errors for the type of {var}
4919 changing. Unlet the variable at the end of the loop
4920 to allow multiple item types.
4921
4922:for {var} in {string}
4923:endfo[r] Like ":for" above, but use each character in {string}
4924 as a list item.
4925 Composing characters are used as separate characters.
4926 A Number is first converted to a String.
4927
4928:for [{var1}, {var2}, ...] in {listlist}
4929:endfo[r]
4930 Like ":for" above, but each item in {listlist} must be
4931 a list, of which each item is assigned to {var1},
4932 {var2}, etc. Example: >
4933 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
4934 :echo getline(lnum)[col]
4935 :endfor
4936<
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00004938:con[tinue] When used inside a ":while" or ":for" loop, jumps back
4939 to the start of the loop.
4940 If it is used after a |:try| inside the loop but
4941 before the matching |:finally| (if present), the
4942 commands following the ":finally" up to the matching
4943 |:endtry| are executed first. This process applies to
4944 all nested ":try"s inside the loop. The outermost
4945 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946
4947 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00004948:brea[k] When used inside a ":while" or ":for" loop, skips to
4949 the command after the matching ":endwhile" or
4950 ":endfor".
4951 If it is used after a |:try| inside the loop but
4952 before the matching |:finally| (if present), the
4953 commands following the ":finally" up to the matching
4954 |:endtry| are executed first. This process applies to
4955 all nested ":try"s inside the loop. The outermost
4956 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957
4958:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
4959:endt[ry] Change the error handling for the commands between
4960 ":try" and ":endtry" including everything being
4961 executed across ":source" commands, function calls,
4962 or autocommand invocations.
4963
4964 When an error or interrupt is detected and there is
4965 a |:finally| command following, execution continues
4966 after the ":finally". Otherwise, or when the
4967 ":endtry" is reached thereafter, the next
4968 (dynamically) surrounding ":try" is checked for
4969 a corresponding ":finally" etc. Then the script
4970 processing is terminated. (Whether a function
4971 definition has an "abort" argument does not matter.)
4972 Example: >
4973 :try | edit too much | finally | echo "cleanup" | endtry
4974 :echo "impossible" " not reached, script terminated above
4975<
4976 Moreover, an error or interrupt (dynamically) inside
4977 ":try" and ":endtry" is converted to an exception. It
4978 can be caught as if it were thrown by a |:throw|
4979 command (see |:catch|). In this case, the script
4980 processing is not terminated.
4981
4982 The value "Vim:Interrupt" is used for an interrupt
4983 exception. An error in a Vim command is converted
4984 to a value of the form "Vim({command}):{errmsg}",
4985 other errors are converted to a value of the form
4986 "Vim:{errmsg}". {command} is the full command name,
4987 and {errmsg} is the message that is displayed if the
4988 error exception is not caught, always beginning with
4989 the error number.
4990 Examples: >
4991 :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
4992 :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
4993<
4994 *:cat* *:catch* *E603* *E604* *E605*
4995:cat[ch] /{pattern}/ The following commands until the next ":catch",
4996 |:finally|, or |:endtry| that belongs to the same
4997 |:try| as the ":catch" are executed when an exception
4998 matching {pattern} is being thrown and has not yet
4999 been caught by a previous ":catch". Otherwise, these
5000 commands are skipped.
5001 When {pattern} is omitted all errors are caught.
5002 Examples: >
5003 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
5004 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
5005 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
5006 :catch /^Vim(write):/ " catch all errors in :write
5007 :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
5008 :catch /my-exception/ " catch user exception
5009 :catch /.*/ " catch everything
5010 :catch " same as /.*/
5011<
5012 Another character can be used instead of / around the
5013 {pattern}, so long as it does not have a special
5014 meaning (e.g., '|' or '"') and doesn't occur inside
5015 {pattern}.
5016 NOTE: It is not reliable to ":catch" the TEXT of
5017 an error message because it may vary in different
5018 locales.
5019
5020 *:fina* *:finally* *E606* *E607*
5021:fina[lly] The following commands until the matching |:endtry|
5022 are executed whenever the part between the matching
5023 |:try| and the ":finally" is left: either by falling
5024 through to the ":finally" or by a |:continue|,
5025 |:break|, |:finish|, or |:return|, or by an error or
5026 interrupt or exception (see |:throw|).
5027
5028 *:th* *:throw* *E608*
5029:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
5030 If the ":throw" is used after a |:try| but before the
5031 first corresponding |:catch|, commands are skipped
5032 until the first ":catch" matching {expr1} is reached.
5033 If there is no such ":catch" or if the ":throw" is
5034 used after a ":catch" but before the |:finally|, the
5035 commands following the ":finally" (if present) up to
5036 the matching |:endtry| are executed. If the ":throw"
5037 is after the ":finally", commands up to the ":endtry"
5038 are skipped. At the ":endtry", this process applies
5039 again for the next dynamically surrounding ":try"
5040 (which may be found in a calling function or sourcing
5041 script), until a matching ":catch" has been found.
5042 If the exception is not caught, the command processing
5043 is terminated.
5044 Example: >
5045 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
5046<
5047
5048 *:ec* *:echo*
5049:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
5050 first {expr1} starts on a new line.
5051 Also see |:comment|.
5052 Use "\n" to start a new line. Use "\r" to move the
5053 cursor to the first column.
5054 Uses the highlighting set by the |:echohl| command.
5055 Cannot be followed by a comment.
5056 Example: >
5057 :echo "the value of 'shell' is" &shell
5058< A later redraw may make the message disappear again.
5059 To avoid that a command from before the ":echo" causes
5060 a redraw afterwards (redraws are often postponed until
5061 you type something), force a redraw with the |:redraw|
5062 command. Example: >
5063 :new | redraw | echo "there is a new window"
5064<
5065 *:echon*
5066:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
5067 |:comment|.
5068 Uses the highlighting set by the |:echohl| command.
5069 Cannot be followed by a comment.
5070 Example: >
5071 :echon "the value of 'shell' is " &shell
5072<
5073 Note the difference between using ":echo", which is a
5074 Vim command, and ":!echo", which is an external shell
5075 command: >
5076 :!echo % --> filename
5077< The arguments of ":!" are expanded, see |:_%|. >
5078 :!echo "%" --> filename or "filename"
5079< Like the previous example. Whether you see the double
5080 quotes or not depends on your 'shell'. >
5081 :echo % --> nothing
5082< The '%' is an illegal character in an expression. >
5083 :echo "%" --> %
5084< This just echoes the '%' character. >
5085 :echo expand("%") --> filename
5086< This calls the expand() function to expand the '%'.
5087
5088 *:echoh* *:echohl*
5089:echoh[l] {name} Use the highlight group {name} for the following
5090 |:echo|, |:echon| and |:echomsg| commands. Also used
5091 for the |input()| prompt. Example: >
5092 :echohl WarningMsg | echo "Don't panic!" | echohl None
5093< Don't forget to set the group back to "None",
5094 otherwise all following echo's will be highlighted.
5095
5096 *:echom* *:echomsg*
5097:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
5098 message in the |message-history|.
5099 Spaces are placed between the arguments as with the
5100 |:echo| command. But unprintable characters are
5101 displayed, not interpreted.
5102 Uses the highlighting set by the |:echohl| command.
5103 Example: >
5104 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
5105<
5106 *:echoe* *:echoerr*
5107:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
5108 message in the |message-history|. When used in a
5109 script or function the line number will be added.
5110 Spaces are placed between the arguments as with the
5111 :echo command. When used inside a try conditional,
5112 the message is raised as an error exception instead
5113 (see |try-echoerr|).
5114 Example: >
5115 :echoerr "This script just failed!"
5116< If you just want a highlighted message use |:echohl|.
5117 And to get a beep: >
5118 :exe "normal \<Esc>"
5119<
5120 *:exe* *:execute*
5121:exe[cute] {expr1} .. Executes the string that results from the evaluation
5122 of {expr1} as an Ex command. Multiple arguments are
5123 concatenated, with a space in between. {expr1} is
5124 used as the processed command, command line editing
5125 keys are not recognized.
5126 Cannot be followed by a comment.
5127 Examples: >
5128 :execute "buffer " nextbuf
5129 :execute "normal " count . "w"
5130<
5131 ":execute" can be used to append a command to commands
5132 that don't accept a '|'. Example: >
5133 :execute '!ls' | echo "theend"
5134
5135< ":execute" is also a nice way to avoid having to type
5136 control characters in a Vim script for a ":normal"
5137 command: >
5138 :execute "normal ixxx\<Esc>"
5139< This has an <Esc> character, see |expr-string|.
5140
5141 Note: The executed string may be any command-line, but
Bram Moolenaard8b02732005-01-14 21:48:43 +00005142 you cannot start or end a "while", "for" or "if"
5143 command. Thus this is illegal: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 :execute 'while i > 5'
5145 :execute 'echo "test" | break'
5146<
5147 It is allowed to have a "while" or "if" command
5148 completely in the executed string: >
5149 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
5150<
5151
5152 *:comment*
5153 ":execute", ":echo" and ":echon" cannot be followed by
5154 a comment directly, because they see the '"' as the
5155 start of a string. But, you can use '|' followed by a
5156 comment. Example: >
5157 :echo "foo" | "this is a comment
5158
5159==============================================================================
51608. Exception handling *exception-handling*
5161
5162The Vim script language comprises an exception handling feature. This section
5163explains how it can be used in a Vim script.
5164
5165Exceptions may be raised by Vim on an error or on interrupt, see
5166|catch-errors| and |catch-interrupt|. You can also explicitly throw an
5167exception by using the ":throw" command, see |throw-catch|.
5168
5169
5170TRY CONDITIONALS *try-conditionals*
5171
5172Exceptions can be caught or can cause cleanup code to be executed. You can
5173use a try conditional to specify catch clauses (that catch exceptions) and/or
5174a finally clause (to be executed for cleanup).
5175 A try conditional begins with a |:try| command and ends at the matching
5176|:endtry| command. In between, you can use a |:catch| command to start
5177a catch clause, or a |:finally| command to start a finally clause. There may
5178be none or multiple catch clauses, but there is at most one finally clause,
5179which must not be followed by any catch clauses. The lines before the catch
5180clauses and the finally clause is called a try block. >
5181
5182 :try
5183 : ...
5184 : ... TRY BLOCK
5185 : ...
5186 :catch /{pattern}/
5187 : ...
5188 : ... CATCH CLAUSE
5189 : ...
5190 :catch /{pattern}/
5191 : ...
5192 : ... CATCH CLAUSE
5193 : ...
5194 :finally
5195 : ...
5196 : ... FINALLY CLAUSE
5197 : ...
5198 :endtry
5199
5200The try conditional allows to watch code for exceptions and to take the
5201appropriate actions. Exceptions from the try block may be caught. Exceptions
5202from the try block and also the catch clauses may cause cleanup actions.
5203 When no exception is thrown during execution of the try block, the control
5204is transferred to the finally clause, if present. After its execution, the
5205script continues with the line following the ":endtry".
5206 When an exception occurs during execution of the try block, the remaining
5207lines in the try block are skipped. The exception is matched against the
5208patterns specified as arguments to the ":catch" commands. The catch clause
5209after the first matching ":catch" is taken, other catch clauses are not
5210executed. The catch clause ends when the next ":catch", ":finally", or
5211":endtry" command is reached - whatever is first. Then, the finally clause
5212(if present) is executed. When the ":endtry" is reached, the script execution
5213continues in the following line as usual.
5214 When an exception that does not match any of the patterns specified by the
5215":catch" commands is thrown in the try block, the exception is not caught by
5216that try conditional and none of the catch clauses is executed. Only the
5217finally clause, if present, is taken. The exception pends during execution of
5218the finally clause. It is resumed at the ":endtry", so that commands after
5219the ":endtry" are not executed and the exception might be caught elsewhere,
5220see |try-nesting|.
5221 When during execution of a catch clause another exception is thrown, the
5222remaining lines in that catch clause are not executed. The new exception is
5223not matched against the patterns in any of the ":catch" commands of the same
5224try conditional and none of its catch clauses is taken. If there is, however,
5225a finally clause, it is executed, and the exception pends during its
5226execution. The commands following the ":endtry" are not executed. The new
5227exception might, however, be caught elsewhere, see |try-nesting|.
5228 When during execution of the finally clause (if present) an exception is
5229thrown, the remaining lines in the finally clause are skipped. If the finally
5230clause has been taken because of an exception from the try block or one of the
5231catch clauses, the original (pending) exception is discarded. The commands
5232following the ":endtry" are not executed, and the exception from the finally
5233clause is propagated and can be caught elsewhere, see |try-nesting|.
5234
5235The finally clause is also executed, when a ":break" or ":continue" for
5236a ":while" loop enclosing the complete try conditional is executed from the
5237try block or a catch clause. Or when a ":return" or ":finish" is executed
5238from the try block or a catch clause of a try conditional in a function or
5239sourced script, respectively. The ":break", ":continue", ":return", or
5240":finish" pends during execution of the finally clause and is resumed when the
5241":endtry" is reached. It is, however, discarded when an exception is thrown
5242from the finally clause.
5243 When a ":break" or ":continue" for a ":while" loop enclosing the complete
5244try conditional or when a ":return" or ":finish" is encountered in the finally
5245clause, the rest of the finally clause is skipped, and the ":break",
5246":continue", ":return" or ":finish" is executed as usual. If the finally
5247clause has been taken because of an exception or an earlier ":break",
5248":continue", ":return", or ":finish" from the try block or a catch clause,
5249this pending exception or command is discarded.
5250
5251For examples see |throw-catch| and |try-finally|.
5252
5253
5254NESTING OF TRY CONDITIONALS *try-nesting*
5255
5256Try conditionals can be nested arbitrarily. That is, a complete try
5257conditional can be put into the try block, a catch clause, or the finally
5258clause of another try conditional. If the inner try conditional does not
5259catch an exception thrown in its try block or throws a new exception from one
5260of its catch clauses or its finally clause, the outer try conditional is
5261checked according to the rules above. If the inner try conditional is in the
5262try block of the outer try conditional, its catch clauses are checked, but
5263otherwise only the finally clause is executed. It does not matter for
5264nesting, whether the inner try conditional is directly contained in the outer
5265one, or whether the outer one sources a script or calls a function containing
5266the inner try conditional.
5267
5268When none of the active try conditionals catches an exception, just their
5269finally clauses are executed. Thereafter, the script processing terminates.
5270An error message is displayed in case of an uncaught exception explicitly
5271thrown by a ":throw" command. For uncaught error and interrupt exceptions
5272implicitly raised by Vim, the error message(s) or interrupt message are shown
5273as usual.
5274
5275For examples see |throw-catch|.
5276
5277
5278EXAMINING EXCEPTION HANDLING CODE *except-examine*
5279
5280Exception handling code can get tricky. If you are in doubt what happens, set
5281'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
5282script file. Then you see when an exception is thrown, discarded, caught, or
5283finished. When using a verbosity level of at least 14, things pending in
5284a finally clause are also shown. This information is also given in debug mode
5285(see |debug-scripts|).
5286
5287
5288THROWING AND CATCHING EXCEPTIONS *throw-catch*
5289
5290You can throw any number or string as an exception. Use the |:throw| command
5291and pass the value to be thrown as argument: >
5292 :throw 4711
5293 :throw "string"
5294< *throw-expression*
5295You can also specify an expression argument. The expression is then evaluated
5296first, and the result is thrown: >
5297 :throw 4705 + strlen("string")
5298 :throw strpart("strings", 0, 6)
5299
5300An exception might be thrown during evaluation of the argument of the ":throw"
5301command. Unless it is caught there, the expression evaluation is abandoned.
5302The ":throw" command then does not throw a new exception.
5303 Example: >
5304
5305 :function! Foo(arg)
5306 : try
5307 : throw a:arg
5308 : catch /foo/
5309 : endtry
5310 : return 1
5311 :endfunction
5312 :
5313 :function! Bar()
5314 : echo "in Bar"
5315 : return 4710
5316 :endfunction
5317 :
5318 :throw Foo("arrgh") + Bar()
5319
5320This throws "arrgh", and "in Bar" is not displayed since Bar() is not
5321executed. >
5322 :throw Foo("foo") + Bar()
5323however displays "in Bar" and throws 4711.
5324
5325Any other command that takes an expression as argument might also be
5326abandoned by an (uncaught) exception during the expression evaluation. The
5327exception is then propagated to the caller of the command.
5328 Example: >
5329
5330 :if Foo("arrgh")
5331 : echo "then"
5332 :else
5333 : echo "else"
5334 :endif
5335
5336Here neither of "then" or "else" is displayed.
5337
5338 *catch-order*
5339Exceptions can be caught by a try conditional with one or more |:catch|
5340commands, see |try-conditionals|. The values to be caught by each ":catch"
5341command can be specified as a pattern argument. The subsequent catch clause
5342gets executed when a matching exception is caught.
5343 Example: >
5344
5345 :function! Foo(value)
5346 : try
5347 : throw a:value
5348 : catch /^\d\+$/
5349 : echo "Number thrown"
5350 : catch /.*/
5351 : echo "String thrown"
5352 : endtry
5353 :endfunction
5354 :
5355 :call Foo(0x1267)
5356 :call Foo('string')
5357
5358The first call to Foo() displays "Number thrown", the second "String thrown".
5359An exception is matched against the ":catch" commands in the order they are
5360specified. Only the first match counts. So you should place the more
5361specific ":catch" first. The following order does not make sense: >
5362
5363 : catch /.*/
5364 : echo "String thrown"
5365 : catch /^\d\+$/
5366 : echo "Number thrown"
5367
5368The first ":catch" here matches always, so that the second catch clause is
5369never taken.
5370
5371 *throw-variables*
5372If you catch an exception by a general pattern, you may access the exact value
5373in the variable |v:exception|: >
5374
5375 : catch /^\d\+$/
5376 : echo "Number thrown. Value is" v:exception
5377
5378You may also be interested where an exception was thrown. This is stored in
5379|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
5380exception most recently caught as long it is not finished.
5381 Example: >
5382
5383 :function! Caught()
5384 : if v:exception != ""
5385 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
5386 : else
5387 : echo 'Nothing caught'
5388 : endif
5389 :endfunction
5390 :
5391 :function! Foo()
5392 : try
5393 : try
5394 : try
5395 : throw 4711
5396 : finally
5397 : call Caught()
5398 : endtry
5399 : catch /.*/
5400 : call Caught()
5401 : throw "oops"
5402 : endtry
5403 : catch /.*/
5404 : call Caught()
5405 : finally
5406 : call Caught()
5407 : endtry
5408 :endfunction
5409 :
5410 :call Foo()
5411
5412This displays >
5413
5414 Nothing caught
5415 Caught "4711" in function Foo, line 4
5416 Caught "oops" in function Foo, line 10
5417 Nothing caught
5418
5419A practical example: The following command ":LineNumber" displays the line
5420number in the script or function where it has been used: >
5421
5422 :function! LineNumber()
5423 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
5424 :endfunction
5425 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
5426<
5427 *try-nested*
5428An exception that is not caught by a try conditional can be caught by
5429a surrounding try conditional: >
5430
5431 :try
5432 : try
5433 : throw "foo"
5434 : catch /foobar/
5435 : echo "foobar"
5436 : finally
5437 : echo "inner finally"
5438 : endtry
5439 :catch /foo/
5440 : echo "foo"
5441 :endtry
5442
5443The inner try conditional does not catch the exception, just its finally
5444clause is executed. The exception is then caught by the outer try
5445conditional. The example displays "inner finally" and then "foo".
5446
5447 *throw-from-catch*
5448You can catch an exception and throw a new one to be caught elsewhere from the
5449catch clause: >
5450
5451 :function! Foo()
5452 : throw "foo"
5453 :endfunction
5454 :
5455 :function! Bar()
5456 : try
5457 : call Foo()
5458 : catch /foo/
5459 : echo "Caught foo, throw bar"
5460 : throw "bar"
5461 : endtry
5462 :endfunction
5463 :
5464 :try
5465 : call Bar()
5466 :catch /.*/
5467 : echo "Caught" v:exception
5468 :endtry
5469
5470This displays "Caught foo, throw bar" and then "Caught bar".
5471
5472 *rethrow*
5473There is no real rethrow in the Vim script language, but you may throw
5474"v:exception" instead: >
5475
5476 :function! Bar()
5477 : try
5478 : call Foo()
5479 : catch /.*/
5480 : echo "Rethrow" v:exception
5481 : throw v:exception
5482 : endtry
5483 :endfunction
5484< *try-echoerr*
5485Note that this method cannot be used to "rethrow" Vim error or interrupt
5486exceptions, because it is not possible to fake Vim internal exceptions.
5487Trying so causes an error exception. You should throw your own exception
5488denoting the situation. If you want to cause a Vim error exception containing
5489the original error exception value, you can use the |:echoerr| command: >
5490
5491 :try
5492 : try
5493 : asdf
5494 : catch /.*/
5495 : echoerr v:exception
5496 : endtry
5497 :catch /.*/
5498 : echo v:exception
5499 :endtry
5500
5501This code displays
5502
5503 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
5504
5505
5506CLEANUP CODE *try-finally*
5507
5508Scripts often change global settings and restore them at their end. If the
5509user however interrupts the script by pressing CTRL-C, the settings remain in
5510an inconsistent state. The same may happen to you in the development phase of
5511a script when an error occurs or you explicitly throw an exception without
5512catching it. You can solve these problems by using a try conditional with
5513a finally clause for restoring the settings. Its execution is guaranteed on
5514normal control flow, on error, on an explicit ":throw", and on interrupt.
5515(Note that errors and interrupts from inside the try conditional are converted
5516to exceptions. When not caught, they terminate the script after the finally
5517clause has been executed.)
5518Example: >
5519
5520 :try
5521 : let s:saved_ts = &ts
5522 : set ts=17
5523 :
5524 : " Do the hard work here.
5525 :
5526 :finally
5527 : let &ts = s:saved_ts
5528 : unlet s:saved_ts
5529 :endtry
5530
5531This method should be used locally whenever a function or part of a script
5532changes global settings which need to be restored on failure or normal exit of
5533that function or script part.
5534
5535 *break-finally*
5536Cleanup code works also when the try block or a catch clause is left by
5537a ":continue", ":break", ":return", or ":finish".
5538 Example: >
5539
5540 :let first = 1
5541 :while 1
5542 : try
5543 : if first
5544 : echo "first"
5545 : let first = 0
5546 : continue
5547 : else
5548 : throw "second"
5549 : endif
5550 : catch /.*/
5551 : echo v:exception
5552 : break
5553 : finally
5554 : echo "cleanup"
5555 : endtry
5556 : echo "still in while"
5557 :endwhile
5558 :echo "end"
5559
5560This displays "first", "cleanup", "second", "cleanup", and "end". >
5561
5562 :function! Foo()
5563 : try
5564 : return 4711
5565 : finally
5566 : echo "cleanup\n"
5567 : endtry
5568 : echo "Foo still active"
5569 :endfunction
5570 :
5571 :echo Foo() "returned by Foo"
5572
5573This displays "cleanup" and "4711 returned by Foo". You don't need to add an
5574extra ":return" in the finally clause. (Above all, this would override the
5575return value.)
5576
5577 *except-from-finally*
5578Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
5579a finally clause is possible, but not recommended since it abandons the
5580cleanup actions for the try conditional. But, of course, interrupt and error
5581exceptions might get raised from a finally clause.
5582 Example where an error in the finally clause stops an interrupt from
5583working correctly: >
5584
5585 :try
5586 : try
5587 : echo "Press CTRL-C for interrupt"
5588 : while 1
5589 : endwhile
5590 : finally
5591 : unlet novar
5592 : endtry
5593 :catch /novar/
5594 :endtry
5595 :echo "Script still running"
5596 :sleep 1
5597
5598If you need to put commands that could fail into a finally clause, you should
5599think about catching or ignoring the errors in these commands, see
5600|catch-errors| and |ignore-errors|.
5601
5602
5603CATCHING ERRORS *catch-errors*
5604
5605If you want to catch specific errors, you just have to put the code to be
5606watched in a try block and add a catch clause for the error message. The
5607presence of the try conditional causes all errors to be converted to an
5608exception. No message is displayed and |v:errmsg| is not set then. To find
5609the right pattern for the ":catch" command, you have to know how the format of
5610the error exception is.
5611 Error exceptions have the following format: >
5612
5613 Vim({cmdname}):{errmsg}
5614or >
5615 Vim:{errmsg}
5616
5617{cmdname} is the name of the command that failed; the second form is used when
5618the command name is not known. {errmsg} is the error message usually produced
5619when the error occurs outside try conditionals. It always begins with
5620a capital "E", followed by a two or three-digit error number, a colon, and
5621a space.
5622
5623Examples:
5624
5625The command >
5626 :unlet novar
5627normally produces the error message >
5628 E108: No such variable: "novar"
5629which is converted inside try conditionals to an exception >
5630 Vim(unlet):E108: No such variable: "novar"
5631
5632The command >
5633 :dwim
5634normally produces the error message >
5635 E492: Not an editor command: dwim
5636which is converted inside try conditionals to an exception >
5637 Vim:E492: Not an editor command: dwim
5638
5639You can catch all ":unlet" errors by a >
5640 :catch /^Vim(unlet):/
5641or all errors for misspelled command names by a >
5642 :catch /^Vim:E492:/
5643
5644Some error messages may be produced by different commands: >
5645 :function nofunc
5646and >
5647 :delfunction nofunc
5648both produce the error message >
5649 E128: Function name must start with a capital: nofunc
5650which is converted inside try conditionals to an exception >
5651 Vim(function):E128: Function name must start with a capital: nofunc
5652or >
5653 Vim(delfunction):E128: Function name must start with a capital: nofunc
5654respectively. You can catch the error by its number independently on the
5655command that caused it if you use the following pattern: >
5656 :catch /^Vim(\a\+):E128:/
5657
5658Some commands like >
5659 :let x = novar
5660produce multiple error messages, here: >
5661 E121: Undefined variable: novar
5662 E15: Invalid expression: novar
5663Only the first is used for the exception value, since it is the most specific
5664one (see |except-several-errors|). So you can catch it by >
5665 :catch /^Vim(\a\+):E121:/
5666
5667You can catch all errors related to the name "nofunc" by >
5668 :catch /\<nofunc\>/
5669
5670You can catch all Vim errors in the ":write" and ":read" commands by >
5671 :catch /^Vim(\(write\|read\)):E\d\+:/
5672
5673You can catch all Vim errors by the pattern >
5674 :catch /^Vim\((\a\+)\)\=:E\d\+:/
5675<
5676 *catch-text*
5677NOTE: You should never catch the error message text itself: >
5678 :catch /No such variable/
5679only works in the english locale, but not when the user has selected
5680a different language by the |:language| command. It is however helpful to
5681cite the message text in a comment: >
5682 :catch /^Vim(\a\+):E108:/ " No such variable
5683
5684
5685IGNORING ERRORS *ignore-errors*
5686
5687You can ignore errors in a specific Vim command by catching them locally: >
5688
5689 :try
5690 : write
5691 :catch
5692 :endtry
5693
5694But you are strongly recommended NOT to use this simple form, since it could
5695catch more than you want. With the ":write" command, some autocommands could
5696be executed and cause errors not related to writing, for instance: >
5697
5698 :au BufWritePre * unlet novar
5699
5700There could even be such errors you are not responsible for as a script
5701writer: a user of your script might have defined such autocommands. You would
5702then hide the error from the user.
5703 It is much better to use >
5704
5705 :try
5706 : write
5707 :catch /^Vim(write):/
5708 :endtry
5709
5710which only catches real write errors. So catch only what you'd like to ignore
5711intentionally.
5712
5713For a single command that does not cause execution of autocommands, you could
5714even suppress the conversion of errors to exceptions by the ":silent!"
5715command: >
5716 :silent! nunmap k
5717This works also when a try conditional is active.
5718
5719
5720CATCHING INTERRUPTS *catch-interrupt*
5721
5722When there are active try conditionals, an interrupt (CTRL-C) is converted to
5723the exception "Vim:Interrupt". You can catch it like every exception. The
5724script is not terminated, then.
5725 Example: >
5726
5727 :function! TASK1()
5728 : sleep 10
5729 :endfunction
5730
5731 :function! TASK2()
5732 : sleep 20
5733 :endfunction
5734
5735 :while 1
5736 : let command = input("Type a command: ")
5737 : try
5738 : if command == ""
5739 : continue
5740 : elseif command == "END"
5741 : break
5742 : elseif command == "TASK1"
5743 : call TASK1()
5744 : elseif command == "TASK2"
5745 : call TASK2()
5746 : else
5747 : echo "\nIllegal command:" command
5748 : continue
5749 : endif
5750 : catch /^Vim:Interrupt$/
5751 : echo "\nCommand interrupted"
5752 : " Caught the interrupt. Continue with next prompt.
5753 : endtry
5754 :endwhile
5755
5756You can interrupt a task here by pressing CTRL-C; the script then asks for
5757a new command. If you press CTRL-C at the prompt, the script is terminated.
5758
5759For testing what happens when CTRL-C would be pressed on a specific line in
5760your script, use the debug mode and execute the |>quit| or |>interrupt|
5761command on that line. See |debug-scripts|.
5762
5763
5764CATCHING ALL *catch-all*
5765
5766The commands >
5767
5768 :catch /.*/
5769 :catch //
5770 :catch
5771
5772catch everything, error exceptions, interrupt exceptions and exceptions
5773explicitly thrown by the |:throw| command. This is useful at the top level of
5774a script in order to catch unexpected things.
5775 Example: >
5776
5777 :try
5778 :
5779 : " do the hard work here
5780 :
5781 :catch /MyException/
5782 :
5783 : " handle known problem
5784 :
5785 :catch /^Vim:Interrupt$/
5786 : echo "Script interrupted"
5787 :catch /.*/
5788 : echo "Internal error (" . v:exception . ")"
5789 : echo " - occurred at " . v:throwpoint
5790 :endtry
5791 :" end of script
5792
5793Note: Catching all might catch more things than you want. Thus, you are
5794strongly encouraged to catch only for problems that you can really handle by
5795specifying a pattern argument to the ":catch".
5796 Example: Catching all could make it nearly impossible to interrupt a script
5797by pressing CTRL-C: >
5798
5799 :while 1
5800 : try
5801 : sleep 1
5802 : catch
5803 : endtry
5804 :endwhile
5805
5806
5807EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
5808
5809Exceptions may be used during execution of autocommands. Example: >
5810
5811 :autocmd User x try
5812 :autocmd User x throw "Oops!"
5813 :autocmd User x catch
5814 :autocmd User x echo v:exception
5815 :autocmd User x endtry
5816 :autocmd User x throw "Arrgh!"
5817 :autocmd User x echo "Should not be displayed"
5818 :
5819 :try
5820 : doautocmd User x
5821 :catch
5822 : echo v:exception
5823 :endtry
5824
5825This displays "Oops!" and "Arrgh!".
5826
5827 *except-autocmd-Pre*
5828For some commands, autocommands get executed before the main action of the
5829command takes place. If an exception is thrown and not caught in the sequence
5830of autocommands, the sequence and the command that caused its execution are
5831abandoned and the exception is propagated to the caller of the command.
5832 Example: >
5833
5834 :autocmd BufWritePre * throw "FAIL"
5835 :autocmd BufWritePre * echo "Should not be displayed"
5836 :
5837 :try
5838 : write
5839 :catch
5840 : echo "Caught:" v:exception "from" v:throwpoint
5841 :endtry
5842
5843Here, the ":write" command does not write the file currently being edited (as
5844you can see by checking 'modified'), since the exception from the BufWritePre
5845autocommand abandons the ":write". The exception is then caught and the
5846script displays: >
5847
5848 Caught: FAIL from BufWrite Auto commands for "*"
5849<
5850 *except-autocmd-Post*
5851For some commands, autocommands get executed after the main action of the
5852command has taken place. If this main action fails and the command is inside
5853an active try conditional, the autocommands are skipped and an error exception
5854is thrown that can be caught by the caller of the command.
5855 Example: >
5856
5857 :autocmd BufWritePost * echo "File successfully written!"
5858 :
5859 :try
5860 : write /i/m/p/o/s/s/i/b/l/e
5861 :catch
5862 : echo v:exception
5863 :endtry
5864
5865This just displays: >
5866
5867 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
5868
5869If you really need to execute the autocommands even when the main action
5870fails, trigger the event from the catch clause.
5871 Example: >
5872
5873 :autocmd BufWritePre * set noreadonly
5874 :autocmd BufWritePost * set readonly
5875 :
5876 :try
5877 : write /i/m/p/o/s/s/i/b/l/e
5878 :catch
5879 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
5880 :endtry
5881<
5882You can also use ":silent!": >
5883
5884 :let x = "ok"
5885 :let v:errmsg = ""
5886 :autocmd BufWritePost * if v:errmsg != ""
5887 :autocmd BufWritePost * let x = "after fail"
5888 :autocmd BufWritePost * endif
5889 :try
5890 : silent! write /i/m/p/o/s/s/i/b/l/e
5891 :catch
5892 :endtry
5893 :echo x
5894
5895This displays "after fail".
5896
5897If the main action of the command does not fail, exceptions from the
5898autocommands will be catchable by the caller of the command: >
5899
5900 :autocmd BufWritePost * throw ":-("
5901 :autocmd BufWritePost * echo "Should not be displayed"
5902 :
5903 :try
5904 : write
5905 :catch
5906 : echo v:exception
5907 :endtry
5908<
5909 *except-autocmd-Cmd*
5910For some commands, the normal action can be replaced by a sequence of
5911autocommands. Exceptions from that sequence will be catchable by the caller
5912of the command.
5913 Example: For the ":write" command, the caller cannot know whether the file
5914had actually been written when the exception occurred. You need to tell it in
5915some way. >
5916
5917 :if !exists("cnt")
5918 : let cnt = 0
5919 :
5920 : autocmd BufWriteCmd * if &modified
5921 : autocmd BufWriteCmd * let cnt = cnt + 1
5922 : autocmd BufWriteCmd * if cnt % 3 == 2
5923 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5924 : autocmd BufWriteCmd * endif
5925 : autocmd BufWriteCmd * write | set nomodified
5926 : autocmd BufWriteCmd * if cnt % 3 == 0
5927 : autocmd BufWriteCmd * throw "BufWriteCmdError"
5928 : autocmd BufWriteCmd * endif
5929 : autocmd BufWriteCmd * echo "File successfully written!"
5930 : autocmd BufWriteCmd * endif
5931 :endif
5932 :
5933 :try
5934 : write
5935 :catch /^BufWriteCmdError$/
5936 : if &modified
5937 : echo "Error on writing (file contents not changed)"
5938 : else
5939 : echo "Error after writing"
5940 : endif
5941 :catch /^Vim(write):/
5942 : echo "Error on writing"
5943 :endtry
5944
5945When this script is sourced several times after making changes, it displays
5946first >
5947 File successfully written!
5948then >
5949 Error on writing (file contents not changed)
5950then >
5951 Error after writing
5952etc.
5953
5954 *except-autocmd-ill*
5955You cannot spread a try conditional over autocommands for different events.
5956The following code is ill-formed: >
5957
5958 :autocmd BufWritePre * try
5959 :
5960 :autocmd BufWritePost * catch
5961 :autocmd BufWritePost * echo v:exception
5962 :autocmd BufWritePost * endtry
5963 :
5964 :write
5965
5966
5967EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
5968
5969Some programming languages allow to use hierarchies of exception classes or to
5970pass additional information with the object of an exception class. You can do
5971similar things in Vim.
5972 In order to throw an exception from a hierarchy, just throw the complete
5973class name with the components separated by a colon, for instance throw the
5974string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
5975 When you want to pass additional information with your exception class, add
5976it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
5977for an error when writing "myfile".
5978 With the appropriate patterns in the ":catch" command, you can catch for
5979base classes or derived classes of your hierarchy. Additional information in
5980parentheses can be cut out from |v:exception| with the ":substitute" command.
5981 Example: >
5982
5983 :function! CheckRange(a, func)
5984 : if a:a < 0
5985 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
5986 : endif
5987 :endfunction
5988 :
5989 :function! Add(a, b)
5990 : call CheckRange(a:a, "Add")
5991 : call CheckRange(a:b, "Add")
5992 : let c = a:a + a:b
5993 : if c < 0
5994 : throw "EXCEPT:MATHERR:OVERFLOW"
5995 : endif
5996 : return c
5997 :endfunction
5998 :
5999 :function! Div(a, b)
6000 : call CheckRange(a:a, "Div")
6001 : call CheckRange(a:b, "Div")
6002 : if (a:b == 0)
6003 : throw "EXCEPT:MATHERR:ZERODIV"
6004 : endif
6005 : return a:a / a:b
6006 :endfunction
6007 :
6008 :function! Write(file)
6009 : try
6010 : execute "write" a:file
6011 : catch /^Vim(write):/
6012 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
6013 : endtry
6014 :endfunction
6015 :
6016 :try
6017 :
6018 : " something with arithmetics and I/O
6019 :
6020 :catch /^EXCEPT:MATHERR:RANGE/
6021 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
6022 : echo "Range error in" function
6023 :
6024 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
6025 : echo "Math error"
6026 :
6027 :catch /^EXCEPT:IO/
6028 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
6029 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
6030 : if file !~ '^/'
6031 : let file = dir . "/" . file
6032 : endif
6033 : echo 'I/O error for "' . file . '"'
6034 :
6035 :catch /^EXCEPT/
6036 : echo "Unspecified error"
6037 :
6038 :endtry
6039
6040The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
6041a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
6042exceptions with the "Vim" prefix; they are reserved for Vim.
6043 Vim error exceptions are parameterized with the name of the command that
6044failed, if known. See |catch-errors|.
6045
6046
6047PECULIARITIES
6048 *except-compat*
6049The exception handling concept requires that the command sequence causing the
6050exception is aborted immediately and control is transferred to finally clauses
6051and/or a catch clause.
6052
6053In the Vim script language there are cases where scripts and functions
6054continue after an error: in functions without the "abort" flag or in a command
6055after ":silent!", control flow goes to the following line, and outside
6056functions, control flow goes to the line following the outermost ":endwhile"
6057or ":endif". On the other hand, errors should be catchable as exceptions
6058(thus, requiring the immediate abortion).
6059
6060This problem has been solved by converting errors to exceptions and using
6061immediate abortion (if not suppressed by ":silent!") only when a try
6062conditional is active. This is no restriction since an (error) exception can
6063be caught only from an active try conditional. If you want an immediate
6064termination without catching the error, just use a try conditional without
6065catch clause. (You can cause cleanup code being executed before termination
6066by specifying a finally clause.)
6067
6068When no try conditional is active, the usual abortion and continuation
6069behavior is used instead of immediate abortion. This ensures compatibility of
6070scripts written for Vim 6.1 and earlier.
6071
6072However, when sourcing an existing script that does not use exception handling
6073commands (or when calling one of its functions) from inside an active try
6074conditional of a new script, you might change the control flow of the existing
6075script on error. You get the immediate abortion on error and can catch the
6076error in the new script. If however the sourced script suppresses error
6077messages by using the ":silent!" command (checking for errors by testing
6078|v:errmsg| if appropriate), its execution path is not changed. The error is
6079not converted to an exception. (See |:silent|.) So the only remaining cause
6080where this happens is for scripts that don't care about errors and produce
6081error messages. You probably won't want to use such code from your new
6082scripts.
6083
6084 *except-syntax-err*
6085Syntax errors in the exception handling commands are never caught by any of
6086the ":catch" commands of the try conditional they belong to. Its finally
6087clauses, however, is executed.
6088 Example: >
6089
6090 :try
6091 : try
6092 : throw 4711
6093 : catch /\(/
6094 : echo "in catch with syntax error"
6095 : catch
6096 : echo "inner catch-all"
6097 : finally
6098 : echo "inner finally"
6099 : endtry
6100 :catch
6101 : echo 'outer catch-all caught "' . v:exception . '"'
6102 : finally
6103 : echo "outer finally"
6104 :endtry
6105
6106This displays: >
6107 inner finally
6108 outer catch-all caught "Vim(catch):E54: Unmatched \("
6109 outer finally
6110The original exception is discarded and an error exception is raised, instead.
6111
6112 *except-single-line*
6113The ":try", ":catch", ":finally", and ":endtry" commands can be put on
6114a single line, but then syntax errors may make it difficult to recognize the
6115"catch" line, thus you better avoid this.
6116 Example: >
6117 :try | unlet! foo # | catch | endtry
6118raises an error exception for the trailing characters after the ":unlet!"
6119argument, but does not see the ":catch" and ":endtry" commands, so that the
6120error exception is discarded and the "E488: Trailing characters" message gets
6121displayed.
6122
6123 *except-several-errors*
6124When several errors appear in a single command, the first error message is
6125usually the most specific one and therefor converted to the error exception.
6126 Example: >
6127 echo novar
6128causes >
6129 E121: Undefined variable: novar
6130 E15: Invalid expression: novar
6131The value of the error exception inside try conditionals is: >
6132 Vim(echo):E121: Undefined variable: novar
6133< *except-syntax-error*
6134But when a syntax error is detected after a normal error in the same command,
6135the syntax error is used for the exception being thrown.
6136 Example: >
6137 unlet novar #
6138causes >
6139 E108: No such variable: "novar"
6140 E488: Trailing characters
6141The value of the error exception inside try conditionals is: >
6142 Vim(unlet):E488: Trailing characters
6143This is done because the syntax error might change the execution path in a way
6144not intended by the user. Example: >
6145 try
6146 try | unlet novar # | catch | echo v:exception | endtry
6147 catch /.*/
6148 echo "outer catch:" v:exception
6149 endtry
6150This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
6151a "E600: Missing :endtry" error message is given, see |except-single-line|.
6152
6153==============================================================================
61549. Examples *eval-examples*
6155
6156Printing in Hex ~
6157>
6158 :" The function Nr2Hex() returns the Hex string of a number.
6159 :func Nr2Hex(nr)
6160 : let n = a:nr
6161 : let r = ""
6162 : while n
6163 : let r = '0123456789ABCDEF'[n % 16] . r
6164 : let n = n / 16
6165 : endwhile
6166 : return r
6167 :endfunc
6168
6169 :" The function String2Hex() converts each character in a string to a two
6170 :" character Hex string.
6171 :func String2Hex(str)
6172 : let out = ''
6173 : let ix = 0
6174 : while ix < strlen(a:str)
6175 : let out = out . Nr2Hex(char2nr(a:str[ix]))
6176 : let ix = ix + 1
6177 : endwhile
6178 : return out
6179 :endfunc
6180
6181Example of its use: >
6182 :echo Nr2Hex(32)
6183result: "20" >
6184 :echo String2Hex("32")
6185result: "3332"
6186
6187
6188Sorting lines (by Robert Webb) ~
6189
6190Here is a Vim script to sort lines. Highlight the lines in Vim and type
6191":Sort". This doesn't call any external programs so it'll work on any
6192platform. The function Sort() actually takes the name of a comparison
6193function as its argument, like qsort() does in C. So you could supply it
6194with different comparison functions in order to sort according to date etc.
6195>
6196 :" Function for use with Sort(), to compare two strings.
6197 :func! Strcmp(str1, str2)
6198 : if (a:str1 < a:str2)
6199 : return -1
6200 : elseif (a:str1 > a:str2)
6201 : return 1
6202 : else
6203 : return 0
6204 : endif
6205 :endfunction
6206
6207 :" Sort lines. SortR() is called recursively.
6208 :func! SortR(start, end, cmp)
6209 : if (a:start >= a:end)
6210 : return
6211 : endif
6212 : let partition = a:start - 1
6213 : let middle = partition
6214 : let partStr = getline((a:start + a:end) / 2)
6215 : let i = a:start
6216 : while (i <= a:end)
6217 : let str = getline(i)
6218 : exec "let result = " . a:cmp . "(str, partStr)"
6219 : if (result <= 0)
6220 : " Need to put it before the partition. Swap lines i and partition.
6221 : let partition = partition + 1
6222 : if (result == 0)
6223 : let middle = partition
6224 : endif
6225 : if (i != partition)
6226 : let str2 = getline(partition)
6227 : call setline(i, str2)
6228 : call setline(partition, str)
6229 : endif
6230 : endif
6231 : let i = i + 1
6232 : endwhile
6233
6234 : " Now we have a pointer to the "middle" element, as far as partitioning
6235 : " goes, which could be anywhere before the partition. Make sure it is at
6236 : " the end of the partition.
6237 : if (middle != partition)
6238 : let str = getline(middle)
6239 : let str2 = getline(partition)
6240 : call setline(middle, str2)
6241 : call setline(partition, str)
6242 : endif
6243 : call SortR(a:start, partition - 1, a:cmp)
6244 : call SortR(partition + 1, a:end, a:cmp)
6245 :endfunc
6246
6247 :" To Sort a range of lines, pass the range to Sort() along with the name of a
6248 :" function that will compare two lines.
6249 :func! Sort(cmp) range
6250 : call SortR(a:firstline, a:lastline, a:cmp)
6251 :endfunc
6252
6253 :" :Sort takes a range of lines and sorts them.
6254 :command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
6255<
6256 *sscanf*
6257There is no sscanf() function in Vim. If you need to extract parts from a
6258line, you can use matchstr() and substitute() to do it. This example shows
6259how to get the file name, line number and column number out of a line like
6260"foobar.txt, 123, 45". >
6261 :" Set up the match bit
6262 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
6263 :"get the part matching the whole expression
6264 :let l = matchstr(line, mx)
6265 :"get each item out of the match
6266 :let file = substitute(l, mx, '\1', '')
6267 :let lnum = substitute(l, mx, '\2', '')
6268 :let col = substitute(l, mx, '\3', '')
6269
6270The input is in the variable "line", the results in the variables "file",
6271"lnum" and "col". (idea from Michael Geddes)
6272
6273==============================================================================
627410. No +eval feature *no-eval-feature*
6275
6276When the |+eval| feature was disabled at compile time, none of the expression
6277evaluation commands are available. To prevent this from causing Vim scripts
6278to generate all kinds of errors, the ":if" and ":endif" commands are still
6279recognized, though the argument of the ":if" and everything between the ":if"
6280and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
6281only if the commands are at the start of the line. The ":else" command is not
6282recognized.
6283
6284Example of how to avoid executing commands when the |+eval| feature is
6285missing: >
6286
6287 :if 1
6288 : echo "Expression evaluation is compiled in"
6289 :else
6290 : echo "You will _never_ see this message"
6291 :endif
6292
6293==============================================================================
629411. The sandbox *eval-sandbox* *sandbox* *E48*
6295
6296The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext'
6297options are evaluated in a sandbox. This means that you are protected from
6298these expressions having nasty side effects. This gives some safety for when
6299these options are set from a modeline. It is also used when the command from
6300a tags file is executed.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006301The sandbox is also used for the |:sandbox| command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302
6303These items are not allowed in the sandbox:
6304 - changing the buffer text
6305 - defining or changing mapping, autocommands, functions, user commands
6306 - setting certain options (see |option-summary|)
6307 - executing a shell command
6308 - reading or writing a file
6309 - jumping to another buffer or editing a file
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00006310This is not guaranteed 100% secure, but it should block most attacks.
6311
6312 *:san* *:sandbox*
6313:sandbox {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
6314 option that may have been set from a modeline, e.g.
6315 'foldexpr'.
6316
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317
6318 vim:tw=78:ts=8:ft=help:norl: