blob: 2c4d1dbc191dd9fdc6c197571d4a5543f5b00de4 [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 Moolenaarea2d8d22020-07-29 22:11:05 +0200121prefixed. Using the "s:" prefix is optional. To define or use a global
122function or variable the "g:" prefix must be used. For functions in an
123autoload script the "name#" prefix is sufficient. >
124 def ThisFunction() # script-local
125 def s:ThisFunction() # script-local
126 def g:ThatFunction() # global
127 def scriptname#function() # autoload
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200128
129When using `:function` or `:def` to specify a new function inside a function,
130the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200131script-local function inside a function. It is possible to define a global
132function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200133
134When referring to a function and no "s:" or "g:" prefix is used, Vim will
135search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200136- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200137- Local to the current script file.
138- Imported functions, see `:import`.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200139In all cases the function must be defined before used. That is when it is
140first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200141
142The result is that functions and variables without a namespace can always be
143found in the script, either defined there or imported. Global functions and
144variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200145
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200146Global functions can be still be defined and deleted at nearly any time. In
147Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200148and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200149
150
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100151Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200152 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100153Local variables need to be declared with `:let`. Local constants need to be
154declared with `:const`. We refer to both as "variables".
155
156Variables can be local to a script, function or code block: >
157 vim9script
158 let script_var = 123
159 def SomeFunc()
160 let func_var = script_var
161 if cond
162 let block_var = func_var
163 ...
164
165The variables are only visible in the block where they are defined and nested
166blocks. Once the block ends the variable is no longer accessible: >
167 if cond
168 let inner = 5
169 else
170 let inner = 0
171 endif
172 echo inner " Error!
173
174The declaration must be done earlier: >
175 let inner: number
176 if cond
177 inner = 5
178 else
179 inner = 0
180 endif
181 echo inner
182
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200183To intentionally avoid a variable being available later, a block can be used:
184>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100185 {
186 let temp = 'temp'
187 ...
188 }
189 echo temp " Error!
190
Bram Moolenaar560979e2020-02-04 22:53:05 +0100191An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200192declaration. Global, window, tab, buffer and Vim variables can only be used
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200193without `:let`, because they are not really declared, they can also be deleted
194with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100195
196Variables cannot shadow previously defined variables.
197Variables may shadow Ex commands, rename the variable if needed.
198
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200199Global variables and user defined functions must be prefixed with "g:", also
200at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200201 vim9script
202 let script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200203 g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200204 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200205
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100206Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
207used to repeat a `:substitute` command.
208
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200209 *E1092*
210Declaring more than one variable at a time, using the unpack notation, is
211currently not supported: >
212 let [v1, v2] = GetValues() # Error!
213That is because the type needs to be inferred from the list item type, which
214isn't that easy.
215
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100216
217Omitting :call and :eval ~
218
219Functions can be called without `:call`: >
220 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100221Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100222
223A method call without `eval` is possible, so long as the start is an
Bram Moolenaarae616492020-07-28 20:07:27 +0200224identifier or can't be an Ex command. Examples: >
225 myList->add(123)
226 g:myList->add(123)
227 [1, 2, 3]->Process()
228 #{a: 1, b: 2}->Process()
229 {'a': 1, 'b': 2}->Process()
230 "foobar"->Process()
231 ("foobar")->Process()
232 'foobar'->Process()
233 ('foobar')->Process()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100234
Bram Moolenaarae616492020-07-28 20:07:27 +0200235In rare case there is ambiguity between a function name and an Ex command, use
236":" to make clear you want to use the Ex command. For example, there is both
237the `:substitute` command and the `substitute()` function. When the line
238starts with `substitute(` this will use the function. Prepend a colon to use
239the command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100240 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100241
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100242Note that while variables need to be defined before they can be used,
243functions can be called before being defined. This is required to be able
244have cyclic dependencies between functions. It is slightly less efficient,
245since the function has to be looked up by name. And a typo in the function
Bram Moolenaarae616492020-07-28 20:07:27 +0200246name will only be found when the function is called.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100247
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100248
Bram Moolenaard1caa942020-04-10 22:10:56 +0200249Omitting function() ~
250
251A user defined function can be used as a function reference in an expression
252without `function()`. The argument types and return type will then be checked.
253The function must already have been defined. >
254
255 let Funcref = MyFunction
256
257When using `function()` the resulting type is "func", a function with any
258number of arguments and any return type. The function can be defined later.
259
260
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200261Automatic line continuation ~
262
263In many cases it is obvious that an expression continues on the next line. In
264those cases there is no need to prefix the line with a backslash. For
265example, when a list spans multiple lines: >
266 let mylist = [
267 'one',
268 'two',
269 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200270And when a dict spans multiple lines: >
271 let mydict = #{
272 one: 1,
273 two: 2,
274 }
275Function call: >
276 let result = Func(
277 arg1,
278 arg2
279 )
280
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200281For binary operators in expressions not in [], {} or () a line break is
282possible just before or after the operator. For example: >
283 let text = lead
284 .. middle
285 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200286 let total = start +
287 end -
288 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200289 let result = positive
290 ? PosFunc(arg)
291 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200292
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200293For a method call using "->" and a member using a dot, a line break is allowed
294before it: >
Bram Moolenaar73fef332020-06-21 22:12:03 +0200295 let result = GetBuilder()
296 ->BuilderSetWidth(333)
297 ->BuilderSetHeight(777)
298 ->BuilderBuild()
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200299 let result = MyDict
300 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200301
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200302< *E1050*
303To make it possible for the operator at the start of the line to be
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200304recognized, it is required to put a colon before a range. This will add
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200305"start" and print: >
306 let result = start
307 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200308Like this: >
309 let result = start + print
310
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200311This will assign "start" and print a line: >
312 let result = start
313 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200314
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200315It is also possible to split a function header over multiple lines, in between
316arguments: >
317 def MyFunc(
318 text: string,
319 separator = '-'
320 ): string
321
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200322Notes:
323- "enddef" cannot be used at the start of a continuation line, it ends the
324 current function.
325- No line break is allowed in the LHS of an assignment. Specifically when
326 unpacking a list |:let-unpack|. This is OK: >
327 [var1, var2] =
328 Func()
329< This does not work: >
330 [var1,
331 var2] =
332 Func()
333- No line break is allowed in between arguments of an `:echo`, `:execute` and
334 similar commands. This is OK: >
335 echo [1,
336 2] [3,
337 4]
338< This does not work: >
339 echo [1, 2]
340 [3, 4]
341- No line break is allowed in the arguments of a lambda, between the "{" and
342 "->". This is OK: >
343 filter(list, {k, v ->
344 v > 0})
345< This does not work: >
346 filter(list, {k,
347 v -> v > 0})
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200348
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200349
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100350No curly braces expansion ~
351
352|curly-braces-names| cannot be used.
353
354
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200355No :xit, :t, :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100356
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200357These commands are too easily confused with local variable names.
358Instead of `:x` or `:xit` you can use `:exit`.
359Instead of `:t` you can use `:copy`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100360
361
362Comparators ~
363
364The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100365
366
367White space ~
368
369Vim9 script enforces proper use of white space. This is no longer allowed: >
370 let var=234 " Error!
371 let var= 234 " Error!
372 let var =234 " Error!
373There must be white space before and after the "=": >
374 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200375White space must also be put before the # that starts a comment after a
376command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200377 let var = 234# Error!
378 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100379
380White space is required around most operators.
381
382White space is not allowed:
383- Between a function name and the "(": >
384 call Func (arg) " Error!
385 call Func
386 \ (arg) " Error!
387 call Func(arg) " OK
388 call Func(
389 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100390 call Func(
391 \ arg " OK
392 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100393
394
395Conditions and expressions ~
396
397Conditions and expression are mostly working like they do in JavaScript. A
398difference is made where JavaScript does not work like most people expect.
399Specifically, an empty list is falsey.
400
401Any type of variable can be used as a condition, there is no error, not even
402for using a list or job. This is very much like JavaScript, but there are a
403few exceptions.
404
405 type TRUE when ~
406 bool v:true
407 number non-zero
408 float non-zero
409 string non-empty
410 blob non-empty
411 list non-empty (different from JavaScript)
412 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200413 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100414 special v:true
415 job when not NULL
416 channel when not NULL
417 class when not NULL
418 object when not NULL (TODO: when isTrue() returns v:true)
419
420The boolean operators "||" and "&&" do not change the value: >
421 8 || 2 == 8
422 0 || 2 == 2
423 0 || '' == ''
424 8 && 2 == 2
425 0 && 2 == 0
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200426 2 && 0 == 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100427 [] && 2 == []
428
429When using `..` for string concatenation the arguments are always converted to
430string. >
431 'hello ' .. 123 == 'hello 123'
432 'hello ' .. v:true == 'hello true'
433
434In Vim9 script one can use "true" for v:true and "false" for v:false.
435
436
Bram Moolenaare46a4402020-06-30 20:38:27 +0200437What to watch out for ~
438 *vim9-gotchas*
439Vim9 was designed to be closer to often used programming languages, but at the
440same time tries to support the legacy Vim commands. Some compromises had to
441be made. Here is a summary of what might be unexpected.
442
443Ex command ranges need to be prefixed with a colon. >
444 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200445 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200446 :-> " Vim9: shifts the previous line to the right
447
448 %s/a/b " legacy Vim: substitute on all lines
449 x = alongname
450 % another " Vim9: line continuation without a backslash
451 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200452 'text'->func() " Vim9: method call
453 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200454
455Functions defined with `:def` compile the whole function. Legacy functions
456can bail out, and the following lines are not parsed: >
457 func Maybe()
458 if !has('feature')
459 return
460 endif
461 use-feature
462 endfunc
463Vim9 functions are compiled as a whole: >
464 def Maybe()
465 if !has('feature')
466 return
467 endif
468 use-feature " May give compilation error
469 enddef
470For a workaround, split it in two functions: >
471 func Maybe()
472 if has('feature')
473 call MaybyInner()
474 endif
475 endfunc
476 if has('feature')
477 def MaybeInner()
478 use-feature
479 enddef
480 endif
481
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100482==============================================================================
483
4843. New style functions *fast-functions*
485
486THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
487
488 *:def*
489:def[!] {name}([arguments])[: {return-type}
490 Define a new function by the name {name}. The body of
491 the function follows in the next lines, until the
492 matching `:enddef`.
493
Bram Moolenaard77a8522020-04-03 21:59:57 +0200494 When {return-type} is omitted or is "void" the
495 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100496
497 {arguments} is a sequence of zero or more argument
498 declarations. There are three forms:
499 {name}: {type}
500 {name} = {value}
501 {name}: {type} = {value}
502 The first form is a mandatory argument, the caller
503 must always provide them.
504 The second and third form are optional arguments.
505 When the caller omits an argument the {value} is used.
506
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200507 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200508 called, or when `:disassemble` or `:defcompile` is
509 used. Syntax and type errors will be produced at that
510 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200511
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200512 It is possible to nest `:def` inside another `:def` or
513 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100514
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200515 [!] is used as with `:function`. Note that in Vim9
516 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200517 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100518
519 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200520:enddef End of a function defined with `:def`. It should be on
521 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100522
523
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100524If the script the function is defined in is Vim9 script, then script-local
525variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200526before the function is compiled. If the script the function is defined in is
527legacy script, then script-local variables must be accessed with the "s:"
528prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100529
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200530 *:defc* *:defcompile*
531:defc[ompile] Compile functions defined in the current script that
532 were not compiled yet.
533 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100534
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100535 *:disa* *:disassemble*
536:disa[ssemble] {func} Show the instructions generated for {func}.
537 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100538 Note that for command line completion of {func} you
539 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100540
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200541Limitations ~
542
543Local variables will not be visible to string evaluation. For example: >
544 def EvalString(): list<string>
545 let list = ['aa', 'bb', 'cc', 'dd']
546 return range(1, 2)->map('list[v:val]')
547 enddef
548
549The map argument is a string expression, which is evaluated without the
550function scope. Instead, use a lambda: >
551 def EvalString(): list<string>
552 let list = ['aa', 'bb', 'cc', 'dd']
553 return range(1, 2)->map({ _, v -> list[v] })
554 enddef
555
556
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100557==============================================================================
558
5594. Types *vim9-types*
560
561THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
562
563The following builtin types are supported:
564 bool
565 number
566 float
567 string
568 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200569 list<{type}>
570 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100571 job
572 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100573 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200574 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200575 func({type}, ...)
576 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100577
578Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200579 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100580
Bram Moolenaard77a8522020-04-03 21:59:57 +0200581These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200582 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100583 void
584 any
585
Bram Moolenaard77a8522020-04-03 21:59:57 +0200586There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100587efficient implementation is used that avoids allocating lot of small pieces of
588memory.
589
Bram Moolenaard77a8522020-04-03 21:59:57 +0200590A partial and function can be declared in more or less specific ways:
591func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200592 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200593func: {type} any number and type of arguments with specific
594 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200595func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200596 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200597func({type}): {type} function with argument type and return type
598func(?{type}) function with type of optional argument, does
599 not return a value
600func(...{type}) function with type of variable number of
601 arguments, does not return a value
602func({type}, ?{type}, ...{type}): {type}
603 function with:
604 - type of mandatory argument
605 - type of optional argument
606 - type of variable number of arguments
607 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200608
609If the return type is "void" the function does not return a value.
610
611The reference can also be a |Partial|, in which case it stores extra arguments
612and/or a dictionary, which are not visible to the caller. Since they are
613called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100614
615Custom types can be defined with `:type`: >
616 :type MyList list<string>
617{not implemented yet}
618
619And classes and interfaces can be used as types: >
620 :class MyClass
621 :let mine: MyClass
622
623 :interface MyInterface
624 :let mine: MyInterface
625
626 :class MyTemplate<Targ>
627 :let mine: MyTemplate<number>
628 :let mine: MyTemplate<string>
629
630 :class MyInterface<Targ>
631 :let mine: MyInterface<number>
632 :let mine: MyInterface<string>
633{not implemented yet}
634
635
636Type inference *type-inference*
637
638In general: Whenever the type is clear it can be omitted. For example, when
639declaring a variable and giving it a value: >
640 let var = 0 " infers number type
641 let var = 'hello' " infers string type
642
643
644==============================================================================
645
6465. Namespace, Import and Export
647 *vim9script* *vim9-export* *vim9-import*
648
649THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
650
651A Vim9 script can be written to be imported. This means that everything in
652the script is local, unless exported. Those exported items, and only those
653items, can then be imported in another script.
654
655
656Namespace ~
657 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100658To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100659appear as the first statement in the file. It tells Vim to interpret the
660script in its own namespace, instead of the global namespace. If a file
661starts with: >
662 vim9script
663 let myvar = 'yes'
664Then "myvar" will only exist in this file. While without `vim9script` it would
665be available as `g:myvar` from any other script and function.
666
667The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200668variables in legacy Vim script, but the "s:" is omitted. And they cannot be
669deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100670
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200671In Vim9 script the global "g:" namespace can still be used as before. And the
672"w:", "b:" and "t:" namespaces. These have in common that variables are not
673declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100674
675A side effect of `:vim9script` is that the 'cpoptions' option is set to the
676Vim default value, like with: >
677 :set cpo&vim
678One of the effects is that |line-continuation| is always enabled.
679The original value of 'cpoptions' is restored at the end of the script.
680
681
682Export ~
683 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200684Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100685 export const EXPORTED_CONST = 1234
686 export let someValue = ...
687 export def MyFunc() ...
688 export class MyClass ...
689
690As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200691be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100692
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200693 *E1042*
694`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100695
696
697Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200698 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100699The exported items can be imported individually in another Vim9 script: >
700 import EXPORTED_CONST from "thatscript.vim"
701 import MyClass from "myclass.vim"
702
703To import multiple items at the same time: >
704 import {someValue, MyClass} from "thatscript.vim"
705
Bram Moolenaar560979e2020-02-04 22:53:05 +0100706In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100707 import MyClass as ThatClass from "myclass.vim"
708 import {someValue, MyClass as ThatClass} from "myclass.vim"
709
710To import all exported items under a specific identifier: >
711 import * as That from 'thatscript.vim'
712
713Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
714to choose the name "That", but it is highly recommended to use the name of the
715script file to avoid confusion.
716
717The script name after `import` can be:
718- A relative path, starting "." or "..". This finds a file relative to the
719 location of the script file itself. This is useful to split up a large
720 plugin into several files.
721- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
722 will be rarely used.
723- A path not being relative or absolute. This will be found in the
724 "import" subdirectories of 'runtimepath' entries. The name will usually be
725 longer and unique, to avoid loading the wrong file.
726
727Once a vim9 script file has been imported, the result is cached and used the
728next time the same script is imported. It will not be read again.
729 *:import-cycle*
730The `import` commands are executed when encountered. If that script (directly
731or indirectly) imports the current script, then items defined after the
732`import` won't be processed yet. Therefore cyclic imports can exist, but may
733result in undefined items.
734
735
736Import in an autoload script ~
737
738For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100739actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100740
7411. In the plugin define user commands, functions and/or mappings that refer to
742 an autoload script. >
743 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
744
745< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
746
7472. In the autocommand script do the actual work. You can import items from
748 other files to split up functionality in appropriate pieces. >
749 vim9script
750 import FilterFunc from "../import/someother.vim"
751 def searchfor#Stuff(arg: string)
752 let filtered = FilterFunc(arg)
753 ...
754< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
755 must be exactly the same as the prefix for the function name, that is how
756 Vim finds the file.
757
7583. Other functionality, possibly shared between plugins, contains the exported
759 items and any private items. >
760 vim9script
761 let localVar = 'local'
762 export def FilterFunc(arg: string): string
763 ...
764< This goes in .../import/someother.vim.
765
766
767Import in legacy Vim script ~
768
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200769If an `import` statement is used in legacy Vim script, the script-local "s:"
770namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100771
772
773==============================================================================
774
7759. Rationale *vim9-rationale*
776
777The :def command ~
778
779Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100780shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100781impossible, because of the overhead involved with calling a function, setting
782up the local function scope and executing lines. There are many details that
783need to be handled, such as error messages and exceptions. The need to create
784a dictionary for a: and l: scopes, the a:000 list and several others add too
785much overhead that cannot be avoided.
786
787Therefore the `:def` method to define a new-style function had to be added,
788which allows for a function with different semantics. Most things still work
789as before, but some parts do not. A new way to define a function was
790considered the best way to separate the old-style code from Vim9 script code.
791
792Using "def" to define a function comes from Python. Other languages use
793"function" which clashes with legacy Vim script.
794
795
796Type checking ~
797
798When compiling lines of Vim commands into instructions as much as possible
799should be done at compile time. Postponing it to runtime makes the execution
800slower and means mistakes are found only later. For example, when
801encountering the "+" character and compiling this into a generic add
802instruction, at execution time the instruction would have to inspect the type
803of the arguments and decide what kind of addition to do. And when the
804type is dictionary throw an error. If the types are known to be numbers then
805an "add number" instruction can be used, which is faster. The error can be
806given at compile time, no error handling is needed at runtime.
807
808The syntax for types is similar to Java, since it is easy to understand and
809widely used. The type names are what was used in Vim before, with some
810additions such as "void" and "bool".
811
812
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200813Compiling functions early ~
814
815Functions are compiled when called or when `:defcompile` is used. Why not
816compile them early, so that syntax and type errors are reported early?
817
818The functions can't be compiled right away when encountered, because there may
819be forward references to functions defined later. Consider defining functions
820A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
821to reorder the functions to avoid forward references.
822
823An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200824figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200825execute the script and compile the functions. This means the script has to be
826parsed twice, which is slower, and some conditions at the script level, such
827as checking if a feature is supported, are hard to use. An attempt was made
828to see if it works, but it turned out to be impossible to make work nicely.
829
830It would be possible to compile all the functions at the end of the script.
831The drawback is that if a function never gets called, the overhead of
832compiling it counts anyway. Since startup speed is very important, in most
833cases it's better to do it later and accept that syntax and type errors are
834only reported then. In case these errors should be found early, e.g. when
835testing, the `:defcompile` command will help out.
836
837
838TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100839
840Script writers have complained that the Vim script syntax is unexpectedly
841different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200842languages are used as an example. At the same time, we do not want to abandon
843the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100844
845Since Vim already uses `:let` and `:const` and optional type checking is
846desirable, the JavaScript/TypeScript syntax fits best for variable
847declarations. >
848 const greeting = 'hello' " string type is inferred
849 let name: string
850 ...
851 name = 'John'
852
853Expression evaluation was already close to what JavaScript and other languages
854are doing. Some details are unexpected and can be fixed. For example how the
855|| and && operators work. Legacy Vim script: >
856 let result = 44
857 ...
858 return result || 0 " returns 1
859
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200860Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100861 let result = 44
862 ...
863 return result || 0 " returns 44
864
865On the other hand, overloading "+" to use both for addition and string
866concatenation goes against legacy Vim script and often leads to mistakes.
867For that reason we will keep using ".." for string concatenation. Lua also
868uses ".." this way.
869
870
871Import and Export ~
872
873A problem of legacy Vim script is that by default all functions and variables
874are global. It is possible to make them script-local, but then they are not
875available in other scripts.
876
877In Vim9 script a mechanism very similar to the Javascript import and export
878mechanism is supported. It is a variant to the existing `:source` command
879that works like one would expect:
880- Instead of making everything global by default, everything is script-local,
881 unless exported.
882- When importing a script the symbols that are imported are listed, avoiding
883 name conflicts and failures if later functionality is added.
884- The mechanism allows for writing a big, long script with a very clear API:
885 the exported function(s) and class(es).
886- By using relative paths loading can be much faster for an import inside of a
887 package, no need to search many directories.
888- Once an import has been used, it can be cached and loading it again can be
889 avoided.
890- The Vim-specific use of "s:" to make things script-local can be dropped.
891
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200892When sourcing a Vim9 script from a legacy script, only the items defined
893globally can be used, not the exported items. Alternatives considered:
894- All the exported items become available as script-local items. This makes
895 it uncontrollable what items get defined.
896- Use the exported items and make them global. Disadvantage is that it's then
897 not possible to avoid name clashes in the global namespace.
898- Completely disallow sourcing a Vim9 script, require using `:import`. That
899 makes it difficult to use scripts for testing, or sourcing them from the
900 command line to try them out.
901
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100902
903Classes ~
904
905Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
906these have never become widespread. When Vim 9 was designed a decision was
907made to phase out these interfaces and concentrate on Vim script, while
908encouraging plugin authors to write code in any language and run it as an
909external tool, using jobs and channels.
910
911Still, using an external tool has disadvantages. An alternative is to convert
912the tool into Vim script. For that to be possible without too much
913translation, and keeping the code fast at the same time, the constructs of the
914tool need to be supported. Since most languages support classes the lack of
915class support in Vim is then a problem.
916
917Previously Vim supported a kind-of object oriented programming by adding
918methods to a dictionary. With some care this could be made to work, but it
919does not look like real classes. On top of that, it's very slow, because of
920the use of dictionaries.
921
922The support of classes in Vim9 script is a "minimal common functionality" of
923class support in most languages. It works mostly like Java, which is the most
924popular programming language.
925
926
927
928 vim:tw=78:ts=8:noet:ft=help:norl: