blob: 748dd7cd55367437c1f237149cac16572df8096b [file] [log] [blame]
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Jul 17
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
8
Bram Moolenaar7ceefb32020-05-01 16:07:38 +02009Vim9 script commands and expressions. *vim9*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010010
11Most expression help is in |eval.txt|. This file is about the new syntax and
12features in Vim9 script.
13
14THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
15
16
171 What is Vim9 script? |vim9-script|
182. Differences |vim9-differences|
193. New style functions |fast-functions|
204. Types |vim9-types|
215. Namespace, Import and Export |vim9script|
22
239. Rationale |vim9-rationale|
24
25==============================================================================
26
271. What is Vim9 script? *vim9-script*
28
29THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
30
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020031Vim script has been growing over time, while preserving backwards
32compatibility. That means bad choices from the past often can't be changed
Bram Moolenaar73fef332020-06-21 22:12:03 +020033and compatibility with Vi restricts possible solutions. Execution is quite
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020034slow, each line is parsed every time it is executed.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010035
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020036The main goal of Vim9 script is to drastically improve performance. This is
37accomplished by compiling commands into instructions that can be efficiently
38executed. An increase in execution speed of 10 to 100 times can be expected.
39
40A secondary goal is to avoid Vim-specific constructs and get closer to
41commonly used programming languages, such as JavaScript, TypeScript and Java.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010042
43The performance improvements can only be achieved by not being 100% backwards
Bram Moolenaar388a5d42020-05-26 21:20:45 +020044compatible. For example, making function arguments available in the
45"a:" dictionary adds quite a lot of overhead. In a Vim9 function this
46dictionary is not available. Other differences are more subtle, such as how
47errors are handled.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010048
49The Vim9 script syntax and semantics are used in:
50- a function defined with the `:def` command
51- a script file where the first command is `vim9script`
52
53When using `:function` in a Vim9 script file the legacy syntax is used.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020054However, this can be confusing and is therefore discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010055
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020056Vim9 script and legacy Vim script can be mixed. There is no requirement to
57rewrite old scripts, they keep working as before.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010058
59==============================================================================
60
612. Differences from legacy Vim script *vim9-differences*
62
63THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
64
Bram Moolenaar2c330432020-04-13 14:41:35 +020065Comments starting with # ~
66
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +020067In legacy Vim script comments start with double quote. In Vim9 script
68comments start with #. >
69 # declarations
Bram Moolenaar73fef332020-06-21 22:12:03 +020070 let count = 0 # number of occurrences
Bram Moolenaar2c330432020-04-13 14:41:35 +020071
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +020072The reason is that a double quote can also be the start of a string. In many
73places, especially halfway an expression with a line break, it's hard to tell
74what the meaning is. To avoid confusion only # comments are recognized.
75This is the same as in shell scripts and Python programs.
76
77In Vi # is a command to list text with numbers. In Vim9 script you can use
78`:number` for that. >
79 101number
80
81To improve readability there must be a space between a command and the #
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020082that starts a comment. Note that #{ is the start of a dictionary, therefore
83it cannot start a comment.
84
Bram Moolenaar2c330432020-04-13 14:41:35 +020085
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010086Vim9 functions ~
87
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020088A function defined with `:def` is compiled. Execution is many times faster,
89often 10x to 100x times.
90
Bram Moolenaar388a5d42020-05-26 21:20:45 +020091Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020092The syntax is strict, to enforce code that is easy to read and understand.
93
Bram Moolenaar388a5d42020-05-26 21:20:45 +020094Compilation is done when the function is first called, or when the
95`:defcompile` command is encountered in the script where the function was
96defined.
97
98`:def` has no options like `:function` does: "range", "abort", "dict" or
99"closure". A `:def` function always aborts on an error, does not get a range
100passed and cannot be a "dict" function.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100101
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200102The argument types and return type need to be specified. The "any" type can
103be used, type checking will then be done at runtime, like with legacy
104functions.
105
106Arguments are accessed by name, without "a:". There is no "a:" dictionary or
107"a:000" list.
108
109Variable arguments are defined as the last argument, with a name and have a
110list type, similar to Typescript. For example, a list of numbers: >
111 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100112 for item in itemlist
113 ...
114
115
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200116Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200117 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200118When using `:function` or `:def` to specify a new function at the script level
119in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200120prefixed. Using the "s:" prefix is optional.
121
122To define or use a global function or variable the "g:" prefix must be used.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200123
124When using `:function` or `:def` to specify a new function inside a function,
125the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200126script-local function inside a function. It is possible to define a global
127function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200128
129When referring to a function and no "s:" or "g:" prefix is used, Vim will
130search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200131- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200132- Local to the current script file.
133- Imported functions, see `:import`.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200134In all cases the function must be defined before used. That is when it is
135first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200136
137The result is that functions and variables without a namespace can always be
138found in the script, either defined there or imported. Global functions and
139variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200140
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200141Global functions can be still be defined and deleted at nearly any time. In
142Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200143and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200144
145
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100146Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200147 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100148Local variables need to be declared with `:let`. Local constants need to be
149declared with `:const`. We refer to both as "variables".
150
151Variables can be local to a script, function or code block: >
152 vim9script
153 let script_var = 123
154 def SomeFunc()
155 let func_var = script_var
156 if cond
157 let block_var = func_var
158 ...
159
160The variables are only visible in the block where they are defined and nested
161blocks. Once the block ends the variable is no longer accessible: >
162 if cond
163 let inner = 5
164 else
165 let inner = 0
166 endif
167 echo inner " Error!
168
169The declaration must be done earlier: >
170 let inner: number
171 if cond
172 inner = 5
173 else
174 inner = 0
175 endif
176 echo inner
177
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200178To intentionally avoid a variable being available later, a block can be used:
179>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100180 {
181 let temp = 'temp'
182 ...
183 }
184 echo temp " Error!
185
Bram Moolenaar560979e2020-02-04 22:53:05 +0100186An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100187declaration. An exception is global variables: these can be both used with
188and without `:let`, because there is no rule about where they are declared.
189
190Variables cannot shadow previously defined variables.
191Variables may shadow Ex commands, rename the variable if needed.
192
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200193Global variables and user defined functions must be prefixed with "g:", also
194at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200195 vim9script
196 let script_local = 'text'
197 let g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200198 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200199
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100200Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
201used to repeat a `:substitute` command.
202
203
204Omitting :call and :eval ~
205
206Functions can be called without `:call`: >
207 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100208Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100209
210A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100211identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100212 myList->add(123) " works
213 g:myList->add(123) " works
214 [1, 2, 3]->Process() " works
215 #{a: 1, b: 2}->Process() " works
216 {'a': 1, 'b': 2}->Process() " works
217 "foobar"->Process() " does NOT work
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100218 ("foobar")->Process() " works
219 'foobar'->Process() " does NOT work
220 ('foobar')->Process() " works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100221
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100222In case there is ambiguity between a function name and an Ex command, use ":"
223to make clear you want to use the Ex command. For example, there is both the
224`:substitute` command and the `substitute()` function. When the line starts
225with `substitute(` this will use the function, prepend a colon to use the
226command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100227 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100228
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100229Note that while variables need to be defined before they can be used,
230functions can be called before being defined. This is required to be able
231have cyclic dependencies between functions. It is slightly less efficient,
232since the function has to be looked up by name. And a typo in the function
233name will only be found when the call is executed.
234
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100235
Bram Moolenaard1caa942020-04-10 22:10:56 +0200236Omitting function() ~
237
238A user defined function can be used as a function reference in an expression
239without `function()`. The argument types and return type will then be checked.
240The function must already have been defined. >
241
242 let Funcref = MyFunction
243
244When using `function()` the resulting type is "func", a function with any
245number of arguments and any return type. The function can be defined later.
246
247
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200248Automatic line continuation ~
249
250In many cases it is obvious that an expression continues on the next line. In
251those cases there is no need to prefix the line with a backslash. For
252example, when a list spans multiple lines: >
253 let mylist = [
254 'one',
255 'two',
256 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200257And when a dict spans multiple lines: >
258 let mydict = #{
259 one: 1,
260 two: 2,
261 }
262Function call: >
263 let result = Func(
264 arg1,
265 arg2
266 )
267
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200268For binary operators in expressions not in [], {} or () a line break is
269possible just before or after the operator. For example: >
270 let text = lead
271 .. middle
272 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200273 let total = start +
274 end -
275 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200276 let result = positive
277 ? PosFunc(arg)
278 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200279
Bram Moolenaar73fef332020-06-21 22:12:03 +0200280 let result = GetBuilder()
281 ->BuilderSetWidth(333)
282 ->BuilderSetHeight(777)
283 ->BuilderBuild()
284
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200285< *E1050*
286To make it possible for the operator at the start of the line to be
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200287recognized, it is required to put a colon before a range. This will add
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200288"start" and print: >
289 let result = start
290 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200291Like this: >
292 let result = start + print
293
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200294This will assign "start" and print a line: >
295 let result = start
296 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200297
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200298It is also possible to split a function header over multiple lines, in between
299arguments: >
300 def MyFunc(
301 text: string,
302 separator = '-'
303 ): string
304
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200305Notes:
306- "enddef" cannot be used at the start of a continuation line, it ends the
307 current function.
308- No line break is allowed in the LHS of an assignment. Specifically when
309 unpacking a list |:let-unpack|. This is OK: >
310 [var1, var2] =
311 Func()
312< This does not work: >
313 [var1,
314 var2] =
315 Func()
316- No line break is allowed in between arguments of an `:echo`, `:execute` and
317 similar commands. This is OK: >
318 echo [1,
319 2] [3,
320 4]
321< This does not work: >
322 echo [1, 2]
323 [3, 4]
324- No line break is allowed in the arguments of a lambda, between the "{" and
325 "->". This is OK: >
326 filter(list, {k, v ->
327 v > 0})
328< This does not work: >
329 filter(list, {k,
330 v -> v > 0})
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200331
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200332
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100333No curly braces expansion ~
334
335|curly-braces-names| cannot be used.
336
337
Bram Moolenaar560979e2020-02-04 22:53:05 +0100338No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100339
Bram Moolenaar560979e2020-02-04 22:53:05 +0100340These commands are too quickly confused with local variable names.
341
342
343Comparators ~
344
345The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100346
347
348White space ~
349
350Vim9 script enforces proper use of white space. This is no longer allowed: >
351 let var=234 " Error!
352 let var= 234 " Error!
353 let var =234 " Error!
354There must be white space before and after the "=": >
355 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200356White space must also be put before the # that starts a comment after a
357command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200358 let var = 234# Error!
359 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100360
361White space is required around most operators.
362
363White space is not allowed:
364- Between a function name and the "(": >
365 call Func (arg) " Error!
366 call Func
367 \ (arg) " Error!
368 call Func(arg) " OK
369 call Func(
370 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100371 call Func(
372 \ arg " OK
373 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100374
375
376Conditions and expressions ~
377
378Conditions and expression are mostly working like they do in JavaScript. A
379difference is made where JavaScript does not work like most people expect.
380Specifically, an empty list is falsey.
381
382Any type of variable can be used as a condition, there is no error, not even
383for using a list or job. This is very much like JavaScript, but there are a
384few exceptions.
385
386 type TRUE when ~
387 bool v:true
388 number non-zero
389 float non-zero
390 string non-empty
391 blob non-empty
392 list non-empty (different from JavaScript)
393 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200394 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100395 special v:true
396 job when not NULL
397 channel when not NULL
398 class when not NULL
399 object when not NULL (TODO: when isTrue() returns v:true)
400
401The boolean operators "||" and "&&" do not change the value: >
402 8 || 2 == 8
403 0 || 2 == 2
404 0 || '' == ''
405 8 && 2 == 2
406 0 && 2 == 0
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200407 2 && 0 == 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100408 [] && 2 == []
409
410When using `..` for string concatenation the arguments are always converted to
411string. >
412 'hello ' .. 123 == 'hello 123'
413 'hello ' .. v:true == 'hello true'
414
415In Vim9 script one can use "true" for v:true and "false" for v:false.
416
417
Bram Moolenaare46a4402020-06-30 20:38:27 +0200418What to watch out for ~
419 *vim9-gotchas*
420Vim9 was designed to be closer to often used programming languages, but at the
421same time tries to support the legacy Vim commands. Some compromises had to
422be made. Here is a summary of what might be unexpected.
423
424Ex command ranges need to be prefixed with a colon. >
425 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200426 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200427 :-> " Vim9: shifts the previous line to the right
428
429 %s/a/b " legacy Vim: substitute on all lines
430 x = alongname
431 % another " Vim9: line continuation without a backslash
432 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200433 'text'->func() " Vim9: method call
434 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200435
436Functions defined with `:def` compile the whole function. Legacy functions
437can bail out, and the following lines are not parsed: >
438 func Maybe()
439 if !has('feature')
440 return
441 endif
442 use-feature
443 endfunc
444Vim9 functions are compiled as a whole: >
445 def Maybe()
446 if !has('feature')
447 return
448 endif
449 use-feature " May give compilation error
450 enddef
451For a workaround, split it in two functions: >
452 func Maybe()
453 if has('feature')
454 call MaybyInner()
455 endif
456 endfunc
457 if has('feature')
458 def MaybeInner()
459 use-feature
460 enddef
461 endif
462
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100463==============================================================================
464
4653. New style functions *fast-functions*
466
467THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
468
469 *:def*
470:def[!] {name}([arguments])[: {return-type}
471 Define a new function by the name {name}. The body of
472 the function follows in the next lines, until the
473 matching `:enddef`.
474
Bram Moolenaard77a8522020-04-03 21:59:57 +0200475 When {return-type} is omitted or is "void" the
476 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100477
478 {arguments} is a sequence of zero or more argument
479 declarations. There are three forms:
480 {name}: {type}
481 {name} = {value}
482 {name}: {type} = {value}
483 The first form is a mandatory argument, the caller
484 must always provide them.
485 The second and third form are optional arguments.
486 When the caller omits an argument the {value} is used.
487
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200488 The function will be compiled into instructions when
489 called, or when `:defcompile` is used. Syntax and
490 type errors will be produced at that time.
491
Bram Moolenaar560979e2020-02-04 22:53:05 +0100492 NOTE: It is possible to nest `:def` inside another
493 `:def`, but it is not possible to nest `:def` inside
494 `:function`, for backwards compatibility.
495
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200496 [!] is used as with `:function`. Note that in Vim9
497 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200498 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100499
500 *:enddef*
501:enddef End of a function defined with `:def`.
502
503
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100504If the script the function is defined in is Vim9 script, then script-local
505variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200506before the function is compiled. If the script the function is defined in is
507legacy script, then script-local variables must be accessed with the "s:"
508prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100509
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200510 *:defc* *:defcompile*
511:defc[ompile] Compile functions defined in the current script that
512 were not compiled yet.
513 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100514
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100515 *:disa* *:disassemble*
516:disa[ssemble] {func} Show the instructions generated for {func}.
517 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100518 Note that for command line completion of {func} you
519 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100520
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200521Limitations ~
522
523Local variables will not be visible to string evaluation. For example: >
524 def EvalString(): list<string>
525 let list = ['aa', 'bb', 'cc', 'dd']
526 return range(1, 2)->map('list[v:val]')
527 enddef
528
529The map argument is a string expression, which is evaluated without the
530function scope. Instead, use a lambda: >
531 def EvalString(): list<string>
532 let list = ['aa', 'bb', 'cc', 'dd']
533 return range(1, 2)->map({ _, v -> list[v] })
534 enddef
535
536
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100537==============================================================================
538
5394. Types *vim9-types*
540
541THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
542
543The following builtin types are supported:
544 bool
545 number
546 float
547 string
548 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200549 list<{type}>
550 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100551 job
552 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100553 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200554 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200555 func({type}, ...)
556 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100557
558Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200559 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100560
Bram Moolenaard77a8522020-04-03 21:59:57 +0200561These types can be used in declarations, but no value will have this type:
562 {type}|{type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100563 void
564 any
565
Bram Moolenaard77a8522020-04-03 21:59:57 +0200566There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100567efficient implementation is used that avoids allocating lot of small pieces of
568memory.
569
Bram Moolenaard77a8522020-04-03 21:59:57 +0200570A partial and function can be declared in more or less specific ways:
571func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200572 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200573func: {type} any number and type of arguments with specific
574 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200575func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200576 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200577func({type}): {type} function with argument type and return type
578func(?{type}) function with type of optional argument, does
579 not return a value
580func(...{type}) function with type of variable number of
581 arguments, does not return a value
582func({type}, ?{type}, ...{type}): {type}
583 function with:
584 - type of mandatory argument
585 - type of optional argument
586 - type of variable number of arguments
587 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200588
589If the return type is "void" the function does not return a value.
590
591The reference can also be a |Partial|, in which case it stores extra arguments
592and/or a dictionary, which are not visible to the caller. Since they are
593called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100594
595Custom types can be defined with `:type`: >
596 :type MyList list<string>
597{not implemented yet}
598
599And classes and interfaces can be used as types: >
600 :class MyClass
601 :let mine: MyClass
602
603 :interface MyInterface
604 :let mine: MyInterface
605
606 :class MyTemplate<Targ>
607 :let mine: MyTemplate<number>
608 :let mine: MyTemplate<string>
609
610 :class MyInterface<Targ>
611 :let mine: MyInterface<number>
612 :let mine: MyInterface<string>
613{not implemented yet}
614
615
616Type inference *type-inference*
617
618In general: Whenever the type is clear it can be omitted. For example, when
619declaring a variable and giving it a value: >
620 let var = 0 " infers number type
621 let var = 'hello' " infers string type
622
623
624==============================================================================
625
6265. Namespace, Import and Export
627 *vim9script* *vim9-export* *vim9-import*
628
629THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
630
631A Vim9 script can be written to be imported. This means that everything in
632the script is local, unless exported. Those exported items, and only those
633items, can then be imported in another script.
634
635
636Namespace ~
637 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100638To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100639appear as the first statement in the file. It tells Vim to interpret the
640script in its own namespace, instead of the global namespace. If a file
641starts with: >
642 vim9script
643 let myvar = 'yes'
644Then "myvar" will only exist in this file. While without `vim9script` it would
645be available as `g:myvar` from any other script and function.
646
647The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200648variables in legacy Vim script, but the "s:" is omitted. And they cannot be
649deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100650
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200651In Vim9 script the global "g:" namespace can still be used as before. And the
652"w:", "b:" and "t:" namespaces. These have in common that variables are not
653declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100654
655A side effect of `:vim9script` is that the 'cpoptions' option is set to the
656Vim default value, like with: >
657 :set cpo&vim
658One of the effects is that |line-continuation| is always enabled.
659The original value of 'cpoptions' is restored at the end of the script.
660
661
662Export ~
663 *:export* *:exp*
664Exporting one item can be written as: >
665 export const EXPORTED_CONST = 1234
666 export let someValue = ...
667 export def MyFunc() ...
668 export class MyClass ...
669
670As this suggests, only constants, variables, `:def` functions and classes can
671be exported.
672
673Alternatively, an export statement can be used to export several already
674defined (otherwise script-local) items: >
675 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200676<
677 *E1042*
678`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100679
680
681Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200682 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100683The exported items can be imported individually in another Vim9 script: >
684 import EXPORTED_CONST from "thatscript.vim"
685 import MyClass from "myclass.vim"
686
687To import multiple items at the same time: >
688 import {someValue, MyClass} from "thatscript.vim"
689
Bram Moolenaar560979e2020-02-04 22:53:05 +0100690In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100691 import MyClass as ThatClass from "myclass.vim"
692 import {someValue, MyClass as ThatClass} from "myclass.vim"
693
694To import all exported items under a specific identifier: >
695 import * as That from 'thatscript.vim'
696
697Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
698to choose the name "That", but it is highly recommended to use the name of the
699script file to avoid confusion.
700
701The script name after `import` can be:
702- A relative path, starting "." or "..". This finds a file relative to the
703 location of the script file itself. This is useful to split up a large
704 plugin into several files.
705- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
706 will be rarely used.
707- A path not being relative or absolute. This will be found in the
708 "import" subdirectories of 'runtimepath' entries. The name will usually be
709 longer and unique, to avoid loading the wrong file.
710
711Once a vim9 script file has been imported, the result is cached and used the
712next time the same script is imported. It will not be read again.
713 *:import-cycle*
714The `import` commands are executed when encountered. If that script (directly
715or indirectly) imports the current script, then items defined after the
716`import` won't be processed yet. Therefore cyclic imports can exist, but may
717result in undefined items.
718
719
720Import in an autoload script ~
721
722For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100723actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100724
7251. In the plugin define user commands, functions and/or mappings that refer to
726 an autoload script. >
727 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
728
729< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
730
7312. In the autocommand script do the actual work. You can import items from
732 other files to split up functionality in appropriate pieces. >
733 vim9script
734 import FilterFunc from "../import/someother.vim"
735 def searchfor#Stuff(arg: string)
736 let filtered = FilterFunc(arg)
737 ...
738< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
739 must be exactly the same as the prefix for the function name, that is how
740 Vim finds the file.
741
7423. Other functionality, possibly shared between plugins, contains the exported
743 items and any private items. >
744 vim9script
745 let localVar = 'local'
746 export def FilterFunc(arg: string): string
747 ...
748< This goes in .../import/someother.vim.
749
750
751Import in legacy Vim script ~
752
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200753If an `import` statement is used in legacy Vim script, the script-local "s:"
754namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100755
756
757==============================================================================
758
7599. Rationale *vim9-rationale*
760
761The :def command ~
762
763Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100764shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100765impossible, because of the overhead involved with calling a function, setting
766up the local function scope and executing lines. There are many details that
767need to be handled, such as error messages and exceptions. The need to create
768a dictionary for a: and l: scopes, the a:000 list and several others add too
769much overhead that cannot be avoided.
770
771Therefore the `:def` method to define a new-style function had to be added,
772which allows for a function with different semantics. Most things still work
773as before, but some parts do not. A new way to define a function was
774considered the best way to separate the old-style code from Vim9 script code.
775
776Using "def" to define a function comes from Python. Other languages use
777"function" which clashes with legacy Vim script.
778
779
780Type checking ~
781
782When compiling lines of Vim commands into instructions as much as possible
783should be done at compile time. Postponing it to runtime makes the execution
784slower and means mistakes are found only later. For example, when
785encountering the "+" character and compiling this into a generic add
786instruction, at execution time the instruction would have to inspect the type
787of the arguments and decide what kind of addition to do. And when the
788type is dictionary throw an error. If the types are known to be numbers then
789an "add number" instruction can be used, which is faster. The error can be
790given at compile time, no error handling is needed at runtime.
791
792The syntax for types is similar to Java, since it is easy to understand and
793widely used. The type names are what was used in Vim before, with some
794additions such as "void" and "bool".
795
796
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200797Compiling functions early ~
798
799Functions are compiled when called or when `:defcompile` is used. Why not
800compile them early, so that syntax and type errors are reported early?
801
802The functions can't be compiled right away when encountered, because there may
803be forward references to functions defined later. Consider defining functions
804A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
805to reorder the functions to avoid forward references.
806
807An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200808figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200809execute the script and compile the functions. This means the script has to be
810parsed twice, which is slower, and some conditions at the script level, such
811as checking if a feature is supported, are hard to use. An attempt was made
812to see if it works, but it turned out to be impossible to make work nicely.
813
814It would be possible to compile all the functions at the end of the script.
815The drawback is that if a function never gets called, the overhead of
816compiling it counts anyway. Since startup speed is very important, in most
817cases it's better to do it later and accept that syntax and type errors are
818only reported then. In case these errors should be found early, e.g. when
819testing, the `:defcompile` command will help out.
820
821
822TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100823
824Script writers have complained that the Vim script syntax is unexpectedly
825different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200826languages are used as an example. At the same time, we do not want to abandon
827the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100828
829Since Vim already uses `:let` and `:const` and optional type checking is
830desirable, the JavaScript/TypeScript syntax fits best for variable
831declarations. >
832 const greeting = 'hello' " string type is inferred
833 let name: string
834 ...
835 name = 'John'
836
837Expression evaluation was already close to what JavaScript and other languages
838are doing. Some details are unexpected and can be fixed. For example how the
839|| and && operators work. Legacy Vim script: >
840 let result = 44
841 ...
842 return result || 0 " returns 1
843
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200844Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100845 let result = 44
846 ...
847 return result || 0 " returns 44
848
849On the other hand, overloading "+" to use both for addition and string
850concatenation goes against legacy Vim script and often leads to mistakes.
851For that reason we will keep using ".." for string concatenation. Lua also
852uses ".." this way.
853
854
855Import and Export ~
856
857A problem of legacy Vim script is that by default all functions and variables
858are global. It is possible to make them script-local, but then they are not
859available in other scripts.
860
861In Vim9 script a mechanism very similar to the Javascript import and export
862mechanism is supported. It is a variant to the existing `:source` command
863that works like one would expect:
864- Instead of making everything global by default, everything is script-local,
865 unless exported.
866- When importing a script the symbols that are imported are listed, avoiding
867 name conflicts and failures if later functionality is added.
868- The mechanism allows for writing a big, long script with a very clear API:
869 the exported function(s) and class(es).
870- By using relative paths loading can be much faster for an import inside of a
871 package, no need to search many directories.
872- Once an import has been used, it can be cached and loading it again can be
873 avoided.
874- The Vim-specific use of "s:" to make things script-local can be dropped.
875
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200876When sourcing a Vim9 script from a legacy script, only the items defined
877globally can be used, not the exported items. Alternatives considered:
878- All the exported items become available as script-local items. This makes
879 it uncontrollable what items get defined.
880- Use the exported items and make them global. Disadvantage is that it's then
881 not possible to avoid name clashes in the global namespace.
882- Completely disallow sourcing a Vim9 script, require using `:import`. That
883 makes it difficult to use scripts for testing, or sourcing them from the
884 command line to try them out.
885
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100886
887Classes ~
888
889Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
890these have never become widespread. When Vim 9 was designed a decision was
891made to phase out these interfaces and concentrate on Vim script, while
892encouraging plugin authors to write code in any language and run it as an
893external tool, using jobs and channels.
894
895Still, using an external tool has disadvantages. An alternative is to convert
896the tool into Vim script. For that to be possible without too much
897translation, and keeping the code fast at the same time, the constructs of the
898tool need to be supported. Since most languages support classes the lack of
899class support in Vim is then a problem.
900
901Previously Vim supported a kind-of object oriented programming by adding
902methods to a dictionary. With some care this could be made to work, but it
903does not look like real classes. On top of that, it's very slow, because of
904the use of dictionaries.
905
906The support of classes in Vim9 script is a "minimal common functionality" of
907class support in most languages. It works mostly like Java, which is the most
908popular programming language.
909
910
911
912 vim:tw=78:ts=8:noet:ft=help:norl: