blob: 5d264b673db88d51883acd1a44fbcb501d8caaf9 [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
193without `:let`, because they are are not really declared, they can also be
194deleted with `: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 Moolenaarae616492020-07-28 20:07:27 +0200355No :xit, :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100356
Bram Moolenaarae616492020-07-28 20:07:27 +0200357These commands are too easily confused with local variable names. Instead of
358`:x` or `:xit` you can use `:exit`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100359
360
361Comparators ~
362
363The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100364
365
366White space ~
367
368Vim9 script enforces proper use of white space. This is no longer allowed: >
369 let var=234 " Error!
370 let var= 234 " Error!
371 let var =234 " Error!
372There must be white space before and after the "=": >
373 let var = 234 " OK
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200374White space must also be put before the # that starts a comment after a
375command: >
Bram Moolenaar2c330432020-04-13 14:41:35 +0200376 let var = 234# Error!
377 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100378
379White space is required around most operators.
380
381White space is not allowed:
382- Between a function name and the "(": >
383 call Func (arg) " Error!
384 call Func
385 \ (arg) " Error!
386 call Func(arg) " OK
387 call Func(
388 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100389 call Func(
390 \ arg " OK
391 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100392
393
394Conditions and expressions ~
395
396Conditions and expression are mostly working like they do in JavaScript. A
397difference is made where JavaScript does not work like most people expect.
398Specifically, an empty list is falsey.
399
400Any type of variable can be used as a condition, there is no error, not even
401for using a list or job. This is very much like JavaScript, but there are a
402few exceptions.
403
404 type TRUE when ~
405 bool v:true
406 number non-zero
407 float non-zero
408 string non-empty
409 blob non-empty
410 list non-empty (different from JavaScript)
411 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200412 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100413 special v:true
414 job when not NULL
415 channel when not NULL
416 class when not NULL
417 object when not NULL (TODO: when isTrue() returns v:true)
418
419The boolean operators "||" and "&&" do not change the value: >
420 8 || 2 == 8
421 0 || 2 == 2
422 0 || '' == ''
423 8 && 2 == 2
424 0 && 2 == 0
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200425 2 && 0 == 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100426 [] && 2 == []
427
428When using `..` for string concatenation the arguments are always converted to
429string. >
430 'hello ' .. 123 == 'hello 123'
431 'hello ' .. v:true == 'hello true'
432
433In Vim9 script one can use "true" for v:true and "false" for v:false.
434
435
Bram Moolenaare46a4402020-06-30 20:38:27 +0200436What to watch out for ~
437 *vim9-gotchas*
438Vim9 was designed to be closer to often used programming languages, but at the
439same time tries to support the legacy Vim commands. Some compromises had to
440be made. Here is a summary of what might be unexpected.
441
442Ex command ranges need to be prefixed with a colon. >
443 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200444 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200445 :-> " Vim9: shifts the previous line to the right
446
447 %s/a/b " legacy Vim: substitute on all lines
448 x = alongname
449 % another " Vim9: line continuation without a backslash
450 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200451 'text'->func() " Vim9: method call
452 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200453
454Functions defined with `:def` compile the whole function. Legacy functions
455can bail out, and the following lines are not parsed: >
456 func Maybe()
457 if !has('feature')
458 return
459 endif
460 use-feature
461 endfunc
462Vim9 functions are compiled as a whole: >
463 def Maybe()
464 if !has('feature')
465 return
466 endif
467 use-feature " May give compilation error
468 enddef
469For a workaround, split it in two functions: >
470 func Maybe()
471 if has('feature')
472 call MaybyInner()
473 endif
474 endfunc
475 if has('feature')
476 def MaybeInner()
477 use-feature
478 enddef
479 endif
480
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100481==============================================================================
482
4833. New style functions *fast-functions*
484
485THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
486
487 *:def*
488:def[!] {name}([arguments])[: {return-type}
489 Define a new function by the name {name}. The body of
490 the function follows in the next lines, until the
491 matching `:enddef`.
492
Bram Moolenaard77a8522020-04-03 21:59:57 +0200493 When {return-type} is omitted or is "void" the
494 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100495
496 {arguments} is a sequence of zero or more argument
497 declarations. There are three forms:
498 {name}: {type}
499 {name} = {value}
500 {name}: {type} = {value}
501 The first form is a mandatory argument, the caller
502 must always provide them.
503 The second and third form are optional arguments.
504 When the caller omits an argument the {value} is used.
505
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200506 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200507 called, or when `:disassemble` or `:defcompile` is
508 used. Syntax and type errors will be produced at that
509 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200510
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200511 It is possible to nest `:def` inside another `:def` or
512 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100513
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200514 [!] is used as with `:function`. Note that in Vim9
515 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200516 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100517
518 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200519:enddef End of a function defined with `:def`. It should be on
520 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100521
522
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100523If the script the function is defined in is Vim9 script, then script-local
524variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200525before the function is compiled. If the script the function is defined in is
526legacy script, then script-local variables must be accessed with the "s:"
527prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100528
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200529 *:defc* *:defcompile*
530:defc[ompile] Compile functions defined in the current script that
531 were not compiled yet.
532 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100533
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100534 *:disa* *:disassemble*
535:disa[ssemble] {func} Show the instructions generated for {func}.
536 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100537 Note that for command line completion of {func} you
538 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100539
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200540Limitations ~
541
542Local variables will not be visible to string evaluation. For example: >
543 def EvalString(): list<string>
544 let list = ['aa', 'bb', 'cc', 'dd']
545 return range(1, 2)->map('list[v:val]')
546 enddef
547
548The map argument is a string expression, which is evaluated without the
549function scope. Instead, use a lambda: >
550 def EvalString(): list<string>
551 let list = ['aa', 'bb', 'cc', 'dd']
552 return range(1, 2)->map({ _, v -> list[v] })
553 enddef
554
555
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100556==============================================================================
557
5584. Types *vim9-types*
559
560THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
561
562The following builtin types are supported:
563 bool
564 number
565 float
566 string
567 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200568 list<{type}>
569 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100570 job
571 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100572 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200573 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200574 func({type}, ...)
575 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100576
577Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200578 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100579
Bram Moolenaard77a8522020-04-03 21:59:57 +0200580These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200581 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100582 void
583 any
584
Bram Moolenaard77a8522020-04-03 21:59:57 +0200585There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100586efficient implementation is used that avoids allocating lot of small pieces of
587memory.
588
Bram Moolenaard77a8522020-04-03 21:59:57 +0200589A partial and function can be declared in more or less specific ways:
590func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200591 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200592func: {type} any number and type of arguments with specific
593 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200594func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200595 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200596func({type}): {type} function with argument type and return type
597func(?{type}) function with type of optional argument, does
598 not return a value
599func(...{type}) function with type of variable number of
600 arguments, does not return a value
601func({type}, ?{type}, ...{type}): {type}
602 function with:
603 - type of mandatory argument
604 - type of optional argument
605 - type of variable number of arguments
606 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200607
608If the return type is "void" the function does not return a value.
609
610The reference can also be a |Partial|, in which case it stores extra arguments
611and/or a dictionary, which are not visible to the caller. Since they are
612called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100613
614Custom types can be defined with `:type`: >
615 :type MyList list<string>
616{not implemented yet}
617
618And classes and interfaces can be used as types: >
619 :class MyClass
620 :let mine: MyClass
621
622 :interface MyInterface
623 :let mine: MyInterface
624
625 :class MyTemplate<Targ>
626 :let mine: MyTemplate<number>
627 :let mine: MyTemplate<string>
628
629 :class MyInterface<Targ>
630 :let mine: MyInterface<number>
631 :let mine: MyInterface<string>
632{not implemented yet}
633
634
635Type inference *type-inference*
636
637In general: Whenever the type is clear it can be omitted. For example, when
638declaring a variable and giving it a value: >
639 let var = 0 " infers number type
640 let var = 'hello' " infers string type
641
642
643==============================================================================
644
6455. Namespace, Import and Export
646 *vim9script* *vim9-export* *vim9-import*
647
648THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
649
650A Vim9 script can be written to be imported. This means that everything in
651the script is local, unless exported. Those exported items, and only those
652items, can then be imported in another script.
653
654
655Namespace ~
656 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100657To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100658appear as the first statement in the file. It tells Vim to interpret the
659script in its own namespace, instead of the global namespace. If a file
660starts with: >
661 vim9script
662 let myvar = 'yes'
663Then "myvar" will only exist in this file. While without `vim9script` it would
664be available as `g:myvar` from any other script and function.
665
666The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200667variables in legacy Vim script, but the "s:" is omitted. And they cannot be
668deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100669
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200670In Vim9 script the global "g:" namespace can still be used as before. And the
671"w:", "b:" and "t:" namespaces. These have in common that variables are not
672declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100673
674A side effect of `:vim9script` is that the 'cpoptions' option is set to the
675Vim default value, like with: >
676 :set cpo&vim
677One of the effects is that |line-continuation| is always enabled.
678The original value of 'cpoptions' is restored at the end of the script.
679
680
681Export ~
682 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200683Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100684 export const EXPORTED_CONST = 1234
685 export let someValue = ...
686 export def MyFunc() ...
687 export class MyClass ...
688
689As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200690be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100691
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200692 *E1042*
693`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100694
695
696Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200697 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100698The exported items can be imported individually in another Vim9 script: >
699 import EXPORTED_CONST from "thatscript.vim"
700 import MyClass from "myclass.vim"
701
702To import multiple items at the same time: >
703 import {someValue, MyClass} from "thatscript.vim"
704
Bram Moolenaar560979e2020-02-04 22:53:05 +0100705In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100706 import MyClass as ThatClass from "myclass.vim"
707 import {someValue, MyClass as ThatClass} from "myclass.vim"
708
709To import all exported items under a specific identifier: >
710 import * as That from 'thatscript.vim'
711
712Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
713to choose the name "That", but it is highly recommended to use the name of the
714script file to avoid confusion.
715
716The script name after `import` can be:
717- A relative path, starting "." or "..". This finds a file relative to the
718 location of the script file itself. This is useful to split up a large
719 plugin into several files.
720- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
721 will be rarely used.
722- A path not being relative or absolute. This will be found in the
723 "import" subdirectories of 'runtimepath' entries. The name will usually be
724 longer and unique, to avoid loading the wrong file.
725
726Once a vim9 script file has been imported, the result is cached and used the
727next time the same script is imported. It will not be read again.
728 *:import-cycle*
729The `import` commands are executed when encountered. If that script (directly
730or indirectly) imports the current script, then items defined after the
731`import` won't be processed yet. Therefore cyclic imports can exist, but may
732result in undefined items.
733
734
735Import in an autoload script ~
736
737For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100738actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100739
7401. In the plugin define user commands, functions and/or mappings that refer to
741 an autoload script. >
742 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
743
744< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
745
7462. In the autocommand script do the actual work. You can import items from
747 other files to split up functionality in appropriate pieces. >
748 vim9script
749 import FilterFunc from "../import/someother.vim"
750 def searchfor#Stuff(arg: string)
751 let filtered = FilterFunc(arg)
752 ...
753< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
754 must be exactly the same as the prefix for the function name, that is how
755 Vim finds the file.
756
7573. Other functionality, possibly shared between plugins, contains the exported
758 items and any private items. >
759 vim9script
760 let localVar = 'local'
761 export def FilterFunc(arg: string): string
762 ...
763< This goes in .../import/someother.vim.
764
765
766Import in legacy Vim script ~
767
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200768If an `import` statement is used in legacy Vim script, the script-local "s:"
769namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100770
771
772==============================================================================
773
7749. Rationale *vim9-rationale*
775
776The :def command ~
777
778Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100779shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100780impossible, because of the overhead involved with calling a function, setting
781up the local function scope and executing lines. There are many details that
782need to be handled, such as error messages and exceptions. The need to create
783a dictionary for a: and l: scopes, the a:000 list and several others add too
784much overhead that cannot be avoided.
785
786Therefore the `:def` method to define a new-style function had to be added,
787which allows for a function with different semantics. Most things still work
788as before, but some parts do not. A new way to define a function was
789considered the best way to separate the old-style code from Vim9 script code.
790
791Using "def" to define a function comes from Python. Other languages use
792"function" which clashes with legacy Vim script.
793
794
795Type checking ~
796
797When compiling lines of Vim commands into instructions as much as possible
798should be done at compile time. Postponing it to runtime makes the execution
799slower and means mistakes are found only later. For example, when
800encountering the "+" character and compiling this into a generic add
801instruction, at execution time the instruction would have to inspect the type
802of the arguments and decide what kind of addition to do. And when the
803type is dictionary throw an error. If the types are known to be numbers then
804an "add number" instruction can be used, which is faster. The error can be
805given at compile time, no error handling is needed at runtime.
806
807The syntax for types is similar to Java, since it is easy to understand and
808widely used. The type names are what was used in Vim before, with some
809additions such as "void" and "bool".
810
811
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200812Compiling functions early ~
813
814Functions are compiled when called or when `:defcompile` is used. Why not
815compile them early, so that syntax and type errors are reported early?
816
817The functions can't be compiled right away when encountered, because there may
818be forward references to functions defined later. Consider defining functions
819A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
820to reorder the functions to avoid forward references.
821
822An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200823figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200824execute the script and compile the functions. This means the script has to be
825parsed twice, which is slower, and some conditions at the script level, such
826as checking if a feature is supported, are hard to use. An attempt was made
827to see if it works, but it turned out to be impossible to make work nicely.
828
829It would be possible to compile all the functions at the end of the script.
830The drawback is that if a function never gets called, the overhead of
831compiling it counts anyway. Since startup speed is very important, in most
832cases it's better to do it later and accept that syntax and type errors are
833only reported then. In case these errors should be found early, e.g. when
834testing, the `:defcompile` command will help out.
835
836
837TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100838
839Script writers have complained that the Vim script syntax is unexpectedly
840different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200841languages are used as an example. At the same time, we do not want to abandon
842the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100843
844Since Vim already uses `:let` and `:const` and optional type checking is
845desirable, the JavaScript/TypeScript syntax fits best for variable
846declarations. >
847 const greeting = 'hello' " string type is inferred
848 let name: string
849 ...
850 name = 'John'
851
852Expression evaluation was already close to what JavaScript and other languages
853are doing. Some details are unexpected and can be fixed. For example how the
854|| and && operators work. Legacy Vim script: >
855 let result = 44
856 ...
857 return result || 0 " returns 1
858
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200859Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100860 let result = 44
861 ...
862 return result || 0 " returns 44
863
864On the other hand, overloading "+" to use both for addition and string
865concatenation goes against legacy Vim script and often leads to mistakes.
866For that reason we will keep using ".." for string concatenation. Lua also
867uses ".." this way.
868
869
870Import and Export ~
871
872A problem of legacy Vim script is that by default all functions and variables
873are global. It is possible to make them script-local, but then they are not
874available in other scripts.
875
876In Vim9 script a mechanism very similar to the Javascript import and export
877mechanism is supported. It is a variant to the existing `:source` command
878that works like one would expect:
879- Instead of making everything global by default, everything is script-local,
880 unless exported.
881- When importing a script the symbols that are imported are listed, avoiding
882 name conflicts and failures if later functionality is added.
883- The mechanism allows for writing a big, long script with a very clear API:
884 the exported function(s) and class(es).
885- By using relative paths loading can be much faster for an import inside of a
886 package, no need to search many directories.
887- Once an import has been used, it can be cached and loading it again can be
888 avoided.
889- The Vim-specific use of "s:" to make things script-local can be dropped.
890
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200891When sourcing a Vim9 script from a legacy script, only the items defined
892globally can be used, not the exported items. Alternatives considered:
893- All the exported items become available as script-local items. This makes
894 it uncontrollable what items get defined.
895- Use the exported items and make them global. Disadvantage is that it's then
896 not possible to avoid name clashes in the global namespace.
897- Completely disallow sourcing a Vim9 script, require using `:import`. That
898 makes it difficult to use scripts for testing, or sourcing them from the
899 command line to try them out.
900
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100901
902Classes ~
903
904Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
905these have never become widespread. When Vim 9 was designed a decision was
906made to phase out these interfaces and concentrate on Vim script, while
907encouraging plugin authors to write code in any language and run it as an
908external tool, using jobs and channels.
909
910Still, using an external tool has disadvantages. An alternative is to convert
911the tool into Vim script. For that to be possible without too much
912translation, and keeping the code fast at the same time, the constructs of the
913tool need to be supported. Since most languages support classes the lack of
914class support in Vim is then a problem.
915
916Previously Vim supported a kind-of object oriented programming by adding
917methods to a dictionary. With some care this could be made to work, but it
918does not look like real classes. On top of that, it's very slow, because of
919the use of dictionaries.
920
921The support of classes in Vim9 script is a "minimal common functionality" of
922class support in most languages. It works mostly like Java, which is the most
923popular programming language.
924
925
926
927 vim:tw=78:ts=8:noet:ft=help:norl: