blob: 7b2597dc6e445e41aeb49a311e7da1f31e70e25a [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
Bram Moolenaarae616492020-07-28 20:07:27 +020074what the meaning is, since both a string and a comment can be followed by
75arbitrary text. To avoid confusion only # comments are recognized. This is
76the same as in shell scripts and Python programs.
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +020077
78In Vi # is a command to list text with numbers. In Vim9 script you can use
79`:number` for that. >
Bram Moolenaarae616492020-07-28 20:07:27 +020080 101 number
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +020081
82To improve readability there must be a space between a command and the #
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020083that starts a comment. Note that #{ is the start of a dictionary, therefore
Bram Moolenaarae616492020-07-28 20:07:27 +020084it does not start a comment.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020085
Bram Moolenaar2c330432020-04-13 14:41:35 +020086
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010087Vim9 functions ~
88
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020089A function defined with `:def` is compiled. Execution is many times faster,
90often 10x to 100x times.
91
Bram Moolenaar388a5d42020-05-26 21:20:45 +020092Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020093The syntax is strict, to enforce code that is easy to read and understand.
94
Bram Moolenaar388a5d42020-05-26 21:20:45 +020095Compilation is done when the function is first called, or when the
96`:defcompile` command is encountered in the script where the function was
Bram Moolenaarae616492020-07-28 20:07:27 +020097defined. `:disassemble` also compiles the function.
Bram Moolenaar388a5d42020-05-26 21:20:45 +020098
99`:def` has no options like `:function` does: "range", "abort", "dict" or
100"closure". A `:def` function always aborts on an error, does not get a range
101passed and cannot be a "dict" function.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100102
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200103The argument types and return type need to be specified. The "any" type can
104be used, type checking will then be done at runtime, like with legacy
105functions.
106
107Arguments are accessed by name, without "a:". There is no "a:" dictionary or
Bram Moolenaarae616492020-07-28 20:07:27 +0200108"a:000" list. Just like any other language.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200109
110Variable arguments are defined as the last argument, with a name and have a
111list type, similar to Typescript. For example, a list of numbers: >
112 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100113 for item in itemlist
114 ...
115
116
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200117Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200118 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200119When using `:function` or `:def` to specify a new function at the script level
120in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200121prefixed. Using the "s:" prefix is optional.
122
123To define or use a global function or variable the "g:" prefix must be used.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200124
125When using `:function` or `:def` to specify a new function inside a function,
126the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200127script-local function inside a function. It is possible to define a global
128function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200129
130When referring to a function and no "s:" or "g:" prefix is used, Vim will
131search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200132- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200133- Local to the current script file.
134- Imported functions, see `:import`.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200135In all cases the function must be defined before used. That is when it is
136first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200137
138The result is that functions and variables without a namespace can always be
139found in the script, either defined there or imported. Global functions and
140variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200141
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200142Global functions can be still be defined and deleted at nearly any time. In
143Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200144and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200145
146
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100147Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200148 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100149Local variables need to be declared with `:let`. Local constants need to be
150declared with `:const`. We refer to both as "variables".
151
152Variables can be local to a script, function or code block: >
153 vim9script
154 let script_var = 123
155 def SomeFunc()
156 let func_var = script_var
157 if cond
158 let block_var = func_var
159 ...
160
161The variables are only visible in the block where they are defined and nested
162blocks. Once the block ends the variable is no longer accessible: >
163 if cond
164 let inner = 5
165 else
166 let inner = 0
167 endif
168 echo inner " Error!
169
170The declaration must be done earlier: >
171 let inner: number
172 if cond
173 inner = 5
174 else
175 inner = 0
176 endif
177 echo inner
178
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200179To intentionally avoid a variable being available later, a block can be used:
180>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100181 {
182 let temp = 'temp'
183 ...
184 }
185 echo temp " Error!
186
Bram Moolenaar560979e2020-02-04 22:53:05 +0100187An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200188declaration. Global, window, tab, buffer and Vim variables can only be used
189without `:let`, because they are are not really declared, they can also be
190deleted with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100191
192Variables cannot shadow previously defined variables.
193Variables may shadow Ex commands, rename the variable if needed.
194
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200195Global variables and user defined functions must be prefixed with "g:", also
196at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200197 vim9script
198 let script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200199 g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200200 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200201
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100202Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
203used to repeat a `:substitute` command.
204
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200205 *E1092*
206Declaring more than one variable at a time, using the unpack notation, is
207currently not supported: >
208 let [v1, v2] = GetValues() # Error!
209That is because the type needs to be inferred from the list item type, which
210isn't that easy.
211
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100212
213Omitting :call and :eval ~
214
215Functions can be called without `:call`: >
216 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100217Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100218
219A method call without `eval` is possible, so long as the start is an
Bram Moolenaarae616492020-07-28 20:07:27 +0200220identifier or can't be an Ex command. Examples: >
221 myList->add(123)
222 g:myList->add(123)
223 [1, 2, 3]->Process()
224 #{a: 1, b: 2}->Process()
225 {'a': 1, 'b': 2}->Process()
226 "foobar"->Process()
227 ("foobar")->Process()
228 'foobar'->Process()
229 ('foobar')->Process()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100230
Bram Moolenaarae616492020-07-28 20:07:27 +0200231In rare case there is ambiguity between a function name and an Ex command, use
232":" to make clear you want to use the Ex command. For example, there is both
233the `:substitute` command and the `substitute()` function. When the line
234starts with `substitute(` this will use the function. Prepend a colon to use
235the command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100236 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100237
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100238Note that while variables need to be defined before they can be used,
239functions can be called before being defined. This is required to be able
240have cyclic dependencies between functions. It is slightly less efficient,
241since the function has to be looked up by name. And a typo in the function
Bram Moolenaarae616492020-07-28 20:07:27 +0200242name will only be found when the function is called.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100243
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100244
Bram Moolenaard1caa942020-04-10 22:10:56 +0200245Omitting function() ~
246
247A user defined function can be used as a function reference in an expression
248without `function()`. The argument types and return type will then be checked.
249The function must already have been defined. >
250
251 let Funcref = MyFunction
252
253When using `function()` the resulting type is "func", a function with any
254number of arguments and any return type. The function can be defined later.
255
256
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200257Automatic line continuation ~
258
259In many cases it is obvious that an expression continues on the next line. In
260those cases there is no need to prefix the line with a backslash. For
261example, when a list spans multiple lines: >
262 let mylist = [
263 'one',
264 'two',
265 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200266And when a dict spans multiple lines: >
267 let mydict = #{
268 one: 1,
269 two: 2,
270 }
271Function call: >
272 let result = Func(
273 arg1,
274 arg2
275 )
276
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200277For binary operators in expressions not in [], {} or () a line break is
278possible just before or after the operator. For example: >
279 let text = lead
280 .. middle
281 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200282 let total = start +
283 end -
284 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200285 let result = positive
286 ? PosFunc(arg)
287 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200288
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200289For a method call using "->" and a member using a dot, a line break is allowed
290before it: >
Bram Moolenaar73fef332020-06-21 22:12:03 +0200291 let result = GetBuilder()
292 ->BuilderSetWidth(333)
293 ->BuilderSetHeight(777)
294 ->BuilderBuild()
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200295 let result = MyDict
296 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200297
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200298< *E1050*
299To make it possible for the operator at the start of the line to be
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200300recognized, it is required to put a colon before a range. This will add
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200301"start" and print: >
302 let result = start
303 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200304Like this: >
305 let result = start + print
306
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200307This will assign "start" and print a line: >
308 let result = start
309 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200310
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200311It is also possible to split a function header over multiple lines, in between
312arguments: >
313 def MyFunc(
314 text: string,
315 separator = '-'
316 ): string
317
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200318Notes:
319- "enddef" cannot be used at the start of a continuation line, it ends the
320 current function.
321- No line break is allowed in the LHS of an assignment. Specifically when
322 unpacking a list |:let-unpack|. This is OK: >
323 [var1, var2] =
324 Func()
325< This does not work: >
326 [var1,
327 var2] =
328 Func()
329- No line break is allowed in between arguments of an `:echo`, `:execute` and
330 similar commands. This is OK: >
331 echo [1,
332 2] [3,
333 4]
334< This does not work: >
335 echo [1, 2]
336 [3, 4]
337- No line break is allowed in the arguments of a lambda, between the "{" and
338 "->". This is OK: >
339 filter(list, {k, v ->
340 v > 0})
341< This does not work: >
342 filter(list, {k,
343 v -> v > 0})
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200344
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200345
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100346No curly braces expansion ~
347
348|curly-braces-names| cannot be used.
349
350
Bram Moolenaarae616492020-07-28 20:07:27 +0200351No :xit, :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100352
Bram Moolenaarae616492020-07-28 20:07:27 +0200353These commands are too easily confused with local variable names. Instead of
354`:x` or `:xit` you can use `:exit`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100355
356
357Comparators ~
358
359The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100360
361
362White space ~
363
364Vim9 script enforces proper use of white space. This is no longer allowed: >
365 let var=234 " Error!
366 let var= 234 " Error!
367 let var =234 " Error!
368There must be white space before and after the "=": >
369 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200370White space must also be put before the # that starts a comment after a
371command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200372 let var = 234# Error!
373 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100374
375White space is required around most operators.
376
377White space is not allowed:
378- Between a function name and the "(": >
379 call Func (arg) " Error!
380 call Func
381 \ (arg) " Error!
382 call Func(arg) " OK
383 call Func(
384 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100385 call Func(
386 \ arg " OK
387 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100388
389
390Conditions and expressions ~
391
392Conditions and expression are mostly working like they do in JavaScript. A
393difference is made where JavaScript does not work like most people expect.
394Specifically, an empty list is falsey.
395
396Any type of variable can be used as a condition, there is no error, not even
397for using a list or job. This is very much like JavaScript, but there are a
398few exceptions.
399
400 type TRUE when ~
401 bool v:true
402 number non-zero
403 float non-zero
404 string non-empty
405 blob non-empty
406 list non-empty (different from JavaScript)
407 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200408 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100409 special v:true
410 job when not NULL
411 channel when not NULL
412 class when not NULL
413 object when not NULL (TODO: when isTrue() returns v:true)
414
415The boolean operators "||" and "&&" do not change the value: >
416 8 || 2 == 8
417 0 || 2 == 2
418 0 || '' == ''
419 8 && 2 == 2
420 0 && 2 == 0
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200421 2 && 0 == 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100422 [] && 2 == []
423
424When using `..` for string concatenation the arguments are always converted to
425string. >
426 'hello ' .. 123 == 'hello 123'
427 'hello ' .. v:true == 'hello true'
428
429In Vim9 script one can use "true" for v:true and "false" for v:false.
430
431
Bram Moolenaare46a4402020-06-30 20:38:27 +0200432What to watch out for ~
433 *vim9-gotchas*
434Vim9 was designed to be closer to often used programming languages, but at the
435same time tries to support the legacy Vim commands. Some compromises had to
436be made. Here is a summary of what might be unexpected.
437
438Ex command ranges need to be prefixed with a colon. >
439 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200440 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200441 :-> " Vim9: shifts the previous line to the right
442
443 %s/a/b " legacy Vim: substitute on all lines
444 x = alongname
445 % another " Vim9: line continuation without a backslash
446 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200447 'text'->func() " Vim9: method call
448 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200449
450Functions defined with `:def` compile the whole function. Legacy functions
451can bail out, and the following lines are not parsed: >
452 func Maybe()
453 if !has('feature')
454 return
455 endif
456 use-feature
457 endfunc
458Vim9 functions are compiled as a whole: >
459 def Maybe()
460 if !has('feature')
461 return
462 endif
463 use-feature " May give compilation error
464 enddef
465For a workaround, split it in two functions: >
466 func Maybe()
467 if has('feature')
468 call MaybyInner()
469 endif
470 endfunc
471 if has('feature')
472 def MaybeInner()
473 use-feature
474 enddef
475 endif
476
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100477==============================================================================
478
4793. New style functions *fast-functions*
480
481THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
482
483 *:def*
484:def[!] {name}([arguments])[: {return-type}
485 Define a new function by the name {name}. The body of
486 the function follows in the next lines, until the
487 matching `:enddef`.
488
Bram Moolenaard77a8522020-04-03 21:59:57 +0200489 When {return-type} is omitted or is "void" the
490 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100491
492 {arguments} is a sequence of zero or more argument
493 declarations. There are three forms:
494 {name}: {type}
495 {name} = {value}
496 {name}: {type} = {value}
497 The first form is a mandatory argument, the caller
498 must always provide them.
499 The second and third form are optional arguments.
500 When the caller omits an argument the {value} is used.
501
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200502 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200503 called, or when `:disassemble` or `:defcompile` is
504 used. Syntax and type errors will be produced at that
505 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200506
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200507 It is possible to nest `:def` inside another `:def` or
508 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100509
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200510 [!] is used as with `:function`. Note that in Vim9
511 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200512 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100513
514 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200515:enddef End of a function defined with `:def`. It should be on
516 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100517
518
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100519If the script the function is defined in is Vim9 script, then script-local
520variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200521before the function is compiled. If the script the function is defined in is
522legacy script, then script-local variables must be accessed with the "s:"
523prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100524
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200525 *:defc* *:defcompile*
526:defc[ompile] Compile functions defined in the current script that
527 were not compiled yet.
528 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100529
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100530 *:disa* *:disassemble*
531:disa[ssemble] {func} Show the instructions generated for {func}.
532 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100533 Note that for command line completion of {func} you
534 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100535
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200536Limitations ~
537
538Local variables will not be visible to string evaluation. For example: >
539 def EvalString(): list<string>
540 let list = ['aa', 'bb', 'cc', 'dd']
541 return range(1, 2)->map('list[v:val]')
542 enddef
543
544The map argument is a string expression, which is evaluated without the
545function scope. Instead, use a lambda: >
546 def EvalString(): list<string>
547 let list = ['aa', 'bb', 'cc', 'dd']
548 return range(1, 2)->map({ _, v -> list[v] })
549 enddef
550
551
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100552==============================================================================
553
5544. Types *vim9-types*
555
556THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
557
558The following builtin types are supported:
559 bool
560 number
561 float
562 string
563 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200564 list<{type}>
565 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100566 job
567 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100568 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200569 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200570 func({type}, ...)
571 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100572
573Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200574 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100575
Bram Moolenaard77a8522020-04-03 21:59:57 +0200576These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200577 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100578 void
579 any
580
Bram Moolenaard77a8522020-04-03 21:59:57 +0200581There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100582efficient implementation is used that avoids allocating lot of small pieces of
583memory.
584
Bram Moolenaard77a8522020-04-03 21:59:57 +0200585A partial and function can be declared in more or less specific ways:
586func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200587 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200588func: {type} any number and type of arguments with specific
589 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200590func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200591 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200592func({type}): {type} function with argument type and return type
593func(?{type}) function with type of optional argument, does
594 not return a value
595func(...{type}) function with type of variable number of
596 arguments, does not return a value
597func({type}, ?{type}, ...{type}): {type}
598 function with:
599 - type of mandatory argument
600 - type of optional argument
601 - type of variable number of arguments
602 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200603
604If the return type is "void" the function does not return a value.
605
606The reference can also be a |Partial|, in which case it stores extra arguments
607and/or a dictionary, which are not visible to the caller. Since they are
608called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100609
610Custom types can be defined with `:type`: >
611 :type MyList list<string>
612{not implemented yet}
613
614And classes and interfaces can be used as types: >
615 :class MyClass
616 :let mine: MyClass
617
618 :interface MyInterface
619 :let mine: MyInterface
620
621 :class MyTemplate<Targ>
622 :let mine: MyTemplate<number>
623 :let mine: MyTemplate<string>
624
625 :class MyInterface<Targ>
626 :let mine: MyInterface<number>
627 :let mine: MyInterface<string>
628{not implemented yet}
629
630
631Type inference *type-inference*
632
633In general: Whenever the type is clear it can be omitted. For example, when
634declaring a variable and giving it a value: >
635 let var = 0 " infers number type
636 let var = 'hello' " infers string type
637
638
639==============================================================================
640
6415. Namespace, Import and Export
642 *vim9script* *vim9-export* *vim9-import*
643
644THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
645
646A Vim9 script can be written to be imported. This means that everything in
647the script is local, unless exported. Those exported items, and only those
648items, can then be imported in another script.
649
650
651Namespace ~
652 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100653To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100654appear as the first statement in the file. It tells Vim to interpret the
655script in its own namespace, instead of the global namespace. If a file
656starts with: >
657 vim9script
658 let myvar = 'yes'
659Then "myvar" will only exist in this file. While without `vim9script` it would
660be available as `g:myvar` from any other script and function.
661
662The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200663variables in legacy Vim script, but the "s:" is omitted. And they cannot be
664deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100665
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200666In Vim9 script the global "g:" namespace can still be used as before. And the
667"w:", "b:" and "t:" namespaces. These have in common that variables are not
668declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100669
670A side effect of `:vim9script` is that the 'cpoptions' option is set to the
671Vim default value, like with: >
672 :set cpo&vim
673One of the effects is that |line-continuation| is always enabled.
674The original value of 'cpoptions' is restored at the end of the script.
675
676
677Export ~
678 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200679Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100680 export const EXPORTED_CONST = 1234
681 export let someValue = ...
682 export def MyFunc() ...
683 export class MyClass ...
684
685As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200686be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100687
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200688 *E1042*
689`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100690
691
692Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200693 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100694The exported items can be imported individually in another Vim9 script: >
695 import EXPORTED_CONST from "thatscript.vim"
696 import MyClass from "myclass.vim"
697
698To import multiple items at the same time: >
699 import {someValue, MyClass} from "thatscript.vim"
700
Bram Moolenaar560979e2020-02-04 22:53:05 +0100701In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100702 import MyClass as ThatClass from "myclass.vim"
703 import {someValue, MyClass as ThatClass} from "myclass.vim"
704
705To import all exported items under a specific identifier: >
706 import * as That from 'thatscript.vim'
707
708Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
709to choose the name "That", but it is highly recommended to use the name of the
710script file to avoid confusion.
711
712The script name after `import` can be:
713- A relative path, starting "." or "..". This finds a file relative to the
714 location of the script file itself. This is useful to split up a large
715 plugin into several files.
716- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
717 will be rarely used.
718- A path not being relative or absolute. This will be found in the
719 "import" subdirectories of 'runtimepath' entries. The name will usually be
720 longer and unique, to avoid loading the wrong file.
721
722Once a vim9 script file has been imported, the result is cached and used the
723next time the same script is imported. It will not be read again.
724 *:import-cycle*
725The `import` commands are executed when encountered. If that script (directly
726or indirectly) imports the current script, then items defined after the
727`import` won't be processed yet. Therefore cyclic imports can exist, but may
728result in undefined items.
729
730
731Import in an autoload script ~
732
733For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100734actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100735
7361. In the plugin define user commands, functions and/or mappings that refer to
737 an autoload script. >
738 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
739
740< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
741
7422. In the autocommand script do the actual work. You can import items from
743 other files to split up functionality in appropriate pieces. >
744 vim9script
745 import FilterFunc from "../import/someother.vim"
746 def searchfor#Stuff(arg: string)
747 let filtered = FilterFunc(arg)
748 ...
749< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
750 must be exactly the same as the prefix for the function name, that is how
751 Vim finds the file.
752
7533. Other functionality, possibly shared between plugins, contains the exported
754 items and any private items. >
755 vim9script
756 let localVar = 'local'
757 export def FilterFunc(arg: string): string
758 ...
759< This goes in .../import/someother.vim.
760
761
762Import in legacy Vim script ~
763
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200764If an `import` statement is used in legacy Vim script, the script-local "s:"
765namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100766
767
768==============================================================================
769
7709. Rationale *vim9-rationale*
771
772The :def command ~
773
774Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100775shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100776impossible, because of the overhead involved with calling a function, setting
777up the local function scope and executing lines. There are many details that
778need to be handled, such as error messages and exceptions. The need to create
779a dictionary for a: and l: scopes, the a:000 list and several others add too
780much overhead that cannot be avoided.
781
782Therefore the `:def` method to define a new-style function had to be added,
783which allows for a function with different semantics. Most things still work
784as before, but some parts do not. A new way to define a function was
785considered the best way to separate the old-style code from Vim9 script code.
786
787Using "def" to define a function comes from Python. Other languages use
788"function" which clashes with legacy Vim script.
789
790
791Type checking ~
792
793When compiling lines of Vim commands into instructions as much as possible
794should be done at compile time. Postponing it to runtime makes the execution
795slower and means mistakes are found only later. For example, when
796encountering the "+" character and compiling this into a generic add
797instruction, at execution time the instruction would have to inspect the type
798of the arguments and decide what kind of addition to do. And when the
799type is dictionary throw an error. If the types are known to be numbers then
800an "add number" instruction can be used, which is faster. The error can be
801given at compile time, no error handling is needed at runtime.
802
803The syntax for types is similar to Java, since it is easy to understand and
804widely used. The type names are what was used in Vim before, with some
805additions such as "void" and "bool".
806
807
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200808Compiling functions early ~
809
810Functions are compiled when called or when `:defcompile` is used. Why not
811compile them early, so that syntax and type errors are reported early?
812
813The functions can't be compiled right away when encountered, because there may
814be forward references to functions defined later. Consider defining functions
815A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
816to reorder the functions to avoid forward references.
817
818An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200819figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200820execute the script and compile the functions. This means the script has to be
821parsed twice, which is slower, and some conditions at the script level, such
822as checking if a feature is supported, are hard to use. An attempt was made
823to see if it works, but it turned out to be impossible to make work nicely.
824
825It would be possible to compile all the functions at the end of the script.
826The drawback is that if a function never gets called, the overhead of
827compiling it counts anyway. Since startup speed is very important, in most
828cases it's better to do it later and accept that syntax and type errors are
829only reported then. In case these errors should be found early, e.g. when
830testing, the `:defcompile` command will help out.
831
832
833TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100834
835Script writers have complained that the Vim script syntax is unexpectedly
836different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200837languages are used as an example. At the same time, we do not want to abandon
838the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100839
840Since Vim already uses `:let` and `:const` and optional type checking is
841desirable, the JavaScript/TypeScript syntax fits best for variable
842declarations. >
843 const greeting = 'hello' " string type is inferred
844 let name: string
845 ...
846 name = 'John'
847
848Expression evaluation was already close to what JavaScript and other languages
849are doing. Some details are unexpected and can be fixed. For example how the
850|| and && operators work. Legacy Vim script: >
851 let result = 44
852 ...
853 return result || 0 " returns 1
854
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200855Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100856 let result = 44
857 ...
858 return result || 0 " returns 44
859
860On the other hand, overloading "+" to use both for addition and string
861concatenation goes against legacy Vim script and often leads to mistakes.
862For that reason we will keep using ".." for string concatenation. Lua also
863uses ".." this way.
864
865
866Import and Export ~
867
868A problem of legacy Vim script is that by default all functions and variables
869are global. It is possible to make them script-local, but then they are not
870available in other scripts.
871
872In Vim9 script a mechanism very similar to the Javascript import and export
873mechanism is supported. It is a variant to the existing `:source` command
874that works like one would expect:
875- Instead of making everything global by default, everything is script-local,
876 unless exported.
877- When importing a script the symbols that are imported are listed, avoiding
878 name conflicts and failures if later functionality is added.
879- The mechanism allows for writing a big, long script with a very clear API:
880 the exported function(s) and class(es).
881- By using relative paths loading can be much faster for an import inside of a
882 package, no need to search many directories.
883- Once an import has been used, it can be cached and loading it again can be
884 avoided.
885- The Vim-specific use of "s:" to make things script-local can be dropped.
886
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200887When sourcing a Vim9 script from a legacy script, only the items defined
888globally can be used, not the exported items. Alternatives considered:
889- All the exported items become available as script-local items. This makes
890 it uncontrollable what items get defined.
891- Use the exported items and make them global. Disadvantage is that it's then
892 not possible to avoid name clashes in the global namespace.
893- Completely disallow sourcing a Vim9 script, require using `:import`. That
894 makes it difficult to use scripts for testing, or sourcing them from the
895 command line to try them out.
896
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100897
898Classes ~
899
900Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
901these have never become widespread. When Vim 9 was designed a decision was
902made to phase out these interfaces and concentrate on Vim script, while
903encouraging plugin authors to write code in any language and run it as an
904external tool, using jobs and channels.
905
906Still, using an external tool has disadvantages. An alternative is to convert
907the tool into Vim script. For that to be possible without too much
908translation, and keeping the code fast at the same time, the constructs of the
909tool need to be supported. Since most languages support classes the lack of
910class support in Vim is then a problem.
911
912Previously Vim supported a kind-of object oriented programming by adding
913methods to a dictionary. With some care this could be made to work, but it
914does not look like real classes. On top of that, it's very slow, because of
915the use of dictionaries.
916
917The support of classes in Vim9 script is a "minimal common functionality" of
918class support in most languages. It works mostly like Java, which is the most
919popular programming language.
920
921
922
923 vim:tw=78:ts=8:noet:ft=help:norl: