blob: f9fd1367ddac5f02a4a37edca0bc0ed33e041d7c [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
Bram Moolenaar418f1df2020-08-12 21:34:49 +0200429When using `..` for string concatenation arguments of simple types are always
430converted to string. >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100431 'hello ' .. 123 == 'hello 123'
432 'hello ' .. v:true == 'hello true'
433
Bram Moolenaar418f1df2020-08-12 21:34:49 +0200434Simple types are string, float, special and bool. For other types |string()|
435can be used.
436
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100437In Vim9 script one can use "true" for v:true and "false" for v:false.
438
439
Bram Moolenaare46a4402020-06-30 20:38:27 +0200440What to watch out for ~
441 *vim9-gotchas*
442Vim9 was designed to be closer to often used programming languages, but at the
443same time tries to support the legacy Vim commands. Some compromises had to
444be made. Here is a summary of what might be unexpected.
445
446Ex command ranges need to be prefixed with a colon. >
447 -> " legacy Vim: shifts the previous line to the right
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200448 ->func() " Vim9: method call in continuation line
Bram Moolenaare46a4402020-06-30 20:38:27 +0200449 :-> " Vim9: shifts the previous line to the right
450
451 %s/a/b " legacy Vim: substitute on all lines
452 x = alongname
453 % another " Vim9: line continuation without a backslash
454 :%s/a/b " Vim9: substitute on all lines
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200455 'text'->func() " Vim9: method call
456 :'t " legacy Vim: jump to mark m
Bram Moolenaare46a4402020-06-30 20:38:27 +0200457
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200458Some Ex commands can be confused with assignments in Vim9 script: >
459 g:name = value # assignment
460 g:pattern:cmd # invalid command - ERROR
461 :g:pattern:cmd # :global command
462
Bram Moolenaare46a4402020-06-30 20:38:27 +0200463Functions defined with `:def` compile the whole function. Legacy functions
464can bail out, and the following lines are not parsed: >
465 func Maybe()
466 if !has('feature')
467 return
468 endif
469 use-feature
470 endfunc
471Vim9 functions are compiled as a whole: >
472 def Maybe()
473 if !has('feature')
474 return
475 endif
476 use-feature " May give compilation error
477 enddef
478For a workaround, split it in two functions: >
479 func Maybe()
480 if has('feature')
481 call MaybyInner()
482 endif
483 endfunc
484 if has('feature')
485 def MaybeInner()
486 use-feature
487 enddef
488 endif
489
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100490==============================================================================
491
4923. New style functions *fast-functions*
493
494THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
495
496 *:def*
497:def[!] {name}([arguments])[: {return-type}
498 Define a new function by the name {name}. The body of
499 the function follows in the next lines, until the
500 matching `:enddef`.
501
Bram Moolenaard77a8522020-04-03 21:59:57 +0200502 When {return-type} is omitted or is "void" the
503 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100504
505 {arguments} is a sequence of zero or more argument
506 declarations. There are three forms:
507 {name}: {type}
508 {name} = {value}
509 {name}: {type} = {value}
510 The first form is a mandatory argument, the caller
511 must always provide them.
512 The second and third form are optional arguments.
513 When the caller omits an argument the {value} is used.
514
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200515 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200516 called, or when `:disassemble` or `:defcompile` is
517 used. Syntax and type errors will be produced at that
518 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200519
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200520 It is possible to nest `:def` inside another `:def` or
521 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100522
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200523 [!] is used as with `:function`. Note that in Vim9
524 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200525 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100526
527 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200528:enddef End of a function defined with `:def`. It should be on
529 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100530
531
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100532If the script the function is defined in is Vim9 script, then script-local
533variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200534before the function is compiled. If the script the function is defined in is
535legacy script, then script-local variables must be accessed with the "s:"
536prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100537
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200538 *:defc* *:defcompile*
539:defc[ompile] Compile functions defined in the current script that
540 were not compiled yet.
541 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100542
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100543 *:disa* *:disassemble*
544:disa[ssemble] {func} Show the instructions generated for {func}.
545 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100546 Note that for command line completion of {func} you
547 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100548
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200549Limitations ~
550
551Local variables will not be visible to string evaluation. For example: >
552 def EvalString(): list<string>
553 let list = ['aa', 'bb', 'cc', 'dd']
554 return range(1, 2)->map('list[v:val]')
555 enddef
556
557The map argument is a string expression, which is evaluated without the
558function scope. Instead, use a lambda: >
559 def EvalString(): list<string>
560 let list = ['aa', 'bb', 'cc', 'dd']
561 return range(1, 2)->map({ _, v -> list[v] })
562 enddef
563
564
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100565==============================================================================
566
5674. Types *vim9-types*
568
569THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
570
571The following builtin types are supported:
572 bool
573 number
574 float
575 string
576 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200577 list<{type}>
578 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100579 job
580 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100581 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200582 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200583 func({type}, ...)
584 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100585
586Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200587 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100588
Bram Moolenaard77a8522020-04-03 21:59:57 +0200589These types can be used in declarations, but no value will have this type:
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200590 {type}|{type} {not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100591 void
592 any
593
Bram Moolenaard77a8522020-04-03 21:59:57 +0200594There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100595efficient implementation is used that avoids allocating lot of small pieces of
596memory.
597
Bram Moolenaard77a8522020-04-03 21:59:57 +0200598A partial and function can be declared in more or less specific ways:
599func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200600 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200601func: {type} any number and type of arguments with specific
602 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200603func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200604 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200605func({type}): {type} function with argument type and return type
606func(?{type}) function with type of optional argument, does
607 not return a value
608func(...{type}) function with type of variable number of
609 arguments, does not return a value
610func({type}, ?{type}, ...{type}): {type}
611 function with:
612 - type of mandatory argument
613 - type of optional argument
614 - type of variable number of arguments
615 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200616
617If the return type is "void" the function does not return a value.
618
619The reference can also be a |Partial|, in which case it stores extra arguments
620and/or a dictionary, which are not visible to the caller. Since they are
621called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100622
623Custom types can be defined with `:type`: >
624 :type MyList list<string>
Bram Moolenaar127542b2020-08-09 17:22:04 +0200625Custom types must start with a capital letter, to avoid name clashes with
626builtin types added later, similarly to user functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100627{not implemented yet}
628
629And classes and interfaces can be used as types: >
630 :class MyClass
631 :let mine: MyClass
632
633 :interface MyInterface
634 :let mine: MyInterface
635
636 :class MyTemplate<Targ>
637 :let mine: MyTemplate<number>
638 :let mine: MyTemplate<string>
639
640 :class MyInterface<Targ>
641 :let mine: MyInterface<number>
642 :let mine: MyInterface<string>
643{not implemented yet}
644
645
Bram Moolenaar64d662d2020-08-09 19:02:50 +0200646Variable types and type casting *variable-types*
647
648Variables declared in Vim9 script or in a `:def` function have a type, either
649specified explicitly or inferred from the initialization.
650
651Global, buffer, window and tab page variables do not have a specific type, the
652value can be changed at any time, possibly changing the type. Therefore, in
653compiled code the "any" type is assumed.
654
655This can be a problem when the "any" type is undesired and the actual type is
656expected to always be the same. For example, when declaring a list: >
657 let l: list<number> = [1, g:two]
658This will give an error, because "g:two" has type "any". To avoid this, use a
659type cast: >
660 let l: list<number> = [1, <number>g:two]
661< *type-casting*
662The compiled code will then check that "g:two" is a number at runtime and give
663an error if it isn't. This is called type casting.
664
665The syntax of a type cast is: "<" {type} ">". There cannot be white space
666after the "<" or before the ">" (to avoid them being confused with
667smaller-than and bigger-than operators).
668
669The semantics is that, if needed, a runtime type check is performed. The
670value is not actually changed. If you need to change the type, e.g. to change
671it to a string, use the |string()| function. Or use |str2nr()| to convert a
672string to a number.
673
674
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100675Type inference *type-inference*
676
677In general: Whenever the type is clear it can be omitted. For example, when
678declaring a variable and giving it a value: >
679 let var = 0 " infers number type
680 let var = 'hello' " infers string type
681
Bram Moolenaar127542b2020-08-09 17:22:04 +0200682The type of a list and dictionary comes from the common type of the values.
683If the values all have the same type, that type is used for the list or
684dictionary. If there is a mix of types, the "any" type is used. >
685 [1, 2, 3] list<number>
686 ['a', 'b', 'c'] list<string>
687 [1, 'x', 3] list<any>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100688
689==============================================================================
690
6915. Namespace, Import and Export
692 *vim9script* *vim9-export* *vim9-import*
693
694THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
695
696A Vim9 script can be written to be imported. This means that everything in
697the script is local, unless exported. Those exported items, and only those
698items, can then be imported in another script.
699
700
701Namespace ~
702 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100703To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100704appear as the first statement in the file. It tells Vim to interpret the
705script in its own namespace, instead of the global namespace. If a file
706starts with: >
707 vim9script
708 let myvar = 'yes'
709Then "myvar" will only exist in this file. While without `vim9script` it would
710be available as `g:myvar` from any other script and function.
711
712The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200713variables in legacy Vim script, but the "s:" is omitted. And they cannot be
714deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100715
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200716In Vim9 script the global "g:" namespace can still be used as before. And the
717"w:", "b:" and "t:" namespaces. These have in common that variables are not
718declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100719
720A side effect of `:vim9script` is that the 'cpoptions' option is set to the
721Vim default value, like with: >
722 :set cpo&vim
723One of the effects is that |line-continuation| is always enabled.
724The original value of 'cpoptions' is restored at the end of the script.
725
726
727Export ~
728 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200729Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100730 export const EXPORTED_CONST = 1234
731 export let someValue = ...
732 export def MyFunc() ...
733 export class MyClass ...
734
735As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200736be exported. {classes are not implemented yet}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100737
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200738 *E1042*
739`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100740
741
742Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200743 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100744The exported items can be imported individually in another Vim9 script: >
745 import EXPORTED_CONST from "thatscript.vim"
746 import MyClass from "myclass.vim"
747
748To import multiple items at the same time: >
749 import {someValue, MyClass} from "thatscript.vim"
750
Bram Moolenaar560979e2020-02-04 22:53:05 +0100751In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100752 import MyClass as ThatClass from "myclass.vim"
753 import {someValue, MyClass as ThatClass} from "myclass.vim"
754
755To import all exported items under a specific identifier: >
756 import * as That from 'thatscript.vim'
757
758Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
759to choose the name "That", but it is highly recommended to use the name of the
760script file to avoid confusion.
761
762The script name after `import` can be:
763- A relative path, starting "." or "..". This finds a file relative to the
764 location of the script file itself. This is useful to split up a large
765 plugin into several files.
766- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
767 will be rarely used.
768- A path not being relative or absolute. This will be found in the
769 "import" subdirectories of 'runtimepath' entries. The name will usually be
770 longer and unique, to avoid loading the wrong file.
771
772Once a vim9 script file has been imported, the result is cached and used the
773next time the same script is imported. It will not be read again.
774 *:import-cycle*
775The `import` commands are executed when encountered. If that script (directly
776or indirectly) imports the current script, then items defined after the
777`import` won't be processed yet. Therefore cyclic imports can exist, but may
778result in undefined items.
779
780
781Import in an autoload script ~
782
783For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100784actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100785
7861. In the plugin define user commands, functions and/or mappings that refer to
787 an autoload script. >
788 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
789
790< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
791
7922. In the autocommand script do the actual work. You can import items from
793 other files to split up functionality in appropriate pieces. >
794 vim9script
795 import FilterFunc from "../import/someother.vim"
796 def searchfor#Stuff(arg: string)
797 let filtered = FilterFunc(arg)
798 ...
799< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
800 must be exactly the same as the prefix for the function name, that is how
801 Vim finds the file.
802
8033. Other functionality, possibly shared between plugins, contains the exported
804 items and any private items. >
805 vim9script
806 let localVar = 'local'
807 export def FilterFunc(arg: string): string
808 ...
809< This goes in .../import/someother.vim.
810
Bram Moolenaar418f1df2020-08-12 21:34:49 +0200811When compiling a `:def` function and a function in an autoload script is
812encountered, the script is not loaded until the `:def` function is called.
813
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100814
815Import in legacy Vim script ~
816
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200817If an `import` statement is used in legacy Vim script, the script-local "s:"
818namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100819
820
821==============================================================================
822
8239. Rationale *vim9-rationale*
824
825The :def command ~
826
827Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100828shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100829impossible, because of the overhead involved with calling a function, setting
830up the local function scope and executing lines. There are many details that
831need to be handled, such as error messages and exceptions. The need to create
832a dictionary for a: and l: scopes, the a:000 list and several others add too
833much overhead that cannot be avoided.
834
835Therefore the `:def` method to define a new-style function had to be added,
836which allows for a function with different semantics. Most things still work
837as before, but some parts do not. A new way to define a function was
838considered the best way to separate the old-style code from Vim9 script code.
839
840Using "def" to define a function comes from Python. Other languages use
841"function" which clashes with legacy Vim script.
842
843
844Type checking ~
845
846When compiling lines of Vim commands into instructions as much as possible
847should be done at compile time. Postponing it to runtime makes the execution
848slower and means mistakes are found only later. For example, when
849encountering the "+" character and compiling this into a generic add
850instruction, at execution time the instruction would have to inspect the type
851of the arguments and decide what kind of addition to do. And when the
852type is dictionary throw an error. If the types are known to be numbers then
853an "add number" instruction can be used, which is faster. The error can be
854given at compile time, no error handling is needed at runtime.
855
856The syntax for types is similar to Java, since it is easy to understand and
857widely used. The type names are what was used in Vim before, with some
858additions such as "void" and "bool".
859
860
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200861Compiling functions early ~
862
863Functions are compiled when called or when `:defcompile` is used. Why not
864compile them early, so that syntax and type errors are reported early?
865
866The functions can't be compiled right away when encountered, because there may
867be forward references to functions defined later. Consider defining functions
868A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
869to reorder the functions to avoid forward references.
870
871An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200872figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200873execute the script and compile the functions. This means the script has to be
874parsed twice, which is slower, and some conditions at the script level, such
875as checking if a feature is supported, are hard to use. An attempt was made
876to see if it works, but it turned out to be impossible to make work nicely.
877
878It would be possible to compile all the functions at the end of the script.
879The drawback is that if a function never gets called, the overhead of
880compiling it counts anyway. Since startup speed is very important, in most
881cases it's better to do it later and accept that syntax and type errors are
882only reported then. In case these errors should be found early, e.g. when
883testing, the `:defcompile` command will help out.
884
885
886TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100887
888Script writers have complained that the Vim script syntax is unexpectedly
889different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200890languages are used as an example. At the same time, we do not want to abandon
891the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100892
893Since Vim already uses `:let` and `:const` and optional type checking is
894desirable, the JavaScript/TypeScript syntax fits best for variable
895declarations. >
896 const greeting = 'hello' " string type is inferred
897 let name: string
898 ...
899 name = 'John'
900
901Expression evaluation was already close to what JavaScript and other languages
902are doing. Some details are unexpected and can be fixed. For example how the
903|| and && operators work. Legacy Vim script: >
904 let result = 44
905 ...
906 return result || 0 " returns 1
907
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200908Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100909 let result = 44
910 ...
911 return result || 0 " returns 44
912
913On the other hand, overloading "+" to use both for addition and string
914concatenation goes against legacy Vim script and often leads to mistakes.
915For that reason we will keep using ".." for string concatenation. Lua also
916uses ".." this way.
917
918
919Import and Export ~
920
921A problem of legacy Vim script is that by default all functions and variables
922are global. It is possible to make them script-local, but then they are not
923available in other scripts.
924
925In Vim9 script a mechanism very similar to the Javascript import and export
926mechanism is supported. It is a variant to the existing `:source` command
927that works like one would expect:
928- Instead of making everything global by default, everything is script-local,
929 unless exported.
930- When importing a script the symbols that are imported are listed, avoiding
931 name conflicts and failures if later functionality is added.
932- The mechanism allows for writing a big, long script with a very clear API:
933 the exported function(s) and class(es).
934- By using relative paths loading can be much faster for an import inside of a
935 package, no need to search many directories.
936- Once an import has been used, it can be cached and loading it again can be
937 avoided.
938- The Vim-specific use of "s:" to make things script-local can be dropped.
939
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200940When sourcing a Vim9 script from a legacy script, only the items defined
941globally can be used, not the exported items. Alternatives considered:
942- All the exported items become available as script-local items. This makes
943 it uncontrollable what items get defined.
944- Use the exported items and make them global. Disadvantage is that it's then
945 not possible to avoid name clashes in the global namespace.
946- Completely disallow sourcing a Vim9 script, require using `:import`. That
947 makes it difficult to use scripts for testing, or sourcing them from the
948 command line to try them out.
949
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100950
951Classes ~
952
953Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
954these have never become widespread. When Vim 9 was designed a decision was
955made to phase out these interfaces and concentrate on Vim script, while
956encouraging plugin authors to write code in any language and run it as an
957external tool, using jobs and channels.
958
959Still, using an external tool has disadvantages. An alternative is to convert
960the tool into Vim script. For that to be possible without too much
961translation, and keeping the code fast at the same time, the constructs of the
962tool need to be supported. Since most languages support classes the lack of
963class support in Vim is then a problem.
964
965Previously Vim supported a kind-of object oriented programming by adding
966methods to a dictionary. With some care this could be made to work, but it
967does not look like real classes. On top of that, it's very slow, because of
968the use of dictionaries.
969
970The support of classes in Vim9 script is a "minimal common functionality" of
971class support in most languages. It works mostly like Java, which is the most
972popular programming language.
973
974
975
976 vim:tw=78:ts=8:noet:ft=help:norl: