blob: c79ae62de103ab70e8c3572a2829f345e936c875 [file] [log] [blame]
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001*vim9.txt* For Vim version 8.2. Last change: 2020 Feb 21
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
9Vim9 script commands and expressions.
10
11Most expression help is in |eval.txt|. This file is about the new syntax and
12features in Vim9 script.
13
14THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
15
16
171 What is Vim9 script? |vim9-script|
182. Differences |vim9-differences|
193. New style functions |fast-functions|
204. Types |vim9-types|
215. Namespace, Import and Export |vim9script|
22
239. Rationale |vim9-rationale|
24
25==============================================================================
26
271. What is Vim9 script? *vim9-script*
28
29THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
30
31Vim script has been growing over time, while keeping backwards compatibility.
32That means bad choices from the past often can't be changed. Execution is
33quite slow, every line is parsed every time it is executed.
34
35The main goal of Vim9 script is to drastically improve performance. An
36increase in execution speed of 10 to 100 times can be expected. A secondary
37goal is to avoid Vim-specific constructs and get closer to commonly used
38programming languages, such as JavaScript, TypeScript and Java.
39
40The performance improvements can only be achieved by not being 100% backwards
41compatible. For example, in a function the arguments are not available in the
42"a:" dictionary, as creating that dictionary adds quite a lot of overhead.
43Other differences are more subtle, such as how errors are handled.
44
45The Vim9 script syntax and semantics are used in:
46- a function defined with the `:def` command
47- a script file where the first command is `vim9script`
48
49When using `:function` in a Vim9 script file the legacy syntax is used.
50However, this is discouraged.
51
52Vim9 script and legacy Vim script can be mixed. There is no need to rewrite
53old scripts, they keep working as before.
54
55==============================================================================
56
572. Differences from legacy Vim script *vim9-differences*
58
59THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
60
61Vim9 functions ~
62
63`:def` has no extra arguments like `:function` does: "range", "abort", "dict"
64or "closure". A `:def` function always aborts on an error, does not get a
65range passed and cannot be a "dict" function.
66
67In the function body:
68- Arguments are accessed by name, without "a:".
69- There is no "a:" dictionary or "a:000" list. Variable arguments are defined
70 with a name and have a list type: >
71 def MyFunc(...itemlist: list<type>)
72 for item in itemlist
73 ...
74
75
76Variable declarations with :let and :const ~
77
78Local variables need to be declared with `:let`. Local constants need to be
79declared with `:const`. We refer to both as "variables".
80
81Variables can be local to a script, function or code block: >
82 vim9script
83 let script_var = 123
84 def SomeFunc()
85 let func_var = script_var
86 if cond
87 let block_var = func_var
88 ...
89
90The variables are only visible in the block where they are defined and nested
91blocks. Once the block ends the variable is no longer accessible: >
92 if cond
93 let inner = 5
94 else
95 let inner = 0
96 endif
97 echo inner " Error!
98
99The declaration must be done earlier: >
100 let inner: number
101 if cond
102 inner = 5
103 else
104 inner = 0
105 endif
106 echo inner
107
108To intentionally use a variable that won't be available later, a block can be
109used: >
110 {
111 let temp = 'temp'
112 ...
113 }
114 echo temp " Error!
115
Bram Moolenaar560979e2020-02-04 22:53:05 +0100116An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100117declaration. An exception is global variables: these can be both used with
118and without `:let`, because there is no rule about where they are declared.
119
120Variables cannot shadow previously defined variables.
121Variables may shadow Ex commands, rename the variable if needed.
122
123Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
124used to repeat a `:substitute` command.
125
126
127Omitting :call and :eval ~
128
129Functions can be called without `:call`: >
130 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100131Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100132
133A method call without `eval` is possible, so long as the start is an
134identifier or can't be an Ex command. It does not work for string constants: >
135 myList->add(123) " works
136 g:myList->add(123) " works
137 [1, 2, 3]->Process() " works
138 #{a: 1, b: 2}->Process() " works
139 {'a': 1, 'b': 2}->Process() " works
140 "foobar"->Process() " does NOT work
141 eval "foobar"->Process() " works
142
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100143In case there is ambiguity between a function name and an Ex command, use ":"
144to make clear you want to use the Ex command. For example, there is both the
145`:substitute` command and the `substitute()` function. When the line starts
146with `substitute(` this will use the function, prepend a colon to use the
147command instead: >
148 :substitute(pattern(replacement(
149
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100150
151No curly braces expansion ~
152
153|curly-braces-names| cannot be used.
154
155
Bram Moolenaar560979e2020-02-04 22:53:05 +0100156No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100157
Bram Moolenaar560979e2020-02-04 22:53:05 +0100158These commands are too quickly confused with local variable names.
159
160
161Comparators ~
162
163The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100164
165
166White space ~
167
168Vim9 script enforces proper use of white space. This is no longer allowed: >
169 let var=234 " Error!
170 let var= 234 " Error!
171 let var =234 " Error!
172There must be white space before and after the "=": >
173 let var = 234 " OK
174
175White space is required around most operators.
176
177White space is not allowed:
178- Between a function name and the "(": >
179 call Func (arg) " Error!
180 call Func
181 \ (arg) " Error!
182 call Func(arg) " OK
183 call Func(
184 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100185 call Func(
186 \ arg " OK
187 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100188
189
190Conditions and expressions ~
191
192Conditions and expression are mostly working like they do in JavaScript. A
193difference is made where JavaScript does not work like most people expect.
194Specifically, an empty list is falsey.
195
196Any type of variable can be used as a condition, there is no error, not even
197for using a list or job. This is very much like JavaScript, but there are a
198few exceptions.
199
200 type TRUE when ~
201 bool v:true
202 number non-zero
203 float non-zero
204 string non-empty
205 blob non-empty
206 list non-empty (different from JavaScript)
207 dictionary non-empty (different from JavaScript)
208 funcref when not NULL
209 partial when not NULL
210 special v:true
211 job when not NULL
212 channel when not NULL
213 class when not NULL
214 object when not NULL (TODO: when isTrue() returns v:true)
215
216The boolean operators "||" and "&&" do not change the value: >
217 8 || 2 == 8
218 0 || 2 == 2
219 0 || '' == ''
220 8 && 2 == 2
221 0 && 2 == 0
222 [] && 2 == []
223
224When using `..` for string concatenation the arguments are always converted to
225string. >
226 'hello ' .. 123 == 'hello 123'
227 'hello ' .. v:true == 'hello true'
228
229In Vim9 script one can use "true" for v:true and "false" for v:false.
230
231
232==============================================================================
233
2343. New style functions *fast-functions*
235
236THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
237
238 *:def*
239:def[!] {name}([arguments])[: {return-type}
240 Define a new function by the name {name}. The body of
241 the function follows in the next lines, until the
242 matching `:enddef`.
243
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100244 When {return-type} is omitted the function is not
245 expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100246
247 {arguments} is a sequence of zero or more argument
248 declarations. There are three forms:
249 {name}: {type}
250 {name} = {value}
251 {name}: {type} = {value}
252 The first form is a mandatory argument, the caller
253 must always provide them.
254 The second and third form are optional arguments.
255 When the caller omits an argument the {value} is used.
256
Bram Moolenaar560979e2020-02-04 22:53:05 +0100257 NOTE: It is possible to nest `:def` inside another
258 `:def`, but it is not possible to nest `:def` inside
259 `:function`, for backwards compatibility.
260
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100261 [!] is used as with `:function`.
262
263 *:enddef*
264:enddef End of a function defined with `:def`.
265
266
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100267If the script the function is defined in is Vim9 script, then script-local
268variables can be accessed without the "s:" prefix. They must be defined
269before the function. If the script the function is defined in is legacy
270script, then script-local variables must be accessed with the "s:" prefix.
271
272
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100273 *:disa* *:disassemble*
274:disa[ssemble] {func} Show the instructions generated for {func}.
275 This is for debugging and testing.
276
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100277==============================================================================
278
2794. Types *vim9-types*
280
281THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
282
283The following builtin types are supported:
284 bool
285 number
286 float
287 string
288 blob
289 list<type>
290 dict<type>
291 (a: type, b: type): type
292 job
293 channel
294
295Not supported yet:
296 tuple<a: type, b: type, ...>
297
298These types can be used in declarations, but no variable will have this type:
299 type|type
300 void
301 any
302
303There is no array type, use list<type> instead. For a list constant an
304efficient implementation is used that avoids allocating lot of small pieces of
305memory.
306
307A function defined with `:def` must declare the return type. If there is no
308type then the function doesn't return anything. "void" is used in type
309declarations.
310
311Custom types can be defined with `:type`: >
312 :type MyList list<string>
313{not implemented yet}
314
315And classes and interfaces can be used as types: >
316 :class MyClass
317 :let mine: MyClass
318
319 :interface MyInterface
320 :let mine: MyInterface
321
322 :class MyTemplate<Targ>
323 :let mine: MyTemplate<number>
324 :let mine: MyTemplate<string>
325
326 :class MyInterface<Targ>
327 :let mine: MyInterface<number>
328 :let mine: MyInterface<string>
329{not implemented yet}
330
331
332Type inference *type-inference*
333
334In general: Whenever the type is clear it can be omitted. For example, when
335declaring a variable and giving it a value: >
336 let var = 0 " infers number type
337 let var = 'hello' " infers string type
338
339
340==============================================================================
341
3425. Namespace, Import and Export
343 *vim9script* *vim9-export* *vim9-import*
344
345THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
346
347A Vim9 script can be written to be imported. This means that everything in
348the script is local, unless exported. Those exported items, and only those
349items, can then be imported in another script.
350
351
352Namespace ~
353 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100354To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100355appear as the first statement in the file. It tells Vim to interpret the
356script in its own namespace, instead of the global namespace. If a file
357starts with: >
358 vim9script
359 let myvar = 'yes'
360Then "myvar" will only exist in this file. While without `vim9script` it would
361be available as `g:myvar` from any other script and function.
362
363The variables at the file level are very much like the script-local "s:"
364variables in legacy Vim script, but the "s:" is omitted.
365
366In Vim9 script the global "g:" namespace can still be used as before.
367
368A side effect of `:vim9script` is that the 'cpoptions' option is set to the
369Vim default value, like with: >
370 :set cpo&vim
371One of the effects is that |line-continuation| is always enabled.
372The original value of 'cpoptions' is restored at the end of the script.
373
374
375Export ~
376 *:export* *:exp*
377Exporting one item can be written as: >
378 export const EXPORTED_CONST = 1234
379 export let someValue = ...
380 export def MyFunc() ...
381 export class MyClass ...
382
383As this suggests, only constants, variables, `:def` functions and classes can
384be exported.
385
386Alternatively, an export statement can be used to export several already
387defined (otherwise script-local) items: >
388 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
389
390
391Import ~
392 *:import* *:imp*
393The exported items can be imported individually in another Vim9 script: >
394 import EXPORTED_CONST from "thatscript.vim"
395 import MyClass from "myclass.vim"
396
397To import multiple items at the same time: >
398 import {someValue, MyClass} from "thatscript.vim"
399
Bram Moolenaar560979e2020-02-04 22:53:05 +0100400In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100401 import MyClass as ThatClass from "myclass.vim"
402 import {someValue, MyClass as ThatClass} from "myclass.vim"
403
404To import all exported items under a specific identifier: >
405 import * as That from 'thatscript.vim'
406
407Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
408to choose the name "That", but it is highly recommended to use the name of the
409script file to avoid confusion.
410
411The script name after `import` can be:
412- A relative path, starting "." or "..". This finds a file relative to the
413 location of the script file itself. This is useful to split up a large
414 plugin into several files.
415- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
416 will be rarely used.
417- A path not being relative or absolute. This will be found in the
418 "import" subdirectories of 'runtimepath' entries. The name will usually be
419 longer and unique, to avoid loading the wrong file.
420
421Once a vim9 script file has been imported, the result is cached and used the
422next time the same script is imported. It will not be read again.
423 *:import-cycle*
424The `import` commands are executed when encountered. If that script (directly
425or indirectly) imports the current script, then items defined after the
426`import` won't be processed yet. Therefore cyclic imports can exist, but may
427result in undefined items.
428
429
430Import in an autoload script ~
431
432For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100433actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100434
4351. In the plugin define user commands, functions and/or mappings that refer to
436 an autoload script. >
437 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
438
439< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
440
4412. In the autocommand script do the actual work. You can import items from
442 other files to split up functionality in appropriate pieces. >
443 vim9script
444 import FilterFunc from "../import/someother.vim"
445 def searchfor#Stuff(arg: string)
446 let filtered = FilterFunc(arg)
447 ...
448< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
449 must be exactly the same as the prefix for the function name, that is how
450 Vim finds the file.
451
4523. Other functionality, possibly shared between plugins, contains the exported
453 items and any private items. >
454 vim9script
455 let localVar = 'local'
456 export def FilterFunc(arg: string): string
457 ...
458< This goes in .../import/someother.vim.
459
460
461Import in legacy Vim script ~
462
463If an `import` statement is used in legacy Vim script, for identifier the
464script-local "s:" namespace will be used, even when "s:" is not specified.
465
466
467==============================================================================
468
4699. Rationale *vim9-rationale*
470
471The :def command ~
472
473Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100474shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100475impossible, because of the overhead involved with calling a function, setting
476up the local function scope and executing lines. There are many details that
477need to be handled, such as error messages and exceptions. The need to create
478a dictionary for a: and l: scopes, the a:000 list and several others add too
479much overhead that cannot be avoided.
480
481Therefore the `:def` method to define a new-style function had to be added,
482which allows for a function with different semantics. Most things still work
483as before, but some parts do not. A new way to define a function was
484considered the best way to separate the old-style code from Vim9 script code.
485
486Using "def" to define a function comes from Python. Other languages use
487"function" which clashes with legacy Vim script.
488
489
490Type checking ~
491
492When compiling lines of Vim commands into instructions as much as possible
493should be done at compile time. Postponing it to runtime makes the execution
494slower and means mistakes are found only later. For example, when
495encountering the "+" character and compiling this into a generic add
496instruction, at execution time the instruction would have to inspect the type
497of the arguments and decide what kind of addition to do. And when the
498type is dictionary throw an error. If the types are known to be numbers then
499an "add number" instruction can be used, which is faster. The error can be
500given at compile time, no error handling is needed at runtime.
501
502The syntax for types is similar to Java, since it is easy to understand and
503widely used. The type names are what was used in Vim before, with some
504additions such as "void" and "bool".
505
506
507JavaScript/TypeScript syntax and semantics ~
508
509Script writers have complained that the Vim script syntax is unexpectedly
510different from what they are used to. To reduce this complaint popular
511languages will be used as an example. At the same time, we do not want to
Bram Moolenaar560979e2020-02-04 22:53:05 +0100512abandon the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100513
514Since Vim already uses `:let` and `:const` and optional type checking is
515desirable, the JavaScript/TypeScript syntax fits best for variable
516declarations. >
517 const greeting = 'hello' " string type is inferred
518 let name: string
519 ...
520 name = 'John'
521
522Expression evaluation was already close to what JavaScript and other languages
523are doing. Some details are unexpected and can be fixed. For example how the
524|| and && operators work. Legacy Vim script: >
525 let result = 44
526 ...
527 return result || 0 " returns 1
528
529Vim9 script works like JavaScript, keep the value: >
530 let result = 44
531 ...
532 return result || 0 " returns 44
533
534On the other hand, overloading "+" to use both for addition and string
535concatenation goes against legacy Vim script and often leads to mistakes.
536For that reason we will keep using ".." for string concatenation. Lua also
537uses ".." this way.
538
539
540Import and Export ~
541
542A problem of legacy Vim script is that by default all functions and variables
543are global. It is possible to make them script-local, but then they are not
544available in other scripts.
545
546In Vim9 script a mechanism very similar to the Javascript import and export
547mechanism is supported. It is a variant to the existing `:source` command
548that works like one would expect:
549- Instead of making everything global by default, everything is script-local,
550 unless exported.
551- When importing a script the symbols that are imported are listed, avoiding
552 name conflicts and failures if later functionality is added.
553- The mechanism allows for writing a big, long script with a very clear API:
554 the exported function(s) and class(es).
555- By using relative paths loading can be much faster for an import inside of a
556 package, no need to search many directories.
557- Once an import has been used, it can be cached and loading it again can be
558 avoided.
559- The Vim-specific use of "s:" to make things script-local can be dropped.
560
561
562Classes ~
563
564Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
565these have never become widespread. When Vim 9 was designed a decision was
566made to phase out these interfaces and concentrate on Vim script, while
567encouraging plugin authors to write code in any language and run it as an
568external tool, using jobs and channels.
569
570Still, using an external tool has disadvantages. An alternative is to convert
571the tool into Vim script. For that to be possible without too much
572translation, and keeping the code fast at the same time, the constructs of the
573tool need to be supported. Since most languages support classes the lack of
574class support in Vim is then a problem.
575
576Previously Vim supported a kind-of object oriented programming by adding
577methods to a dictionary. With some care this could be made to work, but it
578does not look like real classes. On top of that, it's very slow, because of
579the use of dictionaries.
580
581The support of classes in Vim9 script is a "minimal common functionality" of
582class support in most languages. It works mostly like Java, which is the most
583popular programming language.
584
585
586
587 vim:tw=78:ts=8:noet:ft=help:norl: