blob: ad96817ff17f5e6a63730e9fca831afbe63eca90 [file] [log] [blame]
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Jul 10
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 Moolenaar7ff78462020-07-10 22:00:53 +020067In Vim script comments start with double quote. That can also be the start of
68a string, thus in many places it cannot be used. In Vim9 script a comment
69normally starts with #. In Vi this is a command to list text with numbers,
70but you can also use `:number` for that. >
Bram Moolenaar73fef332020-06-21 22:12:03 +020071 let count = 0 # number of occurrences
Bram Moolenaar2c330432020-04-13 14:41:35 +020072
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020073To improve readability there must be a space between the command and the #
74that starts a comment. Note that #{ is the start of a dictionary, therefore
75it cannot start a comment.
76
Bram Moolenaar7ff78462020-07-10 22:00:53 +020077Since Vim9 script allows for line breaks in many places, the double quoted
78comment also cannot be used at the start of a line after an expression. To
79avoid confusion it is best to only use # comments.
80
Bram Moolenaar2c330432020-04-13 14:41:35 +020081
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010082Vim9 functions ~
83
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020084A function defined with `:def` is compiled. Execution is many times faster,
85often 10x to 100x times.
86
Bram Moolenaar388a5d42020-05-26 21:20:45 +020087Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020088The syntax is strict, to enforce code that is easy to read and understand.
89
Bram Moolenaar388a5d42020-05-26 21:20:45 +020090Compilation is done when the function is first called, or when the
91`:defcompile` command is encountered in the script where the function was
92defined.
93
94`:def` has no options like `:function` does: "range", "abort", "dict" or
95"closure". A `:def` function always aborts on an error, does not get a range
96passed and cannot be a "dict" function.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010097
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020098The argument types and return type need to be specified. The "any" type can
99be used, type checking will then be done at runtime, like with legacy
100functions.
101
102Arguments are accessed by name, without "a:". There is no "a:" dictionary or
103"a:000" list.
104
105Variable arguments are defined as the last argument, with a name and have a
106list type, similar to Typescript. For example, a list of numbers: >
107 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100108 for item in itemlist
109 ...
110
111
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200112Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200113 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200114When using `:function` or `:def` to specify a new function at the script level
115in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200116prefixed. Using the "s:" prefix is optional.
117
118To define or use a global function or variable the "g:" prefix must be used.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200119
120When using `:function` or `:def` to specify a new function inside a function,
121the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200122script-local function inside a function. It is possible to define a global
123function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200124
125When referring to a function and no "s:" or "g:" prefix is used, Vim will
126search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200127- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200128- Local to the current script file.
129- Imported functions, see `:import`.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200130In all cases the function must be defined before used. That is when it is
131first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200132
133The result is that functions and variables without a namespace can always be
134found in the script, either defined there or imported. Global functions and
135variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200136
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200137Global functions can be still be defined and deleted at nearly any time. In
138Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200139and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200140
141
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100142Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200143 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100144Local variables need to be declared with `:let`. Local constants need to be
145declared with `:const`. We refer to both as "variables".
146
147Variables can be local to a script, function or code block: >
148 vim9script
149 let script_var = 123
150 def SomeFunc()
151 let func_var = script_var
152 if cond
153 let block_var = func_var
154 ...
155
156The variables are only visible in the block where they are defined and nested
157blocks. Once the block ends the variable is no longer accessible: >
158 if cond
159 let inner = 5
160 else
161 let inner = 0
162 endif
163 echo inner " Error!
164
165The declaration must be done earlier: >
166 let inner: number
167 if cond
168 inner = 5
169 else
170 inner = 0
171 endif
172 echo inner
173
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200174To intentionally avoid a variable being available later, a block can be used:
175>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100176 {
177 let temp = 'temp'
178 ...
179 }
180 echo temp " Error!
181
Bram Moolenaar560979e2020-02-04 22:53:05 +0100182An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100183declaration. An exception is global variables: these can be both used with
184and without `:let`, because there is no rule about where they are declared.
185
186Variables cannot shadow previously defined variables.
187Variables may shadow Ex commands, rename the variable if needed.
188
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200189Global variables and user defined functions must be prefixed with "g:", also
190at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200191 vim9script
192 let script_local = 'text'
193 let g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200194 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200195
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100196Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
197used to repeat a `:substitute` command.
198
199
200Omitting :call and :eval ~
201
202Functions can be called without `:call`: >
203 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100204Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100205
206A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100207identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100208 myList->add(123) " works
209 g:myList->add(123) " works
210 [1, 2, 3]->Process() " works
211 #{a: 1, b: 2}->Process() " works
212 {'a': 1, 'b': 2}->Process() " works
213 "foobar"->Process() " does NOT work
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100214 ("foobar")->Process() " works
215 'foobar'->Process() " does NOT work
216 ('foobar')->Process() " works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100217
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100218In case there is ambiguity between a function name and an Ex command, use ":"
219to make clear you want to use the Ex command. For example, there is both the
220`:substitute` command and the `substitute()` function. When the line starts
221with `substitute(` this will use the function, prepend a colon to use the
222command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100223 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100224
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100225Note that while variables need to be defined before they can be used,
226functions can be called before being defined. This is required to be able
227have cyclic dependencies between functions. It is slightly less efficient,
228since the function has to be looked up by name. And a typo in the function
229name will only be found when the call is executed.
230
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100231
Bram Moolenaard1caa942020-04-10 22:10:56 +0200232Omitting function() ~
233
234A user defined function can be used as a function reference in an expression
235without `function()`. The argument types and return type will then be checked.
236The function must already have been defined. >
237
238 let Funcref = MyFunction
239
240When using `function()` the resulting type is "func", a function with any
241number of arguments and any return type. The function can be defined later.
242
243
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200244Automatic line continuation ~
245
246In many cases it is obvious that an expression continues on the next line. In
247those cases there is no need to prefix the line with a backslash. For
248example, when a list spans multiple lines: >
249 let mylist = [
250 'one',
251 'two',
252 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200253And when a dict spans multiple lines: >
254 let mydict = #{
255 one: 1,
256 two: 2,
257 }
258Function call: >
259 let result = Func(
260 arg1,
261 arg2
262 )
263
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200264For binary operators in expressions not in [], {} or () a line break is
265possible just before or after the operator. For example: >
266 let text = lead
267 .. middle
268 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200269 let total = start +
270 end -
271 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200272 let result = positive
273 ? PosFunc(arg)
274 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200275
Bram Moolenaar73fef332020-06-21 22:12:03 +0200276 let result = GetBuilder()
277 ->BuilderSetWidth(333)
278 ->BuilderSetHeight(777)
279 ->BuilderBuild()
280
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200281< *E1050*
282To make it possible for the operator at the start of the line to be
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200283recognized, it is required to put a colon before a range. This will add
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200284"start" and print: >
285 let result = start
286 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200287Like this: >
288 let result = start + print
289
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200290This will assign "start" and print a line: >
291 let result = start
292 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200293
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200294It is also possible to split a function header over multiple lines, in between
295arguments: >
296 def MyFunc(
297 text: string,
298 separator = '-'
299 ): string
300
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200301Notes:
302- "enddef" cannot be used at the start of a continuation line, it ends the
303 current function.
304- No line break is allowed in the LHS of an assignment. Specifically when
305 unpacking a list |:let-unpack|. This is OK: >
306 [var1, var2] =
307 Func()
308< This does not work: >
309 [var1,
310 var2] =
311 Func()
312- No line break is allowed in between arguments of an `:echo`, `:execute` and
313 similar commands. This is OK: >
314 echo [1,
315 2] [3,
316 4]
317< This does not work: >
318 echo [1, 2]
319 [3, 4]
320- No line break is allowed in the arguments of a lambda, between the "{" and
321 "->". This is OK: >
322 filter(list, {k, v ->
323 v > 0})
324< This does not work: >
325 filter(list, {k,
326 v -> v > 0})
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200327
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200328
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100329No curly braces expansion ~
330
331|curly-braces-names| cannot be used.
332
333
Bram Moolenaar560979e2020-02-04 22:53:05 +0100334No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100335
Bram Moolenaar560979e2020-02-04 22:53:05 +0100336These commands are too quickly confused with local variable names.
337
338
339Comparators ~
340
341The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100342
343
344White space ~
345
346Vim9 script enforces proper use of white space. This is no longer allowed: >
347 let var=234 " Error!
348 let var= 234 " Error!
349 let var =234 " Error!
350There must be white space before and after the "=": >
351 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200352White space must also be put before the # that starts a comment after a
353command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200354 let var = 234# Error!
355 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100356
357White space is required around most operators.
358
359White space is not allowed:
360- Between a function name and the "(": >
361 call Func (arg) " Error!
362 call Func
363 \ (arg) " Error!
364 call Func(arg) " OK
365 call Func(
366 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100367 call Func(
368 \ arg " OK
369 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100370
371
372Conditions and expressions ~
373
374Conditions and expression are mostly working like they do in JavaScript. A
375difference is made where JavaScript does not work like most people expect.
376Specifically, an empty list is falsey.
377
378Any type of variable can be used as a condition, there is no error, not even
379for using a list or job. This is very much like JavaScript, but there are a
380few exceptions.
381
382 type TRUE when ~
383 bool v:true
384 number non-zero
385 float non-zero
386 string non-empty
387 blob non-empty
388 list non-empty (different from JavaScript)
389 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200390 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100391 special v:true
392 job when not NULL
393 channel when not NULL
394 class when not NULL
395 object when not NULL (TODO: when isTrue() returns v:true)
396
397The boolean operators "||" and "&&" do not change the value: >
398 8 || 2 == 8
399 0 || 2 == 2
400 0 || '' == ''
401 8 && 2 == 2
402 0 && 2 == 0
403 [] && 2 == []
404
405When using `..` for string concatenation the arguments are always converted to
406string. >
407 'hello ' .. 123 == 'hello 123'
408 'hello ' .. v:true == 'hello true'
409
410In Vim9 script one can use "true" for v:true and "false" for v:false.
411
412
Bram Moolenaare46a4402020-06-30 20:38:27 +0200413What to watch out for ~
414 *vim9-gotchas*
415Vim9 was designed to be closer to often used programming languages, but at the
416same time tries to support the legacy Vim commands. Some compromises had to
417be made. Here is a summary of what might be unexpected.
418
419Ex command ranges need to be prefixed with a colon. >
420 -> " legacy Vim: shifts the previous line to the right
421 ->func() " Vim9: method call
422 :-> " Vim9: shifts the previous line to the right
423
424 %s/a/b " legacy Vim: substitute on all lines
425 x = alongname
426 % another " Vim9: line continuation without a backslash
427 :%s/a/b " Vim9: substitute on all lines
428
429Functions defined with `:def` compile the whole function. Legacy functions
430can bail out, and the following lines are not parsed: >
431 func Maybe()
432 if !has('feature')
433 return
434 endif
435 use-feature
436 endfunc
437Vim9 functions are compiled as a whole: >
438 def Maybe()
439 if !has('feature')
440 return
441 endif
442 use-feature " May give compilation error
443 enddef
444For a workaround, split it in two functions: >
445 func Maybe()
446 if has('feature')
447 call MaybyInner()
448 endif
449 endfunc
450 if has('feature')
451 def MaybeInner()
452 use-feature
453 enddef
454 endif
455
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100456==============================================================================
457
4583. New style functions *fast-functions*
459
460THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
461
462 *:def*
463:def[!] {name}([arguments])[: {return-type}
464 Define a new function by the name {name}. The body of
465 the function follows in the next lines, until the
466 matching `:enddef`.
467
Bram Moolenaard77a8522020-04-03 21:59:57 +0200468 When {return-type} is omitted or is "void" the
469 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100470
471 {arguments} is a sequence of zero or more argument
472 declarations. There are three forms:
473 {name}: {type}
474 {name} = {value}
475 {name}: {type} = {value}
476 The first form is a mandatory argument, the caller
477 must always provide them.
478 The second and third form are optional arguments.
479 When the caller omits an argument the {value} is used.
480
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200481 The function will be compiled into instructions when
482 called, or when `:defcompile` is used. Syntax and
483 type errors will be produced at that time.
484
Bram Moolenaar560979e2020-02-04 22:53:05 +0100485 NOTE: It is possible to nest `:def` inside another
486 `:def`, but it is not possible to nest `:def` inside
487 `:function`, for backwards compatibility.
488
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200489 [!] is used as with `:function`. Note that in Vim9
490 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200491 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100492
493 *:enddef*
494:enddef End of a function defined with `:def`.
495
496
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100497If the script the function is defined in is Vim9 script, then script-local
498variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200499before the function is compiled. If the script the function is defined in is
500legacy script, then script-local variables must be accessed with the "s:"
501prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100502
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200503 *:defc* *:defcompile*
504:defc[ompile] Compile functions defined in the current script that
505 were not compiled yet.
506 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100507
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100508 *:disa* *:disassemble*
509:disa[ssemble] {func} Show the instructions generated for {func}.
510 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100511 Note that for command line completion of {func} you
512 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100513
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200514Limitations ~
515
516Local variables will not be visible to string evaluation. For example: >
517 def EvalString(): list<string>
518 let list = ['aa', 'bb', 'cc', 'dd']
519 return range(1, 2)->map('list[v:val]')
520 enddef
521
522The map argument is a string expression, which is evaluated without the
523function scope. Instead, use a lambda: >
524 def EvalString(): list<string>
525 let list = ['aa', 'bb', 'cc', 'dd']
526 return range(1, 2)->map({ _, v -> list[v] })
527 enddef
528
529
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100530==============================================================================
531
5324. Types *vim9-types*
533
534THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
535
536The following builtin types are supported:
537 bool
538 number
539 float
540 string
541 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200542 list<{type}>
543 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100544 job
545 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100546 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200547 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200548 func({type}, ...)
549 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100550
551Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200552 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100553
Bram Moolenaard77a8522020-04-03 21:59:57 +0200554These types can be used in declarations, but no value will have this type:
555 {type}|{type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100556 void
557 any
558
Bram Moolenaard77a8522020-04-03 21:59:57 +0200559There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100560efficient implementation is used that avoids allocating lot of small pieces of
561memory.
562
Bram Moolenaard77a8522020-04-03 21:59:57 +0200563A partial and function can be declared in more or less specific ways:
564func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200565 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200566func: {type} any number and type of arguments with specific
567 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200568func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200569 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200570func({type}): {type} function with argument type and return type
571func(?{type}) function with type of optional argument, does
572 not return a value
573func(...{type}) function with type of variable number of
574 arguments, does not return a value
575func({type}, ?{type}, ...{type}): {type}
576 function with:
577 - type of mandatory argument
578 - type of optional argument
579 - type of variable number of arguments
580 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200581
582If the return type is "void" the function does not return a value.
583
584The reference can also be a |Partial|, in which case it stores extra arguments
585and/or a dictionary, which are not visible to the caller. Since they are
586called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100587
588Custom types can be defined with `:type`: >
589 :type MyList list<string>
590{not implemented yet}
591
592And classes and interfaces can be used as types: >
593 :class MyClass
594 :let mine: MyClass
595
596 :interface MyInterface
597 :let mine: MyInterface
598
599 :class MyTemplate<Targ>
600 :let mine: MyTemplate<number>
601 :let mine: MyTemplate<string>
602
603 :class MyInterface<Targ>
604 :let mine: MyInterface<number>
605 :let mine: MyInterface<string>
606{not implemented yet}
607
608
609Type inference *type-inference*
610
611In general: Whenever the type is clear it can be omitted. For example, when
612declaring a variable and giving it a value: >
613 let var = 0 " infers number type
614 let var = 'hello' " infers string type
615
616
617==============================================================================
618
6195. Namespace, Import and Export
620 *vim9script* *vim9-export* *vim9-import*
621
622THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
623
624A Vim9 script can be written to be imported. This means that everything in
625the script is local, unless exported. Those exported items, and only those
626items, can then be imported in another script.
627
628
629Namespace ~
630 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100631To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100632appear as the first statement in the file. It tells Vim to interpret the
633script in its own namespace, instead of the global namespace. If a file
634starts with: >
635 vim9script
636 let myvar = 'yes'
637Then "myvar" will only exist in this file. While without `vim9script` it would
638be available as `g:myvar` from any other script and function.
639
640The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200641variables in legacy Vim script, but the "s:" is omitted. And they cannot be
642deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100643
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200644In Vim9 script the global "g:" namespace can still be used as before. And the
645"w:", "b:" and "t:" namespaces. These have in common that variables are not
646declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100647
648A side effect of `:vim9script` is that the 'cpoptions' option is set to the
649Vim default value, like with: >
650 :set cpo&vim
651One of the effects is that |line-continuation| is always enabled.
652The original value of 'cpoptions' is restored at the end of the script.
653
654
655Export ~
656 *:export* *:exp*
657Exporting one item can be written as: >
658 export const EXPORTED_CONST = 1234
659 export let someValue = ...
660 export def MyFunc() ...
661 export class MyClass ...
662
663As this suggests, only constants, variables, `:def` functions and classes can
664be exported.
665
666Alternatively, an export statement can be used to export several already
667defined (otherwise script-local) items: >
668 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200669<
670 *E1042*
671`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100672
673
674Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200675 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100676The exported items can be imported individually in another Vim9 script: >
677 import EXPORTED_CONST from "thatscript.vim"
678 import MyClass from "myclass.vim"
679
680To import multiple items at the same time: >
681 import {someValue, MyClass} from "thatscript.vim"
682
Bram Moolenaar560979e2020-02-04 22:53:05 +0100683In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100684 import MyClass as ThatClass from "myclass.vim"
685 import {someValue, MyClass as ThatClass} from "myclass.vim"
686
687To import all exported items under a specific identifier: >
688 import * as That from 'thatscript.vim'
689
690Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
691to choose the name "That", but it is highly recommended to use the name of the
692script file to avoid confusion.
693
694The script name after `import` can be:
695- A relative path, starting "." or "..". This finds a file relative to the
696 location of the script file itself. This is useful to split up a large
697 plugin into several files.
698- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
699 will be rarely used.
700- A path not being relative or absolute. This will be found in the
701 "import" subdirectories of 'runtimepath' entries. The name will usually be
702 longer and unique, to avoid loading the wrong file.
703
704Once a vim9 script file has been imported, the result is cached and used the
705next time the same script is imported. It will not be read again.
706 *:import-cycle*
707The `import` commands are executed when encountered. If that script (directly
708or indirectly) imports the current script, then items defined after the
709`import` won't be processed yet. Therefore cyclic imports can exist, but may
710result in undefined items.
711
712
713Import in an autoload script ~
714
715For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100716actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100717
7181. In the plugin define user commands, functions and/or mappings that refer to
719 an autoload script. >
720 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
721
722< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
723
7242. In the autocommand script do the actual work. You can import items from
725 other files to split up functionality in appropriate pieces. >
726 vim9script
727 import FilterFunc from "../import/someother.vim"
728 def searchfor#Stuff(arg: string)
729 let filtered = FilterFunc(arg)
730 ...
731< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
732 must be exactly the same as the prefix for the function name, that is how
733 Vim finds the file.
734
7353. Other functionality, possibly shared between plugins, contains the exported
736 items and any private items. >
737 vim9script
738 let localVar = 'local'
739 export def FilterFunc(arg: string): string
740 ...
741< This goes in .../import/someother.vim.
742
743
744Import in legacy Vim script ~
745
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200746If an `import` statement is used in legacy Vim script, the script-local "s:"
747namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100748
749
750==============================================================================
751
7529. Rationale *vim9-rationale*
753
754The :def command ~
755
756Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100757shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100758impossible, because of the overhead involved with calling a function, setting
759up the local function scope and executing lines. There are many details that
760need to be handled, such as error messages and exceptions. The need to create
761a dictionary for a: and l: scopes, the a:000 list and several others add too
762much overhead that cannot be avoided.
763
764Therefore the `:def` method to define a new-style function had to be added,
765which allows for a function with different semantics. Most things still work
766as before, but some parts do not. A new way to define a function was
767considered the best way to separate the old-style code from Vim9 script code.
768
769Using "def" to define a function comes from Python. Other languages use
770"function" which clashes with legacy Vim script.
771
772
773Type checking ~
774
775When compiling lines of Vim commands into instructions as much as possible
776should be done at compile time. Postponing it to runtime makes the execution
777slower and means mistakes are found only later. For example, when
778encountering the "+" character and compiling this into a generic add
779instruction, at execution time the instruction would have to inspect the type
780of the arguments and decide what kind of addition to do. And when the
781type is dictionary throw an error. If the types are known to be numbers then
782an "add number" instruction can be used, which is faster. The error can be
783given at compile time, no error handling is needed at runtime.
784
785The syntax for types is similar to Java, since it is easy to understand and
786widely used. The type names are what was used in Vim before, with some
787additions such as "void" and "bool".
788
789
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200790Compiling functions early ~
791
792Functions are compiled when called or when `:defcompile` is used. Why not
793compile them early, so that syntax and type errors are reported early?
794
795The functions can't be compiled right away when encountered, because there may
796be forward references to functions defined later. Consider defining functions
797A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
798to reorder the functions to avoid forward references.
799
800An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200801figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200802execute the script and compile the functions. This means the script has to be
803parsed twice, which is slower, and some conditions at the script level, such
804as checking if a feature is supported, are hard to use. An attempt was made
805to see if it works, but it turned out to be impossible to make work nicely.
806
807It would be possible to compile all the functions at the end of the script.
808The drawback is that if a function never gets called, the overhead of
809compiling it counts anyway. Since startup speed is very important, in most
810cases it's better to do it later and accept that syntax and type errors are
811only reported then. In case these errors should be found early, e.g. when
812testing, the `:defcompile` command will help out.
813
814
815TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100816
817Script writers have complained that the Vim script syntax is unexpectedly
818different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200819languages are used as an example. At the same time, we do not want to abandon
820the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100821
822Since Vim already uses `:let` and `:const` and optional type checking is
823desirable, the JavaScript/TypeScript syntax fits best for variable
824declarations. >
825 const greeting = 'hello' " string type is inferred
826 let name: string
827 ...
828 name = 'John'
829
830Expression evaluation was already close to what JavaScript and other languages
831are doing. Some details are unexpected and can be fixed. For example how the
832|| and && operators work. Legacy Vim script: >
833 let result = 44
834 ...
835 return result || 0 " returns 1
836
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200837Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100838 let result = 44
839 ...
840 return result || 0 " returns 44
841
842On the other hand, overloading "+" to use both for addition and string
843concatenation goes against legacy Vim script and often leads to mistakes.
844For that reason we will keep using ".." for string concatenation. Lua also
845uses ".." this way.
846
847
848Import and Export ~
849
850A problem of legacy Vim script is that by default all functions and variables
851are global. It is possible to make them script-local, but then they are not
852available in other scripts.
853
854In Vim9 script a mechanism very similar to the Javascript import and export
855mechanism is supported. It is a variant to the existing `:source` command
856that works like one would expect:
857- Instead of making everything global by default, everything is script-local,
858 unless exported.
859- When importing a script the symbols that are imported are listed, avoiding
860 name conflicts and failures if later functionality is added.
861- The mechanism allows for writing a big, long script with a very clear API:
862 the exported function(s) and class(es).
863- By using relative paths loading can be much faster for an import inside of a
864 package, no need to search many directories.
865- Once an import has been used, it can be cached and loading it again can be
866 avoided.
867- The Vim-specific use of "s:" to make things script-local can be dropped.
868
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200869When sourcing a Vim9 script from a legacy script, only the items defined
870globally can be used, not the exported items. Alternatives considered:
871- All the exported items become available as script-local items. This makes
872 it uncontrollable what items get defined.
873- Use the exported items and make them global. Disadvantage is that it's then
874 not possible to avoid name clashes in the global namespace.
875- Completely disallow sourcing a Vim9 script, require using `:import`. That
876 makes it difficult to use scripts for testing, or sourcing them from the
877 command line to try them out.
878
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100879
880Classes ~
881
882Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
883these have never become widespread. When Vim 9 was designed a decision was
884made to phase out these interfaces and concentrate on Vim script, while
885encouraging plugin authors to write code in any language and run it as an
886external tool, using jobs and channels.
887
888Still, using an external tool has disadvantages. An alternative is to convert
889the tool into Vim script. For that to be possible without too much
890translation, and keeping the code fast at the same time, the constructs of the
891tool need to be supported. Since most languages support classes the lack of
892class support in Vim is then a problem.
893
894Previously Vim supported a kind-of object oriented programming by adding
895methods to a dictionary. With some care this could be made to work, but it
896does not look like real classes. On top of that, it's very slow, because of
897the use of dictionaries.
898
899The support of classes in Vim9 script is a "minimal common functionality" of
900class support in most languages. It works mostly like Java, which is the most
901popular programming language.
902
903
904
905 vim:tw=78:ts=8:noet:ft=help:norl: