blob: a204735ec0e9c81e63ef69d2ad3382c36027497d [file] [log] [blame]
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001*eval.txt* For Vim version 8.2. Last change: 2022 Jan 21
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
Bram Moolenaar446cb832008-06-24 21:56:24 +00004 VIM REFERENCE MANUAL by Bram Moolenaar
Bram Moolenaar071d4272004-06-13 20:20:40 +00005
6
7Expression evaluation *expression* *expr* *E15* *eval*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00008 *E1002*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009Using 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 Moolenaar58b85342016-08-14 19:54:54 +020012done, 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 Moolenaar1cae5a02021-12-27 21:28:34 +000015This file is mainly about the backwards compatible (legacy) Vim script. For
Bram Moolenaar2f0936c2022-01-08 21:51:59 +000016specifics of Vim9 script, which can execute much faster, supports type
17checking and much more, see |vim9.txt|. Where the syntax or semantics differ
18a remark is given.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010019
Bram Moolenaar13065c42005-01-08 16:08:21 +0000201. Variables |variables|
21 1.1 Variable types
Bram Moolenaar9588a0f2005-01-08 21:45:39 +000022 1.2 Function references |Funcref|
Bram Moolenaar7c626922005-02-07 22:01:03 +000023 1.3 Lists |Lists|
Bram Moolenaard8b02732005-01-14 21:48:43 +000024 1.4 Dictionaries |Dictionaries|
Bram Moolenaard8968242019-01-15 22:51:57 +010025 1.5 Blobs |Blobs|
26 1.6 More about variables |more-variables|
Bram Moolenaar13065c42005-01-08 16:08:21 +0000272. Expression syntax |expression-syntax|
283. Internal variable |internal-variables|
294. Builtin Functions |functions|
305. Defining functions |user-functions|
316. Curly braces names |curly-braces-names|
327. Commands |expression-commands|
338. Exception handling |exception-handling|
349. Examples |eval-examples|
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02003510. Vim script version |vimscript-version|
3611. No +eval feature |no-eval-feature|
3712. The sandbox |eval-sandbox|
3813. Textlock |textlock|
Bram Moolenaared997ad2019-07-21 16:42:00 +020039
40Testing support is documented in |testing.txt|.
41Profiling is documented at |profiling|.
Bram Moolenaar071d4272004-06-13 20:20:40 +000042
Bram Moolenaar071d4272004-06-13 20:20:40 +000043==============================================================================
441. Variables *variables*
45
Bram Moolenaar13065c42005-01-08 16:08:21 +0000461.1 Variable types ~
Bram Moolenaarbf821bc2019-01-23 21:15:02 +010047 *E712* *E896* *E897* *E899*
Bram Moolenaar06fe74a2019-08-31 16:20:32 +020048There are ten types of variables:
Bram Moolenaar071d4272004-06-13 20:20:40 +000049
Bram Moolenaar664f3cf2019-12-07 16:03:51 +010050 *Number* *Integer*
51Number A 32 or 64 bit signed number. |expr-number|
Bram Moolenaarf9706e92020-02-22 14:27:04 +010052 The number of bits is available in |v:numbersize|.
Bram Moolenaar6f02b002021-01-10 20:22:54 +010053 Examples: -123 0x10 0177 0o177 0b1011
Bram Moolenaard8b02732005-01-14 21:48:43 +000054
Bram Moolenaar446cb832008-06-24 21:56:24 +000055Float A floating point number. |floating-point-format| *Float*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +000056 {only when compiled with the |+float| feature} *E1076*
Bram Moolenaar446cb832008-06-24 21:56:24 +000057 Examples: 123.456 1.15e-6 -1.1e3
58
Bram Moolenaard8b02732005-01-14 21:48:43 +000059String A NUL terminated string of 8-bit unsigned characters (bytes).
Bram Moolenaar446cb832008-06-24 21:56:24 +000060 |expr-string| Examples: "ab\txx\"--" 'x-z''a,c'
Bram Moolenaard8b02732005-01-14 21:48:43 +000061
Bram Moolenaard8968242019-01-15 22:51:57 +010062List An ordered sequence of items, see |List| for details.
Bram Moolenaard8b02732005-01-14 21:48:43 +000063 Example: [1, 2, ['a', 'b']]
Bram Moolenaar071d4272004-06-13 20:20:40 +000064
Bram Moolenaar39a58ca2005-06-27 22:42:44 +000065Dictionary An associative, unordered array: Each entry has a key and a
66 value. |Dictionary|
Bram Moolenaard5abb4c2019-07-13 22:46:10 +020067 Examples:
68 {'blue': "#0000ff", 'red': "#ff0000"}
Bram Moolenaar4c6d9042019-07-16 22:04:02 +020069 #{blue: "#0000ff", red: "#ff0000"}
Bram Moolenaar39a58ca2005-06-27 22:42:44 +000070
Bram Moolenaar835dc632016-02-07 14:27:38 +010071Funcref A reference to a function |Funcref|.
72 Example: function("strlen")
Bram Moolenaar1d429612016-05-24 15:44:17 +020073 It can be bound to a dictionary and arguments, it then works
74 like a Partial.
75 Example: function("Callback", [arg], myDict)
Bram Moolenaar835dc632016-02-07 14:27:38 +010076
Bram Moolenaar02e83b42016-02-21 20:10:26 +010077Special |v:false|, |v:true|, |v:none| and |v:null|. *Special*
Bram Moolenaar835dc632016-02-07 14:27:38 +010078
Bram Moolenaarebf7dfa2016-04-14 12:46:51 +020079Job Used for a job, see |job_start()|. *Job* *Jobs*
Bram Moolenaar38a55632016-02-15 22:07:32 +010080
Bram Moolenaarebf7dfa2016-04-14 12:46:51 +020081Channel Used for a channel, see |ch_open()|. *Channel* *Channels*
Bram Moolenaar835dc632016-02-07 14:27:38 +010082
Bram Moolenaard8968242019-01-15 22:51:57 +010083Blob Binary Large Object. Stores any sequence of bytes. See |Blob|
84 for details
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +010085 Example: 0zFF00ED015DAF
86 0z is an empty Blob.
87
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +000088The Number and String types are converted automatically, depending on how they
89are used.
Bram Moolenaar071d4272004-06-13 20:20:40 +000090
91Conversion from a Number to a String is by making the ASCII representation of
Bram Moolenaar24ea3ba2010-09-19 19:01:21 +020092the Number. Examples:
93 Number 123 --> String "123" ~
94 Number 0 --> String "0" ~
95 Number -1 --> String "-1" ~
Bram Moolenaar00a927d2010-05-14 23:24:24 +020096 *octal*
Bram Moolenaard43906d2020-07-20 21:31:32 +020097Conversion from a String to a Number only happens in legacy Vim script, not in
98Vim9 script. It is done by converting the first digits to a number.
99Hexadecimal "0xf9", Octal "017" or "0o17", and Binary "0b10"
Bram Moolenaar6f02b002021-01-10 20:22:54 +0100100numbers are recognized
Bram Moolenaar5da36052021-12-27 15:39:57 +0000101NOTE: when using |Vim9| script or |scriptversion-4| octal with a leading "0"
102is not recognized. The 0o notation requires patch 8.2.0886.
Bram Moolenaar6f02b002021-01-10 20:22:54 +0100103If the String doesn't start with digits, the result is zero.
Bram Moolenaarfa735342016-01-03 22:14:44 +0100104Examples:
Bram Moolenaar24ea3ba2010-09-19 19:01:21 +0200105 String "456" --> Number 456 ~
106 String "6bar" --> Number 6 ~
107 String "foo" --> Number 0 ~
108 String "0xf1" --> Number 241 ~
109 String "0100" --> Number 64 ~
Bram Moolenaarc17e66c2020-06-02 21:38:22 +0200110 String "0o100" --> Number 64 ~
Bram Moolenaarfa735342016-01-03 22:14:44 +0100111 String "0b101" --> Number 5 ~
Bram Moolenaar24ea3ba2010-09-19 19:01:21 +0200112 String "-8" --> Number -8 ~
113 String "+8" --> Number 0 ~
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114
115To force conversion from String to Number, add zero to it: >
116 :echo "0100" + 0
Bram Moolenaar97b2ad32006-03-18 21:40:56 +0000117< 64 ~
118
119To avoid a leading zero to cause octal conversion, or for using a different
120base, use |str2nr()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121
Bram Moolenaard09091d2019-01-17 16:07:22 +0100122 *TRUE* *FALSE* *Boolean*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000123For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200124You can also use |v:false| and |v:true|, in Vim9 script |false| and |true|.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200125When TRUE is returned from a function it is the Number one, FALSE is the
126number zero.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127
Bram Moolenaare381d3d2016-07-07 14:50:41 +0200128Note that in the command: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129 :if "foo"
Bram Moolenaare381d3d2016-07-07 14:50:41 +0200130 :" NOT executed
131"foo" is converted to 0, which means FALSE. If the string starts with a
132non-zero number it means TRUE: >
133 :if "8foo"
134 :" executed
135To test for a non-empty string, use empty(): >
Bram Moolenaar3a0d8092012-10-21 03:02:54 +0200136 :if !empty("foo")
Bram Moolenaar92f26c22020-10-03 20:17:30 +0200137
138< *falsy* *truthy*
139An expression can be used as a condition, ignoring the type and only using
140whether the value is "sort of true" or "sort of false". Falsy is:
141 the number zero
142 empty string, blob, list or dictionary
143Other values are truthy. Examples:
144 0 falsy
145 1 truthy
146 -1 truthy
147 0.0 falsy
148 0.1 truthy
149 '' falsy
150 'x' truthy
151 [] falsy
152 [0] truthy
153 {} falsy
154 #{x: 1} truthy
155 0z falsy
156 0z00 truthy
157
Bram Moolenaare381d3d2016-07-07 14:50:41 +0200158 *non-zero-arg*
159Function arguments often behave slightly different from |TRUE|: If the
160argument is present and it evaluates to a non-zero Number, |v:true| or a
Bram Moolenaar64d8e252016-09-06 22:12:34 +0200161non-empty String, then the value is considered to be TRUE.
Bram Moolenaar01164a62017-11-02 22:58:42 +0100162Note that " " and "0" are also non-empty strings, thus considered to be TRUE.
163A List, Dictionary or Float is not a Number or String, thus evaluate to FALSE.
Bram Moolenaare381d3d2016-07-07 14:50:41 +0200164
Bram Moolenaar2f0936c2022-01-08 21:51:59 +0000165 *E611* *E745* *E728* *E703* *E729* *E730* *E731* *E908* *E910*
166 *E913* *E974* *E975* *E976*
Bram Moolenaard09091d2019-01-17 16:07:22 +0100167|List|, |Dictionary|, |Funcref|, |Job|, |Channel| and |Blob| types are not
168automatically converted.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000169
Bram Moolenaar446cb832008-06-24 21:56:24 +0000170 *E805* *E806* *E808*
Bram Moolenaar58b85342016-08-14 19:54:54 +0200171When mixing Number and Float the Number is converted to Float. Otherwise
Bram Moolenaar446cb832008-06-24 21:56:24 +0000172there is no automatic conversion of Float. You can use str2float() for String
173to Float, printf() for Float to String and float2nr() for Float to Number.
174
Bram Moolenaar2f0936c2022-01-08 21:51:59 +0000175 *E362* *E891* *E892* *E893* *E894* *E907* *E911* *E914*
Bram Moolenaar13d5aee2016-01-21 23:36:05 +0100176When expecting a Float a Number can also be used, but nothing else.
177
Bram Moolenaarf6f32c32016-03-12 19:03:59 +0100178 *no-type-checking*
179You will not get an error if you try to change the type of a variable.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000180
Bram Moolenaar13065c42005-01-08 16:08:21 +0000181
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001821.2 Function references ~
Bram Moolenaare46a4402020-06-30 20:38:27 +0200183 *Funcref* *E695* *E718*
Bram Moolenaar58b85342016-08-14 19:54:54 +0200184A Funcref variable is obtained with the |function()| function, the |funcref()|
185function or created with the lambda expression |expr-lambda|. It can be used
186in an expression in the place of a function name, before the parenthesis
187around the arguments, to invoke the function it refers to. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000188
189 :let Fn = function("MyFunc")
190 :echo Fn()
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000191< *E704* *E705* *E707*
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000192A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You
Bram Moolenaar7cba6c02013-09-05 22:13:31 +0200193can use "g:" but the following name must still start with a capital. You
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000194cannot have both a Funcref variable and a function with the same name.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000195
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000196A special case is defining a function and directly assigning its Funcref to a
197Dictionary entry. Example: >
198 :function dict.init() dict
199 : let self.val = 0
200 :endfunction
201
202The key of the Dictionary can start with a lower case letter. The actual
203function name is not used here. Also see |numbered-function|.
204
205A Funcref can also be used with the |:call| command: >
206 :call Fn()
207 :call dict.init()
Bram Moolenaar13065c42005-01-08 16:08:21 +0000208
209The name of the referenced function can be obtained with |string()|. >
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000210 :let func = string(Fn)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000211
212You can use |call()| to invoke a Funcref and use a list variable for the
213arguments: >
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000214 :let r = call(Fn, mylist)
Bram Moolenaar1d429612016-05-24 15:44:17 +0200215<
216 *Partial*
217A Funcref optionally binds a Dictionary and/or arguments. This is also called
218a Partial. This is created by passing the Dictionary and/or arguments to
Bram Moolenaar58b85342016-08-14 19:54:54 +0200219function() or funcref(). When calling the function the Dictionary and/or
220arguments will be passed to the function. Example: >
Bram Moolenaar1d429612016-05-24 15:44:17 +0200221
222 let Cb = function('Callback', ['foo'], myDict)
Bram Moolenaarba3ff532018-11-04 14:45:49 +0100223 call Cb('bar')
Bram Moolenaar1d429612016-05-24 15:44:17 +0200224
225This will invoke the function as if using: >
Bram Moolenaarba3ff532018-11-04 14:45:49 +0100226 call myDict.Callback('foo', 'bar')
Bram Moolenaar1d429612016-05-24 15:44:17 +0200227
228This is very useful when passing a function around, e.g. in the arguments of
229|ch_open()|.
230
231Note that binding a function to a Dictionary also happens when the function is
232a member of the Dictionary: >
233
234 let myDict.myFunction = MyFunction
235 call myDict.myFunction()
236
237Here MyFunction() will get myDict passed as "self". This happens when the
238"myFunction" member is accessed. When making assigning "myFunction" to
239otherDict and calling it, it will be bound to otherDict: >
240
241 let otherDict.myFunction = myDict.myFunction
242 call otherDict.myFunction()
243
244Now "self" will be "otherDict". But when the dictionary was bound explicitly
245this won't happen: >
246
247 let myDict.myFunction = function(MyFunction, myDict)
248 let otherDict.myFunction = myDict.myFunction
249 call otherDict.myFunction()
250
Bram Moolenaard823fa92016-08-12 16:29:27 +0200251Here "self" will be "myDict", because it was bound explicitly.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000252
253
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00002541.3 Lists ~
Bram Moolenaar7e38ea22014-04-05 22:55:53 +0200255 *list* *List* *Lists* *E686*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000256A List is an ordered sequence of items. An item can be of any type. Items
Bram Moolenaar58b85342016-08-14 19:54:54 +0200257can be accessed by their index number. Items can be added and removed at any
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000258position in the sequence.
259
Bram Moolenaar13065c42005-01-08 16:08:21 +0000260
261List creation ~
262 *E696* *E697*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000263A List is created with a comma separated list of items in square brackets.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000264Examples: >
265 :let mylist = [1, two, 3, "four"]
266 :let emptylist = []
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000267
Bram Moolenaar58b85342016-08-14 19:54:54 +0200268An item can be any expression. Using a List for an item creates a
Bram Moolenaarf9393ef2006-04-24 19:47:27 +0000269List of Lists: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000270 :let nestlist = [[11, 12], [21, 22], [31, 32]]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000271
272An extra comma after the last item is ignored.
273
Bram Moolenaar13065c42005-01-08 16:08:21 +0000274
275List index ~
276 *list-index* *E684*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000277An item in the List can be accessed by putting the index in square brackets
Bram Moolenaar13065c42005-01-08 16:08:21 +0000278after the List. Indexes are zero-based, thus the first item has index zero. >
279 :let item = mylist[0] " get the first item: 1
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000280 :let item = mylist[2] " get the third item: 3
Bram Moolenaar13065c42005-01-08 16:08:21 +0000281
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000282When the resulting item is a list this can be repeated: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000283 :let item = nestlist[0][1] " get the first list, second item: 12
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000284<
Bram Moolenaar13065c42005-01-08 16:08:21 +0000285A negative index is counted from the end. Index -1 refers to the last item in
286the List, -2 to the last but one item, etc. >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000287 :let last = mylist[-1] " get the last item: "four"
288
Bram Moolenaar13065c42005-01-08 16:08:21 +0000289To avoid an error for an invalid index use the |get()| function. When an item
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000290is not available it returns zero or the default value you specify: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000291 :echo get(mylist, idx)
292 :echo get(mylist, idx, "NONE")
293
294
295List concatenation ~
Bram Moolenaar34453202021-01-31 13:08:38 +0100296 *list-concatenation*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000297Two lists can be concatenated with the "+" operator: >
298 :let longlist = mylist + [5, 6]
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000299 :let mylist += [7, 8]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000300
Bram Moolenaar34453202021-01-31 13:08:38 +0100301To prepend or append an item, turn the item into a list by putting [] around
302it. To change a list in-place, refer to |list-modification| below.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000303
304
305Sublist ~
Bram Moolenaarbc8801c2016-08-02 21:04:33 +0200306 *sublist*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000307A part of the List can be obtained by specifying the first and last index,
308separated by a colon in square brackets: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000309 :let shortlist = mylist[2:-1] " get List [3, "four"]
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000310
311Omitting the first index is similar to zero. Omitting the last index is
Bram Moolenaaref2f6562007-05-06 13:32:59 +0000312similar to -1. >
Bram Moolenaar540d6e32005-01-09 21:20:18 +0000313 :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
314 :let shortlist = mylist[2:2] " List with one item: [3]
315 :let otherlist = mylist[:] " make a copy of the List
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000316
Bram Moolenaar6601b622021-01-13 21:47:15 +0100317Notice that the last index is inclusive. If you prefer using an exclusive
318index use the |slice()| method.
319
Bram Moolenaarf9393ef2006-04-24 19:47:27 +0000320If the first index is beyond the last item of the List or the second item is
321before the first item, the result is an empty list. There is no error
322message.
323
324If the second index is equal to or greater than the length of the list the
325length minus one is used: >
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +0000326 :let mylist = [0, 1, 2, 3]
327 :echo mylist[2:8] " result: [2, 3]
328
Bram Moolenaara7fc0102005-05-18 22:17:12 +0000329NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for
Bram Moolenaar58b85342016-08-14 19:54:54 +0200330using a single letter variable before the ":". Insert a space when needed:
Bram Moolenaara7fc0102005-05-18 22:17:12 +0000331mylist[s : e].
332
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +0000333
Bram Moolenaar13065c42005-01-08 16:08:21 +0000334List identity ~
Bram Moolenaard8b02732005-01-14 21:48:43 +0000335 *list-identity*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000336When variable "aa" is a list and you assign it to another variable "bb", both
337variables refer to the same list. Thus changing the list "aa" will also
338change "bb": >
339 :let aa = [1, 2, 3]
340 :let bb = aa
341 :call add(aa, 4)
342 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000343< [1, 2, 3, 4]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000344
345Making a copy of a list is done with the |copy()| function. Using [:] also
346works, as explained above. This creates a shallow copy of the list: Changing
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000347a list item in the list will also change the item in the copied list: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000348 :let aa = [[1, 'a'], 2, 3]
349 :let bb = copy(aa)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000350 :call add(aa, 4)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000351 :let aa[0][1] = 'aaa'
352 :echo aa
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000353< [[1, aaa], 2, 3, 4] >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000354 :echo bb
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000355< [[1, aaa], 2, 3]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000356
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000357To make a completely independent list use |deepcopy()|. This also makes a
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000358copy of the values in the list, recursively. Up to a hundred levels deep.
Bram Moolenaar13065c42005-01-08 16:08:21 +0000359
360The operator "is" can be used to check if two variables refer to the same
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000361List. "isnot" does the opposite. In contrast "==" compares if two lists have
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000362the same value. >
363 :let alist = [1, 2, 3]
364 :let blist = [1, 2, 3]
365 :echo alist is blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000366< 0 >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000367 :echo alist == blist
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000368< 1
Bram Moolenaar13065c42005-01-08 16:08:21 +0000369
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000370Note about comparing lists: Two lists are considered equal if they have the
371same length and all items compare equal, as with using "==". There is one
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000372exception: When comparing a number with a string they are considered
373different. There is no automatic type conversion, as with using "==" on
374variables. Example: >
375 echo 4 == "4"
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000376< 1 >
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000377 echo [4] == ["4"]
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000378< 0
379
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000380Thus comparing Lists is more strict than comparing numbers and strings. You
Bram Moolenaar446cb832008-06-24 21:56:24 +0000381can compare simple values this way too by putting them in a list: >
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000382
383 :let a = 5
384 :let b = "5"
Bram Moolenaar446cb832008-06-24 21:56:24 +0000385 :echo a == b
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000386< 1 >
Bram Moolenaar446cb832008-06-24 21:56:24 +0000387 :echo [a] == [b]
Bram Moolenaar7d1f5db2005-07-03 21:39:27 +0000388< 0
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000389
Bram Moolenaar13065c42005-01-08 16:08:21 +0000390
391List unpack ~
392
393To unpack the items in a list to individual variables, put the variables in
394square brackets, like list items: >
395 :let [var1, var2] = mylist
396
397When the number of variables does not match the number of items in the list
398this produces an error. To handle any extra items from the list append ";"
399and a variable name: >
400 :let [var1, var2; rest] = mylist
401
402This works like: >
403 :let var1 = mylist[0]
404 :let var2 = mylist[1]
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000405 :let rest = mylist[2:]
Bram Moolenaar13065c42005-01-08 16:08:21 +0000406
407Except that there is no error if there are only two items. "rest" will be an
408empty list then.
409
410
411List modification ~
412 *list-modification*
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000413To change a specific item of a list use |:let| this way: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000414 :let list[4] = "four"
415 :let listlist[0][3] = item
416
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000417To change part of a list you can specify the first and last item to be
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000418modified. The value must at least have the number of items in the range: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000419 :let list[3:5] = [3, 4, 5]
420
Bram Moolenaar13065c42005-01-08 16:08:21 +0000421Adding and removing items from a list is done with functions. Here are a few
422examples: >
423 :call insert(list, 'a') " prepend item 'a'
424 :call insert(list, 'a', 3) " insert item 'a' before list[3]
425 :call add(list, "new") " append String item
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000426 :call add(list, [1, 2]) " append a List as one new item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000427 :call extend(list, [1, 2]) " extend the list with two more items
428 :let i = remove(list, 3) " remove item 3
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000429 :unlet list[3] " idem
Bram Moolenaar13065c42005-01-08 16:08:21 +0000430 :let l = remove(list, 3, -1) " remove items 3 to last item
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000431 :unlet list[3 : ] " idem
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000432 :call filter(list, 'v:val !~ "x"') " remove items with an 'x'
Bram Moolenaar13065c42005-01-08 16:08:21 +0000433
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000434Changing the order of items in a list: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000435 :call sort(list) " sort a list alphabetically
436 :call reverse(list) " reverse the order of items
Bram Moolenaar327aa022014-03-25 18:24:23 +0100437 :call uniq(sort(list)) " sort and remove duplicates
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000438
Bram Moolenaar13065c42005-01-08 16:08:21 +0000439
440For loop ~
441
Bram Moolenaar74e54fc2021-03-26 20:41:29 +0100442The |:for| loop executes commands for each item in a List, String or Blob.
443A variable is set to each item in sequence. Example with a List: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000444 :for item in mylist
445 : call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000446 :endfor
447
448This works like: >
449 :let index = 0
450 :while index < len(mylist)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000451 : let item = mylist[index]
452 : :call Doit(item)
Bram Moolenaar13065c42005-01-08 16:08:21 +0000453 : let index = index + 1
454 :endwhile
455
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000456If all you want to do is modify each item in the list then the |map()|
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000457function will be a simpler method than a for loop.
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000458
Bram Moolenaar58b85342016-08-14 19:54:54 +0200459Just like the |:let| command, |:for| also accepts a list of variables. This
Bram Moolenaar74e54fc2021-03-26 20:41:29 +0100460requires the argument to be a List of Lists. >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000461 :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
462 : call Doit(lnum, col)
463 :endfor
464
465This works like a |:let| command is done for each list item. Again, the types
466must remain the same to avoid an error.
467
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000468It is also possible to put remaining items in a List variable: >
Bram Moolenaar13065c42005-01-08 16:08:21 +0000469 :for [i, j; rest] in listlist
470 : call Doit(i, j)
471 : if !empty(rest)
472 : echo "remainder: " . string(rest)
473 : endif
474 :endfor
475
Bram Moolenaar74e54fc2021-03-26 20:41:29 +0100476For a Blob one byte at a time is used.
477
478For a String one character, including any composing characters, is used as a
479String. Example: >
480 for c in text
481 echo 'This character is ' .. c
482 endfor
483
Bram Moolenaar13065c42005-01-08 16:08:21 +0000484
485List functions ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000486 *E714*
Bram Moolenaar13065c42005-01-08 16:08:21 +0000487Functions that are useful with a List: >
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000488 :let r = call(funcname, list) " call a function with an argument list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000489 :if empty(list) " check if list is empty
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000490 :let l = len(list) " number of items in list
491 :let big = max(list) " maximum value in list
492 :let small = min(list) " minimum value in list
Bram Moolenaar9588a0f2005-01-08 21:45:39 +0000493 :let xs = count(list, 'x') " count nr of times 'x' appears in list
494 :let i = index(list, 'x') " index of first 'x' in list
Bram Moolenaar13065c42005-01-08 16:08:21 +0000495 :let lines = getline(1, 10) " get ten text lines from buffer
496 :call append('$', lines) " append text lines in buffer
Bram Moolenaar5f2bb9f2005-01-11 21:29:04 +0000497 :let list = split("a b c") " create list from items in a string
498 :let string = join(list, ', ') " create string from list items
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000499 :let s = string(list) " String representation of list
500 :call map(list, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaar13065c42005-01-08 16:08:21 +0000501
Bram Moolenaar0cb032e2005-04-23 20:52:00 +0000502Don't forget that a combination of features can make things simple. For
503example, to add up all the numbers in a list: >
504 :exe 'let sum = ' . join(nrlist, '+')
505
Bram Moolenaar13065c42005-01-08 16:08:21 +0000506
Bram Moolenaard8b02732005-01-14 21:48:43 +00005071.4 Dictionaries ~
Bram Moolenaard8968242019-01-15 22:51:57 +0100508 *dict* *Dict* *Dictionaries* *Dictionary*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000509A Dictionary is an associative array: Each entry has a key and a value. The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000510entry can be located with the key. The entries are stored without a specific
511ordering.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000512
513
514Dictionary creation ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000515 *E720* *E721* *E722* *E723*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000516A Dictionary is created with a comma separated list of entries in curly
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000517braces. Each entry has a key and a value, separated by a colon. Each key can
518only appear once. Examples: >
Bram Moolenaard8b02732005-01-14 21:48:43 +0000519 :let mydict = {1: 'one', 2: 'two', 3: 'three'}
520 :let emptydict = {}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000521< *E713* *E716* *E717*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000522A key is always a String. You can use a Number, it will be converted to a
523String automatically. Thus the String '4' and the number 4 will find the same
Bram Moolenaar58b85342016-08-14 19:54:54 +0200524entry. Note that the String '04' and the Number 04 are different, since the
Bram Moolenaard5abb4c2019-07-13 22:46:10 +0200525Number will be converted to the String '4'. The empty string can also be used
526as a key.
Bram Moolenaar5da36052021-12-27 15:39:57 +0000527
528In |Vim9| script literaly keys can be used if the key consists of alphanumeric
529characters, underscore and dash, see |vim9-literal-dict|.
Bram Moolenaar56c860c2019-08-17 20:09:31 +0200530 *literal-Dict* *#{}*
Bram Moolenaar5da36052021-12-27 15:39:57 +0000531To avoid having to put quotes around every key the #{} form can be used in
532legacy script. This does require the key to consist only of ASCII letters,
533digits, '-' and '_'. Example: >
Bram Moolenaar10455d42019-11-21 15:36:18 +0100534 :let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3}
Bram Moolenaar4c6d9042019-07-16 22:04:02 +0200535Note that 333 here is the string "333". Empty keys are not possible with #{}.
Bram Moolenaar5da36052021-12-27 15:39:57 +0000536In |Vim9| script the #{} form cannot be used.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000537
Bram Moolenaar58b85342016-08-14 19:54:54 +0200538A value can be any expression. Using a Dictionary for a value creates a
Bram Moolenaard8b02732005-01-14 21:48:43 +0000539nested Dictionary: >
540 :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
541
542An extra comma after the last entry is ignored.
543
544
545Accessing entries ~
546
547The normal way to access an entry is by putting the key in square brackets: >
548 :let val = mydict["one"]
549 :let mydict["four"] = 4
550
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000551You can add new entries to an existing Dictionary this way, unlike Lists.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000552
553For keys that consist entirely of letters, digits and underscore the following
554form can be used |expr-entry|: >
555 :let val = mydict.one
556 :let mydict.four = 4
557
558Since an entry can be any type, also a List and a Dictionary, the indexing and
559key lookup can be repeated: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000560 :echo dict.key[idx].key
Bram Moolenaard8b02732005-01-14 21:48:43 +0000561
562
563Dictionary to List conversion ~
564
Bram Moolenaar58b85342016-08-14 19:54:54 +0200565You may want to loop over the entries in a dictionary. For this you need to
Bram Moolenaard8b02732005-01-14 21:48:43 +0000566turn the Dictionary into a List and pass it to |:for|.
567
568Most often you want to loop over the keys, using the |keys()| function: >
569 :for key in keys(mydict)
570 : echo key . ': ' . mydict[key]
571 :endfor
572
573The List of keys is unsorted. You may want to sort them first: >
574 :for key in sort(keys(mydict))
575
576To loop over the values use the |values()| function: >
577 :for v in values(mydict)
578 : echo "value: " . v
579 :endfor
580
581If you want both the key and the value use the |items()| function. It returns
Bram Moolenaard47d5222018-12-09 20:43:55 +0100582a List in which each item is a List with two items, the key and the value: >
Bram Moolenaaref2f6562007-05-06 13:32:59 +0000583 :for [key, value] in items(mydict)
584 : echo key . ': ' . value
Bram Moolenaard8b02732005-01-14 21:48:43 +0000585 :endfor
586
587
588Dictionary identity ~
Bram Moolenaar7c626922005-02-07 22:01:03 +0000589 *dict-identity*
Bram Moolenaard8b02732005-01-14 21:48:43 +0000590Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
591Dictionary. Otherwise, assignment results in referring to the same
592Dictionary: >
593 :let onedict = {'a': 1, 'b': 2}
594 :let adict = onedict
595 :let adict['a'] = 11
596 :echo onedict['a']
597 11
598
Bram Moolenaarf3bd51a2005-06-14 22:11:18 +0000599Two Dictionaries compare equal if all the key-value pairs compare equal. For
600more info see |list-identity|.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000601
602
603Dictionary modification ~
604 *dict-modification*
605To change an already existing entry of a Dictionary, or to add a new entry,
606use |:let| this way: >
607 :let dict[4] = "four"
608 :let dict['one'] = item
609
Bram Moolenaar9cd15162005-01-16 22:02:49 +0000610Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
611Three ways to remove the entry with key "aaa" from dict: >
612 :let i = remove(dict, 'aaa')
613 :unlet dict.aaa
614 :unlet dict['aaa']
Bram Moolenaard8b02732005-01-14 21:48:43 +0000615
616Merging a Dictionary with another is done with |extend()|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000617 :call extend(adict, bdict)
618This extends adict with all entries from bdict. Duplicate keys cause entries
619in adict to be overwritten. An optional third argument can change this.
Bram Moolenaar383f9bc2005-01-19 22:18:32 +0000620Note that the order of entries in a Dictionary is irrelevant, thus don't
621expect ":echo adict" to show the items from bdict after the older entries in
622adict.
Bram Moolenaard8b02732005-01-14 21:48:43 +0000623
624Weeding out entries from a Dictionary can be done with |filter()|: >
Bram Moolenaaref2f6562007-05-06 13:32:59 +0000625 :call filter(dict, 'v:val =~ "x"')
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000626This removes all entries from "dict" with a value not matching 'x'.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200627This can also be used to remove all entries: >
628 call filter(dict, 0)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000629
630
631Dictionary function ~
Bram Moolenaar26402cb2013-02-20 21:26:00 +0100632 *Dictionary-function* *self* *E725* *E862*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000633When a function is defined with the "dict" attribute it can be used in a
Bram Moolenaar58b85342016-08-14 19:54:54 +0200634special way with a dictionary. Example: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000635 :function Mylen() dict
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000636 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000637 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000638 :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
639 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000640
641This is like a method in object oriented programming. The entry in the
642Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
643the function was invoked from.
644
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000645It is also possible to add a function without the "dict" attribute as a
646Funcref to a Dictionary, but the "self" variable is not available then.
647
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000648 *numbered-function* *anonymous-function*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000649To avoid the extra name for the function it can be defined and directly
650assigned to a Dictionary in this way: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000651 :let mydict = {'data': [0, 1, 2, 3]}
Bram Moolenaar5a5f4592015-04-13 12:43:06 +0200652 :function mydict.len()
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000653 : return len(self.data)
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000654 :endfunction
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000655 :echo mydict.len()
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000656
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000657The function will then get a number and the value of dict.len is a |Funcref|
Bram Moolenaar58b85342016-08-14 19:54:54 +0200658that references this function. The function can only be used through a
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000659|Funcref|. It will automatically be deleted when there is no |Funcref|
660remaining that refers to it.
661
662It is not necessary to use the "dict" attribute for a numbered function.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000663
Bram Moolenaar1affd722010-08-04 17:49:30 +0200664If you get an error for a numbered function, you can find out what it is with
665a trick. Assuming the function is 42, the command is: >
Bram Moolenaar34cc7d82021-09-21 20:09:51 +0200666 :function g:42
Bram Moolenaar1affd722010-08-04 17:49:30 +0200667
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000668
669Functions for Dictionaries ~
Bram Moolenaar3a3a7232005-01-17 22:16:15 +0000670 *E715*
671Functions that can be used with a Dictionary: >
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000672 :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
673 :if empty(dict) " TRUE if dict is empty
674 :let l = len(dict) " number of items in dict
675 :let big = max(dict) " maximum value in dict
676 :let small = min(dict) " minimum value in dict
677 :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
678 :let s = string(dict) " String representation of dict
679 :call map(dict, '">> " . v:val') " prepend ">> " to each item
Bram Moolenaard8b02732005-01-14 21:48:43 +0000680
681
Bram Moolenaard8968242019-01-15 22:51:57 +01006821.5 Blobs ~
683 *blob* *Blob* *Blobs* *E978*
Bram Moolenaaraff74912019-03-30 18:11:49 +0100684A Blob is a binary object. It can be used to read an image from a file and
685send it over a channel, for example.
686
687A Blob mostly behaves like a |List| of numbers, where each number has the
688value of an 8-bit byte, from 0 to 255.
Bram Moolenaard8968242019-01-15 22:51:57 +0100689
690
691Blob creation ~
692
693A Blob can be created with a |blob-literal|: >
694 :let b = 0zFF00ED015DAF
Bram Moolenaar0d17f0d2019-01-22 22:20:38 +0100695Dots can be inserted between bytes (pair of hex characters) for readability,
696they don't change the value: >
697 :let b = 0zFF00.ED01.5DAF
Bram Moolenaard8968242019-01-15 22:51:57 +0100698
699A blob can be read from a file with |readfile()| passing the {type} argument
700set to "B", for example: >
701 :let b = readfile('image.png', 'B')
702
703A blob can be read from a channel with the |ch_readblob()| function.
704
705
706Blob index ~
707 *blob-index* *E979*
708A byte in the Blob can be accessed by putting the index in square brackets
709after the Blob. Indexes are zero-based, thus the first byte has index zero. >
710 :let myblob = 0z00112233
711 :let byte = myblob[0] " get the first byte: 0x00
712 :let byte = myblob[2] " get the third byte: 0x22
713
714A negative index is counted from the end. Index -1 refers to the last byte in
715the Blob, -2 to the last but one byte, etc. >
716 :let last = myblob[-1] " get the last byte: 0x33
717
718To avoid an error for an invalid index use the |get()| function. When an item
719is not available it returns -1 or the default value you specify: >
720 :echo get(myblob, idx)
721 :echo get(myblob, idx, 999)
722
723
Bram Moolenaar5e66b422019-01-24 21:58:10 +0100724Blob iteration ~
725
726The |:for| loop executes commands for each byte of a Blob. The loop variable is
727set to each byte in the Blob. Example: >
728 :for byte in 0z112233
729 : call Doit(byte)
730 :endfor
731This calls Doit() with 0x11, 0x22 and 0x33.
732
733
Bram Moolenaard8968242019-01-15 22:51:57 +0100734Blob concatenation ~
735
736Two blobs can be concatenated with the "+" operator: >
737 :let longblob = myblob + 0z4455
738 :let myblob += 0z6677
739
740To change a blob in-place see |blob-modification| below.
741
742
743Part of a blob ~
744
745A part of the Blob can be obtained by specifying the first and last index,
746separated by a colon in square brackets: >
747 :let myblob = 0z00112233
Bram Moolenaard09091d2019-01-17 16:07:22 +0100748 :let shortblob = myblob[1:2] " get 0z1122
Bram Moolenaard8968242019-01-15 22:51:57 +0100749 :let shortblob = myblob[2:-1] " get 0z2233
750
751Omitting the first index is similar to zero. Omitting the last index is
752similar to -1. >
753 :let endblob = myblob[2:] " from item 2 to the end: 0z2233
754 :let shortblob = myblob[2:2] " Blob with one byte: 0z22
755 :let otherblob = myblob[:] " make a copy of the Blob
756
Bram Moolenaard09091d2019-01-17 16:07:22 +0100757If the first index is beyond the last byte of the Blob or the second index is
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100758before the first index, the result is an empty Blob. There is no error
Bram Moolenaard8968242019-01-15 22:51:57 +0100759message.
760
761If the second index is equal to or greater than the length of the list the
762length minus one is used: >
763 :echo myblob[2:8] " result: 0z2233
764
765
766Blob modification ~
767 *blob-modification*
768To change a specific byte of a blob use |:let| this way: >
769 :let blob[4] = 0x44
770
771When the index is just one beyond the end of the Blob, it is appended. Any
772higher index is an error.
773
774To change a sequence of bytes the [:] notation can be used: >
775 let blob[1:3] = 0z445566
Bram Moolenaard09091d2019-01-17 16:07:22 +0100776The length of the replaced bytes must be exactly the same as the value
Bram Moolenaard8968242019-01-15 22:51:57 +0100777provided. *E972*
778
779To change part of a blob you can specify the first and last byte to be
Bram Moolenaard09091d2019-01-17 16:07:22 +0100780modified. The value must have the same number of bytes in the range: >
781 :let blob[3:5] = 0z334455
Bram Moolenaard8968242019-01-15 22:51:57 +0100782
783You can also use the functions |add()|, |remove()| and |insert()|.
784
785
786Blob identity ~
787
788Blobs can be compared for equality: >
789 if blob == 0z001122
790And for equal identity: >
791 if blob is otherblob
792< *blob-identity* *E977*
793When variable "aa" is a Blob and you assign it to another variable "bb", both
794variables refer to the same Blob. Then the "is" operator returns true.
795
796When making a copy using [:] or |copy()| the values are the same, but the
797identity is different: >
798 :let blob = 0z112233
799 :let blob2 = blob
800 :echo blob == blob2
801< 1 >
802 :echo blob is blob2
803< 1 >
804 :let blob3 = blob[:]
805 :echo blob == blob3
806< 1 >
807 :echo blob is blob3
808< 0
809
Bram Moolenaard09091d2019-01-17 16:07:22 +0100810Making a copy of a Blob is done with the |copy()| function. Using [:] also
Bram Moolenaard8968242019-01-15 22:51:57 +0100811works, as explained above.
812
813
8141.6 More about variables ~
Bram Moolenaar13065c42005-01-08 16:08:21 +0000815 *more-variables*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816If you need to know the type of a variable or expression, use the |type()|
817function.
818
819When the '!' flag is included in the 'viminfo' option, global variables that
820start with an uppercase letter, and don't contain a lowercase letter, are
821stored in the viminfo file |viminfo-file|.
822
823When the 'sessionoptions' option contains "global", global variables that
824start with an uppercase letter and contain at least one lowercase letter are
825stored in the session file |session-file|.
826
827variable name can be stored where ~
828my_var_6 not
829My_Var_6 session file
830MY_VAR_6 viminfo file
831
832
Bram Moolenaar5da36052021-12-27 15:39:57 +0000833In legacy script it is possible to form a variable name with curly braces, see
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834|curly-braces-names|.
835
836==============================================================================
8372. Expression syntax *expression-syntax*
838
839Expression syntax summary, from least to most significant:
840
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200841|expr1| expr2
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200842 expr2 ? expr1 : expr1 if-then-else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200844|expr2| expr3
Bram Moolenaar0f248b02019-04-04 15:36:05 +0200845 expr3 || expr3 ... logical OR
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200847|expr3| expr4
Bram Moolenaar0f248b02019-04-04 15:36:05 +0200848 expr4 && expr4 ... logical AND
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200850|expr4| expr5
851 expr5 == expr5 equal
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 expr5 != expr5 not equal
853 expr5 > expr5 greater than
854 expr5 >= expr5 greater than or equal
855 expr5 < expr5 smaller than
856 expr5 <= expr5 smaller than or equal
857 expr5 =~ expr5 regexp matches
858 expr5 !~ expr5 regexp doesn't match
859
860 expr5 ==? expr5 equal, ignoring case
861 expr5 ==# expr5 equal, match case
862 etc. As above, append ? for ignoring case, # for
863 matching case
864
Bram Moolenaar5e66b422019-01-24 21:58:10 +0100865 expr5 is expr5 same |List|, |Dictionary| or |Blob| instance
866 expr5 isnot expr5 different |List|, |Dictionary| or |Blob|
867 instance
Bram Moolenaarde8866b2005-01-06 23:24:37 +0000868
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200869|expr5| expr6
Bram Moolenaar0f248b02019-04-04 15:36:05 +0200870 expr6 + expr6 ... number addition, list or blob concatenation
871 expr6 - expr6 ... number subtraction
872 expr6 . expr6 ... string concatenation
873 expr6 .. expr6 ... string concatenation
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200875|expr6| expr7
Bram Moolenaar0f248b02019-04-04 15:36:05 +0200876 expr7 * expr7 ... number multiplication
877 expr7 / expr7 ... number division
878 expr7 % expr7 ... number modulo
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200880|expr7| expr8
Bram Moolenaar5da36052021-12-27 15:39:57 +0000881 <type>expr8 type check and conversion (|Vim9| only)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882
Bram Moolenaar89bcfda2016-08-30 23:26:57 +0200883|expr8| expr9
Bram Moolenaar5da36052021-12-27 15:39:57 +0000884 ! expr8 logical NOT
885 - expr8 unary minus
886 + expr8 unary plus
Bram Moolenaar2fda12f2005-01-15 22:14:15 +0000887
Bram Moolenaar5da36052021-12-27 15:39:57 +0000888|expr9| expr10
889 expr9[expr1] byte of a String or item of a |List|
890 expr9[expr1 : expr1] substring of a String or sublist of a |List|
891 expr9.name entry in a |Dictionary|
892 expr9(expr1, ...) function call with |Funcref| variable
893 expr9->name(expr1, ...) |method| call
894
895|expr10| number number constant
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000896 "string" string constant, backslash is special
Bram Moolenaard8b02732005-01-14 21:48:43 +0000897 'string' string constant, ' is doubled
Bram Moolenaar32466aa2006-02-24 23:53:04 +0000898 [expr1, ...] |List|
899 {expr1: expr1, ...} |Dictionary|
Bram Moolenaar5da36052021-12-27 15:39:57 +0000900 #{key: expr1, ...} legacy |Dictionary|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 &option option value
902 (expr1) nested expression
903 variable internal variable
904 va{ria}ble internal variable with curly braces
905 $VAR environment variable
906 @r contents of register 'r'
907 function(expr1, ...) function call
908 func{ti}on(expr1, ...) function call with curly braces
Bram Moolenaar5da36052021-12-27 15:39:57 +0000909 {args -> expr1} legacy lambda expression
910 (args) => expr1 Vim9 lambda expression
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911
912
Bram Moolenaar0f248b02019-04-04 15:36:05 +0200913"..." indicates that the operations in this level can be concatenated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914Example: >
915 &nu || &list && &shell == "csh"
916
917All expressions within one level are parsed from left to right.
918
919
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +0200920expr1 *expr1* *trinary* *falsy-operator* *??* *E109*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921-----
922
Bram Moolenaar92f26c22020-10-03 20:17:30 +0200923The trinary operator: expr2 ? expr1 : expr1
924The falsy operator: expr2 ?? expr1
925
926Trinary operator ~
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
Bram Moolenaar5da36052021-12-27 15:39:57 +0000928In legacy script the expression before the '?' is evaluated to a number. If
929it evaluates to |TRUE|, the result is the value of the expression between the
930'?' and ':', otherwise the result is the value of the expression after the
931':'.
932
933In |Vim9| script the first expression must evaluate to a boolean, see
934|vim9-boolean|.
935
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936Example: >
937 :echo lnum == 1 ? "top" : lnum
938
939Since the first expression is an "expr2", it cannot contain another ?:. The
940other two expressions can, thus allow for recursive use of ?:.
941Example: >
942 :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
943
944To keep this readable, using |line-continuation| is suggested: >
945 :echo lnum == 1
946 :\ ? "top"
947 :\ : lnum == 1000
948 :\ ? "last"
949 :\ : lnum
950
Bram Moolenaaref2f6562007-05-06 13:32:59 +0000951You should always put a space before the ':', otherwise it can be mistaken for
952use in a variable such as "a:1".
953
Bram Moolenaar92f26c22020-10-03 20:17:30 +0200954Falsy operator ~
955
956This is also known as the "null coalescing operator", but that's too
957complicated, thus we just call it the falsy operator.
958
959The expression before the '??' is evaluated. If it evaluates to
960|truthy|, this is used as the result. Otherwise the expression after the '??'
961is evaluated and used as the result. This is most useful to have a default
962value for an expression that may result in zero or empty: >
963 echo theList ?? 'list is empty'
964 echo GetName() ?? 'unknown'
965
966These are similar, but not equal: >
967 expr2 ?? expr1
968 expr2 ? expr2 : expr1
Bram Moolenaar5da36052021-12-27 15:39:57 +0000969In the second line "expr2" is evaluated twice. And in |Vim9| script the type
970of expr2 before "?" must be a boolean.
Bram Moolenaar92f26c22020-10-03 20:17:30 +0200971
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
973expr2 and expr3 *expr2* *expr3*
974---------------
975
Bram Moolenaar04186092016-08-29 21:55:35 +0200976expr3 || expr3 .. logical OR *expr-barbar*
977expr4 && expr4 .. logical AND *expr-&&*
978
Bram Moolenaar5da36052021-12-27 15:39:57 +0000979The "||" and "&&" operators take one argument on each side.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980
Bram Moolenaar5da36052021-12-27 15:39:57 +0000981In legacy script the arguments are (converted to) Numbers.
982
983In |Vim9| script the values must be boolean, see |vim9-boolean|. Use "!!" to
984convert any type to a boolean.
985
986The result is:
Bram Moolenaare381d3d2016-07-07 14:50:41 +0200987 input output ~
988n1 n2 n1 || n2 n1 && n2 ~
989|FALSE| |FALSE| |FALSE| |FALSE|
990|FALSE| |TRUE| |TRUE| |FALSE|
991|TRUE| |FALSE| |TRUE| |FALSE|
992|TRUE| |TRUE| |TRUE| |TRUE|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993
994The operators can be concatenated, for example: >
995
996 &nu || &list && &shell == "csh"
997
998Note that "&&" takes precedence over "||", so this has the meaning of: >
999
1000 &nu || (&list && &shell == "csh")
1001
1002Once the result is known, the expression "short-circuits", that is, further
1003arguments are not evaluated. This is like what happens in C. For example: >
1004
1005 let a = 1
1006 echo a || b
1007
Bram Moolenaare381d3d2016-07-07 14:50:41 +02001008This is valid even if there is no variable called "b" because "a" is |TRUE|,
1009so the result must be |TRUE|. Similarly below: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
1011 echo exists("b") && b == "yes"
1012
1013This is valid whether "b" has been defined or not. The second clause will
1014only be evaluated if "b" has been defined.
1015
1016
1017expr4 *expr4*
1018-----
1019
1020expr5 {cmp} expr5
1021
Bram Moolenaar5da36052021-12-27 15:39:57 +00001022Compare two expr5 expressions. In legacy script the result is a 0 if it
1023evaluates to false, or 1 if it evaluates to true. In |Vim9| script the result
1024is |true| or |false|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025
Bram Moolenaar446cb832008-06-24 21:56:24 +00001026 *expr-==* *expr-!=* *expr->* *expr->=*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001027 *expr-<* *expr-<=* *expr-=~* *expr-!~*
1028 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
1029 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
1030 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
1031 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
Bram Moolenaar251e1912011-06-19 05:09:16 +02001032 *expr-is* *expr-isnot* *expr-is#* *expr-isnot#*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001033 *expr-is?* *expr-isnot?* *E1072*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 use 'ignorecase' match case ignore case ~
1035equal == ==# ==?
1036not equal != !=# !=?
1037greater than > ># >?
1038greater than or equal >= >=# >=?
1039smaller than < <# <?
1040smaller than or equal <= <=# <=?
1041regexp matches =~ =~# =~?
1042regexp doesn't match !~ !~# !~?
Bram Moolenaar251e1912011-06-19 05:09:16 +02001043same instance is is# is?
1044different instance isnot isnot# isnot?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045
1046Examples:
1047"abc" ==# "Abc" evaluates to 0
1048"abc" ==? "Abc" evaluates to 1
1049"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
Bram Moolenaar5da36052021-12-27 15:39:57 +00001050NOTE: In |Vim9| script 'ignorecase' is not used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051
Bram Moolenaar13065c42005-01-08 16:08:21 +00001052 *E691* *E692*
Bram Moolenaar01164a62017-11-02 22:58:42 +01001053A |List| can only be compared with a |List| and only "equal", "not equal",
1054"is" and "isnot" can be used. This compares the values of the list,
1055recursively. Ignoring case means case is ignored when comparing item values.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001056
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001057 *E735* *E736*
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001058A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not
Bram Moolenaar01164a62017-11-02 22:58:42 +01001059equal", "is" and "isnot" can be used. This compares the key/values of the
1060|Dictionary| recursively. Ignoring case means case is ignored when comparing
1061item values.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00001062
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +02001063 *E694*
Bram Moolenaare18dbe82016-07-02 21:42:23 +02001064A |Funcref| can only be compared with a |Funcref| and only "equal", "not
1065equal", "is" and "isnot" can be used. Case is never ignored. Whether
1066arguments or a Dictionary are bound (with a partial) matters. The
1067Dictionaries must also be equal (or the same, in case of "is") and the
1068arguments must be equal (or the same).
1069
1070To compare Funcrefs to see if they refer to the same function, ignoring bound
1071Dictionary and arguments, use |get()| to get the function name: >
1072 if get(Part1, 'name') == get(Part2, 'name')
1073 " Part1 and Part2 refer to the same function
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001074< *E1037*
Bram Moolenaar5e66b422019-01-24 21:58:10 +01001075Using "is" or "isnot" with a |List|, |Dictionary| or |Blob| checks whether
1076the expressions are referring to the same |List|, |Dictionary| or |Blob|
1077instance. A copy of a |List| is different from the original |List|. When
1078using "is" without a |List|, |Dictionary| or |Blob|, it is equivalent to
1079using "equal", using "isnot" equivalent to using "not equal". Except that
1080a different type means the values are different: >
Bram Moolenaar86edef62016-03-13 18:07:30 +01001081 echo 4 == '4'
1082 1
1083 echo 4 is '4'
1084 0
1085 echo 0 is []
1086 0
1087"is#"/"isnot#" and "is?"/"isnot?" can be used to match and ignore case.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001088
Bram Moolenaar5da36052021-12-27 15:39:57 +00001089In legacy script, when comparing a String with a Number, the String is
1090converted to a Number, and the comparison is done on Numbers. This means
1091that: >
Bram Moolenaar86edef62016-03-13 18:07:30 +01001092 echo 0 == 'x'
1093 1
1094because 'x' converted to a Number is zero. However: >
1095 echo [0] == ['x']
1096 0
1097Inside a List or Dictionary this conversion is not used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098
Bram Moolenaar5da36052021-12-27 15:39:57 +00001099In |Vim9| script the types must match.
1100
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101When comparing two Strings, this is done with strcmp() or stricmp(). This
1102results in the mathematical difference (comparing byte values), not
1103necessarily the alphabetical difference in the local language.
1104
Bram Moolenaar446cb832008-06-24 21:56:24 +00001105When using the operators with a trailing '#', or the short version and
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001106'ignorecase' is off, the comparing is done with strcmp(): case matters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107
1108When using the operators with a trailing '?', or the short version and
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001109'ignorecase' is set, the comparing is done with stricmp(): case is ignored.
1110
1111'smartcase' is not used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112
1113The "=~" and "!~" operators match the lefthand argument with the righthand
1114argument, which is used as a pattern. See |pattern| for what a pattern is.
1115This matching is always done like 'magic' was set and 'cpoptions' is empty, no
1116matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
1117portable. To avoid backslashes in the regexp pattern to be doubled, use a
1118single-quote string, see |literal-string|.
1119Since a string is considered to be a single line, a multi-line pattern
1120(containing \n, backslash-n) will not match. However, a literal NL character
1121can be matched like an ordinary character. Examples:
1122 "foo\nbar" =~ "\n" evaluates to 1
1123 "foo\nbar" =~ "\\n" evaluates to 0
1124
1125
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001126expr5 and expr6 *expr5* *expr6* *E1036* *E1051*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127---------------
Bram Moolenaar0f248b02019-04-04 15:36:05 +02001128expr6 + expr6 Number addition, |List| or |Blob| concatenation *expr-+*
1129expr6 - expr6 Number subtraction *expr--*
1130expr6 . expr6 String concatenation *expr-.*
1131expr6 .. expr6 String concatenation *expr-..*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132
Bram Moolenaara23ccb82006-02-27 00:08:02 +00001133For |Lists| only "+" is possible and then both expr6 must be a list. The
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001134result is a new list with the two lists Concatenated.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001135
Bram Moolenaar0f248b02019-04-04 15:36:05 +02001136For String concatenation ".." is preferred, since "." is ambiguous, it is also
1137used for |Dict| member access and floating point numbers.
Bram Moolenaar5da36052021-12-27 15:39:57 +00001138In |Vim9| script and when |vimscript-version| is 2 or higher, using "." is not
1139allowed.
1140
1141In |Vim9| script the arguments of ".." are converted to String for simple
1142types: Number, Float, Special and Bool. For other types |string()| should be
1143used.
Bram Moolenaar0f248b02019-04-04 15:36:05 +02001144
Bram Moolenaar5e66b422019-01-24 21:58:10 +01001145expr7 * expr7 Number multiplication *expr-star*
1146expr7 / expr7 Number division *expr-/*
1147expr7 % expr7 Number modulo *expr-%*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148
Bram Moolenaar5da36052021-12-27 15:39:57 +00001149In legacy script, for all operators except "." and "..", Strings are converted
1150to Numbers.
1151
Bram Moolenaard6e256c2011-12-14 15:32:50 +01001152For bitwise operators see |and()|, |or()| and |xor()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153
Bram Moolenaar5da36052021-12-27 15:39:57 +00001154Note the difference between "+" and ".." in legacy script:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 "123" + "456" = 579
Bram Moolenaar5da36052021-12-27 15:39:57 +00001156 "123" .. "456" = "123456"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157
Bram Moolenaar5da36052021-12-27 15:39:57 +00001158Since '..' has the same precedence as '+' and '-', you need to read: >
1159 1 .. 90 + 90.0
Bram Moolenaar446cb832008-06-24 21:56:24 +00001160As: >
Bram Moolenaar5da36052021-12-27 15:39:57 +00001161 (1 .. 90) + 90.0
1162That works in legacy script, since the String "190" is automatically converted
1163to the Number 190, which can be added to the Float 90.0. However: >
1164 1 .. 90 * 90.0
Bram Moolenaar446cb832008-06-24 21:56:24 +00001165Should be read as: >
Bram Moolenaar5da36052021-12-27 15:39:57 +00001166 1 .. (90 * 90.0)
1167Since '..' has lower precedence than '*'. This does NOT work, since this
Bram Moolenaar446cb832008-06-24 21:56:24 +00001168attempts to concatenate a Float and a String.
1169
1170When dividing a Number by zero the result depends on the value:
1171 0 / 0 = -0x80000000 (like NaN for Float)
1172 >0 / 0 = 0x7fffffff (like positive infinity)
1173 <0 / 0 = -0x7fffffff (like negative infinity)
1174 (before Vim 7.2 it was always 0x7fffffff)
1175
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02001176When 64-bit Number support is enabled:
1177 0 / 0 = -0x8000000000000000 (like NaN for Float)
1178 >0 / 0 = 0x7fffffffffffffff (like positive infinity)
1179 <0 / 0 = -0x7fffffffffffffff (like negative infinity)
1180
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181When the righthand side of '%' is zero, the result is 0.
1182
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001183None of these work for |Funcref|s.
Bram Moolenaarde8866b2005-01-06 23:24:37 +00001184
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001185".", ".." and "%" do not work for Float. *E804* *E1035*
Bram Moolenaar446cb832008-06-24 21:56:24 +00001186
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187
1188expr7 *expr7*
1189-----
Bram Moolenaar5da36052021-12-27 15:39:57 +00001190<type>expr8
1191
1192This is only available in |Vim9| script, see |type-casting|.
1193
1194
1195expr8 *expr8*
1196-----
1197! expr8 logical NOT *expr-!*
1198- expr8 unary minus *expr-unary--*
1199+ expr8 unary plus *expr-unary-+*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200
Bram Moolenaare381d3d2016-07-07 14:50:41 +02001201For '!' |TRUE| becomes |FALSE|, |FALSE| becomes |TRUE| (one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202For '-' the sign of the number is changed.
Bram Moolenaar6f02b002021-01-10 20:22:54 +01001203For '+' the number is unchanged. Note: "++" has no effect.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204
Bram Moolenaar5da36052021-12-27 15:39:57 +00001205In legacy script a String will be converted to a Number first. Note that if
1206the string does not start with a digit you likely don't get what you expect.
1207
1208In |Vim9| script an error is given when "-" or "+" is used and the type is not
1209a number.
1210
1211In |Vim9| script "!" can be used for any type and the result is always a
1212boolean. Use "!!" to convert any type to a boolean, according to whether the
1213value is |falsy|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214
Bram Moolenaar58b85342016-08-14 19:54:54 +02001215These three can be repeated and mixed. Examples:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 !-1 == 0
1217 !!8 == 1
1218 --9 == 9
1219
1220
Bram Moolenaar5da36052021-12-27 15:39:57 +00001221expr9 *expr9*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222-----
Bram Moolenaar5da36052021-12-27 15:39:57 +00001223This expression is either |expr10| or a sequence of the alternatives below,
Bram Moolenaarfc65cab2018-08-28 22:58:02 +02001224in any order. E.g., these are all possible:
Bram Moolenaar5da36052021-12-27 15:39:57 +00001225 expr9[expr1].name
1226 expr9.name[expr1]
1227 expr9(expr1, ...)[expr1].name
1228 expr9->(expr1, ...)[expr1]
Bram Moolenaarac92e252019-08-03 21:58:38 +02001229Evaluation is always from left to right.
Bram Moolenaarfc65cab2018-08-28 22:58:02 +02001230
Bram Moolenaar5da36052021-12-27 15:39:57 +00001231expr9[expr1] item of String or |List| *expr-[]* *E111*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001232 *E909* *subscript* *E1062*
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001233In legacy Vim script:
Bram Moolenaar5da36052021-12-27 15:39:57 +00001234If expr9 is a Number or String this results in a String that contains the
1235expr1'th single byte from expr9. expr9 is used as a String (a number is
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001236automatically converted to a String), expr1 as a Number. This doesn't
Bram Moolenaar207f0092020-08-30 17:20:20 +02001237recognize multibyte encodings, see `byteidx()` for an alternative, or use
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001238`split()` to turn the string into a list of characters. Example, to get the
1239byte under the cursor: >
Bram Moolenaar61660ea2006-04-07 21:40:07 +00001240 :let c = getline(".")[col(".") - 1]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241
Bram Moolenaar5da36052021-12-27 15:39:57 +00001242In |Vim9| script:
1243If expr9 is a String this results in a String that contains the expr1'th
1244single character (including any composing characters) from expr9. To use byte
Bram Moolenaar02b4d9b2021-03-14 19:46:45 +01001245indexes use |strpart()|.
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001246
1247Index zero gives the first byte or character. Careful: text column numbers
1248start with one!
1249
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250If the length of the String is less than the index, the result is an empty
Bram Moolenaar85084ef2016-01-17 22:26:33 +01001251String. A negative index always results in an empty string (reason: backward
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001252compatibility). Use [-1:] to get the last byte or character.
Bram Moolenaar6f02b002021-01-10 20:22:54 +01001253In Vim9 script a negative index is used like with a list: count from the end.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001254
Bram Moolenaar5da36052021-12-27 15:39:57 +00001255If expr9 is a |List| then it results the item at index expr1. See |list-index|
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001256for possible index values. If the index is out of range this results in an
Bram Moolenaar58b85342016-08-14 19:54:54 +02001257error. Example: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001258 :let item = mylist[-1] " get last item
1259
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001260Generally, if a |List| index is equal to or higher than the length of the
1261|List|, or more negative than the length of the |List|, this results in an
1262error.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001263
Bram Moolenaard8b02732005-01-14 21:48:43 +00001264
Bram Moolenaar5da36052021-12-27 15:39:57 +00001265expr9[expr1a : expr1b] substring or sublist *expr-[:]*
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001266
Bram Moolenaar5da36052021-12-27 15:39:57 +00001267If expr9 is a String this results in the substring with the bytes or
1268characters from expr1a to and including expr1b. expr9 is used as a String,
Bram Moolenaar207f0092020-08-30 17:20:20 +02001269expr1a and expr1b are used as a Number.
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001270
1271In legacy Vim script the indexes are byte indexes. This doesn't recognize
Bram Moolenaar5da36052021-12-27 15:39:57 +00001272multibyte encodings, see |byteidx()| for computing the indexes. If expr9 is
Bram Moolenaare3c37d82020-08-15 18:39:05 +02001273a Number it is first converted to a String.
1274
Bram Moolenaar02b4d9b2021-03-14 19:46:45 +01001275In Vim9 script the indexes are character indexes and include composing
1276characters. To use byte indexes use |strpart()|. To use character indexes
1277without including composing characters use |strcharpart()|.
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001278
Bram Moolenaar6601b622021-01-13 21:47:15 +01001279The item at index expr1b is included, it is inclusive. For an exclusive index
1280use the |slice()| function.
1281
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001282If expr1a is omitted zero is used. If expr1b is omitted the length of the
1283string minus one is used.
1284
1285A negative number can be used to measure from the end of the string. -1 is
1286the last character, -2 the last but one, etc.
1287
1288If an index goes out of range for the string characters are omitted. If
1289expr1b is smaller than expr1a the result is an empty string.
1290
1291Examples: >
1292 :let c = name[-1:] " last byte of a string
Bram Moolenaar207f0092020-08-30 17:20:20 +02001293 :let c = name[0:-1] " the whole string
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001294 :let c = name[-2:-2] " last but one byte of a string
1295 :let s = line(".")[4:] " from the fifth byte to the end
1296 :let s = s[:-3] " remove last two bytes
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01001297<
Bram Moolenaarbc8801c2016-08-02 21:04:33 +02001298 *slice*
Bram Moolenaar5da36052021-12-27 15:39:57 +00001299If expr9 is a |List| this results in a new |List| with the items indicated by
Bram Moolenaar58b85342016-08-14 19:54:54 +02001300the indexes expr1a and expr1b. This works like with a String, as explained
Bram Moolenaarbc8801c2016-08-02 21:04:33 +02001301just above. Also see |sublist| below. Examples: >
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00001302 :let l = mylist[:3] " first four items
1303 :let l = mylist[4:4] " List with one item
1304 :let l = mylist[:] " shallow copy of a List
1305
Bram Moolenaar5da36052021-12-27 15:39:57 +00001306If expr9 is a |Blob| this results in a new |Blob| with the bytes in the
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01001307indexes expr1a and expr1b, inclusive. Examples: >
1308 :let b = 0zDEADBEEF
1309 :let bs = b[1:2] " 0zADBE
Bram Moolenaard09091d2019-01-17 16:07:22 +01001310 :let bs = b[:] " copy of 0zDEADBEEF
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01001311
Bram Moolenaar5da36052021-12-27 15:39:57 +00001312Using expr9[expr1] or expr9[expr1a : expr1b] on a |Funcref| results in an
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001313error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
Bram Moolenaarda440d22016-01-16 21:27:23 +01001315Watch out for confusion between a namespace and a variable followed by a colon
1316for a sublist: >
1317 mylist[n:] " uses variable n
1318 mylist[s:] " uses namespace s:, error!
1319
Bram Moolenaard8b02732005-01-14 21:48:43 +00001320
Bram Moolenaar5da36052021-12-27 15:39:57 +00001321expr9.name entry in a |Dictionary| *expr-entry*
Bram Moolenaard8b02732005-01-14 21:48:43 +00001322
Bram Moolenaar5da36052021-12-27 15:39:57 +00001323If expr9 is a |Dictionary| and it is followed by a dot, then the following
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001324name will be used as a key in the |Dictionary|. This is just like:
Bram Moolenaar5da36052021-12-27 15:39:57 +00001325expr9[name].
Bram Moolenaard8b02732005-01-14 21:48:43 +00001326
1327The name must consist of alphanumeric characters, just like a variable name,
1328but it may start with a number. Curly braces cannot be used.
1329
1330There must not be white space before or after the dot.
1331
1332Examples: >
1333 :let dict = {"one": 1, 2: "two"}
Bram Moolenaar68e65602019-05-26 21:33:31 +02001334 :echo dict.one " shows "1"
1335 :echo dict.2 " shows "two"
1336 :echo dict .2 " error because of space before the dot
Bram Moolenaard8b02732005-01-14 21:48:43 +00001337
1338Note that the dot is also used for String concatenation. To avoid confusion
1339always put spaces around the dot for String concatenation.
1340
1341
Bram Moolenaar5da36052021-12-27 15:39:57 +00001342expr9(expr1, ...) |Funcref| function call
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001343
Bram Moolenaar5da36052021-12-27 15:39:57 +00001344When expr9 is a |Funcref| type variable, invoke the function it refers to.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001345
1346
Bram Moolenaar5da36052021-12-27 15:39:57 +00001347expr9->name([args]) method call *method* *->*
1348expr9->{lambda}([args])
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001349 *E260* *E276*
Bram Moolenaar25e42232019-08-04 15:04:10 +02001350For methods that are also available as global functions this is the same as: >
Bram Moolenaar5da36052021-12-27 15:39:57 +00001351 name(expr9 [, args])
1352There can also be methods specifically for the type of "expr9".
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00001353
Bram Moolenaar51841322019-08-08 21:10:01 +02001354This allows for chaining, passing the value that one method returns to the
1355next method: >
Bram Moolenaar25e42232019-08-04 15:04:10 +02001356 mylist->filter(filterexpr)->map(mapexpr)->sort()->join()
1357<
Bram Moolenaar22a0c0c2019-08-09 23:25:08 +02001358Example of using a lambda: >
Bram Moolenaar02b31112019-08-31 22:16:38 +02001359 GetPercentage()->{x -> x * 100}()->printf('%d%%')
Bram Moolenaar56c860c2019-08-17 20:09:31 +02001360<
Bram Moolenaar5da36052021-12-27 15:39:57 +00001361When using -> the |expr8| operators will be applied first, thus: >
Bram Moolenaar93cf85f2019-08-17 21:36:28 +02001362 -1.234->string()
1363Is equivalent to: >
1364 (-1.234)->string()
1365And NOT: >
1366 -(1.234->string())
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001367
1368What comes after "->" can be a name, a simple expression (not containing any
1369parenthesis), or any expression in parenthesis: >
1370 base->name(args)
1371 base->some.name(args)
1372 base->alist[idx](args)
1373 base->(getFuncRef())(args)
1374Note that in the last call the base is passed to the function resulting from
1375"(getFuncRef())", inserted before "args".
1376
Bram Moolenaar51841322019-08-08 21:10:01 +02001377 *E274*
1378"->name(" must not contain white space. There can be white space before the
1379"->" and after the "(", thus you can split the lines like this: >
1380 mylist
1381 \ ->filter(filterexpr)
1382 \ ->map(mapexpr)
1383 \ ->sort()
1384 \ ->join()
Bram Moolenaar56c860c2019-08-17 20:09:31 +02001385
1386When using the lambda form there must be no white space between the } and the
1387(.
1388
Bram Moolenaar25e42232019-08-04 15:04:10 +02001389
Bram Moolenaar5da36052021-12-27 15:39:57 +00001390 *expr10*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391number
1392------
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01001393number number constant *expr-number*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394
Bram Moolenaar6f02b002021-01-10 20:22:54 +01001395 *0x* *hex-number* *0o* *octal-number* *binary-number*
Bram Moolenaar7571d552016-08-18 22:54:46 +02001396Decimal, Hexadecimal (starting with 0x or 0X), Binary (starting with 0b or 0B)
Bram Moolenaarc17e66c2020-06-02 21:38:22 +02001397and Octal (starting with 0, 0o or 0O).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398
Bram Moolenaar446cb832008-06-24 21:56:24 +00001399 *floating-point-format*
1400Floating point numbers can be written in two forms:
1401
1402 [-+]{N}.{M}
Bram Moolenaar8a94d872015-01-25 13:02:57 +01001403 [-+]{N}.{M}[eE][-+]{exp}
Bram Moolenaar446cb832008-06-24 21:56:24 +00001404
1405{N} and {M} are numbers. Both {N} and {M} must be present and can only
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001406contain digits, except that in |Vim9| script in {N} single quotes between
1407digits are ignored.
Bram Moolenaar446cb832008-06-24 21:56:24 +00001408[-+] means there is an optional plus or minus sign.
1409{exp} is the exponent, power of 10.
Bram Moolenaar58b85342016-08-14 19:54:54 +02001410Only a decimal point is accepted, not a comma. No matter what the current
Bram Moolenaar446cb832008-06-24 21:56:24 +00001411locale is.
1412{only when compiled with the |+float| feature}
1413
1414Examples:
1415 123.456
1416 +0.0001
1417 55.0
1418 -0.123
1419 1.234e03
1420 1.0E-6
1421 -3.1416e+88
1422
1423These are INVALID:
1424 3. empty {M}
1425 1e40 missing .{M}
1426
1427Rationale:
1428Before floating point was introduced, the text "123.456" was interpreted as
1429the two numbers "123" and "456", both converted to a string and concatenated,
1430resulting in the string "123456". Since this was considered pointless, and we
Bram Moolenaare37d50a2008-08-06 17:06:04 +00001431could not find it intentionally being used in Vim scripts, this backwards
Bram Moolenaar446cb832008-06-24 21:56:24 +00001432incompatibility was accepted in favor of being able to use the normal notation
1433for floating point numbers.
1434
Bram Moolenaard47d5222018-12-09 20:43:55 +01001435 *float-pi* *float-e*
1436A few useful values to copy&paste: >
1437 :let pi = 3.14159265359
1438 :let e = 2.71828182846
1439Or, if you don't want to write them in as floating-point literals, you can
1440also use functions, like the following: >
1441 :let pi = acos(-1.0)
1442 :let e = exp(1.0)
Bram Moolenaar98aefe72018-12-13 22:20:09 +01001443<
Bram Moolenaar446cb832008-06-24 21:56:24 +00001444 *floating-point-precision*
1445The precision and range of floating points numbers depends on what "double"
1446means in the library Vim was compiled with. There is no way to change this at
1447runtime.
1448
1449The default for displaying a |Float| is to use 6 decimal places, like using
1450printf("%g", f). You can select something else when using the |printf()|
1451function. Example: >
1452 :echo printf('%.15e', atan(1))
1453< 7.853981633974483e-01
1454
1455
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456
Bram Moolenaar979243b2015-06-26 19:35:49 +02001457string *string* *String* *expr-string* *E114*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458------
1459"string" string constant *expr-quote*
1460
1461Note that double quotes are used.
1462
1463A string constant accepts these special characters:
1464\... three-digit octal number (e.g., "\316")
1465\.. two-digit octal number (must be followed by non-digit)
1466\. one-digit octal number (must be followed by non-digit)
1467\x.. byte specified with two hex numbers (e.g., "\x1f")
1468\x. byte specified with one hex number (must be followed by non-hex char)
1469\X.. same as \x..
1470\X. same as \x.
Bram Moolenaar446cb832008-06-24 21:56:24 +00001471\u.... character specified with up to 4 hex numbers, stored according to the
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 current value of 'encoding' (e.g., "\u02a4")
Bram Moolenaar541f92d2015-06-19 13:27:23 +02001473\U.... same as \u but allows up to 8 hex numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474\b backspace <BS>
1475\e escape <Esc>
Bram Moolenaar6e649222021-10-04 21:32:54 +01001476\f formfeed 0x0C
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477\n newline <NL>
1478\r return <CR>
1479\t tab <Tab>
1480\\ backslash
1481\" double quote
Bram Moolenaar00a927d2010-05-14 23:24:24 +02001482\<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W. This is for use
Bram Moolenaar58b85342016-08-14 19:54:54 +02001483 in mappings, the 0x80 byte is escaped.
1484 To use the double quote character it must be escaped: "<M-\">".
Bram Moolenaar6e649222021-10-04 21:32:54 +01001485 Don't use <Char-xxxx> to get a UTF-8 character, use \uxxxx as
Bram Moolenaar58b85342016-08-14 19:54:54 +02001486 mentioned above.
Bram Moolenaarfccd93f2020-05-31 22:06:51 +02001487\<*xxx> Like \<xxx> but prepends a modifier instead of including it in the
1488 character. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is four
Bram Moolenaarebe9d342020-05-30 21:52:54 +02001489 bytes: 3 for the CTRL modifier and then character "W".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001491Note that "\xff" is stored as the byte 255, which may be invalid in some
1492encodings. Use "\u00ff" to store character 255 according to the current value
1493of 'encoding'.
1494
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495Note that "\000" and "\x00" force the end of the string.
1496
1497
Bram Moolenaard8968242019-01-15 22:51:57 +01001498blob-literal *blob-literal* *E973*
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01001499------------
1500
1501Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes.
1502The sequence must be an even number of hex characters. Example: >
1503 :let b = 0zFF00ED015DAF
1504
1505
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506literal-string *literal-string* *E115*
1507---------------
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001508'string' string constant *expr-'*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509
1510Note that single quotes are used.
1511
Bram Moolenaar58b85342016-08-14 19:54:54 +02001512This string is taken as it is. No backslashes are removed or have a special
Bram Moolenaard8b02732005-01-14 21:48:43 +00001513meaning. The only exception is that two quotes stand for one quote.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001514
1515Single quoted strings are useful for patterns, so that backslashes do not need
Bram Moolenaar58b85342016-08-14 19:54:54 +02001516to be doubled. These two commands are equivalent: >
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001517 if a =~ "\\s*"
1518 if a =~ '\s*'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519
1520
1521option *expr-option* *E112* *E113*
1522------
1523&option option value, local value if possible
1524&g:option global option value
1525&l:option local option value
1526
1527Examples: >
1528 echo "tabstop is " . &tabstop
1529 if &insertmode
1530
1531Any option name can be used here. See |options|. When using the local value
1532and there is no buffer-local or window-local value, the global value is used
1533anyway.
1534
1535
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001536register *expr-register* *@r*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537--------
1538@r contents of register 'r'
1539
1540The result is the contents of the named register, as a single string.
1541Newlines are inserted where required. To get the contents of the unnamed
Bram Moolenaar58b85342016-08-14 19:54:54 +02001542register use @" or @@. See |registers| for an explanation of the available
Bram Moolenaare7566042005-06-17 22:00:15 +00001543registers.
1544
1545When using the '=' register you get the expression itself, not what it
1546evaluates to. Use |eval()| to evaluate it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547
1548
1549nesting *expr-nesting* *E110*
1550-------
1551(expr1) nested expression
1552
1553
1554environment variable *expr-env*
1555--------------------
1556$VAR environment variable
1557
1558The String value of any environment variable. When it is not defined, the
1559result is an empty string.
Bram Moolenaar691ddee2019-05-09 14:52:41 +02001560
1561The functions `getenv()` and `setenv()` can also be used and work for
1562environment variables with non-alphanumeric names.
1563The function `environ()` can be used to get a Dict with all environment
1564variables.
1565
1566
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 *expr-env-expand*
1568Note that there is a difference between using $VAR directly and using
1569expand("$VAR"). Using it directly will only expand environment variables that
1570are known inside the current Vim session. Using expand() will first try using
1571the environment variables known inside the current Vim session. If that
1572fails, a shell will be used to expand the variable. This can be slow, but it
1573does expand all variables that the shell knows about. Example: >
Bram Moolenaar34401cc2014-08-29 15:12:19 +02001574 :echo $shell
1575 :echo expand("$shell")
1576The first one probably doesn't echo anything, the second echoes the $shell
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577variable (if your shell supports it).
1578
1579
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001580internal variable *expr-variable* *E1015*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581-----------------
1582variable internal variable
1583See below |internal-variables|.
1584
1585
Bram Moolenaar05159a02005-02-26 23:04:13 +00001586function call *expr-function* *E116* *E118* *E119* *E120*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587-------------
1588function(expr1, ...) function call
1589See below |functions|.
1590
1591
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001592lambda expression *expr-lambda* *lambda*
1593-----------------
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001594{args -> expr1} legacy lambda expression *E451*
Bram Moolenaar5da36052021-12-27 15:39:57 +00001595(args) => expr1 |Vim9| lambda expression
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001596
1597A lambda expression creates a new unnamed function which returns the result of
Bram Moolenaar42ebd062016-07-17 13:35:14 +02001598evaluating |expr1|. Lambda expressions differ from |user-functions| in
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001599the following ways:
1600
16011. The body of the lambda expression is an |expr1| and not a sequence of |Ex|
1602 commands.
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +020016032. The prefix "a:" should not be used for arguments. E.g.: >
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001604 :let F = {arg1, arg2 -> arg1 - arg2}
1605 :echo F(5, 2)
1606< 3
1607
1608The arguments are optional. Example: >
1609 :let F = {-> 'error function'}
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001610 :echo F('ignored')
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001611< error function
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001612
Bram Moolenaar5da36052021-12-27 15:39:57 +00001613The |Vim9| lambda does not only use a different syntax, it also adds type
1614checking and can be split over multiple lines, see |vim9-lambda|.
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001615
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001616 *closure*
1617Lambda expressions can access outer scope variables and arguments. This is
Bram Moolenaar50ba5262016-09-22 22:33:02 +02001618often called a closure. Example where "i" and "a:arg" are used in a lambda
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01001619while they already exist in the function scope. They remain valid even after
1620the function returns: >
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001621 :function Foo(arg)
1622 : let i = 3
1623 : return {x -> x + i - a:arg}
1624 :endfunction
1625 :let Bar = Foo(4)
1626 :echo Bar(6)
1627< 5
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001628
Bram Moolenaar388a5d42020-05-26 21:20:45 +02001629Note that the variables must exist in the outer scope before the lambda is
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01001630defined for this to work. See also |:func-closure|.
1631
1632Lambda and closure support can be checked with: >
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001633 if has('lambda')
Bram Moolenaar069c1e72016-07-15 21:25:08 +02001634
1635Examples for using a lambda expression with |sort()|, |map()| and |filter()|: >
1636 :echo map([1, 2, 3], {idx, val -> val + 1})
1637< [2, 3, 4] >
1638 :echo sort([3,7,2,1,4], {a, b -> a - b})
1639< [1, 2, 3, 4, 7]
1640
1641The lambda expression is also useful for Channel, Job and timer: >
1642 :let timer = timer_start(500,
1643 \ {-> execute("echo 'Handler called'", "")},
1644 \ {'repeat': 3})
1645< Handler called
1646 Handler called
1647 Handler called
1648
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001649Note that it is possible to cause memory to be used and not freed if the
1650closure is referenced by the context it depends on: >
1651 function Function()
1652 let x = 0
1653 let F = {-> x}
1654 endfunction
1655The closure uses "x" from the function scope, and "F" in that same scope
1656refers to the closure. This cycle results in the memory not being freed.
1657Recommendation: don't do this.
1658
1659Notice how execute() is used to execute an Ex command. That's ugly though.
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001660In Vim9 script you can use a command block, see |inline-function|.
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001661
1662Lambda expressions have internal names like '<lambda>42'. If you get an error
1663for a lambda expression, you can find what it is with the following command: >
Bram Moolenaar6f02b002021-01-10 20:22:54 +01001664 :function <lambda>42
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001665See also: |numbered-function|
1666
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667==============================================================================
Bram Moolenaar6f4754b2022-01-23 12:07:04 +000016683. Internal variable *internal-variables* *E461* *E1001*
Bram Moolenaar4a748032010-09-30 21:47:56 +02001669
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670An internal variable name can be made up of letters, digits and '_'. But it
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001671cannot start with a digit. In legacy script it is also possible to use curly
Bram Moolenaar5da36052021-12-27 15:39:57 +00001672braces, see |curly-braces-names|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001674In legacy script an internal variable is created with the ":let" command
Bram Moolenaar5da36052021-12-27 15:39:57 +00001675|:let|. An internal variable is explicitly destroyed with the ":unlet"
1676command |:unlet|.
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00001677Using a name that is not an internal variable or refers to a variable that has
1678been destroyed results in an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
Bram Moolenaar5da36052021-12-27 15:39:57 +00001680In |Vim9| script `:let` is not used and variables work differently, see |:var|.
1681
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001682 *variable-scope*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683There are several name spaces for variables. Which one is to be used is
1684specified by what is prepended:
1685
Bram Moolenaar5da36052021-12-27 15:39:57 +00001686 (nothing) In a function: local to the function;
1687 in a legacy script: global;
1688 in a |Vim9| script: local to the script
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689|buffer-variable| b: Local to the current buffer.
1690|window-variable| w: Local to the current window.
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001691|tabpage-variable| t: Local to the current tab page.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692|global-variable| g: Global.
Bram Moolenaar5da36052021-12-27 15:39:57 +00001693|local-variable| l: Local to a function (only in a legacy function)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694|script-variable| s: Local to a |:source|'ed Vim script.
Bram Moolenaar5da36052021-12-27 15:39:57 +00001695|function-argument| a: Function argument (only in a legacy function).
Bram Moolenaar75b81562014-04-06 14:09:13 +02001696|vim-variable| v: Global, predefined by Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697
Bram Moolenaar32466aa2006-02-24 23:53:04 +00001698The scope name by itself can be used as a |Dictionary|. For example, to
1699delete all script-local variables: >
Bram Moolenaar8f999f12005-01-25 22:12:55 +00001700 :for k in keys(s:)
1701 : unlet s:[k]
1702 :endfor
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001703
Bram Moolenaar5da36052021-12-27 15:39:57 +00001704Note: in Vim9 script variables can also be local to a block of commands, see
1705|vim9-scopes|.
Bram Moolenaar531da592013-05-06 05:58:55 +02001706 *buffer-variable* *b:var* *b:*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707A variable name that is preceded with "b:" is local to the current buffer.
1708Thus you can have several "b:foo" variables, one for each buffer.
1709This kind of variable is deleted when the buffer is wiped out or deleted with
1710|:bdelete|.
1711
1712One local buffer variable is predefined:
Bram Moolenaarbf884932013-04-05 22:26:15 +02001713 *b:changedtick* *changetick*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714b:changedtick The total number of changes to the current buffer. It is
1715 incremented for each change. An undo command is also a change
Bram Moolenaarc024b462019-06-08 18:07:21 +02001716 in this case. Resetting 'modified' when writing the buffer is
1717 also counted.
1718 This can be used to perform an action only when the buffer has
1719 changed. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 :if my_changedtick != b:changedtick
Bram Moolenaar446cb832008-06-24 21:56:24 +00001721 : let my_changedtick = b:changedtick
1722 : call My_Update()
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 :endif
Bram Moolenaar3df01732017-02-17 22:47:16 +01001724< You cannot change or delete the b:changedtick variable.
1725
Bram Moolenaar531da592013-05-06 05:58:55 +02001726 *window-variable* *w:var* *w:*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727A variable name that is preceded with "w:" is local to the current window. It
1728is deleted when the window is closed.
1729
Bram Moolenaarad3b3662013-05-17 18:14:19 +02001730 *tabpage-variable* *t:var* *t:*
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001731A variable name that is preceded with "t:" is local to the current tab page,
1732It is deleted when the tab page is closed. {not available when compiled
Bram Moolenaardb84e452010-08-15 13:50:43 +02001733without the |+windows| feature}
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001734
Bram Moolenaar531da592013-05-06 05:58:55 +02001735 *global-variable* *g:var* *g:*
Bram Moolenaar04fb9162021-12-30 20:24:12 +00001736Inside functions and in |Vim9| script global variables are accessed with "g:".
1737Omitting this will access a variable local to a function or script. "g:"
1738can also be used in any other place if you like.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739
Bram Moolenaar531da592013-05-06 05:58:55 +02001740 *local-variable* *l:var* *l:*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741Inside functions local variables are accessed without prepending anything.
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001742But you can also prepend "l:" if you like. However, without prepending "l:"
1743you may run into reserved variable names. For example "count". By itself it
1744refers to "v:count". Using "l:count" you can have a local variable with the
1745same name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746
1747 *script-variable* *s:var*
Bram Moolenaar04fb9162021-12-30 20:24:12 +00001748In a legacy Vim script variables starting with "s:" can be used. They cannot
1749be accessed from outside of the scripts, thus are local to the script.
1750In |Vim9| script the "s:" prefix can be omitted, variables are script-local by
1751default.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752
1753They can be used in:
1754- commands executed while the script is sourced
1755- functions defined in the script
1756- autocommands defined in the script
1757- functions and autocommands defined in functions and autocommands which were
1758 defined in the script (recursively)
1759- user defined commands defined in the script
1760Thus not in:
1761- other scripts sourced from this one
1762- mappings
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01001763- menus
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764- etc.
1765
Bram Moolenaaref2f6562007-05-06 13:32:59 +00001766Script variables can be used to avoid conflicts with global variable names.
1767Take this example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768
1769 let s:counter = 0
1770 function MyCounter()
1771 let s:counter = s:counter + 1
1772 echo s:counter
1773 endfunction
1774 command Tick call MyCounter()
1775
1776You can now invoke "Tick" from any script, and the "s:counter" variable in
1777that script will not be changed, only the "s:counter" in the script where
1778"Tick" was defined is used.
1779
1780Another example that does the same: >
1781
1782 let s:counter = 0
1783 command Tick let s:counter = s:counter + 1 | echo s:counter
1784
1785When calling a function and invoking a user-defined command, the context for
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001786script variables is set to the script where the function or command was
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787defined.
1788
1789The script variables are also available when a function is defined inside a
1790function that is defined in a script. Example: >
1791
1792 let s:counter = 0
1793 function StartCounting(incr)
1794 if a:incr
1795 function MyCounter()
1796 let s:counter = s:counter + 1
1797 endfunction
1798 else
1799 function MyCounter()
1800 let s:counter = s:counter - 1
1801 endfunction
1802 endif
1803 endfunction
1804
1805This defines the MyCounter() function either for counting up or counting down
1806when calling StartCounting(). It doesn't matter from where StartCounting() is
1807called, the s:counter variable will be accessible in MyCounter().
1808
1809When the same script is sourced again it will use the same script variables.
1810They will remain valid as long as Vim is running. This can be used to
1811maintain a counter: >
1812
1813 if !exists("s:counter")
1814 let s:counter = 1
1815 echo "script executed for the first time"
1816 else
1817 let s:counter = s:counter + 1
1818 echo "script executed " . s:counter . " times now"
1819 endif
1820
1821Note that this means that filetype plugins don't get a different set of script
1822variables for each buffer. Use local buffer variables instead |b:var|.
1823
1824
Bram Moolenaard47d5222018-12-09 20:43:55 +01001825PREDEFINED VIM VARIABLES *vim-variable* *v:var* *v:*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001826 *E963* *E1063*
Bram Moolenaard47d5222018-12-09 20:43:55 +01001827Some variables can be set by the user, but the type cannot be changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828
Bram Moolenaar69bf6342019-10-29 04:16:57 +01001829 *v:argv* *argv-variable*
1830v:argv The command line arguments Vim was invoked with. This is a
1831 list of strings. The first item is the Vim command.
1832
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001833 *v:beval_col* *beval_col-variable*
1834v:beval_col The number of the column, over which the mouse pointer is.
1835 This is the byte index in the |v:beval_lnum| line.
1836 Only valid while evaluating the 'balloonexpr' option.
1837
1838 *v:beval_bufnr* *beval_bufnr-variable*
1839v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
1840 valid while evaluating the 'balloonexpr' option.
1841
1842 *v:beval_lnum* *beval_lnum-variable*
1843v:beval_lnum The number of the line, over which the mouse pointer is. Only
1844 valid while evaluating the 'balloonexpr' option.
1845
1846 *v:beval_text* *beval_text-variable*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001847v:beval_text The text under or after the mouse pointer. Usually a word as
1848 it is useful for debugging a C program. 'iskeyword' applies,
1849 but a dot and "->" before the position is included. When on a
1850 ']' the text before it is used, including the matching '[' and
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001851 word before it. When on a Visual area within one line the
Bram Moolenaarb4d5fba2017-09-11 19:31:28 +02001852 highlighted text is used. Also see |<cexpr>|.
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001853 Only valid while evaluating the 'balloonexpr' option.
1854
1855 *v:beval_winnr* *beval_winnr-variable*
1856v:beval_winnr The number of the window, over which the mouse pointer is. Only
Bram Moolenaar00654022011-02-25 14:42:19 +01001857 valid while evaluating the 'balloonexpr' option. The first
1858 window has number zero (unlike most other places where a
1859 window gets a number).
Bram Moolenaare4efc3b2005-03-07 23:16:51 +00001860
Bram Moolenaar511972d2016-06-04 18:09:59 +02001861 *v:beval_winid* *beval_winid-variable*
Bram Moolenaar7571d552016-08-18 22:54:46 +02001862v:beval_winid The |window-ID| of the window, over which the mouse pointer
1863 is. Otherwise like v:beval_winnr.
Bram Moolenaar511972d2016-06-04 18:09:59 +02001864
Bram Moolenaarf193fff2006-04-27 00:02:13 +00001865 *v:char* *char-variable*
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01001866v:char Argument for evaluating 'formatexpr' and used for the typed
Bram Moolenaar945e2db2010-06-05 17:43:32 +02001867 character when using <expr> in an abbreviation |:map-<expr>|.
Bram Moolenaare6ae6222013-05-21 21:01:10 +02001868 It is also used by the |InsertCharPre| and |InsertEnter| events.
Bram Moolenaarf193fff2006-04-27 00:02:13 +00001869
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 *v:charconvert_from* *charconvert_from-variable*
1871v:charconvert_from
1872 The name of the character encoding of a file to be converted.
1873 Only valid while evaluating the 'charconvert' option.
1874
1875 *v:charconvert_to* *charconvert_to-variable*
1876v:charconvert_to
1877 The name of the character encoding of a file after conversion.
1878 Only valid while evaluating the 'charconvert' option.
1879
1880 *v:cmdarg* *cmdarg-variable*
1881v:cmdarg This variable is used for two purposes:
1882 1. The extra arguments given to a file read/write command.
1883 Currently these are "++enc=" and "++ff=". This variable is
1884 set before an autocommand event for a file read/write
1885 command is triggered. There is a leading space to make it
1886 possible to append this variable directly after the
Bram Moolenaar58b85342016-08-14 19:54:54 +02001887 read/write command. Note: The "+cmd" argument isn't
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888 included here, because it will be executed anyway.
1889 2. When printing a PostScript file with ":hardcopy" this is
1890 the argument for the ":hardcopy" command. This can be used
1891 in 'printexpr'.
1892
1893 *v:cmdbang* *cmdbang-variable*
1894v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
1895 was used the value is 1, otherwise it is 0. Note that this
1896 can only be used in autocommands. For user commands |<bang>|
1897 can be used.
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001898 *v:collate* *collate-variable*
1899v:collate The current locale setting for collation order of the runtime
1900 environment. This allows Vim scripts to be aware of the
1901 current locale encoding. Technical: it's the value of
1902 LC_COLLATE. When not using a locale the value is "C".
1903 This variable can not be set directly, use the |:language|
1904 command.
1905 See |multi-lang|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906
Drew Vogele30d1022021-10-24 20:35:07 +01001907 *v:colornames*
1908v:colornames A dictionary that maps color names to hex color strings. These
1909 color names can be used with the |highlight-guifg|,
1910 |highlight-guibg|, and |highlight-guisp| parameters. Updating
1911 an entry in v:colornames has no immediate effect on the syntax
1912 highlighting. The highlight commands (probably in a
1913 colorscheme script) need to be re-evaluated in order to use
1914 the updated color values. For example: >
1915
1916 :let v:colornames['fuscia'] = '#cf3ab4'
1917 :let v:colornames['mauve'] = '#915f6d'
1918 :highlight Normal guifg=fuscia guibg=mauve
1919<
1920 This cannot be used to override the |cterm-colors| but it can
1921 be used to override other colors. For example, the X11 colors
1922 defined in the `colors/lists/default.vim` (previously defined
1923 in |rgb.txt|). When defining new color names in a plugin, the
1924 recommended practice is to set a color entry only when it does
1925 not already exist. For example: >
1926
1927 :call extend(v:colornames, {
1928 \ 'fuscia': '#cf3ab4',
1929 \ 'mauve': '#915f6d,
1930 \ }, 'keep')
1931<
Bram Moolenaar113cb512021-11-07 20:27:04 +00001932 Using |extend()| with the 'keep' option updates each color only
Drew Vogele30d1022021-10-24 20:35:07 +01001933 if it did not exist in |v:colornames|. Doing so allows the
1934 user to choose the precise color value for a common name
1935 by setting it in their |.vimrc|.
1936
1937 It is possible to remove entries from this dictionary but
Drew Vogela0fca172021-11-13 10:50:01 +00001938 doing so is NOT recommended, because it is disruptive to
Drew Vogele30d1022021-10-24 20:35:07 +01001939 other scripts. It is also unlikely to achieve the desired
Bram Moolenaar113cb512021-11-07 20:27:04 +00001940 result because the |:colorscheme| and |:highlight| commands will
Drew Vogele30d1022021-10-24 20:35:07 +01001941 both automatically load all `colors/lists/default.vim` color
1942 scripts.
1943
Bram Moolenaar42a45122015-07-10 17:56:23 +02001944 *v:completed_item* *completed_item-variable*
1945v:completed_item
1946 |Dictionary| containing the |complete-items| for the most
1947 recently completed word after |CompleteDone|. The
1948 |Dictionary| is empty if the completion failed.
1949
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 *v:count* *count-variable*
1951v:count The count given for the last Normal mode command. Can be used
Bram Moolenaar58b85342016-08-14 19:54:54 +02001952 to get the count before a mapping. Read-only. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 :map _x :<C-U>echo "the count is " . v:count<CR>
1954< Note: The <C-U> is required to remove the line range that you
1955 get when typing ':' after a count.
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01001956 When there are two counts, as in "3d2w", they are multiplied,
1957 just like what happens in the command, "d6w" for the example.
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +00001958 Also used for evaluating the 'formatexpr' option.
Bram Moolenaard2e716e2019-04-20 14:39:52 +02001959 "count" also works, for backwards compatibility, unless
1960 |scriptversion| is 3 or higher.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961
1962 *v:count1* *count1-variable*
1963v:count1 Just like "v:count", but defaults to one when no count is
1964 used.
1965
1966 *v:ctype* *ctype-variable*
1967v:ctype The current locale setting for characters of the runtime
1968 environment. This allows Vim scripts to be aware of the
1969 current locale encoding. Technical: it's the value of
1970 LC_CTYPE. When not using a locale the value is "C".
1971 This variable can not be set directly, use the |:language|
1972 command.
1973 See |multi-lang|.
1974
1975 *v:dying* *dying-variable*
Bram Moolenaar58b85342016-08-14 19:54:54 +02001976v:dying Normally zero. When a deadly signal is caught it's set to
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 one. When multiple signals are caught the number increases.
1978 Can be used in an autocommand to check if Vim didn't
1979 terminate normally. {only works on Unix}
1980 Example: >
1981 :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
Bram Moolenaar0e1e25f2010-05-28 21:07:08 +02001982< Note: if another deadly signal is caught when v:dying is one,
1983 VimLeave autocommands will not be executed.
1984
Bram Moolenaarf0068c52020-11-30 17:42:10 +01001985 *v:exiting* *exiting-variable*
1986v:exiting Vim exit code. Normally zero, non-zero when something went
1987 wrong. The value is v:null before invoking the |VimLeavePre|
1988 and |VimLeave| autocmds. See |:q|, |:x| and |:cquit|.
1989 Example: >
1990 :au VimLeave * echo "Exit value is " .. v:exiting
1991<
Bram Moolenaar37f4cbd2019-08-23 20:58:45 +02001992 *v:echospace* *echospace-variable*
1993v:echospace Number of screen cells that can be used for an `:echo` message
1994 in the last screen line before causing the |hit-enter-prompt|.
1995 Depends on 'showcmd', 'ruler' and 'columns'. You need to
1996 check 'cmdheight' for whether there are full-width lines
1997 available above the last line.
1998
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999 *v:errmsg* *errmsg-variable*
2000v:errmsg Last given error message. It's allowed to set this variable.
2001 Example: >
2002 :let v:errmsg = ""
2003 :silent! next
2004 :if v:errmsg != ""
2005 : ... handle error
Bram Moolenaard2e716e2019-04-20 14:39:52 +02002006< "errmsg" also works, for backwards compatibility, unless
2007 |scriptversion| is 3 or higher.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008
Bram Moolenaar65a54642018-04-28 16:56:53 +02002009 *v:errors* *errors-variable* *assert-return*
Bram Moolenaar683fa182015-11-30 21:38:24 +01002010v:errors Errors found by assert functions, such as |assert_true()|.
Bram Moolenaar43345542015-11-29 17:35:35 +01002011 This is a list of strings.
2012 The assert functions append an item when an assert fails.
Bram Moolenaar65a54642018-04-28 16:56:53 +02002013 The return value indicates this: a one is returned if an item
2014 was added to v:errors, otherwise zero is returned.
Bram Moolenaar43345542015-11-29 17:35:35 +01002015 To remove old results make it empty: >
2016 :let v:errors = []
2017< If v:errors is set to anything but a list it is made an empty
2018 list by the assert function.
2019
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01002020 *v:event* *event-variable*
2021v:event Dictionary containing information about the current
Bram Moolenaar560979e2020-02-04 22:53:05 +01002022 |autocommand|. See the specific event for what it puts in
2023 this dictionary.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02002024 The dictionary is emptied when the |autocommand| finishes,
2025 please refer to |dict-identity| for how to get an independent
2026 copy of it. Use |deepcopy()| if you want to keep the
2027 information after the event triggers. Example: >
2028 au TextYankPost * let g:foo = deepcopy(v:event)
2029<
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 *v:exception* *exception-variable*
2031v:exception The value of the exception most recently caught and not
2032 finished. See also |v:throwpoint| and |throw-variables|.
2033 Example: >
2034 :try
2035 : throw "oops"
2036 :catch /.*/
Bram Moolenaar54775062019-07-31 21:07:14 +02002037 : echo "caught " .. v:exception
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038 :endtry
2039< Output: "caught oops".
2040
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002041 *v:false* *false-variable*
2042v:false A Number with value zero. Used to put "false" in JSON. See
Bram Moolenaar6463ca22016-02-13 17:04:46 +01002043 |json_encode()|.
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002044 When used as a string this evaluates to "v:false". >
Bram Moolenaar705ada12016-01-24 17:56:50 +01002045 echo v:false
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002046< v:false ~
2047 That is so that eval() can parse the string back to the same
Bram Moolenaardf48fb42016-07-22 21:50:18 +02002048 value. Read-only.
Bram Moolenaar5da36052021-12-27 15:39:57 +00002049 In |Vim9| script "false" can be used which has a boolean type.
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002050
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002051 *v:fcs_reason* *fcs_reason-variable*
2052v:fcs_reason The reason why the |FileChangedShell| event was triggered.
2053 Can be used in an autocommand to decide what to do and/or what
2054 to set v:fcs_choice to. Possible values:
2055 deleted file no longer exists
2056 conflict file contents, mode or timestamp was
2057 changed and buffer is modified
2058 changed file contents has changed
2059 mode mode of file changed
2060 time only file timestamp changed
2061
2062 *v:fcs_choice* *fcs_choice-variable*
2063v:fcs_choice What should happen after a |FileChangedShell| event was
2064 triggered. Can be used in an autocommand to tell Vim what to
2065 do with the affected buffer:
2066 reload Reload the buffer (does not work if
2067 the file was deleted).
2068 ask Ask the user what to do, as if there
2069 was no autocommand. Except that when
2070 only the timestamp changed nothing
2071 will happen.
2072 <empty> Nothing, the autocommand should do
2073 everything that needs to be done.
2074 The default is empty. If another (invalid) value is used then
2075 Vim behaves like it is empty, there is no warning message.
2076
Bram Moolenaar4c295022021-05-02 17:19:11 +02002077 *v:fname* *fname-variable*
Bram Moolenaar90df4b92021-07-07 20:26:08 +02002078v:fname When evaluating 'includeexpr': the file name that was
2079 detected. Empty otherwise.
Bram Moolenaar4c295022021-05-02 17:19:11 +02002080
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 *v:fname_in* *fname_in-variable*
Bram Moolenaar4e330bb2005-12-07 21:04:31 +00002082v:fname_in The name of the input file. Valid while evaluating:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 option used for ~
2084 'charconvert' file to be converted
2085 'diffexpr' original file
2086 'patchexpr' original file
2087 'printexpr' file to be printed
Bram Moolenaar2c7a29c2005-12-12 22:02:31 +00002088 And set to the swap file name for |SwapExists|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089
2090 *v:fname_out* *fname_out-variable*
2091v:fname_out The name of the output file. Only valid while
2092 evaluating:
2093 option used for ~
2094 'charconvert' resulting converted file (*)
2095 'diffexpr' output of diff
2096 'patchexpr' resulting patched file
2097 (*) When doing conversion for a write command (e.g., ":w
Bram Moolenaar58b85342016-08-14 19:54:54 +02002098 file") it will be equal to v:fname_in. When doing conversion
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 for a read command (e.g., ":e file") it will be a temporary
2100 file and different from v:fname_in.
2101
2102 *v:fname_new* *fname_new-variable*
2103v:fname_new The name of the new version of the file. Only valid while
2104 evaluating 'diffexpr'.
2105
2106 *v:fname_diff* *fname_diff-variable*
2107v:fname_diff The name of the diff (patch) file. Only valid while
2108 evaluating 'patchexpr'.
2109
2110 *v:folddashes* *folddashes-variable*
2111v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
2112 fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002113 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114
2115 *v:foldlevel* *foldlevel-variable*
2116v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002117 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118
2119 *v:foldend* *foldend-variable*
2120v:foldend Used for 'foldtext': last line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002121 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122
2123 *v:foldstart* *foldstart-variable*
2124v:foldstart Used for 'foldtext': first line of closed fold.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00002125 Read-only in the |sandbox|. |fold-foldtext|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126
Bram Moolenaar817a8802013-11-09 01:44:43 +01002127 *v:hlsearch* *hlsearch-variable*
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01002128v:hlsearch Variable that indicates whether search highlighting is on.
Bram Moolenaar76440e22014-11-27 19:14:49 +01002129 Setting it makes sense only if 'hlsearch' is enabled which
2130 requires |+extra_search|. Setting this variable to zero acts
Bram Moolenaar705ada12016-01-24 17:56:50 +01002131 like the |:nohlsearch| command, setting it to one acts like >
Bram Moolenaar817a8802013-11-09 01:44:43 +01002132 let &hlsearch = &hlsearch
Bram Moolenaar86ae7202015-07-10 19:31:35 +02002133< Note that the value is restored when returning from a
2134 function. |function-search-undo|.
2135
Bram Moolenaar843ee412004-06-30 16:16:41 +00002136 *v:insertmode* *insertmode-variable*
2137v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
2138 events. Values:
2139 i Insert mode
2140 r Replace mode
2141 v Virtual Replace mode
2142
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002143 *v:key* *key-variable*
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002144v:key Key of the current item of a |Dictionary|. Only valid while
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002145 evaluating the expression used with |map()| and |filter()|.
2146 Read-only.
2147
Bram Moolenaar071d4272004-06-13 20:20:40 +00002148 *v:lang* *lang-variable*
2149v:lang The current locale setting for messages of the runtime
2150 environment. This allows Vim scripts to be aware of the
2151 current language. Technical: it's the value of LC_MESSAGES.
2152 The value is system dependent.
2153 This variable can not be set directly, use the |:language|
2154 command.
2155 It can be different from |v:ctype| when messages are desired
2156 in a different language than what is used for character
2157 encoding. See |multi-lang|.
2158
2159 *v:lc_time* *lc_time-variable*
2160v:lc_time The current locale setting for time messages of the runtime
2161 environment. This allows Vim scripts to be aware of the
2162 current language. Technical: it's the value of LC_TIME.
2163 This variable can not be set directly, use the |:language|
2164 command. See |multi-lang|.
2165
2166 *v:lnum* *lnum-variable*
Bram Moolenaar368373e2010-07-19 20:46:22 +02002167v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and
2168 'indentexpr' expressions, tab page number for 'guitablabel'
2169 and 'guitabtooltip'. Only valid while one of these
2170 expressions is being evaluated. Read-only when in the
2171 |sandbox|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172
naohiro ono56200ee2022-01-01 14:59:44 +00002173 *v:maxcol* *maxcol-variable*
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00002174v:maxcol Maximum line length. Depending on where it is used it can be
2175 screen columns, characters or bytes.
naohiro ono56200ee2022-01-01 14:59:44 +00002176
Bram Moolenaar219b8702006-11-01 14:32:36 +00002177 *v:mouse_win* *mouse_win-variable*
2178v:mouse_win Window number for a mouse click obtained with |getchar()|.
2179 First window has number 1, like with |winnr()|. The value is
2180 zero when there was no mouse button click.
2181
Bram Moolenaar511972d2016-06-04 18:09:59 +02002182 *v:mouse_winid* *mouse_winid-variable*
2183v:mouse_winid Window ID for a mouse click obtained with |getchar()|.
2184 The value is zero when there was no mouse button click.
2185
Bram Moolenaar219b8702006-11-01 14:32:36 +00002186 *v:mouse_lnum* *mouse_lnum-variable*
2187v:mouse_lnum Line number for a mouse click obtained with |getchar()|.
2188 This is the text line number, not the screen line number. The
2189 value is zero when there was no mouse button click.
2190
2191 *v:mouse_col* *mouse_col-variable*
2192v:mouse_col Column number for a mouse click obtained with |getchar()|.
2193 This is the screen column number, like with |virtcol()|. The
2194 value is zero when there was no mouse button click.
2195
Bram Moolenaard09091d2019-01-17 16:07:22 +01002196 *v:none* *none-variable* *None*
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002197v:none An empty String. Used to put an empty item in JSON. See
Bram Moolenaar6463ca22016-02-13 17:04:46 +01002198 |json_encode()|.
Bram Moolenaar2547aa92020-07-26 17:00:44 +02002199 This can also be used as a function argument to use the
2200 default value, see |none-function_argument|.
Bram Moolenaar705ada12016-01-24 17:56:50 +01002201 When used as a number this evaluates to zero.
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002202 When used as a string this evaluates to "v:none". >
Bram Moolenaar705ada12016-01-24 17:56:50 +01002203 echo v:none
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002204< v:none ~
2205 That is so that eval() can parse the string back to the same
Bram Moolenaardf48fb42016-07-22 21:50:18 +02002206 value. Read-only.
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002207
2208 *v:null* *null-variable*
2209v:null An empty String. Used to put "null" in JSON. See
Bram Moolenaar6463ca22016-02-13 17:04:46 +01002210 |json_encode()|.
Bram Moolenaar705ada12016-01-24 17:56:50 +01002211 When used as a number this evaluates to zero.
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002212 When used as a string this evaluates to "v:null". >
Bram Moolenaar705ada12016-01-24 17:56:50 +01002213 echo v:null
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002214< v:null ~
2215 That is so that eval() can parse the string back to the same
Bram Moolenaardf48fb42016-07-22 21:50:18 +02002216 value. Read-only.
Bram Moolenaar5da36052021-12-27 15:39:57 +00002217 In |Vim9| script "null" can be used without "v:".
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002218
Bram Moolenaar57d5a012021-01-21 21:42:31 +01002219 *v:numbermax* *numbermax-variable*
2220v:numbermax Maximum value of a number.
2221
Bram Moolenaare0e39172021-01-25 21:14:57 +01002222 *v:numbermin* *numbermin-variable*
Bram Moolenaar2346a632021-06-13 19:02:49 +02002223v:numbermin Minimum value of a number (negative).
Bram Moolenaar57d5a012021-01-21 21:42:31 +01002224
Bram Moolenaarf9706e92020-02-22 14:27:04 +01002225 *v:numbersize* *numbersize-variable*
2226v:numbersize Number of bits in a Number. This is normally 64, but on some
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01002227 systems it may be 32.
Bram Moolenaarf9706e92020-02-22 14:27:04 +01002228
Bram Moolenaard812df62008-11-09 12:46:09 +00002229 *v:oldfiles* *oldfiles-variable*
2230v:oldfiles List of file names that is loaded from the |viminfo| file on
2231 startup. These are the files that Vim remembers marks for.
2232 The length of the List is limited by the ' argument of the
2233 'viminfo' option (default is 100).
Bram Moolenaar8d043172014-01-23 14:24:41 +01002234 When the |viminfo| file is not used the List is empty.
Bram Moolenaard812df62008-11-09 12:46:09 +00002235 Also see |:oldfiles| and |c_#<|.
2236 The List can be modified, but this has no effect on what is
2237 stored in the |viminfo| file later. If you use values other
2238 than String this will cause trouble.
Bram Moolenaardb84e452010-08-15 13:50:43 +02002239 {only when compiled with the |+viminfo| feature}
Bram Moolenaard812df62008-11-09 12:46:09 +00002240
Bram Moolenaar53744302015-07-17 17:38:22 +02002241 *v:option_new*
2242v:option_new New value of the option. Valid while executing an |OptionSet|
2243 autocommand.
2244 *v:option_old*
2245v:option_old Old value of the option. Valid while executing an |OptionSet|
Bram Moolenaard7c96872019-06-15 17:12:48 +02002246 autocommand. Depending on the command used for setting and the
2247 kind of option this is either the local old value or the
2248 global old value.
2249 *v:option_oldlocal*
2250v:option_oldlocal
2251 Old local value of the option. Valid while executing an
2252 |OptionSet| autocommand.
2253 *v:option_oldglobal*
2254v:option_oldglobal
2255 Old global value of the option. Valid while executing an
2256 |OptionSet| autocommand.
Bram Moolenaar53744302015-07-17 17:38:22 +02002257 *v:option_type*
2258v:option_type Scope of the set command. Valid while executing an
2259 |OptionSet| autocommand. Can be either "global" or "local"
Bram Moolenaard7c96872019-06-15 17:12:48 +02002260 *v:option_command*
2261v:option_command
2262 Command used to set the option. Valid while executing an
2263 |OptionSet| autocommand.
2264 value option was set via ~
2265 "setlocal" |:setlocal| or ":let l:xxx"
2266 "setglobal" |:setglobal| or ":let g:xxx"
2267 "set" |:set| or |:let|
2268 "modeline" |modeline|
Bram Moolenaar8af1fbf2008-01-05 12:35:21 +00002269 *v:operator* *operator-variable*
2270v:operator The last operator given in Normal mode. This is a single
2271 character except for commands starting with <g> or <z>,
2272 in which case it is two characters. Best used alongside
2273 |v:prevcount| and |v:register|. Useful if you want to cancel
2274 Operator-pending mode and then use the operator, e.g.: >
2275 :omap O <Esc>:call MyMotion(v:operator)<CR>
2276< The value remains set until another operator is entered, thus
2277 don't expect it to be empty.
2278 v:operator is not set for |:delete|, |:yank| or other Ex
2279 commands.
2280 Read-only.
2281
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 *v:prevcount* *prevcount-variable*
2283v:prevcount The count given for the last but one Normal mode command.
2284 This is the v:count value of the previous command. Useful if
Bram Moolenaar8af1fbf2008-01-05 12:35:21 +00002285 you want to cancel Visual or Operator-pending mode and then
2286 use the count, e.g.: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
2288< Read-only.
2289
Bram Moolenaar05159a02005-02-26 23:04:13 +00002290 *v:profiling* *profiling-variable*
Bram Moolenaar58b85342016-08-14 19:54:54 +02002291v:profiling Normally zero. Set to one after using ":profile start".
Bram Moolenaar05159a02005-02-26 23:04:13 +00002292 See |profiling|.
2293
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 *v:progname* *progname-variable*
2295v:progname Contains the name (with path removed) with which Vim was
Bram Moolenaard38b0552012-04-25 19:07:41 +02002296 invoked. Allows you to do special initialisations for |view|,
2297 |evim| etc., or any other name you might symlink to Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 Read-only.
2299
Bram Moolenaara1706c92014-04-01 19:55:49 +02002300 *v:progpath* *progpath-variable*
Bram Moolenaar56c860c2019-08-17 20:09:31 +02002301v:progpath Contains the command with which Vim was invoked, in a form
2302 that when passed to the shell will run the same Vim executable
2303 as the current one (if $PATH remains unchanged).
2304 Useful if you want to message a Vim server using a
Bram Moolenaara1706c92014-04-01 19:55:49 +02002305 |--remote-expr|.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002306 To get the full path use: >
2307 echo exepath(v:progpath)
Bram Moolenaar56c860c2019-08-17 20:09:31 +02002308< If the command has a relative path it will be expanded to the
2309 full path, so that it still works after `:cd`. Thus starting
2310 "./vim" results in "/home/user/path/to/vim/src/vim".
2311 On Linux and other systems it will always be the full path.
2312 On Mac it may just be "vim" and using exepath() as mentioned
2313 above should be used to get the full path.
Bram Moolenaar08cab962017-03-04 14:37:18 +01002314 On MS-Windows the executable may be called "vim.exe", but the
2315 ".exe" is not added to v:progpath.
Bram Moolenaara1706c92014-04-01 19:55:49 +02002316 Read-only.
2317
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 *v:register* *register-variable*
Bram Moolenaard58e9292011-02-09 17:07:58 +01002319v:register The name of the register in effect for the current normal mode
Bram Moolenaard38b0552012-04-25 19:07:41 +02002320 command (regardless of whether that command actually used a
2321 register). Or for the currently executing normal mode mapping
2322 (use this in custom commands that take a register).
2323 If none is supplied it is the default register '"', unless
2324 'clipboard' contains "unnamed" or "unnamedplus", then it is
2325 '*' or '+'.
Bram Moolenaard58e9292011-02-09 17:07:58 +01002326 Also see |getreg()| and |setreg()|
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002328 *v:scrollstart* *scrollstart-variable*
2329v:scrollstart String describing the script or function that caused the
2330 screen to scroll up. It's only set when it is empty, thus the
2331 first reason is remembered. It is set to "Unknown" for a
2332 typed command.
2333 This can be used to find out why your script causes the
2334 hit-enter prompt.
2335
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336 *v:servername* *servername-variable*
Bram Moolenaarc2ce52c2017-08-01 18:35:38 +02002337v:servername The resulting registered |client-server-name| if any.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 Read-only.
2339
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01002340
Bram Moolenaar446cb832008-06-24 21:56:24 +00002341v:searchforward *v:searchforward* *searchforward-variable*
2342 Search direction: 1 after a forward search, 0 after a
2343 backward search. It is reset to forward when directly setting
2344 the last search pattern, see |quote/|.
2345 Note that the value is restored when returning from a
2346 function. |function-search-undo|.
2347 Read-write.
2348
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 *v:shell_error* *shell_error-variable*
2350v:shell_error Result of the last shell command. When non-zero, the last
2351 shell command had an error. When zero, there was no problem.
2352 This only works when the shell returns the error code to Vim.
2353 The value -1 is often used when the command could not be
2354 executed. Read-only.
2355 Example: >
2356 :!mv foo bar
2357 :if v:shell_error
2358 : echo 'could not rename "foo" to "bar"!'
2359 :endif
Bram Moolenaard2e716e2019-04-20 14:39:52 +02002360< "shell_error" also works, for backwards compatibility, unless
2361 |scriptversion| is 3 or higher.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362
Bram Moolenaar113cb512021-11-07 20:27:04 +00002363 *v:sizeofint* *sizeofint-variable*
2364v:sizeofint Number of bytes in an int. Depends on how Vim was compiled.
2365 This is only useful for deciding whether a test will give the
2366 expected result.
2367
2368 *v:sizeoflong* *sizeoflong-variable*
2369v:sizeoflong Number of bytes in a long. Depends on how Vim was compiled.
2370 This is only useful for deciding whether a test will give the
2371 expected result.
2372
2373 *v:sizeofpointer* *sizeofpointer-variable*
2374v:sizeofpointer Number of bytes in a pointer. Depends on how Vim was compiled.
2375 This is only useful for deciding whether a test will give the
2376 expected result.
2377
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 *v:statusmsg* *statusmsg-variable*
2379v:statusmsg Last given status message. It's allowed to set this variable.
2380
Bram Moolenaar4e330bb2005-12-07 21:04:31 +00002381 *v:swapname* *swapname-variable*
2382v:swapname Only valid when executing |SwapExists| autocommands: Name of
2383 the swap file found. Read-only.
2384
2385 *v:swapchoice* *swapchoice-variable*
2386v:swapchoice |SwapExists| autocommands can set this to the selected choice
2387 for handling an existing swap file:
2388 'o' Open read-only
2389 'e' Edit anyway
2390 'r' Recover
2391 'd' Delete swapfile
2392 'q' Quit
2393 'a' Abort
Bram Moolenaar58b85342016-08-14 19:54:54 +02002394 The value should be a single-character string. An empty value
Bram Moolenaar4e330bb2005-12-07 21:04:31 +00002395 results in the user being asked, as would happen when there is
2396 no SwapExists autocommand. The default is empty.
2397
Bram Moolenaarb3480382005-12-11 21:33:32 +00002398 *v:swapcommand* *swapcommand-variable*
Bram Moolenaar4770d092006-01-12 23:22:24 +00002399v:swapcommand Normal mode command to be executed after a file has been
Bram Moolenaarb3480382005-12-11 21:33:32 +00002400 opened. Can be used for a |SwapExists| autocommand to have
Bram Moolenaar58b85342016-08-14 19:54:54 +02002401 another Vim open the file and jump to the right place. For
Bram Moolenaarb3480382005-12-11 21:33:32 +00002402 example, when jumping to a tag the value is ":tag tagname\r".
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00002403 For ":edit +cmd file" the value is ":cmd\r".
Bram Moolenaarb3480382005-12-11 21:33:32 +00002404
Bram Moolenaard823fa92016-08-12 16:29:27 +02002405 *v:t_TYPE* *v:t_bool* *t_bool-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002406v:t_bool Value of |Boolean| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002407 *v:t_channel* *t_channel-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002408v:t_channel Value of |Channel| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002409 *v:t_dict* *t_dict-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002410v:t_dict Value of |Dictionary| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002411 *v:t_float* *t_float-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002412v:t_float Value of |Float| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002413 *v:t_func* *t_func-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002414v:t_func Value of |Funcref| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002415 *v:t_job* *t_job-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002416v:t_job Value of |Job| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002417 *v:t_list* *t_list-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002418v:t_list Value of |List| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002419 *v:t_none* *t_none-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002420v:t_none Value of |None| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002421 *v:t_number* *t_number-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002422v:t_number Value of |Number| type. Read-only. See: |type()|
Bram Moolenaard823fa92016-08-12 16:29:27 +02002423 *v:t_string* *t_string-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002424v:t_string Value of |String| type. Read-only. See: |type()|
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01002425 *v:t_blob* *t_blob-variable*
Bram Moolenaard09091d2019-01-17 16:07:22 +01002426v:t_blob Value of |Blob| type. Read-only. See: |type()|
Bram Moolenaarf562e722016-07-19 17:25:25 +02002427
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 *v:termresponse* *termresponse-variable*
2429v:termresponse The escape sequence returned by the terminal for the |t_RV|
Bram Moolenaar58b85342016-08-14 19:54:54 +02002430 termcap entry. It is set when Vim receives an escape sequence
Bram Moolenaarb4230122019-05-30 18:40:53 +02002431 that starts with ESC [ or CSI, then '>' or '?' and ends in a
2432 'c', with only digits and ';' in between.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 When this option is set, the TermResponse autocommand event is
2434 fired, so that you can react to the response from the
Bram Moolenaar0c0eddd2020-06-13 15:47:25 +02002435 terminal. You can use |terminalprops()| to see what Vim
2436 figured out about the terminal.
Bram Moolenaarb4230122019-05-30 18:40:53 +02002437 The response from a new xterm is: "<Esc>[> Pp ; Pv ; Pc c". Pp
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
2439 patch level (since this was introduced in patch 95, it's
Bram Moolenaarfa3b7232021-12-24 13:18:38 +00002440 always 95 or higher). Pc is always zero.
2441 If Pv is 141 or higher then Vim will try to request terminal
2442 codes. This only works with xterm |xterm-codes|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 {only when compiled with |+termresponse| feature}
2444
Bram Moolenaarf3af54e2017-08-30 14:53:06 +02002445 *v:termblinkresp*
2446v:termblinkresp The escape sequence returned by the terminal for the |t_RC|
2447 termcap entry. This is used to find out whether the terminal
2448 cursor is blinking. This is used by |term_getcursor()|.
2449
2450 *v:termstyleresp*
2451v:termstyleresp The escape sequence returned by the terminal for the |t_RS|
2452 termcap entry. This is used to find out what the shape of the
2453 cursor is. This is used by |term_getcursor()|.
2454
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002455 *v:termrbgresp*
2456v:termrbgresp The escape sequence returned by the terminal for the |t_RB|
Bram Moolenaarf3af54e2017-08-30 14:53:06 +02002457 termcap entry. This is used to find out what the terminal
2458 background color is, see 'background'.
2459
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002460 *v:termrfgresp*
2461v:termrfgresp The escape sequence returned by the terminal for the |t_RF|
2462 termcap entry. This is used to find out what the terminal
2463 foreground color is.
2464
Bram Moolenaarf3af54e2017-08-30 14:53:06 +02002465 *v:termu7resp*
2466v:termu7resp The escape sequence returned by the terminal for the |t_u7|
2467 termcap entry. This is used to find out what the terminal
2468 does with ambiguous width characters, see 'ambiwidth'.
2469
Bram Moolenaarebf7dfa2016-04-14 12:46:51 +02002470 *v:testing* *testing-variable*
Bram Moolenaar8e8df252016-05-25 21:23:21 +02002471v:testing Must be set before using `test_garbagecollect_now()`.
Bram Moolenaar036986f2017-03-16 17:41:02 +01002472 Also, when set certain error messages won't be shown for 2
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01002473 seconds. (e.g. "'dictionary' option is empty")
Bram Moolenaarebf7dfa2016-04-14 12:46:51 +02002474
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 *v:this_session* *this_session-variable*
2476v:this_session Full filename of the last loaded or saved session file. See
2477 |:mksession|. It is allowed to set this variable. When no
2478 session file has been saved, this variable is empty.
Bram Moolenaard2e716e2019-04-20 14:39:52 +02002479 "this_session" also works, for backwards compatibility, unless
2480 |scriptversion| is 3 or higher
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481
2482 *v:throwpoint* *throwpoint-variable*
2483v:throwpoint The point where the exception most recently caught and not
Bram Moolenaar58b85342016-08-14 19:54:54 +02002484 finished was thrown. Not set when commands are typed. See
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 also |v:exception| and |throw-variables|.
2486 Example: >
2487 :try
2488 : throw "oops"
2489 :catch /.*/
2490 : echo "Exception from" v:throwpoint
2491 :endtry
2492< Output: "Exception from test.vim, line 2"
2493
Bram Moolenaar520e1e42016-01-23 19:46:28 +01002494 *v:true* *true-variable*
2495v:true A Number with value one. Used to put "true" in JSON. See
Bram Moolenaar6463ca22016-02-13 17:04:46 +01002496 |json_encode()|.
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002497 When used as a string this evaluates to "v:true". >
Bram Moolenaar705ada12016-01-24 17:56:50 +01002498 echo v:true
Bram Moolenaarc95a3022016-06-12 23:01:46 +02002499< v:true ~
2500 That is so that eval() can parse the string back to the same
Bram Moolenaardf48fb42016-07-22 21:50:18 +02002501 value. Read-only.
Bram Moolenaar5da36052021-12-27 15:39:57 +00002502 In |Vim9| script "true" can be used which has a boolean type.
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002503 *v:val* *val-variable*
Bram Moolenaar58b85342016-08-14 19:54:54 +02002504v:val Value of the current item of a |List| or |Dictionary|. Only
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002505 valid while evaluating the expression used with |map()| and
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002506 |filter()|. Read-only.
2507
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 *v:version* *version-variable*
2509v:version Version number of Vim: Major version number times 100 plus
Bram Moolenaar9b283522019-06-17 22:19:33 +02002510 minor version number. Version 5.0 is 500. Version 5.1
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 is 501. Read-only. "version" also works, for backwards
Bram Moolenaard2e716e2019-04-20 14:39:52 +02002512 compatibility, unless |scriptversion| is 3 or higher.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 Use |has()| to check if a certain patch was included, e.g.: >
Bram Moolenaar6716d9a2014-04-02 12:12:08 +02002514 if has("patch-7.4.123")
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515< Note that patch numbers are specific to the version, thus both
2516 version 5.0 and 5.1 may have a patch 123, but these are
2517 completely different.
2518
Bram Moolenaar37df9a42019-06-14 14:39:51 +02002519 *v:versionlong* *versionlong-variable*
Bram Moolenaar9b283522019-06-17 22:19:33 +02002520v:versionlong Like v:version, but also including the patchlevel in the last
2521 four digits. Version 8.1 with patch 123 has value 8010123.
2522 This can be used like this: >
2523 if v:versionlong >= 8010123
Bram Moolenaar37df9a42019-06-14 14:39:51 +02002524< However, if there are gaps in the list of patches included
2525 this will not work well. This can happen if a recent patch
2526 was included into an older version, e.g. for a security fix.
2527 Use the has() function to make sure the patch is actually
2528 included.
2529
Bram Moolenaar14735512016-03-26 21:00:08 +01002530 *v:vim_did_enter* *vim_did_enter-variable*
2531v:vim_did_enter Zero until most of startup is done. It is set to one just
2532 before |VimEnter| autocommands are triggered.
2533
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 *v:warningmsg* *warningmsg-variable*
2535v:warningmsg Last given warning message. It's allowed to set this variable.
2536
Bram Moolenaar727c8762010-10-20 19:17:48 +02002537 *v:windowid* *windowid-variable*
2538v:windowid When any X11 based GUI is running or when running in a
2539 terminal and Vim connects to the X server (|-X|) this will be
Bram Moolenaar264e9fd2010-10-27 12:33:17 +02002540 set to the window ID.
2541 When an MS-Windows GUI is running this will be set to the
2542 window handle.
2543 Otherwise the value is zero.
Bram Moolenaar7571d552016-08-18 22:54:46 +02002544 Note: for windows inside Vim use |winnr()| or |win_getid()|,
2545 see |window-ID|.
Bram Moolenaar727c8762010-10-20 19:17:48 +02002546
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547==============================================================================
25484. Builtin Functions *functions*
2549
2550See |function-list| for a list grouped by what the function is used for.
2551
Bram Moolenaar1cae5a02021-12-27 21:28:34 +00002552The alphabetic list of all builtin functions and details are in a separate
2553help file: |builtin-functions|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554
2555==============================================================================
25565. Defining functions *user-functions*
2557
2558New functions can be defined. These can be called just like builtin
2559functions. The function executes a sequence of Ex commands. Normal mode
2560commands can be executed with the |:normal| command.
2561
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002562This section is about the legacy functions. For the Vim9 functions, which
2563execute much faster, support type checking and more, see |vim9.txt|.
2564
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565The function name must start with an uppercase letter, to avoid confusion with
2566builtin functions. To prevent from using the same name in different scripts
2567avoid obvious, short names. A good habit is to start the function name with
2568the name of the script, e.g., "HTMLcolor()".
2569
Bram Moolenaar5da36052021-12-27 15:39:57 +00002570In legacy script it is also possible to use curly braces, see
2571|curly-braces-names|.
2572The |autoload| facility is useful to define a function only when it's called.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573
2574 *local-function*
Bram Moolenaar5da36052021-12-27 15:39:57 +00002575A function local to a legacy script must start with "s:". A local script
2576function can only be called from within the script and from functions, user
2577commands and autocommands defined in the script. It is also possible to call
2578the function from a mapping defined in the script, but then |<SID>| must be
2579used instead of "s:" when the mapping is expanded outside of the script.
Bram Moolenaarbcb98982014-05-01 14:08:19 +02002580There are only script-local functions, no buffer-local or window-local
2581functions.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582
Bram Moolenaar5da36052021-12-27 15:39:57 +00002583In |Vim9| script functions are local to the script by default, prefix "g:" to
2584define a global function.
2585
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00002586 *:fu* *:function* *E128* *E129* *E123* *E454*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587:fu[nction] List all functions and their arguments.
2588
2589:fu[nction] {name} List function {name}.
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002590 {name} can also be a |Dictionary| entry that is a
2591 |Funcref|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002592 :function dict.init
Bram Moolenaar92d640f2005-09-05 22:11:52 +00002593
2594:fu[nction] /{pattern} List functions with a name matching {pattern}.
2595 Example that lists all functions ending with "File": >
2596 :function /File$
Bram Moolenaar5b8d8fd2005-08-16 23:01:50 +00002597<
2598 *:function-verbose*
2599When 'verbose' is non-zero, listing a function will also display where it was
2600last defined. Example: >
2601
2602 :verbose function SetFileTypeSH
2603 function SetFileTypeSH(name)
2604 Last set from /usr/share/vim/vim-7.0/filetype.vim
2605<
Bram Moolenaar8aff23a2005-08-19 20:40:30 +00002606See |:verbose-cmd| for more information.
Bram Moolenaar5b8d8fd2005-08-16 23:01:50 +00002607
Bram Moolenaarbcb98982014-05-01 14:08:19 +02002608 *E124* *E125* *E853* *E884*
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002609:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
Bram Moolenaar01164a62017-11-02 22:58:42 +01002610 Define a new function by the name {name}. The body of
2611 the function follows in the next lines, until the
2612 matching |:endfunction|.
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01002613
Bram Moolenaar01164a62017-11-02 22:58:42 +01002614 The name must be made of alphanumeric characters and
2615 '_', and must start with a capital or "s:" (see
2616 above). Note that using "b:" or "g:" is not allowed.
2617 (since patch 7.4.260 E884 is given if the function
2618 name has a colon in the name, e.g. for "foo:bar()".
2619 Before that patch no error was given).
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002620
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002621 {name} can also be a |Dictionary| entry that is a
2622 |Funcref|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002623 :function dict.init(arg)
Bram Moolenaar58b85342016-08-14 19:54:54 +02002624< "dict" must be an existing dictionary. The entry
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002625 "init" is added if it didn't exist yet. Otherwise [!]
Bram Moolenaar58b85342016-08-14 19:54:54 +02002626 is required to overwrite an existing function. The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002627 result is a |Funcref| to a numbered function. The
2628 function can only be used with a |Funcref| and will be
2629 deleted if there are no more references to it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 *E127* *E122*
2631 When a function by this name already exists and [!] is
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002632 not used an error message is given. There is one
2633 exception: When sourcing a script again, a function
2634 that was previously defined in that script will be
2635 silently replaced.
2636 When [!] is used, an existing function is silently
2637 replaced. Unless it is currently being executed, that
2638 is an error.
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002639 NOTE: Use ! wisely. If used without care it can cause
2640 an existing function to be replaced unexpectedly,
2641 which is hard to debug.
Bram Moolenaar388a5d42020-05-26 21:20:45 +02002642 NOTE: In Vim9 script script-local functions cannot be
2643 deleted or redefined.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002644
2645 For the {arguments} see |function-argument|.
2646
Bram Moolenaar8d043172014-01-23 14:24:41 +01002647 *:func-range* *a:firstline* *a:lastline*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 When the [range] argument is added, the function is
2649 expected to take care of a range itself. The range is
2650 passed as "a:firstline" and "a:lastline". If [range]
2651 is excluded, ":{range}call" will call the function for
2652 each line in the range, with the cursor on the start
2653 of each line. See |function-range-example|.
Bram Moolenaar2df58b42012-11-28 18:21:11 +01002654 The cursor is still moved to the first line of the
2655 range, as is the case with all Ex commands.
Bram Moolenaar8d043172014-01-23 14:24:41 +01002656 *:func-abort*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 When the [abort] argument is added, the function will
2658 abort as soon as an error is detected.
Bram Moolenaar8d043172014-01-23 14:24:41 +01002659 *:func-dict*
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002660 When the [dict] argument is added, the function must
Bram Moolenaar58b85342016-08-14 19:54:54 +02002661 be invoked through an entry in a |Dictionary|. The
Bram Moolenaar2fda12f2005-01-15 22:14:15 +00002662 local variable "self" will then be set to the
2663 dictionary. See |Dictionary-function|.
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002664 *:func-closure* *E932*
2665 When the [closure] argument is added, the function
2666 can access variables and arguments from the outer
2667 scope. This is usually called a closure. In this
2668 example Bar() uses "x" from the scope of Foo(). It
2669 remains referenced even after Foo() returns: >
2670 :function! Foo()
2671 : let x = 0
2672 : function! Bar() closure
2673 : let x += 1
2674 : return x
2675 : endfunction
Bram Moolenaarbc8801c2016-08-02 21:04:33 +02002676 : return funcref('Bar')
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002677 :endfunction
2678
2679 :let F = Foo()
2680 :echo F()
2681< 1 >
2682 :echo F()
2683< 2 >
2684 :echo F()
2685< 3
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686
Bram Moolenaar446cb832008-06-24 21:56:24 +00002687 *function-search-undo*
Bram Moolenaar98692072006-02-04 00:57:42 +00002688 The last used search pattern and the redo command "."
Bram Moolenaar446cb832008-06-24 21:56:24 +00002689 will not be changed by the function. This also
2690 implies that the effect of |:nohlsearch| is undone
2691 when the function returns.
Bram Moolenaar98692072006-02-04 00:57:42 +00002692
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002693 *:endf* *:endfunction* *E126* *E193* *W22*
Bram Moolenaar663bb232017-06-22 19:12:10 +02002694:endf[unction] [argument]
2695 The end of a function definition. Best is to put it
2696 on a line by its own, without [argument].
2697
2698 [argument] can be:
2699 | command command to execute next
2700 \n command command to execute next
2701 " comment always ignored
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002702 anything else ignored, warning given when
2703 'verbose' is non-zero
Bram Moolenaar663bb232017-06-22 19:12:10 +02002704 The support for a following command was added in Vim
2705 8.0.0654, before that any argument was silently
2706 ignored.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002708 To be able to define a function inside an `:execute`
2709 command, use line breaks instead of |:bar|: >
2710 :exe "func Foo()\necho 'foo'\nendfunc"
2711<
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00002712 *:delf* *:delfunction* *E131* *E933*
Bram Moolenaar663bb232017-06-22 19:12:10 +02002713:delf[unction][!] {name}
2714 Delete function {name}.
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002715 {name} can also be a |Dictionary| entry that is a
2716 |Funcref|: >
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002717 :delfunc dict.init
Bram Moolenaar58b85342016-08-14 19:54:54 +02002718< This will remove the "init" entry from "dict". The
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00002719 function is deleted if there are no more references to
2720 it.
Bram Moolenaar663bb232017-06-22 19:12:10 +02002721 With the ! there is no error if the function does not
2722 exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 *:retu* *:return* *E133*
2724:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
2725 evaluated and returned as the result of the function.
2726 If "[expr]" is not given, the number 0 is returned.
2727 When a function ends without an explicit ":return",
2728 the number 0 is returned.
2729 Note that there is no check for unreachable lines,
2730 thus there is no warning if commands follow ":return".
2731
2732 If the ":return" is used after a |:try| but before the
2733 matching |:finally| (if present), the commands
2734 following the ":finally" up to the matching |:endtry|
2735 are executed first. This process applies to all
2736 nested ":try"s inside the function. The function
2737 returns at the outermost ":endtry".
2738
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002739 *function-argument* *a:var*
Bram Moolenaar58b85342016-08-14 19:54:54 +02002740An argument can be defined by giving its name. In the function this can then
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002741be used as "a:name" ("a:" for argument).
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002742 *a:0* *a:1* *a:000* *E740* *...*
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002743Up to 20 arguments can be given, separated by commas. After the named
2744arguments an argument "..." can be specified, which means that more arguments
2745may optionally be following. In the function the extra arguments can be used
2746as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
Bram Moolenaar32466aa2006-02-24 23:53:04 +00002747can be 0). "a:000" is set to a |List| that contains these arguments. Note
2748that "a:1" is the same as "a:000[0]".
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00002749 *E742*
2750The a: scope and the variables in it cannot be changed, they are fixed.
Bram Moolenaar069c1e72016-07-15 21:25:08 +02002751However, if a composite type is used, such as |List| or |Dictionary| , you can
2752change their contents. Thus you can pass a |List| to a function and have the
2753function add an item to it. If you want to make sure the function cannot
2754change a |List| or |Dictionary| use |:lockvar|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002756It is also possible to define a function without any arguments. You must
Bram Moolenaar01164a62017-11-02 22:58:42 +01002757still supply the () then.
2758
Bram Moolenaar98ef2332018-03-18 14:44:37 +01002759It is allowed to define another function inside a function body.
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002760
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002761 *optional-function-argument*
2762You can provide default values for positional named arguments. This makes
2763them optional for function calls. When a positional argument is not
2764specified at a call, the default expression is used to initialize it.
Bram Moolenaard1caa942020-04-10 22:10:56 +02002765This only works for functions declared with `:function` or `:def`, not for
2766lambda expressions |expr-lambda|.
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002767
2768Example: >
2769 function Something(key, value = 10)
Bram Moolenaar8aad88d2019-05-12 13:53:50 +02002770 echo a:key .. ": " .. a:value
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002771 endfunction
2772 call Something('empty') "empty: 10"
Bram Moolenaar8aad88d2019-05-12 13:53:50 +02002773 call Something('key', 20) "key: 20"
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002774
2775The argument default expressions are evaluated at the time of the function
2776call, not definition. Thus it is possible to use an expression which is
Bram Moolenaar68e65602019-05-26 21:33:31 +02002777invalid the moment the function is defined. The expressions are also only
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002778evaluated when arguments are not specified during a call.
Bram Moolenaar2547aa92020-07-26 17:00:44 +02002779 *none-function_argument*
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002780You can pass |v:none| to use the default expression. Note that this means you
2781cannot pass v:none as an ordinary value when an argument has a default
2782expression.
2783
2784Example: >
2785 function Something(a = 10, b = 20, c = 30)
2786 endfunction
2787 call Something(1, v:none, 3) " b = 20
2788<
2789 *E989*
2790Optional arguments with default expressions must occur after any mandatory
2791arguments. You can use "..." after all optional named arguments.
2792
2793It is possible for later argument defaults to refer to prior arguments,
2794but not the other way around. They must be prefixed with "a:", as with all
2795arguments.
2796
2797Example that works: >
2798 :function Okay(mandatory, optional = a:mandatory)
2799 :endfunction
2800Example that does NOT work: >
2801 :function NoGood(first = a:second, second = 10)
2802 :endfunction
2803<
Bram Moolenaard1caa942020-04-10 22:10:56 +02002804When not using "...", the number of arguments in a function call must be at
2805least equal to the number of mandatory named arguments. When using "...", the
2806number of arguments may be larger than the total of mandatory and optional
2807arguments.
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002808
Bram Moolenaar8f999f12005-01-25 22:12:55 +00002809 *local-variables*
Bram Moolenaar069c1e72016-07-15 21:25:08 +02002810Inside a function local variables can be used. These will disappear when the
2811function returns. Global variables need to be accessed with "g:".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812
2813Example: >
2814 :function Table(title, ...)
2815 : echohl Title
2816 : echo a:title
2817 : echohl None
Bram Moolenaar677ee682005-01-27 14:41:15 +00002818 : echo a:0 . " items:"
2819 : for s in a:000
2820 : echon ' ' . s
2821 : endfor
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 :endfunction
2823
2824This function can then be called with: >
Bram Moolenaar677ee682005-01-27 14:41:15 +00002825 call Table("Table", "line1", "line2")
2826 call Table("Empty Table")
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002828To return more than one value, return a |List|: >
2829 :function Compute(n1, n2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830 : if a:n2 == 0
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002831 : return ["fail", 0]
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 : endif
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002833 : return ["ok", a:n1 / a:n2]
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 :endfunction
2835
2836This function can then be called with: >
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002837 :let [success, div] = Compute(102, 6)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838 :if success == "ok"
2839 : echo div
2840 :endif
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002841<
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00002842 *:cal* *:call* *E107*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843:[range]cal[l] {name}([arguments])
2844 Call a function. The name of the function and its arguments
Bram Moolenaar68e65602019-05-26 21:33:31 +02002845 are as specified with `:function`. Up to 20 arguments can be
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002846 used. The returned value is discarded.
Bram Moolenaar5da36052021-12-27 15:39:57 +00002847 In |Vim9| script using `:call` is optional, these two lines do
2848 the same thing: >
2849 call SomeFunc(arg)
2850 SomeFunc(arg)
2851< Without a range and for functions that accept a range, the
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852 function is called once. When a range is given the cursor is
2853 positioned at the start of the first line before executing the
2854 function.
2855 When a range is given and the function doesn't handle it
2856 itself, the function is executed for each line in the range,
2857 with the cursor in the first column of that line. The cursor
2858 is left at the last line (possibly moved by the last function
Bram Moolenaar58b85342016-08-14 19:54:54 +02002859 call). The arguments are re-evaluated for each line. Thus
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860 this works:
2861 *function-range-example* >
2862 :function Mynumber(arg)
2863 : echo line(".") . " " . a:arg
2864 :endfunction
2865 :1,5call Mynumber(getline("."))
2866<
2867 The "a:firstline" and "a:lastline" are defined anyway, they
2868 can be used to do something different at the start or end of
2869 the range.
2870
2871 Example of a function that handles the range itself: >
2872
2873 :function Cont() range
2874 : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
2875 :endfunction
2876 :4,8call Cont()
2877<
2878 This function inserts the continuation character "\" in front
2879 of all the lines in the range, except the first one.
2880
Bram Moolenaaref2f6562007-05-06 13:32:59 +00002881 When the function returns a composite value it can be further
2882 dereferenced, but the range will not be used then. Example: >
2883 :4,8call GetDict().method()
2884< Here GetDict() gets the range but method() does not.
2885
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00002886 *E117*
2887When a function cannot be found the error "E117: Unknown function" will be
2888given. If the function was using an autoload path or an autoload import and
2889the script is a |Vim9| script, this may also be caused by the function not
2890being exported.
2891
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892 *E132*
2893The recursiveness of user functions is restricted with the |'maxfuncdepth'|
2894option.
2895
Bram Moolenaar25e42232019-08-04 15:04:10 +02002896It is also possible to use `:eval`. It does not support a range, but does
2897allow for method chaining, e.g.: >
2898 eval GetList()->Filter()->append('$')
2899
Bram Moolenaar088e8e32019-08-08 22:15:18 +02002900A function can also be called as part of evaluating an expression or when it
2901is used as a method: >
2902 let x = GetList()
2903 let y = GetList()->Filter()
2904
Bram Moolenaar7c626922005-02-07 22:01:03 +00002905
2906AUTOMATICALLY LOADING FUNCTIONS ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 *autoload-functions*
2908When using many or large functions, it's possible to automatically define them
Bram Moolenaar7c626922005-02-07 22:01:03 +00002909only when they are used. There are two methods: with an autocommand and with
2910the "autoload" directory in 'runtimepath'.
2911
2912
2913Using an autocommand ~
2914
Bram Moolenaar05159a02005-02-26 23:04:13 +00002915This is introduced in the user manual, section |41.14|.
2916
Bram Moolenaar7c626922005-02-07 22:01:03 +00002917The autocommand is useful if you have a plugin that is a long Vim script file.
Bram Moolenaar68e65602019-05-26 21:33:31 +02002918You can define the autocommand and quickly quit the script with `:finish`.
Bram Moolenaar58b85342016-08-14 19:54:54 +02002919That makes Vim startup faster. The autocommand should then load the same file
Bram Moolenaar68e65602019-05-26 21:33:31 +02002920again, setting a variable to skip the `:finish` command.
Bram Moolenaar7c626922005-02-07 22:01:03 +00002921
2922Use the FuncUndefined autocommand event with a pattern that matches the
2923function(s) to be defined. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924
2925 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
2926
2927The file "~/vim/bufnetfuncs.vim" should then define functions that start with
2928"BufNet". Also see |FuncUndefined|.
2929
Bram Moolenaar7c626922005-02-07 22:01:03 +00002930
2931Using an autoload script ~
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002932 *autoload* *E746*
Bram Moolenaar05159a02005-02-26 23:04:13 +00002933This is introduced in the user manual, section |41.15|.
2934
Bram Moolenaar7c626922005-02-07 22:01:03 +00002935Using a script in the "autoload" directory is simpler, but requires using
2936exactly the right file name. A function that can be autoloaded has a name
2937like this: >
2938
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002939 :call filename#funcname()
Bram Moolenaar7c626922005-02-07 22:01:03 +00002940
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002941These functions are always global, in Vim9 script "g:" needs to be used: >
2942 :call g:filename#funcname()
2943
Bram Moolenaar7c626922005-02-07 22:01:03 +00002944When such a function is called, and it is not defined yet, Vim will search the
2945"autoload" directories in 'runtimepath' for a script file called
2946"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
2947then define the function like this: >
2948
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002949 function filename#funcname()
Bram Moolenaar7c626922005-02-07 22:01:03 +00002950 echo "Done!"
2951 endfunction
2952
Bram Moolenaar60a795a2005-09-16 21:55:43 +00002953The file name and the name used before the # in the function must match
Bram Moolenaar7c626922005-02-07 22:01:03 +00002954exactly, and the defined function must have the name exactly as it will be
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002955called. In Vim9 script the "g:" prefix must be used: >
2956 function g:filename#funcname()
2957
2958or for a compiled function: >
2959 def g:filename#funcname()
Bram Moolenaar7c626922005-02-07 22:01:03 +00002960
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002961It is possible to use subdirectories. Every # in the function name works like
2962a path separator. Thus when calling a function: >
Bram Moolenaar7c626922005-02-07 22:01:03 +00002963
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002964 :call foo#bar#func()
Bram Moolenaar7c626922005-02-07 22:01:03 +00002965
2966Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
2967
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002968This also works when reading a variable that has not been set yet: >
2969
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002970 :let l = foo#bar#lvar
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002971
Bram Moolenaara5792f52005-11-23 21:25:05 +00002972However, when the autoload script was already loaded it won't be loaded again
2973for an unknown variable.
2974
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002975When assigning a value to such a variable nothing special happens. This can
2976be used to pass settings to the autoload script before it's loaded: >
2977
Bram Moolenaara7fc0102005-05-18 22:17:12 +00002978 :let foo#bar#toggle = 1
2979 :call foo#bar#func()
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002980
Bram Moolenaar4399ef42005-02-12 14:29:27 +00002981Note that when you make a mistake and call a function that is supposed to be
2982defined in an autoload script, but the script doesn't actually define the
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01002983function, you will get an error message for the missing function. If you fix
2984the autoload script it won't be automatically loaded again. Either restart
2985Vim or manually source the script.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002986
2987Also note that if you have two script files, and one calls a function in the
Bram Moolenaar446cb832008-06-24 21:56:24 +00002988other and vice versa, before the used function is defined, it won't work.
Bram Moolenaar26a60b42005-02-22 08:49:11 +00002989Avoid using the autoload functionality at the toplevel.
Bram Moolenaar7c626922005-02-07 22:01:03 +00002990
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00002991In |Vim9| script you will get error *E1263* if you use a function name with a
2992"#" character when not in an autoload script.
2993
Bram Moolenaar433f7c82006-03-21 21:29:36 +00002994Hint: If you distribute a bunch of scripts you can pack them together with the
2995|vimball| utility. Also read the user manual |distribute-script|.
2996
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997==============================================================================
29986. Curly braces names *curly-braces-names*
2999
Bram Moolenaar84f72352012-03-11 15:57:40 +01003000In most places where you can use a variable, you can use a "curly braces name"
3001variable. This is a regular variable name with one or more expressions
3002wrapped in braces {} like this: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 my_{adjective}_variable
3004
Bram Moolenaar5da36052021-12-27 15:39:57 +00003005This only works in legacy Vim script, not in |Vim9| script.
3006
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007When Vim encounters this, it evaluates the expression inside the braces, puts
3008that in place of the expression, and re-interprets the whole as a variable
3009name. So in the above example, if the variable "adjective" was set to
3010"noisy", then the reference would be to "my_noisy_variable", whereas if
3011"adjective" was set to "quiet", then it would be to "my_quiet_variable".
3012
3013One application for this is to create a set of variables governed by an option
Bram Moolenaar58b85342016-08-14 19:54:54 +02003014value. For example, the statement >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015 echo my_{&background}_message
3016
3017would output the contents of "my_dark_message" or "my_light_message" depending
3018on the current value of 'background'.
3019
3020You can use multiple brace pairs: >
3021 echo my_{adverb}_{adjective}_message
3022..or even nest them: >
3023 echo my_{ad{end_of_word}}_message
3024where "end_of_word" is either "verb" or "jective".
3025
3026However, the expression inside the braces must evaluate to a valid single
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003027variable name, e.g. this is invalid: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 :let foo='a + b'
3029 :echo c{foo}d
3030.. since the result of expansion is "ca + bd", which is not a variable name.
3031
3032 *curly-braces-function-names*
3033You can call and define functions by an evaluated name in a similar way.
3034Example: >
3035 :let func_end='whizz'
3036 :call my_func_{func_end}(parameter)
3037
3038This would call the function "my_func_whizz(parameter)".
3039
Bram Moolenaar84f72352012-03-11 15:57:40 +01003040This does NOT work: >
3041 :let i = 3
3042 :let @{i} = '' " error
3043 :echo @{i} " error
3044
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045==============================================================================
30467. Commands *expression-commands*
3047
Bram Moolenaar5da36052021-12-27 15:39:57 +00003048Note: in |Vim9| script `:let` is not used. `:var` is used for variable
3049declarations and assignments do not use a command. |vim9-declaration|
Bram Moolenaar65e0d772020-06-14 17:29:55 +02003050
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051:let {var-name} = {expr1} *:let* *E18*
3052 Set internal variable {var-name} to the result of the
3053 expression {expr1}. The variable will get the type
3054 from the {expr}. If {var-name} didn't exist yet, it
3055 is created.
3056
Bram Moolenaar13065c42005-01-08 16:08:21 +00003057:let {var-name}[{idx}] = {expr1} *E689*
3058 Set a list item to the result of the expression
3059 {expr1}. {var-name} must refer to a list and {idx}
3060 must be a valid index in that list. For nested list
3061 the index can be repeated.
Bram Moolenaar446cb832008-06-24 21:56:24 +00003062 This cannot be used to add an item to a |List|.
Bram Moolenaar58b85342016-08-14 19:54:54 +02003063 This cannot be used to set a byte in a String. You
Bram Moolenaar446cb832008-06-24 21:56:24 +00003064 can do that like this: >
3065 :let var = var[0:2] . 'X' . var[4:]
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01003066< When {var-name} is a |Blob| then {idx} can be the
3067 length of the blob, in which case one byte is
3068 appended.
3069
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003070 *E711* *E719*
3071:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003072 Set a sequence of items in a |List| to the result of
3073 the expression {expr1}, which must be a list with the
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003074 correct number of items.
3075 {idx1} can be omitted, zero is used instead.
3076 {idx2} can be omitted, meaning the end of the list.
3077 When the selected range of items is partly past the
3078 end of the list, items will be added.
3079
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003080 *:let+=* *:let-=* *:letstar=* *:let/=* *:let%=*
3081 *:let.=* *:let..=* *E734* *E985* *E1019*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003082:let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
3083:let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
Bram Moolenaarff697e62019-02-12 22:28:33 +01003084:let {var} *= {expr1} Like ":let {var} = {var} * {expr1}".
3085:let {var} /= {expr1} Like ":let {var} = {var} / {expr1}".
3086:let {var} %= {expr1} Like ":let {var} = {var} % {expr1}".
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003087:let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02003088:let {var} ..= {expr1} Like ":let {var} = {var} .. {expr1}".
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003089 These fail if {var} was not set yet and when the type
3090 of {var} and {expr1} don't fit the operator.
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02003091 `.=` is not supported with Vim script version 2 and
3092 later, see |vimscript-version|.
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003093
3094
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095:let ${env-name} = {expr1} *:let-environment* *:let-$*
3096 Set environment variable {env-name} to the result of
3097 the expression {expr1}. The type is always String.
Bram Moolenaar56c860c2019-08-17 20:09:31 +02003098
3099 On some systems making an environment variable empty
3100 causes it to be deleted. Many systems do not make a
3101 difference between an environment variable that is not
3102 set and an environment variable that is empty.
3103
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003104:let ${env-name} .= {expr1}
3105 Append {expr1} to the environment variable {env-name}.
3106 If the environment variable didn't exist yet this
3107 works like "=".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108
3109:let @{reg-name} = {expr1} *:let-register* *:let-@*
3110 Write the result of the expression {expr1} in register
3111 {reg-name}. {reg-name} must be a single letter, and
3112 must be the name of a writable register (see
3113 |registers|). "@@" can be used for the unnamed
3114 register, "@/" for the search pattern.
3115 If the result of {expr1} ends in a <CR> or <NL>, the
3116 register will be linewise, otherwise it will be set to
3117 characterwise.
3118 This can be used to clear the last search pattern: >
3119 :let @/ = ""
3120< This is different from searching for an empty string,
3121 that would match everywhere.
3122
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003123:let @{reg-name} .= {expr1}
Bram Moolenaar58b85342016-08-14 19:54:54 +02003124 Append {expr1} to register {reg-name}. If the
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003125 register was empty it's like setting it to {expr1}.
3126
Bram Moolenaaref2f6562007-05-06 13:32:59 +00003127:let &{option-name} = {expr1} *:let-option* *:let-&*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 Set option {option-name} to the result of the
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003129 expression {expr1}. A String or Number value is
3130 always converted to the type of the option.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 For an option local to a window or buffer the effect
3132 is just like using the |:set| command: both the local
Bram Moolenaara5fac542005-10-12 20:58:49 +00003133 value and the global value are changed.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003134 Example: >
3135 :let &path = &path . ',/usr/local/include'
Bram Moolenaar3df01732017-02-17 22:47:16 +01003136< This also works for terminal codes in the form t_xx.
3137 But only for alphanumerical names. Example: >
3138 :let &t_k1 = "\<Esc>[234;"
3139< When the code does not exist yet it will be created as
3140 a terminal key code, there is no error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003142:let &{option-name} .= {expr1}
3143 For a string option: Append {expr1} to the value.
3144 Does not insert a comma like |:set+=|.
3145
3146:let &{option-name} += {expr1}
3147:let &{option-name} -= {expr1}
3148 For a number or boolean option: Add or subtract
3149 {expr1}.
3150
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151:let &l:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003152:let &l:{option-name} .= {expr1}
3153:let &l:{option-name} += {expr1}
3154:let &l:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 Like above, but only set the local value of an option
3156 (if there is one). Works like |:setlocal|.
3157
3158:let &g:{option-name} = {expr1}
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003159:let &g:{option-name} .= {expr1}
3160:let &g:{option-name} += {expr1}
3161:let &g:{option-name} -= {expr1}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 Like above, but only set the global value of an option
3163 (if there is one). Works like |:setglobal|.
3164
Bram Moolenaar13065c42005-01-08 16:08:21 +00003165:let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003166 {expr1} must evaluate to a |List|. The first item in
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003167 the list is assigned to {name1}, the second item to
3168 {name2}, etc.
3169 The number of names must match the number of items in
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003170 the |List|.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003171 Each name can be one of the items of the ":let"
3172 command as mentioned above.
3173 Example: >
3174 :let [s, item] = GetItem(s)
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003175< Detail: {expr1} is evaluated first, then the
3176 assignments are done in sequence. This matters if
3177 {name2} depends on {name1}. Example: >
3178 :let x = [0, 1]
3179 :let i = 0
3180 :let [i, x[i]] = [1, 2]
3181 :echo x
3182< The result is [0, 2].
3183
3184:let [{name1}, {name2}, ...] .= {expr1}
3185:let [{name1}, {name2}, ...] += {expr1}
3186:let [{name1}, {name2}, ...] -= {expr1}
3187 Like above, but append/add/subtract the value for each
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003188 |List| item.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003189
Bram Moolenaard1caa942020-04-10 22:10:56 +02003190:let [{name}, ..., ; {lastname}] = {expr1} *E452*
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003191 Like |:let-unpack| above, but the |List| may have more
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003192 items than there are names. A list of the remaining
3193 items is assigned to {lastname}. If there are no
3194 remaining items {lastname} is set to an empty list.
Bram Moolenaarfca34d62005-01-04 21:38:36 +00003195 Example: >
3196 :let [a, b; rest] = ["aval", "bval", 3, 4]
3197<
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003198:let [{name}, ..., ; {lastname}] .= {expr1}
3199:let [{name}, ..., ; {lastname}] += {expr1}
3200:let [{name}, ..., ; {lastname}] -= {expr1}
3201 Like above, but append/add/subtract the value for each
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003202 |List| item.
Bram Moolenaar4a748032010-09-30 21:47:56 +02003203
Bram Moolenaar24582002019-07-21 14:14:26 +02003204 *:let=<<* *:let-heredoc*
3205 *E990* *E991* *E172* *E221*
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003206:let {var-name} =<< [trim] {endmarker}
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003207text...
3208text...
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003209{endmarker}
Bram Moolenaare46a4402020-06-30 20:38:27 +02003210 Set internal variable {var-name} to a |List|
3211 containing the lines of text bounded by the string
Bram Moolenaaraa970ab2020-08-02 16:10:39 +02003212 {endmarker}. The lines of text is used as a
3213 |literal-string|.
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003214 {endmarker} must not contain white space.
3215 {endmarker} cannot start with a lower case character.
3216 The last line should end only with the {endmarker}
3217 string without any other character. Watch out for
3218 white space after {endmarker}!
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003219
Bram Moolenaare7eb9272019-06-24 00:58:07 +02003220 Without "trim" any white space characters in the lines
3221 of text are preserved. If "trim" is specified before
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003222 {endmarker}, then indentation is stripped so you can
3223 do: >
Bram Moolenaare7eb9272019-06-24 00:58:07 +02003224 let text =<< trim END
3225 if ok
3226 echo 'done'
3227 endif
3228 END
3229< Results in: ["if ok", " echo 'done'", "endif"]
3230 The marker must line up with "let" and the indentation
3231 of the first line is removed from all the text lines.
3232 Specifically: all the leading indentation exactly
3233 matching the leading indentation of the first
3234 non-empty text line is stripped from the input lines.
3235 All leading indentation exactly matching the leading
3236 indentation before `let` is stripped from the line
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003237 containing {endmarker}. Note that the difference
3238 between space and tab matters here.
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003239
3240 If {var-name} didn't exist yet, it is created.
3241 Cannot be followed by another command, but can be
3242 followed by a comment.
3243
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003244 To avoid line continuation to be applied, consider
3245 adding 'C' to 'cpoptions': >
3246 set cpo+=C
3247 let var =<< END
3248 \ leading backslash
3249 END
3250 set cpo-=C
3251<
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003252 Examples: >
3253 let var1 =<< END
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003254 Sample text 1
3255 Sample text 2
3256 Sample text 3
3257 END
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003258
3259 let data =<< trim DATA
Bram Moolenaar2e693a82019-10-16 22:35:02 +02003260 1 2 3 4
3261 5 6 7 8
Bram Moolenaarf5842c52019-05-19 18:41:26 +02003262 DATA
3263<
Bram Moolenaar4a748032010-09-30 21:47:56 +02003264 *E121*
Bram Moolenaar58b85342016-08-14 19:54:54 +02003265:let {var-name} .. List the value of variable {var-name}. Multiple
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00003266 variable names may be given. Special names recognized
3267 here: *E738*
Bram Moolenaarca003e12006-03-17 23:19:38 +00003268 g: global variables
3269 b: local buffer variables
3270 w: local window variables
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003271 t: local tab page variables
Bram Moolenaarca003e12006-03-17 23:19:38 +00003272 s: script-local variables
3273 l: local function variables
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00003274 v: Vim variables.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02003275 This does not work in Vim9 script. |vim9-declaration|
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276
Bram Moolenaard7ee7ce2005-01-03 21:02:03 +00003277:let List the values of all variables. The type of the
3278 variable is indicated before the value:
3279 <nothing> String
3280 # Number
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00003281 * Funcref
Bram Moolenaar65e0d772020-06-14 17:29:55 +02003282 This does not work in Vim9 script. |vim9-declaration|
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003284:unl[et][!] {name} ... *:unlet* *:unl* *E108* *E795* *E1081*
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003285 Remove the internal variable {name}. Several variable
3286 names can be given, they are all removed. The name
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003287 may also be a |List| or |Dictionary| item.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 With [!] no error message is given for non-existing
3289 variables.
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003290 One or more items from a |List| can be removed: >
Bram Moolenaar9cd15162005-01-16 22:02:49 +00003291 :unlet list[3] " remove fourth item
3292 :unlet list[3:] " remove fourth item to last
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003293< One item from a |Dictionary| can be removed at a time: >
Bram Moolenaar9cd15162005-01-16 22:02:49 +00003294 :unlet dict['two']
3295 :unlet dict.two
Bram Moolenaarc236c162008-07-13 17:41:49 +00003296< This is especially useful to clean up used global
3297 variables and script-local variables (these are not
3298 deleted when the script ends). Function-local
3299 variables are automatically deleted when the function
3300 ends.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301
Bram Moolenaar137374f2018-05-13 15:59:50 +02003302:unl[et] ${env-name} ... *:unlet-environment* *:unlet-$*
3303 Remove environment variable {env-name}.
3304 Can mix {name} and ${env-name} in one :unlet command.
3305 No error message is given for a non-existing
3306 variable, also without !.
3307 If the system does not support deleting an environment
Bram Moolenaar9937a052019-06-15 15:45:06 +02003308 variable, it is made empty.
Bram Moolenaar137374f2018-05-13 15:59:50 +02003309
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003310 *:cons* *:const* *E1018*
Bram Moolenaar9937a052019-06-15 15:45:06 +02003311:cons[t] {var-name} = {expr1}
3312:cons[t] [{name1}, {name2}, ...] = {expr1}
Bram Moolenaar9937a052019-06-15 15:45:06 +02003313:cons[t] [{name}, ..., ; {lastname}] = {expr1}
3314:cons[t] {var-name} =<< [trim] {marker}
3315text...
3316text...
3317{marker}
3318 Similar to |:let|, but additionally lock the variable
3319 after setting the value. This is the same as locking
3320 the variable with |:lockvar| just after |:let|, thus: >
3321 :const x = 1
3322< is equivalent to: >
3323 :let x = 1
Bram Moolenaar021bda52020-08-17 21:07:22 +02003324 :lockvar! x
Bram Moolenaara187c432020-09-16 21:08:28 +02003325< NOTE: in Vim9 script `:const` works differently, see
3326 |vim9-const|
3327 This is useful if you want to make sure the variable
Bram Moolenaar021bda52020-08-17 21:07:22 +02003328 is not modified. If the value is a List or Dictionary
3329 literal then the items also cannot be changed: >
3330 const ll = [1, 2, 3]
3331 let ll[1] = 5 " Error!
Bram Moolenaar6e649222021-10-04 21:32:54 +01003332< Nested references are not locked: >
Bram Moolenaar021bda52020-08-17 21:07:22 +02003333 let lvar = ['a']
3334 const lconst = [0, lvar]
3335 let lconst[0] = 2 " Error!
3336 let lconst[1][0] = 'b' " OK
3337< *E995*
Bram Moolenaar9b283522019-06-17 22:19:33 +02003338 |:const| does not allow to for changing a variable: >
Bram Moolenaar9937a052019-06-15 15:45:06 +02003339 :let x = 1
3340 :const x = 2 " Error!
Bram Moolenaar1c196e72019-06-16 15:41:58 +02003341< *E996*
3342 Note that environment variables, option values and
3343 register values cannot be used here, since they cannot
3344 be locked.
3345
Bram Moolenaar85850f32019-07-19 22:05:51 +02003346:cons[t]
3347:cons[t] {var-name}
3348 If no argument is given or only {var-name} is given,
3349 the behavior is the same as |:let|.
3350
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003351:lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv*
3352 Lock the internal variable {name}. Locking means that
3353 it can no longer be changed (until it is unlocked).
3354 A locked variable can be deleted: >
3355 :lockvar v
Bram Moolenaardad44732021-03-31 20:07:33 +02003356 :let v = 'asdf' " fails!
3357 :unlet v " works
Bram Moolenaare7877fe2017-02-20 22:35:33 +01003358< *E741* *E940*
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003359 If you try to change a locked variable you get an
Bram Moolenaare7877fe2017-02-20 22:35:33 +01003360 error message: "E741: Value is locked: {name}".
3361 If you try to lock or unlock a built-in variable you
3362 get an error message: "E940: Cannot lock or unlock
3363 variable {name}".
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003364
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003365 [depth] is relevant when locking a |List| or
3366 |Dictionary|. It specifies how deep the locking goes:
Bram Moolenaara187c432020-09-16 21:08:28 +02003367 0 Lock the variable {name} but not its
3368 value.
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003369 1 Lock the |List| or |Dictionary| itself,
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003370 cannot add or remove items, but can
3371 still change their values.
3372 2 Also lock the values, cannot change
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003373 the items. If an item is a |List| or
3374 |Dictionary|, cannot add or remove
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003375 items, but can still change the
3376 values.
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003377 3 Like 2 but for the |List| /
3378 |Dictionary| in the |List| /
3379 |Dictionary|, one level deeper.
3380 The default [depth] is 2, thus when {name} is a |List|
3381 or |Dictionary| the values cannot be changed.
Bram Moolenaara187c432020-09-16 21:08:28 +02003382
3383 Example with [depth] 0: >
3384 let mylist = [1, 2, 3]
3385 lockvar 0 mylist
Bram Moolenaar6e649222021-10-04 21:32:54 +01003386 let mylist[0] = 77 " OK
3387 call add(mylist, 4] " OK
Bram Moolenaara187c432020-09-16 21:08:28 +02003388 let mylist = [7, 8, 9] " Error!
3389< *E743*
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003390 For unlimited depth use [!] and omit [depth].
3391 However, there is a maximum depth of 100 to catch
3392 loops.
3393
Bram Moolenaar32466aa2006-02-24 23:53:04 +00003394 Note that when two variables refer to the same |List|
3395 and you lock one of them, the |List| will also be
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003396 locked when used through the other variable.
3397 Example: >
Bram Moolenaar2ce06f62005-01-31 19:19:04 +00003398 :let l = [0, 1, 2, 3]
3399 :let cl = l
3400 :lockvar l
3401 :let cl[1] = 99 " won't work!
3402< You may want to make a copy of a list to avoid this.
3403 See |deepcopy()|.
3404
3405
3406:unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo*
3407 Unlock the internal variable {name}. Does the
3408 opposite of |:lockvar|.
3409
Bram Moolenaar61da1bf2019-06-06 12:14:49 +02003410:if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411:en[dif] Execute the commands until the next matching ":else"
3412 or ":endif" if {expr1} evaluates to non-zero.
3413
3414 From Vim version 4.5 until 5.0, every Ex command in
3415 between the ":if" and ":endif" is ignored. These two
3416 commands were just to allow for future expansions in a
Bram Moolenaar85084ef2016-01-17 22:26:33 +01003417 backward compatible way. Nesting was allowed. Note
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 that any ":else" or ":elseif" was ignored, the "else"
3419 part was not executed either.
3420
3421 You can use this to remain compatible with older
3422 versions: >
3423 :if version >= 500
3424 : version-5-specific-commands
3425 :endif
3426< The commands still need to be parsed to find the
3427 "endif". Sometimes an older Vim has a problem with a
3428 new command. For example, ":silent" is recognized as
3429 a ":substitute" command. In that case ":execute" can
3430 avoid problems: >
3431 :if version >= 600
3432 : execute "silent 1,$delete"
3433 :endif
3434<
3435 NOTE: The ":append" and ":insert" commands don't work
3436 properly in between ":if" and ":endif".
3437
3438 *:else* *:el* *E581* *E583*
3439:el[se] Execute the commands until the next matching ":else"
3440 or ":endif" if they previously were not being
3441 executed.
3442
3443 *:elseif* *:elsei* *E582* *E584*
3444:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
3445 is no extra ":endif".
3446
3447:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
Bram Moolenaar3a3a7232005-01-17 22:16:15 +00003448 *E170* *E585* *E588* *E733*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449:endw[hile] Repeat the commands between ":while" and ":endwhile",
3450 as long as {expr1} evaluates to non-zero.
3451 When an error is detected from a command inside the
3452 loop, execution continues after the "endwhile".
Bram Moolenaar12805862005-01-05 22:16:17 +00003453 Example: >
3454 :let lnum = 1
3455 :while lnum <= line("$")
3456 :call FixLine(lnum)
3457 :let lnum = lnum + 1
3458 :endwhile
3459<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 NOTE: The ":append" and ":insert" commands don't work
Bram Moolenaard8b02732005-01-14 21:48:43 +00003461 properly inside a ":while" and ":for" loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003463:for {var} in {object} *:for* *E690* *E732*
Bram Moolenaar12805862005-01-05 22:16:17 +00003464:endfo[r] *:endfo* *:endfor*
3465 Repeat the commands between ":for" and ":endfor" for
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003466 each item in {object}. {object} can be a |List| or
Bram Moolenaar5da36052021-12-27 15:39:57 +00003467 a |Blob|.
3468
3469 Variable {var} is set to the value of each item.
3470 In |Vim9| script the loop variable must not have been
3471 declared yet, unless when it is a
3472 global/window/tab/buffer variable.
3473
3474 When an error is detected for a command inside the
3475 loop, execution continues after the "endfor".
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003476 Changing {object} inside the loop affects what items
3477 are used. Make a copy if this is unwanted: >
Bram Moolenaarde8866b2005-01-06 23:24:37 +00003478 :for item in copy(mylist)
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003479<
Bram Moolenaar5da36052021-12-27 15:39:57 +00003480 When {object} is a |List| and not making a copy, in
3481 legacy script Vim stores a reference to the next item
3482 in the |List| before executing the commands with the
3483 current item. Thus the current item can be removed
3484 without effect. Removing any later item means it will
3485 not be found. Thus the following example works (an
3486 inefficient way to make a |List| empty): >
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01003487 for item in mylist
3488 call remove(mylist, 0)
3489 endfor
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003490< Note that reordering the |List| (e.g., with sort() or
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003491 reverse()) may have unexpected effects.
Bram Moolenaar5da36052021-12-27 15:39:57 +00003492 In |Vim9| script the index is used. If an item before
3493 the current one is deleted the next item will be
3494 skipped.
Bram Moolenaar12805862005-01-05 22:16:17 +00003495
Bram Moolenaar5e66b422019-01-24 21:58:10 +01003496 When {object} is a |Blob|, Vim always makes a copy to
3497 iterate over. Unlike with |List|, modifying the
3498 |Blob| does not affect the iteration.
3499
Bram Moolenaar12805862005-01-05 22:16:17 +00003500:for [{var1}, {var2}, ...] in {listlist}
3501:endfo[r]
3502 Like ":for" above, but each item in {listlist} must be
3503 a list, of which each item is assigned to {var1},
3504 {var2}, etc. Example: >
3505 :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
3506 :echo getline(lnum)[col]
3507 :endfor
3508<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 *:continue* *:con* *E586*
Bram Moolenaar12805862005-01-05 22:16:17 +00003510:con[tinue] When used inside a ":while" or ":for" loop, jumps back
3511 to the start of the loop.
3512 If it is used after a |:try| inside the loop but
3513 before the matching |:finally| (if present), the
3514 commands following the ":finally" up to the matching
3515 |:endtry| are executed first. This process applies to
3516 all nested ":try"s inside the loop. The outermost
3517 ":endtry" then jumps back to the start of the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518
3519 *:break* *:brea* *E587*
Bram Moolenaar12805862005-01-05 22:16:17 +00003520:brea[k] When used inside a ":while" or ":for" loop, skips to
3521 the command after the matching ":endwhile" or
3522 ":endfor".
3523 If it is used after a |:try| inside the loop but
3524 before the matching |:finally| (if present), the
3525 commands following the ":finally" up to the matching
3526 |:endtry| are executed first. This process applies to
3527 all nested ":try"s inside the loop. The outermost
3528 ":endtry" then jumps to the command after the loop.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003530:try *:try* *:endt* *:endtry*
3531 *E600* *E601* *E602* *E1032*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532:endt[ry] Change the error handling for the commands between
3533 ":try" and ":endtry" including everything being
3534 executed across ":source" commands, function calls,
3535 or autocommand invocations.
3536
3537 When an error or interrupt is detected and there is
3538 a |:finally| command following, execution continues
3539 after the ":finally". Otherwise, or when the
3540 ":endtry" is reached thereafter, the next
3541 (dynamically) surrounding ":try" is checked for
3542 a corresponding ":finally" etc. Then the script
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01003543 processing is terminated. Whether a function
3544 definition has an "abort" argument does not matter.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 Example: >
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01003546 try | call Unknown() | finally | echomsg "cleanup" | endtry
3547 echomsg "not reached"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548<
3549 Moreover, an error or interrupt (dynamically) inside
3550 ":try" and ":endtry" is converted to an exception. It
3551 can be caught as if it were thrown by a |:throw|
3552 command (see |:catch|). In this case, the script
3553 processing is not terminated.
3554
3555 The value "Vim:Interrupt" is used for an interrupt
3556 exception. An error in a Vim command is converted
3557 to a value of the form "Vim({command}):{errmsg}",
3558 other errors are converted to a value of the form
3559 "Vim:{errmsg}". {command} is the full command name,
3560 and {errmsg} is the message that is displayed if the
3561 error exception is not caught, always beginning with
3562 the error number.
3563 Examples: >
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01003564 try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
3565 try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566<
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003567 *:cat* *:catch*
3568 *E603* *E604* *E605* *E654* *E1033*
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01003569:cat[ch] /{pattern}/ The following commands until the next |:catch|,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570 |:finally|, or |:endtry| that belongs to the same
3571 |:try| as the ":catch" are executed when an exception
3572 matching {pattern} is being thrown and has not yet
3573 been caught by a previous ":catch". Otherwise, these
3574 commands are skipped.
3575 When {pattern} is omitted all errors are caught.
3576 Examples: >
Bram Moolenaar647e24b2019-03-17 16:39:46 +01003577 :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
3578 :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
3579 :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
3580 :catch /^Vim(write):/ " catch all errors in :write
3581 :catch /^Vim\%((\a\+)\)\=:E123:/ " catch error E123
3582 :catch /my-exception/ " catch user exception
3583 :catch /.*/ " catch everything
3584 :catch " same as /.*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585<
3586 Another character can be used instead of / around the
3587 {pattern}, so long as it does not have a special
3588 meaning (e.g., '|' or '"') and doesn't occur inside
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00003589 {pattern}. *E1067*
Bram Moolenaar7e38ea22014-04-05 22:55:53 +02003590 Information about the exception is available in
3591 |v:exception|. Also see |throw-variables|.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592 NOTE: It is not reliable to ":catch" the TEXT of
3593 an error message because it may vary in different
3594 locales.
3595
3596 *:fina* *:finally* *E606* *E607*
3597:fina[lly] The following commands until the matching |:endtry|
3598 are executed whenever the part between the matching
3599 |:try| and the ":finally" is left: either by falling
3600 through to the ":finally" or by a |:continue|,
3601 |:break|, |:finish|, or |:return|, or by an error or
3602 interrupt or exception (see |:throw|).
3603
3604 *:th* *:throw* *E608*
3605:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
3606 If the ":throw" is used after a |:try| but before the
3607 first corresponding |:catch|, commands are skipped
3608 until the first ":catch" matching {expr1} is reached.
3609 If there is no such ":catch" or if the ":throw" is
3610 used after a ":catch" but before the |:finally|, the
3611 commands following the ":finally" (if present) up to
3612 the matching |:endtry| are executed. If the ":throw"
3613 is after the ":finally", commands up to the ":endtry"
3614 are skipped. At the ":endtry", this process applies
3615 again for the next dynamically surrounding ":try"
3616 (which may be found in a calling function or sourcing
3617 script), until a matching ":catch" has been found.
3618 If the exception is not caught, the command processing
3619 is terminated.
3620 Example: >
3621 :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
Bram Moolenaar662db672011-03-22 14:05:35 +01003622< Note that "catch" may need to be on a separate line
3623 for when an error causes the parsing to skip the whole
3624 line and not see the "|" that separates the commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625
3626 *:ec* *:echo*
3627:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
3628 first {expr1} starts on a new line.
3629 Also see |:comment|.
3630 Use "\n" to start a new line. Use "\r" to move the
3631 cursor to the first column.
3632 Uses the highlighting set by the |:echohl| command.
3633 Cannot be followed by a comment.
3634 Example: >
3635 :echo "the value of 'shell' is" &shell
Bram Moolenaaref2f6562007-05-06 13:32:59 +00003636< *:echo-redraw*
3637 A later redraw may make the message disappear again.
3638 And since Vim mostly postpones redrawing until it's
3639 finished with a sequence of commands this happens
3640 quite often. To avoid that a command from before the
3641 ":echo" causes a redraw afterwards (redraws are often
3642 postponed until you type something), force a redraw
3643 with the |:redraw| command. Example: >
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644 :new | redraw | echo "there is a new window"
3645<
3646 *:echon*
3647:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
3648 |:comment|.
3649 Uses the highlighting set by the |:echohl| command.
3650 Cannot be followed by a comment.
3651 Example: >
3652 :echon "the value of 'shell' is " &shell
3653<
3654 Note the difference between using ":echo", which is a
3655 Vim command, and ":!echo", which is an external shell
3656 command: >
3657 :!echo % --> filename
3658< The arguments of ":!" are expanded, see |:_%|. >
3659 :!echo "%" --> filename or "filename"
3660< Like the previous example. Whether you see the double
3661 quotes or not depends on your 'shell'. >
3662 :echo % --> nothing
3663< The '%' is an illegal character in an expression. >
3664 :echo "%" --> %
3665< This just echoes the '%' character. >
3666 :echo expand("%") --> filename
3667< This calls the expand() function to expand the '%'.
3668
3669 *:echoh* *:echohl*
3670:echoh[l] {name} Use the highlight group {name} for the following
3671 |:echo|, |:echon| and |:echomsg| commands. Also used
3672 for the |input()| prompt. Example: >
3673 :echohl WarningMsg | echo "Don't panic!" | echohl None
3674< Don't forget to set the group back to "None",
3675 otherwise all following echo's will be highlighted.
3676
3677 *:echom* *:echomsg*
3678:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
3679 message in the |message-history|.
3680 Spaces are placed between the arguments as with the
3681 |:echo| command. But unprintable characters are
3682 displayed, not interpreted.
Bram Moolenaaref2f6562007-05-06 13:32:59 +00003683 The parsing works slightly different from |:echo|,
3684 more like |:execute|. All the expressions are first
3685 evaluated and concatenated before echoing anything.
Bram Moolenaar461a7fc2018-12-22 13:28:07 +01003686 If expressions does not evaluate to a Number or
3687 String, string() is used to turn it into a string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688 Uses the highlighting set by the |:echohl| command.
3689 Example: >
3690 :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
Bram Moolenaaref2f6562007-05-06 13:32:59 +00003691< See |:echo-redraw| to avoid the message disappearing
3692 when the screen is redrawn.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 *:echoe* *:echoerr*
3694:echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
3695 message in the |message-history|. When used in a
3696 script or function the line number will be added.
3697 Spaces are placed between the arguments as with the
Bram Moolenaar461a7fc2018-12-22 13:28:07 +01003698 |:echomsg| command. When used inside a try conditional,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 the message is raised as an error exception instead
3700 (see |try-echoerr|).
3701 Example: >
3702 :echoerr "This script just failed!"
3703< If you just want a highlighted message use |:echohl|.
3704 And to get a beep: >
3705 :exe "normal \<Esc>"
Bram Moolenaar4c868302021-03-22 16:19:45 +01003706
3707:echoc[onsole] {expr1} .. *:echoc* *:echoconsole*
3708 Intended for testing: works like `:echomsg` but when
3709 running in the GUI and started from a terminal write
3710 the text to stdout.
3711
Bram Moolenaar09c6f262019-11-17 15:55:14 +01003712 *:eval*
3713:eval {expr} Evaluate {expr} and discard the result. Example: >
3714 :eval Getlist()->Filter()->append('$')
3715
3716< The expression is supposed to have a side effect,
3717 since the resulting value is not used. In the example
3718 the `append()` call appends the List with text to the
3719 buffer. This is similar to `:call` but works with any
3720 expression.
3721
3722 The command can be shortened to `:ev` or `:eva`, but
3723 these are hard to recognize and therefore not to be
3724 used.
3725
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01003726 The command cannot be followed by "|" and another
3727 command, since "|" is seen as part of the expression.
3728
Bram Moolenaar09c6f262019-11-17 15:55:14 +01003729
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 *:exe* *:execute*
3731:exe[cute] {expr1} .. Executes the string that results from the evaluation
Bram Moolenaar00a927d2010-05-14 23:24:24 +02003732 of {expr1} as an Ex command.
3733 Multiple arguments are concatenated, with a space in
Bram Moolenaar7e6a5152021-01-02 16:39:53 +01003734 between. To avoid the extra space use the ".."
Bram Moolenaar00a927d2010-05-14 23:24:24 +02003735 operator to concatenate strings into one argument.
3736 {expr1} is used as the processed command, command line
3737 editing keys are not recognized.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 Cannot be followed by a comment.
3739 Examples: >
Bram Moolenaar00a927d2010-05-14 23:24:24 +02003740 :execute "buffer" nextbuf
Bram Moolenaarc8cdf0f2021-03-13 13:28:13 +01003741 :execute "normal" count .. "w"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742<
3743 ":execute" can be used to append a command to commands
3744 that don't accept a '|'. Example: >
3745 :execute '!ls' | echo "theend"
3746
3747< ":execute" is also a nice way to avoid having to type
3748 control characters in a Vim script for a ":normal"
3749 command: >
3750 :execute "normal ixxx\<Esc>"
3751< This has an <Esc> character, see |expr-string|.
3752
Bram Moolenaar446cb832008-06-24 21:56:24 +00003753 Be careful to correctly escape special characters in
3754 file names. The |fnameescape()| function can be used
Bram Moolenaar05bb9532008-07-04 09:44:11 +00003755 for Vim commands, |shellescape()| for |:!| commands.
3756 Examples: >
Bram Moolenaarc8cdf0f2021-03-13 13:28:13 +01003757 :execute "e " .. fnameescape(filename)
3758 :execute "!ls " .. shellescape(filename, 1)
Bram Moolenaar446cb832008-06-24 21:56:24 +00003759<
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 Note: The executed string may be any command-line, but
Bram Moolenaar76f3b1a2014-03-27 22:30:07 +01003761 starting or ending "if", "while" and "for" does not
3762 always work, because when commands are skipped the
3763 ":execute" is not evaluated and Vim loses track of
3764 where blocks start and end. Also "break" and
3765 "continue" should not be inside ":execute".
3766 This example does not work, because the ":execute" is
3767 not evaluated and Vim does not see the "while", and
3768 gives an error for finding an ":endwhile": >
3769 :if 0
3770 : execute 'while i > 5'
3771 : echo "test"
3772 : endwhile
3773 :endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774<
3775 It is allowed to have a "while" or "if" command
3776 completely in the executed string: >
3777 :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
3778<
3779
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01003780 *:exe-comment*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 ":execute", ":echo" and ":echon" cannot be followed by
3782 a comment directly, because they see the '"' as the
3783 start of a string. But, you can use '|' followed by a
3784 comment. Example: >
3785 :echo "foo" | "this is a comment
3786
3787==============================================================================
37888. Exception handling *exception-handling*
3789
3790The Vim script language comprises an exception handling feature. This section
3791explains how it can be used in a Vim script.
3792
3793Exceptions may be raised by Vim on an error or on interrupt, see
3794|catch-errors| and |catch-interrupt|. You can also explicitly throw an
3795exception by using the ":throw" command, see |throw-catch|.
3796
3797
3798TRY CONDITIONALS *try-conditionals*
3799
3800Exceptions can be caught or can cause cleanup code to be executed. You can
3801use a try conditional to specify catch clauses (that catch exceptions) and/or
3802a finally clause (to be executed for cleanup).
3803 A try conditional begins with a |:try| command and ends at the matching
3804|:endtry| command. In between, you can use a |:catch| command to start
3805a catch clause, or a |:finally| command to start a finally clause. There may
3806be none or multiple catch clauses, but there is at most one finally clause,
3807which must not be followed by any catch clauses. The lines before the catch
3808clauses and the finally clause is called a try block. >
3809
3810 :try
Bram Moolenaar446cb832008-06-24 21:56:24 +00003811 : ...
3812 : ... TRY BLOCK
3813 : ...
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 :catch /{pattern}/
Bram Moolenaar446cb832008-06-24 21:56:24 +00003815 : ...
3816 : ... CATCH CLAUSE
3817 : ...
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 :catch /{pattern}/
Bram Moolenaar446cb832008-06-24 21:56:24 +00003819 : ...
3820 : ... CATCH CLAUSE
3821 : ...
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 :finally
Bram Moolenaar446cb832008-06-24 21:56:24 +00003823 : ...
3824 : ... FINALLY CLAUSE
3825 : ...
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826 :endtry
3827
3828The try conditional allows to watch code for exceptions and to take the
3829appropriate actions. Exceptions from the try block may be caught. Exceptions
3830from the try block and also the catch clauses may cause cleanup actions.
3831 When no exception is thrown during execution of the try block, the control
3832is transferred to the finally clause, if present. After its execution, the
3833script continues with the line following the ":endtry".
3834 When an exception occurs during execution of the try block, the remaining
3835lines in the try block are skipped. The exception is matched against the
3836patterns specified as arguments to the ":catch" commands. The catch clause
3837after the first matching ":catch" is taken, other catch clauses are not
3838executed. The catch clause ends when the next ":catch", ":finally", or
3839":endtry" command is reached - whatever is first. Then, the finally clause
3840(if present) is executed. When the ":endtry" is reached, the script execution
3841continues in the following line as usual.
3842 When an exception that does not match any of the patterns specified by the
3843":catch" commands is thrown in the try block, the exception is not caught by
3844that try conditional and none of the catch clauses is executed. Only the
3845finally clause, if present, is taken. The exception pends during execution of
3846the finally clause. It is resumed at the ":endtry", so that commands after
3847the ":endtry" are not executed and the exception might be caught elsewhere,
3848see |try-nesting|.
3849 When during execution of a catch clause another exception is thrown, the
Bram Moolenaar58b85342016-08-14 19:54:54 +02003850remaining lines in that catch clause are not executed. The new exception is
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851not matched against the patterns in any of the ":catch" commands of the same
3852try conditional and none of its catch clauses is taken. If there is, however,
3853a finally clause, it is executed, and the exception pends during its
3854execution. The commands following the ":endtry" are not executed. The new
3855exception might, however, be caught elsewhere, see |try-nesting|.
3856 When during execution of the finally clause (if present) an exception is
Bram Moolenaar58b85342016-08-14 19:54:54 +02003857thrown, the remaining lines in the finally clause are skipped. If the finally
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858clause has been taken because of an exception from the try block or one of the
3859catch clauses, the original (pending) exception is discarded. The commands
3860following the ":endtry" are not executed, and the exception from the finally
3861clause is propagated and can be caught elsewhere, see |try-nesting|.
3862
3863The finally clause is also executed, when a ":break" or ":continue" for
3864a ":while" loop enclosing the complete try conditional is executed from the
3865try block or a catch clause. Or when a ":return" or ":finish" is executed
3866from the try block or a catch clause of a try conditional in a function or
3867sourced script, respectively. The ":break", ":continue", ":return", or
3868":finish" pends during execution of the finally clause and is resumed when the
3869":endtry" is reached. It is, however, discarded when an exception is thrown
3870from the finally clause.
3871 When a ":break" or ":continue" for a ":while" loop enclosing the complete
3872try conditional or when a ":return" or ":finish" is encountered in the finally
3873clause, the rest of the finally clause is skipped, and the ":break",
3874":continue", ":return" or ":finish" is executed as usual. If the finally
3875clause has been taken because of an exception or an earlier ":break",
3876":continue", ":return", or ":finish" from the try block or a catch clause,
3877this pending exception or command is discarded.
3878
3879For examples see |throw-catch| and |try-finally|.
3880
3881
3882NESTING OF TRY CONDITIONALS *try-nesting*
3883
3884Try conditionals can be nested arbitrarily. That is, a complete try
3885conditional can be put into the try block, a catch clause, or the finally
3886clause of another try conditional. If the inner try conditional does not
3887catch an exception thrown in its try block or throws a new exception from one
3888of its catch clauses or its finally clause, the outer try conditional is
3889checked according to the rules above. If the inner try conditional is in the
3890try block of the outer try conditional, its catch clauses are checked, but
Bram Moolenaar58b85342016-08-14 19:54:54 +02003891otherwise only the finally clause is executed. It does not matter for
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892nesting, whether the inner try conditional is directly contained in the outer
3893one, or whether the outer one sources a script or calls a function containing
3894the inner try conditional.
3895
3896When none of the active try conditionals catches an exception, just their
3897finally clauses are executed. Thereafter, the script processing terminates.
3898An error message is displayed in case of an uncaught exception explicitly
3899thrown by a ":throw" command. For uncaught error and interrupt exceptions
3900implicitly raised by Vim, the error message(s) or interrupt message are shown
3901as usual.
3902
3903For examples see |throw-catch|.
3904
3905
3906EXAMINING EXCEPTION HANDLING CODE *except-examine*
3907
3908Exception handling code can get tricky. If you are in doubt what happens, set
3909'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
3910script file. Then you see when an exception is thrown, discarded, caught, or
3911finished. When using a verbosity level of at least 14, things pending in
3912a finally clause are also shown. This information is also given in debug mode
3913(see |debug-scripts|).
3914
3915
3916THROWING AND CATCHING EXCEPTIONS *throw-catch*
3917
3918You can throw any number or string as an exception. Use the |:throw| command
3919and pass the value to be thrown as argument: >
3920 :throw 4711
3921 :throw "string"
3922< *throw-expression*
3923You can also specify an expression argument. The expression is then evaluated
3924first, and the result is thrown: >
3925 :throw 4705 + strlen("string")
3926 :throw strpart("strings", 0, 6)
3927
3928An exception might be thrown during evaluation of the argument of the ":throw"
3929command. Unless it is caught there, the expression evaluation is abandoned.
3930The ":throw" command then does not throw a new exception.
3931 Example: >
3932
3933 :function! Foo(arg)
3934 : try
3935 : throw a:arg
3936 : catch /foo/
3937 : endtry
3938 : return 1
3939 :endfunction
3940 :
3941 :function! Bar()
3942 : echo "in Bar"
3943 : return 4710
3944 :endfunction
3945 :
3946 :throw Foo("arrgh") + Bar()
3947
3948This throws "arrgh", and "in Bar" is not displayed since Bar() is not
3949executed. >
3950 :throw Foo("foo") + Bar()
3951however displays "in Bar" and throws 4711.
3952
3953Any other command that takes an expression as argument might also be
Bram Moolenaar58b85342016-08-14 19:54:54 +02003954abandoned by an (uncaught) exception during the expression evaluation. The
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955exception is then propagated to the caller of the command.
3956 Example: >
3957
3958 :if Foo("arrgh")
3959 : echo "then"
3960 :else
3961 : echo "else"
3962 :endif
3963
3964Here neither of "then" or "else" is displayed.
3965
3966 *catch-order*
3967Exceptions can be caught by a try conditional with one or more |:catch|
3968commands, see |try-conditionals|. The values to be caught by each ":catch"
3969command can be specified as a pattern argument. The subsequent catch clause
3970gets executed when a matching exception is caught.
3971 Example: >
3972
3973 :function! Foo(value)
3974 : try
3975 : throw a:value
3976 : catch /^\d\+$/
3977 : echo "Number thrown"
3978 : catch /.*/
3979 : echo "String thrown"
3980 : endtry
3981 :endfunction
3982 :
3983 :call Foo(0x1267)
3984 :call Foo('string')
3985
3986The first call to Foo() displays "Number thrown", the second "String thrown".
3987An exception is matched against the ":catch" commands in the order they are
3988specified. Only the first match counts. So you should place the more
3989specific ":catch" first. The following order does not make sense: >
3990
3991 : catch /.*/
3992 : echo "String thrown"
3993 : catch /^\d\+$/
3994 : echo "Number thrown"
3995
3996The first ":catch" here matches always, so that the second catch clause is
3997never taken.
3998
3999 *throw-variables*
4000If you catch an exception by a general pattern, you may access the exact value
4001in the variable |v:exception|: >
4002
4003 : catch /^\d\+$/
4004 : echo "Number thrown. Value is" v:exception
4005
4006You may also be interested where an exception was thrown. This is stored in
4007|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
4008exception most recently caught as long it is not finished.
4009 Example: >
4010
4011 :function! Caught()
4012 : if v:exception != ""
4013 : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
4014 : else
4015 : echo 'Nothing caught'
4016 : endif
4017 :endfunction
4018 :
4019 :function! Foo()
4020 : try
4021 : try
4022 : try
4023 : throw 4711
4024 : finally
4025 : call Caught()
4026 : endtry
4027 : catch /.*/
4028 : call Caught()
4029 : throw "oops"
4030 : endtry
4031 : catch /.*/
4032 : call Caught()
4033 : finally
4034 : call Caught()
4035 : endtry
4036 :endfunction
4037 :
4038 :call Foo()
4039
4040This displays >
4041
4042 Nothing caught
4043 Caught "4711" in function Foo, line 4
4044 Caught "oops" in function Foo, line 10
4045 Nothing caught
4046
4047A practical example: The following command ":LineNumber" displays the line
4048number in the script or function where it has been used: >
4049
4050 :function! LineNumber()
4051 : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
4052 :endfunction
4053 :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
4054<
4055 *try-nested*
4056An exception that is not caught by a try conditional can be caught by
4057a surrounding try conditional: >
4058
4059 :try
4060 : try
4061 : throw "foo"
4062 : catch /foobar/
4063 : echo "foobar"
4064 : finally
4065 : echo "inner finally"
4066 : endtry
4067 :catch /foo/
4068 : echo "foo"
4069 :endtry
4070
4071The inner try conditional does not catch the exception, just its finally
4072clause is executed. The exception is then caught by the outer try
4073conditional. The example displays "inner finally" and then "foo".
4074
4075 *throw-from-catch*
4076You can catch an exception and throw a new one to be caught elsewhere from the
4077catch clause: >
4078
4079 :function! Foo()
4080 : throw "foo"
4081 :endfunction
4082 :
4083 :function! Bar()
4084 : try
4085 : call Foo()
4086 : catch /foo/
4087 : echo "Caught foo, throw bar"
4088 : throw "bar"
4089 : endtry
4090 :endfunction
4091 :
4092 :try
4093 : call Bar()
4094 :catch /.*/
4095 : echo "Caught" v:exception
4096 :endtry
4097
4098This displays "Caught foo, throw bar" and then "Caught bar".
4099
4100 *rethrow*
4101There is no real rethrow in the Vim script language, but you may throw
4102"v:exception" instead: >
4103
4104 :function! Bar()
4105 : try
4106 : call Foo()
4107 : catch /.*/
4108 : echo "Rethrow" v:exception
4109 : throw v:exception
4110 : endtry
4111 :endfunction
4112< *try-echoerr*
4113Note that this method cannot be used to "rethrow" Vim error or interrupt
4114exceptions, because it is not possible to fake Vim internal exceptions.
4115Trying so causes an error exception. You should throw your own exception
4116denoting the situation. If you want to cause a Vim error exception containing
4117the original error exception value, you can use the |:echoerr| command: >
4118
4119 :try
4120 : try
4121 : asdf
4122 : catch /.*/
4123 : echoerr v:exception
4124 : endtry
4125 :catch /.*/
4126 : echo v:exception
4127 :endtry
4128
4129This code displays
4130
Bram Moolenaar446cb832008-06-24 21:56:24 +00004131 Vim(echoerr):Vim:E492: Not an editor command: asdf ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132
4133
4134CLEANUP CODE *try-finally*
4135
4136Scripts often change global settings and restore them at their end. If the
4137user however interrupts the script by pressing CTRL-C, the settings remain in
Bram Moolenaar58b85342016-08-14 19:54:54 +02004138an inconsistent state. The same may happen to you in the development phase of
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139a script when an error occurs or you explicitly throw an exception without
4140catching it. You can solve these problems by using a try conditional with
4141a finally clause for restoring the settings. Its execution is guaranteed on
4142normal control flow, on error, on an explicit ":throw", and on interrupt.
4143(Note that errors and interrupts from inside the try conditional are converted
Bram Moolenaar58b85342016-08-14 19:54:54 +02004144to exceptions. When not caught, they terminate the script after the finally
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145clause has been executed.)
4146Example: >
4147
4148 :try
4149 : let s:saved_ts = &ts
4150 : set ts=17
4151 :
4152 : " Do the hard work here.
4153 :
4154 :finally
4155 : let &ts = s:saved_ts
4156 : unlet s:saved_ts
4157 :endtry
4158
4159This method should be used locally whenever a function or part of a script
4160changes global settings which need to be restored on failure or normal exit of
4161that function or script part.
4162
4163 *break-finally*
4164Cleanup code works also when the try block or a catch clause is left by
4165a ":continue", ":break", ":return", or ":finish".
4166 Example: >
4167
4168 :let first = 1
4169 :while 1
4170 : try
4171 : if first
4172 : echo "first"
4173 : let first = 0
4174 : continue
4175 : else
4176 : throw "second"
4177 : endif
4178 : catch /.*/
4179 : echo v:exception
4180 : break
4181 : finally
4182 : echo "cleanup"
4183 : endtry
4184 : echo "still in while"
4185 :endwhile
4186 :echo "end"
4187
4188This displays "first", "cleanup", "second", "cleanup", and "end". >
4189
4190 :function! Foo()
4191 : try
4192 : return 4711
4193 : finally
4194 : echo "cleanup\n"
4195 : endtry
4196 : echo "Foo still active"
4197 :endfunction
4198 :
4199 :echo Foo() "returned by Foo"
4200
4201This displays "cleanup" and "4711 returned by Foo". You don't need to add an
Bram Moolenaar58b85342016-08-14 19:54:54 +02004202extra ":return" in the finally clause. (Above all, this would override the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203return value.)
4204
4205 *except-from-finally*
4206Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
4207a finally clause is possible, but not recommended since it abandons the
4208cleanup actions for the try conditional. But, of course, interrupt and error
4209exceptions might get raised from a finally clause.
4210 Example where an error in the finally clause stops an interrupt from
4211working correctly: >
4212
4213 :try
4214 : try
4215 : echo "Press CTRL-C for interrupt"
4216 : while 1
4217 : endwhile
4218 : finally
4219 : unlet novar
4220 : endtry
4221 :catch /novar/
4222 :endtry
4223 :echo "Script still running"
4224 :sleep 1
4225
4226If you need to put commands that could fail into a finally clause, you should
4227think about catching or ignoring the errors in these commands, see
4228|catch-errors| and |ignore-errors|.
4229
4230
4231CATCHING ERRORS *catch-errors*
4232
4233If you want to catch specific errors, you just have to put the code to be
4234watched in a try block and add a catch clause for the error message. The
4235presence of the try conditional causes all errors to be converted to an
4236exception. No message is displayed and |v:errmsg| is not set then. To find
4237the right pattern for the ":catch" command, you have to know how the format of
4238the error exception is.
4239 Error exceptions have the following format: >
4240
4241 Vim({cmdname}):{errmsg}
4242or >
4243 Vim:{errmsg}
4244
4245{cmdname} is the name of the command that failed; the second form is used when
Bram Moolenaar58b85342016-08-14 19:54:54 +02004246the command name is not known. {errmsg} is the error message usually produced
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247when the error occurs outside try conditionals. It always begins with
4248a capital "E", followed by a two or three-digit error number, a colon, and
4249a space.
4250
4251Examples:
4252
4253The command >
4254 :unlet novar
4255normally produces the error message >
4256 E108: No such variable: "novar"
4257which is converted inside try conditionals to an exception >
4258 Vim(unlet):E108: No such variable: "novar"
4259
4260The command >
4261 :dwim
4262normally produces the error message >
4263 E492: Not an editor command: dwim
4264which is converted inside try conditionals to an exception >
4265 Vim:E492: Not an editor command: dwim
4266
4267You can catch all ":unlet" errors by a >
4268 :catch /^Vim(unlet):/
4269or all errors for misspelled command names by a >
4270 :catch /^Vim:E492:/
4271
4272Some error messages may be produced by different commands: >
4273 :function nofunc
4274and >
4275 :delfunction nofunc
4276both produce the error message >
4277 E128: Function name must start with a capital: nofunc
4278which is converted inside try conditionals to an exception >
4279 Vim(function):E128: Function name must start with a capital: nofunc
4280or >
4281 Vim(delfunction):E128: Function name must start with a capital: nofunc
4282respectively. You can catch the error by its number independently on the
4283command that caused it if you use the following pattern: >
4284 :catch /^Vim(\a\+):E128:/
4285
4286Some commands like >
4287 :let x = novar
4288produce multiple error messages, here: >
4289 E121: Undefined variable: novar
4290 E15: Invalid expression: novar
4291Only the first is used for the exception value, since it is the most specific
4292one (see |except-several-errors|). So you can catch it by >
4293 :catch /^Vim(\a\+):E121:/
4294
4295You can catch all errors related to the name "nofunc" by >
4296 :catch /\<nofunc\>/
4297
4298You can catch all Vim errors in the ":write" and ":read" commands by >
4299 :catch /^Vim(\(write\|read\)):E\d\+:/
4300
4301You can catch all Vim errors by the pattern >
4302 :catch /^Vim\((\a\+)\)\=:E\d\+:/
4303<
4304 *catch-text*
4305NOTE: You should never catch the error message text itself: >
4306 :catch /No such variable/
Bram Moolenaar2b8388b2015-02-28 13:11:45 +01004307only works in the English locale, but not when the user has selected
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308a different language by the |:language| command. It is however helpful to
4309cite the message text in a comment: >
4310 :catch /^Vim(\a\+):E108:/ " No such variable
4311
4312
4313IGNORING ERRORS *ignore-errors*
4314
4315You can ignore errors in a specific Vim command by catching them locally: >
4316
4317 :try
4318 : write
4319 :catch
4320 :endtry
4321
4322But you are strongly recommended NOT to use this simple form, since it could
4323catch more than you want. With the ":write" command, some autocommands could
4324be executed and cause errors not related to writing, for instance: >
4325
4326 :au BufWritePre * unlet novar
4327
4328There could even be such errors you are not responsible for as a script
4329writer: a user of your script might have defined such autocommands. You would
4330then hide the error from the user.
4331 It is much better to use >
4332
4333 :try
4334 : write
4335 :catch /^Vim(write):/
4336 :endtry
4337
4338which only catches real write errors. So catch only what you'd like to ignore
4339intentionally.
4340
4341For a single command that does not cause execution of autocommands, you could
4342even suppress the conversion of errors to exceptions by the ":silent!"
4343command: >
4344 :silent! nunmap k
4345This works also when a try conditional is active.
4346
4347
4348CATCHING INTERRUPTS *catch-interrupt*
4349
4350When there are active try conditionals, an interrupt (CTRL-C) is converted to
Bram Moolenaar58b85342016-08-14 19:54:54 +02004351the exception "Vim:Interrupt". You can catch it like every exception. The
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352script is not terminated, then.
4353 Example: >
4354
4355 :function! TASK1()
4356 : sleep 10
4357 :endfunction
4358
4359 :function! TASK2()
4360 : sleep 20
4361 :endfunction
4362
4363 :while 1
4364 : let command = input("Type a command: ")
4365 : try
4366 : if command == ""
4367 : continue
4368 : elseif command == "END"
4369 : break
4370 : elseif command == "TASK1"
4371 : call TASK1()
4372 : elseif command == "TASK2"
4373 : call TASK2()
4374 : else
4375 : echo "\nIllegal command:" command
4376 : continue
4377 : endif
4378 : catch /^Vim:Interrupt$/
4379 : echo "\nCommand interrupted"
4380 : " Caught the interrupt. Continue with next prompt.
4381 : endtry
4382 :endwhile
4383
4384You can interrupt a task here by pressing CTRL-C; the script then asks for
Bram Moolenaar58b85342016-08-14 19:54:54 +02004385a new command. If you press CTRL-C at the prompt, the script is terminated.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386
4387For testing what happens when CTRL-C would be pressed on a specific line in
4388your script, use the debug mode and execute the |>quit| or |>interrupt|
4389command on that line. See |debug-scripts|.
4390
4391
4392CATCHING ALL *catch-all*
4393
4394The commands >
4395
4396 :catch /.*/
4397 :catch //
4398 :catch
4399
4400catch everything, error exceptions, interrupt exceptions and exceptions
4401explicitly thrown by the |:throw| command. This is useful at the top level of
4402a script in order to catch unexpected things.
4403 Example: >
4404
4405 :try
4406 :
4407 : " do the hard work here
4408 :
4409 :catch /MyException/
4410 :
4411 : " handle known problem
4412 :
4413 :catch /^Vim:Interrupt$/
4414 : echo "Script interrupted"
4415 :catch /.*/
4416 : echo "Internal error (" . v:exception . ")"
4417 : echo " - occurred at " . v:throwpoint
4418 :endtry
4419 :" end of script
4420
4421Note: Catching all might catch more things than you want. Thus, you are
4422strongly encouraged to catch only for problems that you can really handle by
4423specifying a pattern argument to the ":catch".
4424 Example: Catching all could make it nearly impossible to interrupt a script
4425by pressing CTRL-C: >
4426
4427 :while 1
4428 : try
4429 : sleep 1
4430 : catch
4431 : endtry
4432 :endwhile
4433
4434
4435EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
4436
4437Exceptions may be used during execution of autocommands. Example: >
4438
4439 :autocmd User x try
4440 :autocmd User x throw "Oops!"
4441 :autocmd User x catch
4442 :autocmd User x echo v:exception
4443 :autocmd User x endtry
4444 :autocmd User x throw "Arrgh!"
4445 :autocmd User x echo "Should not be displayed"
4446 :
4447 :try
4448 : doautocmd User x
4449 :catch
4450 : echo v:exception
4451 :endtry
4452
4453This displays "Oops!" and "Arrgh!".
4454
4455 *except-autocmd-Pre*
4456For some commands, autocommands get executed before the main action of the
4457command takes place. If an exception is thrown and not caught in the sequence
4458of autocommands, the sequence and the command that caused its execution are
4459abandoned and the exception is propagated to the caller of the command.
4460 Example: >
4461
4462 :autocmd BufWritePre * throw "FAIL"
4463 :autocmd BufWritePre * echo "Should not be displayed"
4464 :
4465 :try
4466 : write
4467 :catch
4468 : echo "Caught:" v:exception "from" v:throwpoint
4469 :endtry
4470
4471Here, the ":write" command does not write the file currently being edited (as
4472you can see by checking 'modified'), since the exception from the BufWritePre
4473autocommand abandons the ":write". The exception is then caught and the
4474script displays: >
4475
4476 Caught: FAIL from BufWrite Auto commands for "*"
4477<
4478 *except-autocmd-Post*
4479For some commands, autocommands get executed after the main action of the
4480command has taken place. If this main action fails and the command is inside
4481an active try conditional, the autocommands are skipped and an error exception
4482is thrown that can be caught by the caller of the command.
4483 Example: >
4484
4485 :autocmd BufWritePost * echo "File successfully written!"
4486 :
4487 :try
4488 : write /i/m/p/o/s/s/i/b/l/e
4489 :catch
4490 : echo v:exception
4491 :endtry
4492
4493This just displays: >
4494
4495 Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
4496
4497If you really need to execute the autocommands even when the main action
4498fails, trigger the event from the catch clause.
4499 Example: >
4500
4501 :autocmd BufWritePre * set noreadonly
4502 :autocmd BufWritePost * set readonly
4503 :
4504 :try
4505 : write /i/m/p/o/s/s/i/b/l/e
4506 :catch
4507 : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
4508 :endtry
4509<
4510You can also use ":silent!": >
4511
4512 :let x = "ok"
4513 :let v:errmsg = ""
4514 :autocmd BufWritePost * if v:errmsg != ""
4515 :autocmd BufWritePost * let x = "after fail"
4516 :autocmd BufWritePost * endif
4517 :try
4518 : silent! write /i/m/p/o/s/s/i/b/l/e
4519 :catch
4520 :endtry
4521 :echo x
4522
4523This displays "after fail".
4524
4525If the main action of the command does not fail, exceptions from the
4526autocommands will be catchable by the caller of the command: >
4527
4528 :autocmd BufWritePost * throw ":-("
4529 :autocmd BufWritePost * echo "Should not be displayed"
4530 :
4531 :try
4532 : write
4533 :catch
4534 : echo v:exception
4535 :endtry
4536<
4537 *except-autocmd-Cmd*
4538For some commands, the normal action can be replaced by a sequence of
4539autocommands. Exceptions from that sequence will be catchable by the caller
4540of the command.
4541 Example: For the ":write" command, the caller cannot know whether the file
Bram Moolenaar58b85342016-08-14 19:54:54 +02004542had actually been written when the exception occurred. You need to tell it in
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543some way. >
4544
4545 :if !exists("cnt")
4546 : let cnt = 0
4547 :
4548 : autocmd BufWriteCmd * if &modified
4549 : autocmd BufWriteCmd * let cnt = cnt + 1
4550 : autocmd BufWriteCmd * if cnt % 3 == 2
4551 : autocmd BufWriteCmd * throw "BufWriteCmdError"
4552 : autocmd BufWriteCmd * endif
4553 : autocmd BufWriteCmd * write | set nomodified
4554 : autocmd BufWriteCmd * if cnt % 3 == 0
4555 : autocmd BufWriteCmd * throw "BufWriteCmdError"
4556 : autocmd BufWriteCmd * endif
4557 : autocmd BufWriteCmd * echo "File successfully written!"
4558 : autocmd BufWriteCmd * endif
4559 :endif
4560 :
4561 :try
4562 : write
4563 :catch /^BufWriteCmdError$/
4564 : if &modified
4565 : echo "Error on writing (file contents not changed)"
4566 : else
4567 : echo "Error after writing"
4568 : endif
4569 :catch /^Vim(write):/
4570 : echo "Error on writing"
4571 :endtry
4572
4573When this script is sourced several times after making changes, it displays
4574first >
4575 File successfully written!
4576then >
4577 Error on writing (file contents not changed)
4578then >
4579 Error after writing
4580etc.
4581
4582 *except-autocmd-ill*
4583You cannot spread a try conditional over autocommands for different events.
4584The following code is ill-formed: >
4585
4586 :autocmd BufWritePre * try
4587 :
4588 :autocmd BufWritePost * catch
4589 :autocmd BufWritePost * echo v:exception
4590 :autocmd BufWritePost * endtry
4591 :
4592 :write
4593
4594
4595EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
4596
4597Some programming languages allow to use hierarchies of exception classes or to
4598pass additional information with the object of an exception class. You can do
4599similar things in Vim.
4600 In order to throw an exception from a hierarchy, just throw the complete
4601class name with the components separated by a colon, for instance throw the
4602string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
4603 When you want to pass additional information with your exception class, add
4604it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
4605for an error when writing "myfile".
4606 With the appropriate patterns in the ":catch" command, you can catch for
4607base classes or derived classes of your hierarchy. Additional information in
4608parentheses can be cut out from |v:exception| with the ":substitute" command.
4609 Example: >
4610
4611 :function! CheckRange(a, func)
4612 : if a:a < 0
4613 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
4614 : endif
4615 :endfunction
4616 :
4617 :function! Add(a, b)
4618 : call CheckRange(a:a, "Add")
4619 : call CheckRange(a:b, "Add")
4620 : let c = a:a + a:b
4621 : if c < 0
4622 : throw "EXCEPT:MATHERR:OVERFLOW"
4623 : endif
4624 : return c
4625 :endfunction
4626 :
4627 :function! Div(a, b)
4628 : call CheckRange(a:a, "Div")
4629 : call CheckRange(a:b, "Div")
4630 : if (a:b == 0)
4631 : throw "EXCEPT:MATHERR:ZERODIV"
4632 : endif
4633 : return a:a / a:b
4634 :endfunction
4635 :
4636 :function! Write(file)
4637 : try
Bram Moolenaar446cb832008-06-24 21:56:24 +00004638 : execute "write" fnameescape(a:file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 : catch /^Vim(write):/
4640 : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
4641 : endtry
4642 :endfunction
4643 :
4644 :try
4645 :
4646 : " something with arithmetics and I/O
4647 :
4648 :catch /^EXCEPT:MATHERR:RANGE/
4649 : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
4650 : echo "Range error in" function
4651 :
4652 :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
4653 : echo "Math error"
4654 :
4655 :catch /^EXCEPT:IO/
4656 : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
4657 : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
4658 : if file !~ '^/'
4659 : let file = dir . "/" . file
4660 : endif
4661 : echo 'I/O error for "' . file . '"'
4662 :
4663 :catch /^EXCEPT/
4664 : echo "Unspecified error"
4665 :
4666 :endtry
4667
4668The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
4669a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
4670exceptions with the "Vim" prefix; they are reserved for Vim.
4671 Vim error exceptions are parameterized with the name of the command that
4672failed, if known. See |catch-errors|.
4673
4674
4675PECULIARITIES
4676 *except-compat*
4677The exception handling concept requires that the command sequence causing the
4678exception is aborted immediately and control is transferred to finally clauses
4679and/or a catch clause.
4680
4681In the Vim script language there are cases where scripts and functions
4682continue after an error: in functions without the "abort" flag or in a command
4683after ":silent!", control flow goes to the following line, and outside
4684functions, control flow goes to the line following the outermost ":endwhile"
4685or ":endif". On the other hand, errors should be catchable as exceptions
4686(thus, requiring the immediate abortion).
4687
4688This problem has been solved by converting errors to exceptions and using
4689immediate abortion (if not suppressed by ":silent!") only when a try
Bram Moolenaar58b85342016-08-14 19:54:54 +02004690conditional is active. This is no restriction since an (error) exception can
4691be caught only from an active try conditional. If you want an immediate
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692termination without catching the error, just use a try conditional without
4693catch clause. (You can cause cleanup code being executed before termination
4694by specifying a finally clause.)
4695
4696When no try conditional is active, the usual abortion and continuation
4697behavior is used instead of immediate abortion. This ensures compatibility of
4698scripts written for Vim 6.1 and earlier.
4699
4700However, when sourcing an existing script that does not use exception handling
4701commands (or when calling one of its functions) from inside an active try
4702conditional of a new script, you might change the control flow of the existing
4703script on error. You get the immediate abortion on error and can catch the
4704error in the new script. If however the sourced script suppresses error
4705messages by using the ":silent!" command (checking for errors by testing
Bram Moolenaar58b85342016-08-14 19:54:54 +02004706|v:errmsg| if appropriate), its execution path is not changed. The error is
4707not converted to an exception. (See |:silent|.) So the only remaining cause
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708where this happens is for scripts that don't care about errors and produce
4709error messages. You probably won't want to use such code from your new
4710scripts.
4711
4712 *except-syntax-err*
4713Syntax errors in the exception handling commands are never caught by any of
4714the ":catch" commands of the try conditional they belong to. Its finally
4715clauses, however, is executed.
4716 Example: >
4717
4718 :try
4719 : try
4720 : throw 4711
4721 : catch /\(/
4722 : echo "in catch with syntax error"
4723 : catch
4724 : echo "inner catch-all"
4725 : finally
4726 : echo "inner finally"
4727 : endtry
4728 :catch
4729 : echo 'outer catch-all caught "' . v:exception . '"'
4730 : finally
4731 : echo "outer finally"
4732 :endtry
4733
4734This displays: >
4735 inner finally
4736 outer catch-all caught "Vim(catch):E54: Unmatched \("
4737 outer finally
4738The original exception is discarded and an error exception is raised, instead.
4739
4740 *except-single-line*
4741The ":try", ":catch", ":finally", and ":endtry" commands can be put on
4742a single line, but then syntax errors may make it difficult to recognize the
4743"catch" line, thus you better avoid this.
4744 Example: >
4745 :try | unlet! foo # | catch | endtry
4746raises an error exception for the trailing characters after the ":unlet!"
4747argument, but does not see the ":catch" and ":endtry" commands, so that the
4748error exception is discarded and the "E488: Trailing characters" message gets
4749displayed.
4750
4751 *except-several-errors*
4752When several errors appear in a single command, the first error message is
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02004753usually the most specific one and therefore converted to the error exception.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 Example: >
4755 echo novar
4756causes >
4757 E121: Undefined variable: novar
4758 E15: Invalid expression: novar
4759The value of the error exception inside try conditionals is: >
4760 Vim(echo):E121: Undefined variable: novar
4761< *except-syntax-error*
4762But when a syntax error is detected after a normal error in the same command,
4763the syntax error is used for the exception being thrown.
4764 Example: >
4765 unlet novar #
4766causes >
4767 E108: No such variable: "novar"
4768 E488: Trailing characters
4769The value of the error exception inside try conditionals is: >
4770 Vim(unlet):E488: Trailing characters
4771This is done because the syntax error might change the execution path in a way
4772not intended by the user. Example: >
4773 try
4774 try | unlet novar # | catch | echo v:exception | endtry
4775 catch /.*/
4776 echo "outer catch:" v:exception
4777 endtry
4778This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
4779a "E600: Missing :endtry" error message is given, see |except-single-line|.
4780
4781==============================================================================
47829. Examples *eval-examples*
4783
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004784Printing in Binary ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785>
Bram Moolenaar8f3f58f2010-01-06 20:52:26 +01004786 :" The function Nr2Bin() returns the binary string representation of a number.
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004787 :func Nr2Bin(nr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 : let n = a:nr
4789 : let r = ""
4790 : while n
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004791 : let r = '01'[n % 2] . r
4792 : let n = n / 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 : endwhile
4794 : return r
4795 :endfunc
4796
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004797 :" The function String2Bin() converts each character in a string to a
4798 :" binary string, separated with dashes.
4799 :func String2Bin(str)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 : let out = ''
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004801 : for ix in range(strlen(a:str))
4802 : let out = out . '-' . Nr2Bin(char2nr(a:str[ix]))
4803 : endfor
4804 : return out[1:]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 :endfunc
4806
4807Example of its use: >
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004808 :echo Nr2Bin(32)
4809result: "100000" >
4810 :echo String2Bin("32")
4811result: "110011-110010"
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
4813
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004814Sorting lines ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004816This example sorts lines with a specific compare function. >
4817
4818 :func SortBuffer()
4819 : let lines = getline(1, '$')
4820 : call sort(lines, function("Strcmp"))
4821 : call setline(1, lines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822 :endfunction
4823
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004824As a one-liner: >
4825 :call setline(1, sort(getline(1, '$'), function("Strcmp")))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004828scanf() replacement ~
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829 *sscanf*
4830There is no sscanf() function in Vim. If you need to extract parts from a
4831line, you can use matchstr() and substitute() to do it. This example shows
4832how to get the file name, line number and column number out of a line like
4833"foobar.txt, 123, 45". >
4834 :" Set up the match bit
4835 :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
4836 :"get the part matching the whole expression
4837 :let l = matchstr(line, mx)
4838 :"get each item out of the match
4839 :let file = substitute(l, mx, '\1', '')
4840 :let lnum = substitute(l, mx, '\2', '')
4841 :let col = substitute(l, mx, '\3', '')
4842
4843The input is in the variable "line", the results in the variables "file",
4844"lnum" and "col". (idea from Michael Geddes)
4845
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004846
4847getting the scriptnames in a Dictionary ~
4848 *scriptnames-dictionary*
4849The |:scriptnames| command can be used to get a list of all script files that
4850have been sourced. There is no equivalent function or variable for this
4851(because it's rarely needed). In case you need to manipulate the list this
4852code can be used: >
4853 " Get the output of ":scriptnames" in the scriptnames_output variable.
4854 let scriptnames_output = ''
4855 redir => scriptnames_output
4856 silent scriptnames
4857 redir END
Bram Moolenaarb0d45e72017-11-05 18:19:24 +01004858
Bram Moolenaar446cb832008-06-24 21:56:24 +00004859 " Split the output into lines and parse each line. Add an entry to the
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004860 " "scripts" dictionary.
4861 let scripts = {}
4862 for line in split(scriptnames_output, "\n")
4863 " Only do non-blank lines.
4864 if line =~ '\S'
4865 " Get the first number in the line.
Bram Moolenaar446cb832008-06-24 21:56:24 +00004866 let nr = matchstr(line, '\d\+')
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004867 " Get the file name, remove the script number " 123: ".
Bram Moolenaar446cb832008-06-24 21:56:24 +00004868 let name = substitute(line, '.\+:\s*', '', '')
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004869 " Add an item to the Dictionary
Bram Moolenaar446cb832008-06-24 21:56:24 +00004870 let scripts[nr] = name
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004871 endif
4872 endfor
4873 unlet scriptnames_output
4874
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875==============================================================================
Bram Moolenaar558ca4a2019-04-04 18:15:38 +0200487610. Vim script versions *vimscript-version* *vimscript-versions*
Bram Moolenaar911ead12019-04-21 00:03:35 +02004877 *scriptversion*
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004878Over time many features have been added to Vim script. This includes Ex
4879commands, functions, variable types, etc. Each individual feature can be
4880checked with the |has()| and |exists()| functions.
4881
4882Sometimes old syntax of functionality gets in the way of making Vim better.
4883When support is taken away this will break older Vim scripts. To make this
4884explicit the |:scriptversion| command can be used. When a Vim script is not
4885compatible with older versions of Vim this will give an explicit error,
Bram Moolenaar3ff5f0f2019-06-10 13:11:22 +02004886instead of failing in mysterious ways.
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004887
Bram Moolenaar3ff5f0f2019-06-10 13:11:22 +02004888 *scriptversion-1* >
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004889 :scriptversion 1
4890< This is the original Vim script, same as not using a |:scriptversion|
4891 command. Can be used to go back to old syntax for a range of lines.
4892 Test for support with: >
4893 has('vimscript-1')
4894
Bram Moolenaar3ff5f0f2019-06-10 13:11:22 +02004895< *scriptversion-2* >
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004896 :scriptversion 2
Bram Moolenaar68e65602019-05-26 21:33:31 +02004897< String concatenation with "." is not supported, use ".." instead.
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004898 This avoids the ambiguity using "." for Dict member access and
4899 floating point numbers. Now ".5" means the number 0.5.
Bram Moolenaar3ff5f0f2019-06-10 13:11:22 +02004900
4901 *scriptversion-3* >
Bram Moolenaar911ead12019-04-21 00:03:35 +02004902 :scriptversion 3
4903< All |vim-variable|s must be prefixed by "v:". E.g. "version" doesn't
4904 work as |v:version| anymore, it can be used as a normal variable.
4905 Same for some obvious names as "count" and others.
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004906
Bram Moolenaar911ead12019-04-21 00:03:35 +02004907 Test for support with: >
4908 has('vimscript-3')
Bram Moolenaar60a8de22019-09-15 14:33:22 +02004909<
4910 *scriptversion-4* >
4911 :scriptversion 4
Bram Moolenaarc17e66c2020-06-02 21:38:22 +02004912< Numbers with a leading zero are not recognized as octal. "0o" or "0O"
4913 is still recognized as octal. With the
Bram Moolenaar60a8de22019-09-15 14:33:22 +02004914 previous version you get: >
Bram Moolenaarc17e66c2020-06-02 21:38:22 +02004915 echo 017 " displays 15 (octal)
4916 echo 0o17 " displays 15 (octal)
4917 echo 018 " displays 18 (decimal)
Bram Moolenaar60a8de22019-09-15 14:33:22 +02004918< with script version 4: >
Bram Moolenaarc17e66c2020-06-02 21:38:22 +02004919 echo 017 " displays 17 (decimal)
4920 echo 0o17 " displays 15 (octal)
4921 echo 018 " displays 18 (decimal)
Bram Moolenaar60a8de22019-09-15 14:33:22 +02004922< Also, it is possible to use single quotes inside numbers to make them
4923 easier to read: >
4924 echo 1'000'000
4925< The quotes must be surrounded by digits.
4926
4927 Test for support with: >
4928 has('vimscript-4')
Bram Moolenaar558ca4a2019-04-04 18:15:38 +02004929
4930==============================================================================
493111. No +eval feature *no-eval-feature*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932
4933When the |+eval| feature was disabled at compile time, none of the expression
4934evaluation commands are available. To prevent this from causing Vim scripts
4935to generate all kinds of errors, the ":if" and ":endif" commands are still
4936recognized, though the argument of the ":if" and everything between the ":if"
4937and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
4938only if the commands are at the start of the line. The ":else" command is not
4939recognized.
4940
4941Example of how to avoid executing commands when the |+eval| feature is
4942missing: >
4943
4944 :if 1
4945 : echo "Expression evaluation is compiled in"
4946 :else
4947 : echo "You will _never_ see this message"
4948 :endif
4949
Bram Moolenaar773a97c2019-06-06 20:39:55 +02004950To execute a command only when the |+eval| feature is disabled can be done in
4951two ways. The simplest is to exit the script (or Vim) prematurely: >
4952 if 1
4953 echo "commands executed with +eval"
4954 finish
4955 endif
4956 args " command executed without +eval
4957
4958If you do not want to abort loading the script you can use a trick, as this
4959example shows: >
Bram Moolenaar45d2cca2017-04-30 16:36:05 +02004960
4961 silent! while 0
4962 set history=111
4963 silent! endwhile
4964
4965When the |+eval| feature is available the command is skipped because of the
4966"while 0". Without the |+eval| feature the "while 0" is an error, which is
4967silently ignored, and the command is executed.
Bram Moolenaarcd5c8f82017-04-09 20:11:58 +02004968
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969==============================================================================
Bram Moolenaar2f0936c2022-01-08 21:51:59 +0000497012. The sandbox *eval-sandbox* *sandbox*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971
Bram Moolenaar368373e2010-07-19 20:46:22 +02004972The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and
4973'foldtext' options may be evaluated in a sandbox. This means that you are
4974protected from these expressions having nasty side effects. This gives some
4975safety for when these options are set from a modeline. It is also used when
4976the command from a tags file is executed and for CTRL-R = in the command line.
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004977The sandbox is also used for the |:sandbox| command.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00004978 *E48*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979These items are not allowed in the sandbox:
4980 - changing the buffer text
Bram Moolenaarb477af22018-07-15 20:20:18 +02004981 - defining or changing mapping, autocommands, user commands
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 - setting certain options (see |option-summary|)
Bram Moolenaaref2f6562007-05-06 13:32:59 +00004983 - setting certain v: variables (see |v:var|) *E794*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 - executing a shell command
4985 - reading or writing a file
4986 - jumping to another buffer or editing a file
Bram Moolenaar4770d092006-01-12 23:22:24 +00004987 - executing Python, Perl, etc. commands
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004988This is not guaranteed 100% secure, but it should block most attacks.
4989
4990 *:san* *:sandbox*
Bram Moolenaar045e82d2005-07-08 22:25:33 +00004991:san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004992 option that may have been set from a modeline, e.g.
4993 'foldexpr'.
4994
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00004995 *sandbox-option*
4996A few options contain an expression. When this expression is evaluated it may
Bram Moolenaar9b2200a2006-03-20 21:55:45 +00004997have to be done in the sandbox to avoid a security risk. But the sandbox is
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00004998restrictive, thus this only happens when the option was set from an insecure
4999location. Insecure in this context are:
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00005000- sourcing a .vimrc or .exrc in the current directory
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00005001- while executing in the sandbox
5002- value coming from a modeline
Bram Moolenaarb477af22018-07-15 20:20:18 +02005003- executing a function that was defined in the sandbox
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00005004
5005Note that when in the sandbox and saving an option value and restoring it, the
5006option will still be marked as it was set in the sandbox.
5007
5008==============================================================================
Bram Moolenaar558ca4a2019-04-04 18:15:38 +0200500913. Textlock *textlock*
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00005010
5011In a few situations it is not allowed to change the text in the buffer, jump
5012to another window and some other things that might confuse or break what Vim
5013is currently doing. This mostly applies to things that happen when Vim is
Bram Moolenaar58b85342016-08-14 19:54:54 +02005014actually doing something else. For example, evaluating the 'balloonexpr' may
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00005015happen any moment the mouse cursor is resting at some position.
5016
5017This is not allowed when the textlock is active:
5018 - changing the buffer text
5019 - jumping to another buffer or window
5020 - editing another file
5021 - closing a window or quitting Vim
5022 - etc.
5023
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024
Bram Moolenaar91f84f62018-07-29 15:07:52 +02005025 vim:tw=78:ts=8:noet:ft=help:norl: