blob: 7c4a64f972dc4169162fe44b03ec5863ac53ebe0 [file] [log] [blame]
Bram Moolenaare7b1ea02020-08-07 19:54:59 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Aug 01
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
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200171. What is Vim9 script? |vim9-script|
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100182. 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
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200122function or variable the "g:" prefix should be used. For functions in an
Bram Moolenaarea2d8d22020-07-29 22:11:05 +0200123autoload script the "name#" prefix is sufficient. >
124 def ThisFunction() # script-local
125 def s:ThisFunction() # script-local
126 def g:ThatFunction() # global
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200127 def ThatFunction() # global if no local ThatFunction()
Bram Moolenaarea2d8d22020-07-29 22:11:05 +0200128 def scriptname#function() # autoload
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200129
130When using `:function` or `:def` to specify a new function inside a function,
131the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200132script-local function inside a function. It is possible to define a global
133function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200134
135When referring to a function and no "s:" or "g:" prefix is used, Vim will
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200136prefer using a local function (in the function scope, script scope or
137imported) before looking for a global function.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200138In all cases the function must be defined before used. That is when it is
139first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200140
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200141The result is that functions and variables without a namespace can usually be
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200142found in the script, either defined there or imported. Global functions and
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200143variables could be defined anywhere (good luck finding out where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200144
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200145Global functions can be still be defined and deleted at nearly any time. In
146Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200147and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200148
149
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100150Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200151 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100152Local variables need to be declared with `:let`. Local constants need to be
153declared with `:const`. We refer to both as "variables".
154
155Variables can be local to a script, function or code block: >
156 vim9script
157 let script_var = 123
158 def SomeFunc()
159 let func_var = script_var
160 if cond
161 let block_var = func_var
162 ...
163
164The variables are only visible in the block where they are defined and nested
165blocks. Once the block ends the variable is no longer accessible: >
166 if cond
167 let inner = 5
168 else
169 let inner = 0
170 endif
171 echo inner " Error!
172
173The declaration must be done earlier: >
174 let inner: number
175 if cond
176 inner = 5
177 else
178 inner = 0
179 endif
180 echo inner
181
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200182To intentionally avoid a variable being available later, a block can be used:
183>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100184 {
185 let temp = 'temp'
186 ...
187 }
188 echo temp " Error!
189
Bram Moolenaar560979e2020-02-04 22:53:05 +0100190An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200191declaration. Global, window, tab, buffer and Vim variables can only be used
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200192without `:let`, because they are not really declared, they can also be deleted
193with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100194
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200195Variables and functions cannot shadow previously defined or imported variables
196and functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100197Variables 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 Moolenaare7b1ea02020-08-07 19:54:59 +0200235In rare case there is ambiguity between a function name and an Ex command,
236prepend ":" to make clear you want to use the Ex command. For example, there
237is both the `:substitute` command and the `substitute()` function. When the
238line starts with `substitute(` this will use the function. Prepend a colon to
239use the 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
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200264those cases there is no need to prefix the line with a backslash
265|line-continuation|. For example, when a list spans multiple lines: >
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200266 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
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200455Some Ex commands can be confused with assignments in Vim9 script: >
456 g:name = value # assignment
457 g:pattern:cmd # invalid command - ERROR
458 :g:pattern:cmd # :global command
459
Bram Moolenaare46a4402020-06-30 20:38:27 +0200460Functions defined with `:def` compile the whole function. Legacy functions
461can bail out, and the following lines are not parsed: >
462 func Maybe()
463 if !has('feature')
464 return
465 endif
466 use-feature
467 endfunc
468Vim9 functions are compiled as a whole: >
469 def Maybe()
470 if !has('feature')
471 return
472 endif
473 use-feature " May give compilation error
474 enddef
475For a workaround, split it in two functions: >
476 func Maybe()
477 if has('feature')
478 call MaybyInner()
479 endif
480 endfunc
481 if has('feature')
482 def MaybeInner()
483 use-feature
484 enddef
485 endif
486
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100487==============================================================================
488
4893. New style functions *fast-functions*
490
491THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
492
493 *:def*
494:def[!] {name}([arguments])[: {return-type}
495 Define a new function by the name {name}. The body of
496 the function follows in the next lines, until the
497 matching `:enddef`.
498
Bram Moolenaard77a8522020-04-03 21:59:57 +0200499 When {return-type} is omitted or is "void" the
500 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100501
502 {arguments} is a sequence of zero or more argument
503 declarations. There are three forms:
504 {name}: {type}
505 {name} = {value}
506 {name}: {type} = {value}
507 The first form is a mandatory argument, the caller
508 must always provide them.
509 The second and third form are optional arguments.
510 When the caller omits an argument the {value} is used.
511
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200512 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200513 called, or when `:disassemble` or `:defcompile` is
514 used. Syntax and type errors will be produced at that
515 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200516
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200517 It is possible to nest `:def` inside another `:def` or
518 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100519
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200520 [!] is used as with `:function`. Note that in Vim9
521 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200522 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100523
524 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200525:enddef End of a function defined with `:def`. It should be on
526 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100527
528
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100529If the script the function is defined in is Vim9 script, then script-local
530variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200531before the function is compiled. If the script the function is defined in is
532legacy script, then script-local variables must be accessed with the "s:"
533prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100534
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200535 *:defc* *:defcompile*
536:defc[ompile] Compile functions defined in the current script that
537 were not compiled yet.
538 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100539
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100540 *:disa* *:disassemble*
541:disa[ssemble] {func} Show the instructions generated for {func}.
542 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100543 Note that for command line completion of {func} you
544 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100545
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200546Limitations ~
547
548Local variables will not be visible to string evaluation. For example: >
549 def EvalString(): list<string>
550 let list = ['aa', 'bb', 'cc', 'dd']
551 return range(1, 2)->map('list[v:val]')
552 enddef
553
554The map argument is a string expression, which is evaluated without the
555function scope. Instead, use a lambda: >
556 def EvalString(): list<string>
557 let list = ['aa', 'bb', 'cc', 'dd']
558 return range(1, 2)->map({ _, v -> list[v] })
559 enddef
560
561
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100562==============================================================================
563
5644. Types *vim9-types*
565
566THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
567
568The following builtin types are supported:
569 bool
570 number
571 float
572 string
573 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200574 list<{type}>
575 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100576 job
577 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100578 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200579 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200580 func({type}, ...)
581 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100582
583Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200584 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100585
Bram Moolenaard77a8522020-04-03 21:59:57 +0200586These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200587 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100588 void
589 any
590
Bram Moolenaard77a8522020-04-03 21:59:57 +0200591There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100592efficient implementation is used that avoids allocating lot of small pieces of
593memory.
594
Bram Moolenaard77a8522020-04-03 21:59:57 +0200595A partial and function can be declared in more or less specific ways:
596func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200597 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200598func: {type} any number and type of arguments with specific
599 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200600func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200601 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200602func({type}): {type} function with argument type and return type
603func(?{type}) function with type of optional argument, does
604 not return a value
605func(...{type}) function with type of variable number of
606 arguments, does not return a value
607func({type}, ?{type}, ...{type}): {type}
608 function with:
609 - type of mandatory argument
610 - type of optional argument
611 - type of variable number of arguments
612 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200613
614If the return type is "void" the function does not return a value.
615
616The reference can also be a |Partial|, in which case it stores extra arguments
617and/or a dictionary, which are not visible to the caller. Since they are
618called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100619
620Custom types can be defined with `:type`: >
621 :type MyList list<string>
Bram Moolenaar127542b2020-08-09 17:22:04 +0200622Custom types must start with a capital letter, to avoid name clashes with
623builtin types added later, similarly to user functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100624{not implemented yet}
625
626And classes and interfaces can be used as types: >
627 :class MyClass
628 :let mine: MyClass
629
630 :interface MyInterface
631 :let mine: MyInterface
632
633 :class MyTemplate<Targ>
634 :let mine: MyTemplate<number>
635 :let mine: MyTemplate<string>
636
637 :class MyInterface<Targ>
638 :let mine: MyInterface<number>
639 :let mine: MyInterface<string>
640{not implemented yet}
641
642
Bram Moolenaar64d662d2020-08-09 19:02:50 +0200643Variable types and type casting *variable-types*
644
645Variables declared in Vim9 script or in a `:def` function have a type, either
646specified explicitly or inferred from the initialization.
647
648Global, buffer, window and tab page variables do not have a specific type, the
649value can be changed at any time, possibly changing the type. Therefore, in
650compiled code the "any" type is assumed.
651
652This can be a problem when the "any" type is undesired and the actual type is
653expected to always be the same. For example, when declaring a list: >
654 let l: list<number> = [1, g:two]
655This will give an error, because "g:two" has type "any". To avoid this, use a
656type cast: >
657 let l: list<number> = [1, <number>g:two]
658< *type-casting*
659The compiled code will then check that "g:two" is a number at runtime and give
660an error if it isn't. This is called type casting.
661
662The syntax of a type cast is: "<" {type} ">". There cannot be white space
663after the "<" or before the ">" (to avoid them being confused with
664smaller-than and bigger-than operators).
665
666The semantics is that, if needed, a runtime type check is performed. The
667value is not actually changed. If you need to change the type, e.g. to change
668it to a string, use the |string()| function. Or use |str2nr()| to convert a
669string to a number.
670
671
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100672Type inference *type-inference*
673
674In general: Whenever the type is clear it can be omitted. For example, when
675declaring a variable and giving it a value: >
676 let var = 0 " infers number type
677 let var = 'hello' " infers string type
678
Bram Moolenaar127542b2020-08-09 17:22:04 +0200679The type of a list and dictionary comes from the common type of the values.
680If the values all have the same type, that type is used for the list or
681dictionary. If there is a mix of types, the "any" type is used. >
682 [1, 2, 3] list<number>
683 ['a', 'b', 'c'] list<string>
684 [1, 'x', 3] list<any>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100685
686==============================================================================
687
6885. Namespace, Import and Export
689 *vim9script* *vim9-export* *vim9-import*
690
691THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
692
693A Vim9 script can be written to be imported. This means that everything in
694the script is local, unless exported. Those exported items, and only those
695items, can then be imported in another script.
696
697
698Namespace ~
699 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100700To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100701appear as the first statement in the file. It tells Vim to interpret the
702script in its own namespace, instead of the global namespace. If a file
703starts with: >
704 vim9script
705 let myvar = 'yes'
706Then "myvar" will only exist in this file. While without `vim9script` it would
707be available as `g:myvar` from any other script and function.
708
709The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200710variables in legacy Vim script, but the "s:" is omitted. And they cannot be
711deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100712
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200713In Vim9 script the global "g:" namespace can still be used as before. And the
714"w:", "b:" and "t:" namespaces. These have in common that variables are not
715declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100716
717A side effect of `:vim9script` is that the 'cpoptions' option is set to the
718Vim default value, like with: >
719 :set cpo&vim
720One of the effects is that |line-continuation| is always enabled.
721The original value of 'cpoptions' is restored at the end of the script.
722
723
724Export ~
725 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200726Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100727 export const EXPORTED_CONST = 1234
728 export let someValue = ...
729 export def MyFunc() ...
730 export class MyClass ...
731
732As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200733be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100734
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200735 *E1042*
736`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100737
738
739Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200740 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100741The exported items can be imported individually in another Vim9 script: >
742 import EXPORTED_CONST from "thatscript.vim"
743 import MyClass from "myclass.vim"
744
745To import multiple items at the same time: >
746 import {someValue, MyClass} from "thatscript.vim"
747
Bram Moolenaar560979e2020-02-04 22:53:05 +0100748In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100749 import MyClass as ThatClass from "myclass.vim"
750 import {someValue, MyClass as ThatClass} from "myclass.vim"
751
752To import all exported items under a specific identifier: >
753 import * as That from 'thatscript.vim'
754
755Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
756to choose the name "That", but it is highly recommended to use the name of the
757script file to avoid confusion.
758
759The script name after `import` can be:
760- A relative path, starting "." or "..". This finds a file relative to the
761 location of the script file itself. This is useful to split up a large
762 plugin into several files.
763- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
764 will be rarely used.
765- A path not being relative or absolute. This will be found in the
766 "import" subdirectories of 'runtimepath' entries. The name will usually be
767 longer and unique, to avoid loading the wrong file.
768
769Once a vim9 script file has been imported, the result is cached and used the
770next time the same script is imported. It will not be read again.
771 *:import-cycle*
772The `import` commands are executed when encountered. If that script (directly
773or indirectly) imports the current script, then items defined after the
774`import` won't be processed yet. Therefore cyclic imports can exist, but may
775result in undefined items.
776
777
778Import in an autoload script ~
779
780For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100781actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100782
7831. In the plugin define user commands, functions and/or mappings that refer to
784 an autoload script. >
785 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
786
787< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
788
7892. In the autocommand script do the actual work. You can import items from
790 other files to split up functionality in appropriate pieces. >
791 vim9script
792 import FilterFunc from "../import/someother.vim"
793 def searchfor#Stuff(arg: string)
794 let filtered = FilterFunc(arg)
795 ...
796< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
797 must be exactly the same as the prefix for the function name, that is how
798 Vim finds the file.
799
8003. Other functionality, possibly shared between plugins, contains the exported
801 items and any private items. >
802 vim9script
803 let localVar = 'local'
804 export def FilterFunc(arg: string): string
805 ...
806< This goes in .../import/someother.vim.
807
808
809Import in legacy Vim script ~
810
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200811If an `import` statement is used in legacy Vim script, the script-local "s:"
812namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100813
814
815==============================================================================
816
8179. Rationale *vim9-rationale*
818
819The :def command ~
820
821Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100822shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100823impossible, because of the overhead involved with calling a function, setting
824up the local function scope and executing lines. There are many details that
825need to be handled, such as error messages and exceptions. The need to create
826a dictionary for a: and l: scopes, the a:000 list and several others add too
827much overhead that cannot be avoided.
828
829Therefore the `:def` method to define a new-style function had to be added,
830which allows for a function with different semantics. Most things still work
831as before, but some parts do not. A new way to define a function was
832considered the best way to separate the old-style code from Vim9 script code.
833
834Using "def" to define a function comes from Python. Other languages use
835"function" which clashes with legacy Vim script.
836
837
838Type checking ~
839
840When compiling lines of Vim commands into instructions as much as possible
841should be done at compile time. Postponing it to runtime makes the execution
842slower and means mistakes are found only later. For example, when
843encountering the "+" character and compiling this into a generic add
844instruction, at execution time the instruction would have to inspect the type
845of the arguments and decide what kind of addition to do. And when the
846type is dictionary throw an error. If the types are known to be numbers then
847an "add number" instruction can be used, which is faster. The error can be
848given at compile time, no error handling is needed at runtime.
849
850The syntax for types is similar to Java, since it is easy to understand and
851widely used. The type names are what was used in Vim before, with some
852additions such as "void" and "bool".
853
854
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200855Compiling functions early ~
856
857Functions are compiled when called or when `:defcompile` is used. Why not
858compile them early, so that syntax and type errors are reported early?
859
860The functions can't be compiled right away when encountered, because there may
861be forward references to functions defined later. Consider defining functions
862A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
863to reorder the functions to avoid forward references.
864
865An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200866figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200867execute the script and compile the functions. This means the script has to be
868parsed twice, which is slower, and some conditions at the script level, such
869as checking if a feature is supported, are hard to use. An attempt was made
870to see if it works, but it turned out to be impossible to make work nicely.
871
872It would be possible to compile all the functions at the end of the script.
873The drawback is that if a function never gets called, the overhead of
874compiling it counts anyway. Since startup speed is very important, in most
875cases it's better to do it later and accept that syntax and type errors are
876only reported then. In case these errors should be found early, e.g. when
877testing, the `:defcompile` command will help out.
878
879
880TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100881
882Script writers have complained that the Vim script syntax is unexpectedly
883different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200884languages are used as an example. At the same time, we do not want to abandon
885the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100886
887Since Vim already uses `:let` and `:const` and optional type checking is
888desirable, the JavaScript/TypeScript syntax fits best for variable
889declarations. >
890 const greeting = 'hello' " string type is inferred
891 let name: string
892 ...
893 name = 'John'
894
895Expression evaluation was already close to what JavaScript and other languages
896are doing. Some details are unexpected and can be fixed. For example how the
897|| and && operators work. Legacy Vim script: >
898 let result = 44
899 ...
900 return result || 0 " returns 1
901
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200902Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100903 let result = 44
904 ...
905 return result || 0 " returns 44
906
907On the other hand, overloading "+" to use both for addition and string
908concatenation goes against legacy Vim script and often leads to mistakes.
909For that reason we will keep using ".." for string concatenation. Lua also
910uses ".." this way.
911
912
913Import and Export ~
914
915A problem of legacy Vim script is that by default all functions and variables
916are global. It is possible to make them script-local, but then they are not
917available in other scripts.
918
919In Vim9 script a mechanism very similar to the Javascript import and export
920mechanism is supported. It is a variant to the existing `:source` command
921that works like one would expect:
922- Instead of making everything global by default, everything is script-local,
923 unless exported.
924- When importing a script the symbols that are imported are listed, avoiding
925 name conflicts and failures if later functionality is added.
926- The mechanism allows for writing a big, long script with a very clear API:
927 the exported function(s) and class(es).
928- By using relative paths loading can be much faster for an import inside of a
929 package, no need to search many directories.
930- Once an import has been used, it can be cached and loading it again can be
931 avoided.
932- The Vim-specific use of "s:" to make things script-local can be dropped.
933
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200934When sourcing a Vim9 script from a legacy script, only the items defined
935globally can be used, not the exported items. Alternatives considered:
936- All the exported items become available as script-local items. This makes
937 it uncontrollable what items get defined.
938- Use the exported items and make them global. Disadvantage is that it's then
939 not possible to avoid name clashes in the global namespace.
940- Completely disallow sourcing a Vim9 script, require using `:import`. That
941 makes it difficult to use scripts for testing, or sourcing them from the
942 command line to try them out.
943
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100944
945Classes ~
946
947Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
948these have never become widespread. When Vim 9 was designed a decision was
949made to phase out these interfaces and concentrate on Vim script, while
950encouraging plugin authors to write code in any language and run it as an
951external tool, using jobs and channels.
952
953Still, using an external tool has disadvantages. An alternative is to convert
954the tool into Vim script. For that to be possible without too much
955translation, and keeping the code fast at the same time, the constructs of the
956tool need to be supported. Since most languages support classes the lack of
957class support in Vim is then a problem.
958
959Previously Vim supported a kind-of object oriented programming by adding
960methods to a dictionary. With some care this could be made to work, but it
961does not look like real classes. On top of that, it's very slow, because of
962the use of dictionaries.
963
964The support of classes in Vim9 script is a "minimal common functionality" of
965class support in most languages. It works mostly like Java, which is the most
966popular programming language.
967
968
969
970 vim:tw=78:ts=8:noet:ft=help:norl: