blob: 2ba2275274e176dc6df68195da5a3ede084d3357 [file] [log] [blame]
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Jul 25
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 Moolenaar2547aa92020-07-26 17:00:44 +0200187declaration. Global, window, tab, buffer and Vim variables can only be used
188without `:let`, because they are are not really declared, they can also be
189deleted with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100190
191Variables cannot shadow previously defined variables.
192Variables may shadow Ex commands, rename the variable if needed.
193
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200194Global variables and user defined functions must be prefixed with "g:", also
195at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200196 vim9script
197 let script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200198 g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200199 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200200
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100201Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
202used to repeat a `:substitute` command.
203
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200204 *E1092*
205Declaring more than one variable at a time, using the unpack notation, is
206currently not supported: >
207 let [v1, v2] = GetValues() # Error!
208That is because the type needs to be inferred from the list item type, which
209isn't that easy.
210
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100211
212Omitting :call and :eval ~
213
214Functions can be called without `:call`: >
215 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100216Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100217
218A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100219identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200220 myList->add(123) # works
221 g:myList->add(123) # works
222 [1, 2, 3]->Process() # works
223 #{a: 1, b: 2}->Process() # works
224 {'a': 1, 'b': 2}->Process() # works
225 "foobar"->Process() # does NOT work
226 ("foobar")->Process() # works
227 'foobar'->Process() # does NOT work
228 ('foobar')->Process() # works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100229
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100230In case there is ambiguity between a function name and an Ex command, use ":"
231to make clear you want to use the Ex command. For example, there is both the
232`:substitute` command and the `substitute()` function. When the line starts
233with `substitute(` this will use the function, prepend a colon to use the
234command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100235 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100236
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100237Note that while variables need to be defined before they can be used,
238functions can be called before being defined. This is required to be able
239have cyclic dependencies between functions. It is slightly less efficient,
240since the function has to be looked up by name. And a typo in the function
241name will only be found when the call is executed.
242
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100243
Bram Moolenaard1caa942020-04-10 22:10:56 +0200244Omitting function() ~
245
246A user defined function can be used as a function reference in an expression
247without `function()`. The argument types and return type will then be checked.
248The function must already have been defined. >
249
250 let Funcref = MyFunction
251
252When using `function()` the resulting type is "func", a function with any
253number of arguments and any return type. The function can be defined later.
254
255
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200256Automatic line continuation ~
257
258In many cases it is obvious that an expression continues on the next line. In
259those cases there is no need to prefix the line with a backslash. For
260example, when a list spans multiple lines: >
261 let mylist = [
262 'one',
263 'two',
264 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200265And when a dict spans multiple lines: >
266 let mydict = #{
267 one: 1,
268 two: 2,
269 }
270Function call: >
271 let result = Func(
272 arg1,
273 arg2
274 )
275
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200276For binary operators in expressions not in [], {} or () a line break is
277possible just before or after the operator. For example: >
278 let text = lead
279 .. middle
280 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200281 let total = start +
282 end -
283 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200284 let result = positive
285 ? PosFunc(arg)
286 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200287
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200288For a method call using "->" and a member using a dot, a line break is allowed
289before it: >
Bram Moolenaar73fef332020-06-21 22:12:03 +0200290 let result = GetBuilder()
291 ->BuilderSetWidth(333)
292 ->BuilderSetHeight(777)
293 ->BuilderBuild()
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200294 let result = MyDict
295 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200296
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200297< *E1050*
298To make it possible for the operator at the start of the line to be
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200299recognized, it is required to put a colon before a range. This will add
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200300"start" and print: >
301 let result = start
302 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200303Like this: >
304 let result = start + print
305
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200306This will assign "start" and print a line: >
307 let result = start
308 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200309
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200310It is also possible to split a function header over multiple lines, in between
311arguments: >
312 def MyFunc(
313 text: string,
314 separator = '-'
315 ): string
316
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200317Notes:
318- "enddef" cannot be used at the start of a continuation line, it ends the
319 current function.
320- No line break is allowed in the LHS of an assignment. Specifically when
321 unpacking a list |:let-unpack|. This is OK: >
322 [var1, var2] =
323 Func()
324< This does not work: >
325 [var1,
326 var2] =
327 Func()
328- No line break is allowed in between arguments of an `:echo`, `:execute` and
329 similar commands. This is OK: >
330 echo [1,
331 2] [3,
332 4]
333< This does not work: >
334 echo [1, 2]
335 [3, 4]
336- No line break is allowed in the arguments of a lambda, between the "{" and
337 "->". This is OK: >
338 filter(list, {k, v ->
339 v > 0})
340< This does not work: >
341 filter(list, {k,
342 v -> v > 0})
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200343
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200344
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100345No curly braces expansion ~
346
347|curly-braces-names| cannot be used.
348
349
Bram Moolenaar560979e2020-02-04 22:53:05 +0100350No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100351
Bram Moolenaar560979e2020-02-04 22:53:05 +0100352These commands are too quickly confused with local variable names.
353
354
355Comparators ~
356
357The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100358
359
360White space ~
361
362Vim9 script enforces proper use of white space. This is no longer allowed: >
363 let var=234 " Error!
364 let var= 234 " Error!
365 let var =234 " Error!
366There must be white space before and after the "=": >
367 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200368White space must also be put before the # that starts a comment after a
369command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200370 let var = 234# Error!
371 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100372
373White space is required around most operators.
374
375White space is not allowed:
376- Between a function name and the "(": >
377 call Func (arg) " Error!
378 call Func
379 \ (arg) " Error!
380 call Func(arg) " OK
381 call Func(
382 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100383 call Func(
384 \ arg " OK
385 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100386
387
388Conditions and expressions ~
389
390Conditions and expression are mostly working like they do in JavaScript. A
391difference is made where JavaScript does not work like most people expect.
392Specifically, an empty list is falsey.
393
394Any type of variable can be used as a condition, there is no error, not even
395for using a list or job. This is very much like JavaScript, but there are a
396few exceptions.
397
398 type TRUE when ~
399 bool v:true
400 number non-zero
401 float non-zero
402 string non-empty
403 blob non-empty
404 list non-empty (different from JavaScript)
405 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200406 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100407 special v:true
408 job when not NULL
409 channel when not NULL
410 class when not NULL
411 object when not NULL (TODO: when isTrue() returns v:true)
412
413The boolean operators "||" and "&&" do not change the value: >
414 8 || 2 == 8
415 0 || 2 == 2
416 0 || '' == ''
417 8 && 2 == 2
418 0 && 2 == 0
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200419 2 && 0 == 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100420 [] && 2 == []
421
422When using `..` for string concatenation the arguments are always converted to
423string. >
424 'hello ' .. 123 == 'hello 123'
425 'hello ' .. v:true == 'hello true'
426
427In Vim9 script one can use "true" for v:true and "false" for v:false.
428
429
Bram Moolenaare46a4402020-06-30 20:38:27 +0200430What to watch out for ~
431 *vim9-gotchas*
432Vim9 was designed to be closer to often used programming languages, but at the
433same time tries to support the legacy Vim commands. Some compromises had to
434be made. Here is a summary of what might be unexpected.
435
436Ex command ranges need to be prefixed with a colon. >
437 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200438 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200439 :-> " Vim9: shifts the previous line to the right
440
441 %s/a/b " legacy Vim: substitute on all lines
442 x = alongname
443 % another " Vim9: line continuation without a backslash
444 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200445 'text'->func() " Vim9: method call
446 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200447
448Functions defined with `:def` compile the whole function. Legacy functions
449can bail out, and the following lines are not parsed: >
450 func Maybe()
451 if !has('feature')
452 return
453 endif
454 use-feature
455 endfunc
456Vim9 functions are compiled as a whole: >
457 def Maybe()
458 if !has('feature')
459 return
460 endif
461 use-feature " May give compilation error
462 enddef
463For a workaround, split it in two functions: >
464 func Maybe()
465 if has('feature')
466 call MaybyInner()
467 endif
468 endfunc
469 if has('feature')
470 def MaybeInner()
471 use-feature
472 enddef
473 endif
474
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100475==============================================================================
476
4773. New style functions *fast-functions*
478
479THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
480
481 *:def*
482:def[!] {name}([arguments])[: {return-type}
483 Define a new function by the name {name}. The body of
484 the function follows in the next lines, until the
485 matching `:enddef`.
486
Bram Moolenaard77a8522020-04-03 21:59:57 +0200487 When {return-type} is omitted or is "void" the
488 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100489
490 {arguments} is a sequence of zero or more argument
491 declarations. There are three forms:
492 {name}: {type}
493 {name} = {value}
494 {name}: {type} = {value}
495 The first form is a mandatory argument, the caller
496 must always provide them.
497 The second and third form are optional arguments.
498 When the caller omits an argument the {value} is used.
499
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200500 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200501 called, or when `:disassemble` or `:defcompile` is
502 used. Syntax and type errors will be produced at that
503 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200504
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200505 It is possible to nest `:def` inside another `:def` or
506 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100507
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200508 [!] is used as with `:function`. Note that in Vim9
509 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200510 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100511
512 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200513:enddef End of a function defined with `:def`. It should be on
514 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100515
516
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100517If the script the function is defined in is Vim9 script, then script-local
518variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200519before the function is compiled. If the script the function is defined in is
520legacy script, then script-local variables must be accessed with the "s:"
521prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100522
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200523 *:defc* *:defcompile*
524:defc[ompile] Compile functions defined in the current script that
525 were not compiled yet.
526 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100527
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100528 *:disa* *:disassemble*
529:disa[ssemble] {func} Show the instructions generated for {func}.
530 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100531 Note that for command line completion of {func} you
532 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100533
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200534Limitations ~
535
536Local variables will not be visible to string evaluation. For example: >
537 def EvalString(): list<string>
538 let list = ['aa', 'bb', 'cc', 'dd']
539 return range(1, 2)->map('list[v:val]')
540 enddef
541
542The map argument is a string expression, which is evaluated without the
543function scope. Instead, use a lambda: >
544 def EvalString(): list<string>
545 let list = ['aa', 'bb', 'cc', 'dd']
546 return range(1, 2)->map({ _, v -> list[v] })
547 enddef
548
549
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100550==============================================================================
551
5524. Types *vim9-types*
553
554THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
555
556The following builtin types are supported:
557 bool
558 number
559 float
560 string
561 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200562 list<{type}>
563 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100564 job
565 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100566 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200567 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200568 func({type}, ...)
569 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100570
571Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200572 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100573
Bram Moolenaard77a8522020-04-03 21:59:57 +0200574These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200575 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100576 void
577 any
578
Bram Moolenaard77a8522020-04-03 21:59:57 +0200579There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100580efficient implementation is used that avoids allocating lot of small pieces of
581memory.
582
Bram Moolenaard77a8522020-04-03 21:59:57 +0200583A partial and function can be declared in more or less specific ways:
584func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200585 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200586func: {type} any number and type of arguments with specific
587 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200588func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200589 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200590func({type}): {type} function with argument type and return type
591func(?{type}) function with type of optional argument, does
592 not return a value
593func(...{type}) function with type of variable number of
594 arguments, does not return a value
595func({type}, ?{type}, ...{type}): {type}
596 function with:
597 - type of mandatory argument
598 - type of optional argument
599 - type of variable number of arguments
600 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200601
602If the return type is "void" the function does not return a value.
603
604The reference can also be a |Partial|, in which case it stores extra arguments
605and/or a dictionary, which are not visible to the caller. Since they are
606called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100607
608Custom types can be defined with `:type`: >
609 :type MyList list<string>
610{not implemented yet}
611
612And classes and interfaces can be used as types: >
613 :class MyClass
614 :let mine: MyClass
615
616 :interface MyInterface
617 :let mine: MyInterface
618
619 :class MyTemplate<Targ>
620 :let mine: MyTemplate<number>
621 :let mine: MyTemplate<string>
622
623 :class MyInterface<Targ>
624 :let mine: MyInterface<number>
625 :let mine: MyInterface<string>
626{not implemented yet}
627
628
629Type inference *type-inference*
630
631In general: Whenever the type is clear it can be omitted. For example, when
632declaring a variable and giving it a value: >
633 let var = 0 " infers number type
634 let var = 'hello' " infers string type
635
636
637==============================================================================
638
6395. Namespace, Import and Export
640 *vim9script* *vim9-export* *vim9-import*
641
642THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
643
644A Vim9 script can be written to be imported. This means that everything in
645the script is local, unless exported. Those exported items, and only those
646items, can then be imported in another script.
647
648
649Namespace ~
650 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100651To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100652appear as the first statement in the file. It tells Vim to interpret the
653script in its own namespace, instead of the global namespace. If a file
654starts with: >
655 vim9script
656 let myvar = 'yes'
657Then "myvar" will only exist in this file. While without `vim9script` it would
658be available as `g:myvar` from any other script and function.
659
660The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200661variables in legacy Vim script, but the "s:" is omitted. And they cannot be
662deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100663
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200664In Vim9 script the global "g:" namespace can still be used as before. And the
665"w:", "b:" and "t:" namespaces. These have in common that variables are not
666declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100667
668A side effect of `:vim9script` is that the 'cpoptions' option is set to the
669Vim default value, like with: >
670 :set cpo&vim
671One of the effects is that |line-continuation| is always enabled.
672The original value of 'cpoptions' is restored at the end of the script.
673
674
675Export ~
676 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200677Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100678 export const EXPORTED_CONST = 1234
679 export let someValue = ...
680 export def MyFunc() ...
681 export class MyClass ...
682
683As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200684be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100685
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200686 *E1042*
687`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100688
689
690Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200691 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100692The exported items can be imported individually in another Vim9 script: >
693 import EXPORTED_CONST from "thatscript.vim"
694 import MyClass from "myclass.vim"
695
696To import multiple items at the same time: >
697 import {someValue, MyClass} from "thatscript.vim"
698
Bram Moolenaar560979e2020-02-04 22:53:05 +0100699In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100700 import MyClass as ThatClass from "myclass.vim"
701 import {someValue, MyClass as ThatClass} from "myclass.vim"
702
703To import all exported items under a specific identifier: >
704 import * as That from 'thatscript.vim'
705
706Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
707to choose the name "That", but it is highly recommended to use the name of the
708script file to avoid confusion.
709
710The script name after `import` can be:
711- A relative path, starting "." or "..". This finds a file relative to the
712 location of the script file itself. This is useful to split up a large
713 plugin into several files.
714- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
715 will be rarely used.
716- A path not being relative or absolute. This will be found in the
717 "import" subdirectories of 'runtimepath' entries. The name will usually be
718 longer and unique, to avoid loading the wrong file.
719
720Once a vim9 script file has been imported, the result is cached and used the
721next time the same script is imported. It will not be read again.
722 *:import-cycle*
723The `import` commands are executed when encountered. If that script (directly
724or indirectly) imports the current script, then items defined after the
725`import` won't be processed yet. Therefore cyclic imports can exist, but may
726result in undefined items.
727
728
729Import in an autoload script ~
730
731For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100732actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100733
7341. In the plugin define user commands, functions and/or mappings that refer to
735 an autoload script. >
736 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
737
738< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
739
7402. In the autocommand script do the actual work. You can import items from
741 other files to split up functionality in appropriate pieces. >
742 vim9script
743 import FilterFunc from "../import/someother.vim"
744 def searchfor#Stuff(arg: string)
745 let filtered = FilterFunc(arg)
746 ...
747< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
748 must be exactly the same as the prefix for the function name, that is how
749 Vim finds the file.
750
7513. Other functionality, possibly shared between plugins, contains the exported
752 items and any private items. >
753 vim9script
754 let localVar = 'local'
755 export def FilterFunc(arg: string): string
756 ...
757< This goes in .../import/someother.vim.
758
759
760Import in legacy Vim script ~
761
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200762If an `import` statement is used in legacy Vim script, the script-local "s:"
763namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100764
765
766==============================================================================
767
7689. Rationale *vim9-rationale*
769
770The :def command ~
771
772Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100773shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100774impossible, because of the overhead involved with calling a function, setting
775up the local function scope and executing lines. There are many details that
776need to be handled, such as error messages and exceptions. The need to create
777a dictionary for a: and l: scopes, the a:000 list and several others add too
778much overhead that cannot be avoided.
779
780Therefore the `:def` method to define a new-style function had to be added,
781which allows for a function with different semantics. Most things still work
782as before, but some parts do not. A new way to define a function was
783considered the best way to separate the old-style code from Vim9 script code.
784
785Using "def" to define a function comes from Python. Other languages use
786"function" which clashes with legacy Vim script.
787
788
789Type checking ~
790
791When compiling lines of Vim commands into instructions as much as possible
792should be done at compile time. Postponing it to runtime makes the execution
793slower and means mistakes are found only later. For example, when
794encountering the "+" character and compiling this into a generic add
795instruction, at execution time the instruction would have to inspect the type
796of the arguments and decide what kind of addition to do. And when the
797type is dictionary throw an error. If the types are known to be numbers then
798an "add number" instruction can be used, which is faster. The error can be
799given at compile time, no error handling is needed at runtime.
800
801The syntax for types is similar to Java, since it is easy to understand and
802widely used. The type names are what was used in Vim before, with some
803additions such as "void" and "bool".
804
805
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200806Compiling functions early ~
807
808Functions are compiled when called or when `:defcompile` is used. Why not
809compile them early, so that syntax and type errors are reported early?
810
811The functions can't be compiled right away when encountered, because there may
812be forward references to functions defined later. Consider defining functions
813A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
814to reorder the functions to avoid forward references.
815
816An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200817figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200818execute the script and compile the functions. This means the script has to be
819parsed twice, which is slower, and some conditions at the script level, such
820as checking if a feature is supported, are hard to use. An attempt was made
821to see if it works, but it turned out to be impossible to make work nicely.
822
823It would be possible to compile all the functions at the end of the script.
824The drawback is that if a function never gets called, the overhead of
825compiling it counts anyway. Since startup speed is very important, in most
826cases it's better to do it later and accept that syntax and type errors are
827only reported then. In case these errors should be found early, e.g. when
828testing, the `:defcompile` command will help out.
829
830
831TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100832
833Script writers have complained that the Vim script syntax is unexpectedly
834different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200835languages are used as an example. At the same time, we do not want to abandon
836the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100837
838Since Vim already uses `:let` and `:const` and optional type checking is
839desirable, the JavaScript/TypeScript syntax fits best for variable
840declarations. >
841 const greeting = 'hello' " string type is inferred
842 let name: string
843 ...
844 name = 'John'
845
846Expression evaluation was already close to what JavaScript and other languages
847are doing. Some details are unexpected and can be fixed. For example how the
848|| and && operators work. Legacy Vim script: >
849 let result = 44
850 ...
851 return result || 0 " returns 1
852
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200853Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100854 let result = 44
855 ...
856 return result || 0 " returns 44
857
858On the other hand, overloading "+" to use both for addition and string
859concatenation goes against legacy Vim script and often leads to mistakes.
860For that reason we will keep using ".." for string concatenation. Lua also
861uses ".." this way.
862
863
864Import and Export ~
865
866A problem of legacy Vim script is that by default all functions and variables
867are global. It is possible to make them script-local, but then they are not
868available in other scripts.
869
870In Vim9 script a mechanism very similar to the Javascript import and export
871mechanism is supported. It is a variant to the existing `:source` command
872that works like one would expect:
873- Instead of making everything global by default, everything is script-local,
874 unless exported.
875- When importing a script the symbols that are imported are listed, avoiding
876 name conflicts and failures if later functionality is added.
877- The mechanism allows for writing a big, long script with a very clear API:
878 the exported function(s) and class(es).
879- By using relative paths loading can be much faster for an import inside of a
880 package, no need to search many directories.
881- Once an import has been used, it can be cached and loading it again can be
882 avoided.
883- The Vim-specific use of "s:" to make things script-local can be dropped.
884
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200885When sourcing a Vim9 script from a legacy script, only the items defined
886globally can be used, not the exported items. Alternatives considered:
887- All the exported items become available as script-local items. This makes
888 it uncontrollable what items get defined.
889- Use the exported items and make them global. Disadvantage is that it's then
890 not possible to avoid name clashes in the global namespace.
891- Completely disallow sourcing a Vim9 script, require using `:import`. That
892 makes it difficult to use scripts for testing, or sourcing them from the
893 command line to try them out.
894
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100895
896Classes ~
897
898Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
899these have never become widespread. When Vim 9 was designed a decision was
900made to phase out these interfaces and concentrate on Vim script, while
901encouraging plugin authors to write code in any language and run it as an
902external tool, using jobs and channels.
903
904Still, using an external tool has disadvantages. An alternative is to convert
905the tool into Vim script. For that to be possible without too much
906translation, and keeping the code fast at the same time, the constructs of the
907tool need to be supported. Since most languages support classes the lack of
908class support in Vim is then a problem.
909
910Previously Vim supported a kind-of object oriented programming by adding
911methods to a dictionary. With some care this could be made to work, but it
912does not look like real classes. On top of that, it's very slow, because of
913the use of dictionaries.
914
915The support of classes in Vim9 script is a "minimal common functionality" of
916class support in most languages. It works mostly like Java, which is the most
917popular programming language.
918
919
920
921 vim:tw=78:ts=8:noet:ft=help:norl: