blob: d634f22fdddaa578cc317d7d5b282e7fe7b8b615 [file] [log] [blame]
Bram Moolenaarbc93ceb2020-02-26 13:36:21 +01001*vim9.txt* For Vim version 8.2. Last change: 2020 Feb 22
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
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100134identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100135 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
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100141 ("foobar")->Process() " works
142 'foobar'->Process() " does NOT work
143 ('foobar')->Process() " works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100144
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100145In case there is ambiguity between a function name and an Ex command, use ":"
146to make clear you want to use the Ex command. For example, there is both the
147`:substitute` command and the `substitute()` function. When the line starts
148with `substitute(` this will use the function, prepend a colon to use the
149command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100150 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100151
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100152
153No curly braces expansion ~
154
155|curly-braces-names| cannot be used.
156
157
Bram Moolenaar560979e2020-02-04 22:53:05 +0100158No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100159
Bram Moolenaar560979e2020-02-04 22:53:05 +0100160These commands are too quickly confused with local variable names.
161
162
163Comparators ~
164
165The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100166
167
168White space ~
169
170Vim9 script enforces proper use of white space. This is no longer allowed: >
171 let var=234 " Error!
172 let var= 234 " Error!
173 let var =234 " Error!
174There must be white space before and after the "=": >
175 let var = 234 " OK
176
177White space is required around most operators.
178
179White space is not allowed:
180- Between a function name and the "(": >
181 call Func (arg) " Error!
182 call Func
183 \ (arg) " Error!
184 call Func(arg) " OK
185 call Func(
186 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100187 call Func(
188 \ arg " OK
189 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100190
191
192Conditions and expressions ~
193
194Conditions and expression are mostly working like they do in JavaScript. A
195difference is made where JavaScript does not work like most people expect.
196Specifically, an empty list is falsey.
197
198Any type of variable can be used as a condition, there is no error, not even
199for using a list or job. This is very much like JavaScript, but there are a
200few exceptions.
201
202 type TRUE when ~
203 bool v:true
204 number non-zero
205 float non-zero
206 string non-empty
207 blob non-empty
208 list non-empty (different from JavaScript)
209 dictionary non-empty (different from JavaScript)
210 funcref when not NULL
211 partial when not NULL
212 special v:true
213 job when not NULL
214 channel when not NULL
215 class when not NULL
216 object when not NULL (TODO: when isTrue() returns v:true)
217
218The boolean operators "||" and "&&" do not change the value: >
219 8 || 2 == 8
220 0 || 2 == 2
221 0 || '' == ''
222 8 && 2 == 2
223 0 && 2 == 0
224 [] && 2 == []
225
226When using `..` for string concatenation the arguments are always converted to
227string. >
228 'hello ' .. 123 == 'hello 123'
229 'hello ' .. v:true == 'hello true'
230
231In Vim9 script one can use "true" for v:true and "false" for v:false.
232
233
234==============================================================================
235
2363. New style functions *fast-functions*
237
238THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
239
240 *:def*
241:def[!] {name}([arguments])[: {return-type}
242 Define a new function by the name {name}. The body of
243 the function follows in the next lines, until the
244 matching `:enddef`.
245
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100246 When {return-type} is omitted the function is not
247 expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100248
249 {arguments} is a sequence of zero or more argument
250 declarations. There are three forms:
251 {name}: {type}
252 {name} = {value}
253 {name}: {type} = {value}
254 The first form is a mandatory argument, the caller
255 must always provide them.
256 The second and third form are optional arguments.
257 When the caller omits an argument the {value} is used.
258
Bram Moolenaar560979e2020-02-04 22:53:05 +0100259 NOTE: It is possible to nest `:def` inside another
260 `:def`, but it is not possible to nest `:def` inside
261 `:function`, for backwards compatibility.
262
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100263 [!] is used as with `:function`.
264
265 *:enddef*
266:enddef End of a function defined with `:def`.
267
268
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100269If the script the function is defined in is Vim9 script, then script-local
270variables can be accessed without the "s:" prefix. They must be defined
271before the function. If the script the function is defined in is legacy
272script, then script-local variables must be accessed with the "s:" prefix.
273
274
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100275 *:disa* *:disassemble*
276:disa[ssemble] {func} Show the instructions generated for {func}.
277 This is for debugging and testing.
278
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100279==============================================================================
280
2814. Types *vim9-types*
282
283THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
284
285The following builtin types are supported:
286 bool
287 number
288 float
289 string
290 blob
291 list<type>
292 dict<type>
293 (a: type, b: type): type
294 job
295 channel
296
297Not supported yet:
298 tuple<a: type, b: type, ...>
299
300These types can be used in declarations, but no variable will have this type:
301 type|type
302 void
303 any
304
305There is no array type, use list<type> instead. For a list constant an
306efficient implementation is used that avoids allocating lot of small pieces of
307memory.
308
309A function defined with `:def` must declare the return type. If there is no
310type then the function doesn't return anything. "void" is used in type
311declarations.
312
313Custom types can be defined with `:type`: >
314 :type MyList list<string>
315{not implemented yet}
316
317And classes and interfaces can be used as types: >
318 :class MyClass
319 :let mine: MyClass
320
321 :interface MyInterface
322 :let mine: MyInterface
323
324 :class MyTemplate<Targ>
325 :let mine: MyTemplate<number>
326 :let mine: MyTemplate<string>
327
328 :class MyInterface<Targ>
329 :let mine: MyInterface<number>
330 :let mine: MyInterface<string>
331{not implemented yet}
332
333
334Type inference *type-inference*
335
336In general: Whenever the type is clear it can be omitted. For example, when
337declaring a variable and giving it a value: >
338 let var = 0 " infers number type
339 let var = 'hello' " infers string type
340
341
342==============================================================================
343
3445. Namespace, Import and Export
345 *vim9script* *vim9-export* *vim9-import*
346
347THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
348
349A Vim9 script can be written to be imported. This means that everything in
350the script is local, unless exported. Those exported items, and only those
351items, can then be imported in another script.
352
353
354Namespace ~
355 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100356To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100357appear as the first statement in the file. It tells Vim to interpret the
358script in its own namespace, instead of the global namespace. If a file
359starts with: >
360 vim9script
361 let myvar = 'yes'
362Then "myvar" will only exist in this file. While without `vim9script` it would
363be available as `g:myvar` from any other script and function.
364
365The variables at the file level are very much like the script-local "s:"
366variables in legacy Vim script, but the "s:" is omitted.
367
368In Vim9 script the global "g:" namespace can still be used as before.
369
370A side effect of `:vim9script` is that the 'cpoptions' option is set to the
371Vim default value, like with: >
372 :set cpo&vim
373One of the effects is that |line-continuation| is always enabled.
374The original value of 'cpoptions' is restored at the end of the script.
375
376
377Export ~
378 *:export* *:exp*
379Exporting one item can be written as: >
380 export const EXPORTED_CONST = 1234
381 export let someValue = ...
382 export def MyFunc() ...
383 export class MyClass ...
384
385As this suggests, only constants, variables, `:def` functions and classes can
386be exported.
387
388Alternatively, an export statement can be used to export several already
389defined (otherwise script-local) items: >
390 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
391
392
393Import ~
394 *:import* *:imp*
395The exported items can be imported individually in another Vim9 script: >
396 import EXPORTED_CONST from "thatscript.vim"
397 import MyClass from "myclass.vim"
398
399To import multiple items at the same time: >
400 import {someValue, MyClass} from "thatscript.vim"
401
Bram Moolenaar560979e2020-02-04 22:53:05 +0100402In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100403 import MyClass as ThatClass from "myclass.vim"
404 import {someValue, MyClass as ThatClass} from "myclass.vim"
405
406To import all exported items under a specific identifier: >
407 import * as That from 'thatscript.vim'
408
409Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
410to choose the name "That", but it is highly recommended to use the name of the
411script file to avoid confusion.
412
413The script name after `import` can be:
414- A relative path, starting "." or "..". This finds a file relative to the
415 location of the script file itself. This is useful to split up a large
416 plugin into several files.
417- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
418 will be rarely used.
419- A path not being relative or absolute. This will be found in the
420 "import" subdirectories of 'runtimepath' entries. The name will usually be
421 longer and unique, to avoid loading the wrong file.
422
423Once a vim9 script file has been imported, the result is cached and used the
424next time the same script is imported. It will not be read again.
425 *:import-cycle*
426The `import` commands are executed when encountered. If that script (directly
427or indirectly) imports the current script, then items defined after the
428`import` won't be processed yet. Therefore cyclic imports can exist, but may
429result in undefined items.
430
431
432Import in an autoload script ~
433
434For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100435actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100436
4371. In the plugin define user commands, functions and/or mappings that refer to
438 an autoload script. >
439 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
440
441< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
442
4432. In the autocommand script do the actual work. You can import items from
444 other files to split up functionality in appropriate pieces. >
445 vim9script
446 import FilterFunc from "../import/someother.vim"
447 def searchfor#Stuff(arg: string)
448 let filtered = FilterFunc(arg)
449 ...
450< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
451 must be exactly the same as the prefix for the function name, that is how
452 Vim finds the file.
453
4543. Other functionality, possibly shared between plugins, contains the exported
455 items and any private items. >
456 vim9script
457 let localVar = 'local'
458 export def FilterFunc(arg: string): string
459 ...
460< This goes in .../import/someother.vim.
461
462
463Import in legacy Vim script ~
464
465If an `import` statement is used in legacy Vim script, for identifier the
466script-local "s:" namespace will be used, even when "s:" is not specified.
467
468
469==============================================================================
470
4719. Rationale *vim9-rationale*
472
473The :def command ~
474
475Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100476shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100477impossible, because of the overhead involved with calling a function, setting
478up the local function scope and executing lines. There are many details that
479need to be handled, such as error messages and exceptions. The need to create
480a dictionary for a: and l: scopes, the a:000 list and several others add too
481much overhead that cannot be avoided.
482
483Therefore the `:def` method to define a new-style function had to be added,
484which allows for a function with different semantics. Most things still work
485as before, but some parts do not. A new way to define a function was
486considered the best way to separate the old-style code from Vim9 script code.
487
488Using "def" to define a function comes from Python. Other languages use
489"function" which clashes with legacy Vim script.
490
491
492Type checking ~
493
494When compiling lines of Vim commands into instructions as much as possible
495should be done at compile time. Postponing it to runtime makes the execution
496slower and means mistakes are found only later. For example, when
497encountering the "+" character and compiling this into a generic add
498instruction, at execution time the instruction would have to inspect the type
499of the arguments and decide what kind of addition to do. And when the
500type is dictionary throw an error. If the types are known to be numbers then
501an "add number" instruction can be used, which is faster. The error can be
502given at compile time, no error handling is needed at runtime.
503
504The syntax for types is similar to Java, since it is easy to understand and
505widely used. The type names are what was used in Vim before, with some
506additions such as "void" and "bool".
507
508
509JavaScript/TypeScript syntax and semantics ~
510
511Script writers have complained that the Vim script syntax is unexpectedly
512different from what they are used to. To reduce this complaint popular
513languages will be used as an example. At the same time, we do not want to
Bram Moolenaar560979e2020-02-04 22:53:05 +0100514abandon the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100515
516Since Vim already uses `:let` and `:const` and optional type checking is
517desirable, the JavaScript/TypeScript syntax fits best for variable
518declarations. >
519 const greeting = 'hello' " string type is inferred
520 let name: string
521 ...
522 name = 'John'
523
524Expression evaluation was already close to what JavaScript and other languages
525are doing. Some details are unexpected and can be fixed. For example how the
526|| and && operators work. Legacy Vim script: >
527 let result = 44
528 ...
529 return result || 0 " returns 1
530
531Vim9 script works like JavaScript, keep the value: >
532 let result = 44
533 ...
534 return result || 0 " returns 44
535
536On the other hand, overloading "+" to use both for addition and string
537concatenation goes against legacy Vim script and often leads to mistakes.
538For that reason we will keep using ".." for string concatenation. Lua also
539uses ".." this way.
540
541
542Import and Export ~
543
544A problem of legacy Vim script is that by default all functions and variables
545are global. It is possible to make them script-local, but then they are not
546available in other scripts.
547
548In Vim9 script a mechanism very similar to the Javascript import and export
549mechanism is supported. It is a variant to the existing `:source` command
550that works like one would expect:
551- Instead of making everything global by default, everything is script-local,
552 unless exported.
553- When importing a script the symbols that are imported are listed, avoiding
554 name conflicts and failures if later functionality is added.
555- The mechanism allows for writing a big, long script with a very clear API:
556 the exported function(s) and class(es).
557- By using relative paths loading can be much faster for an import inside of a
558 package, no need to search many directories.
559- Once an import has been used, it can be cached and loading it again can be
560 avoided.
561- The Vim-specific use of "s:" to make things script-local can be dropped.
562
563
564Classes ~
565
566Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
567these have never become widespread. When Vim 9 was designed a decision was
568made to phase out these interfaces and concentrate on Vim script, while
569encouraging plugin authors to write code in any language and run it as an
570external tool, using jobs and channels.
571
572Still, using an external tool has disadvantages. An alternative is to convert
573the tool into Vim script. For that to be possible without too much
574translation, and keeping the code fast at the same time, the constructs of the
575tool need to be supported. Since most languages support classes the lack of
576class support in Vim is then a problem.
577
578Previously Vim supported a kind-of object oriented programming by adding
579methods to a dictionary. With some care this could be made to work, but it
580does not look like real classes. On top of that, it's very slow, because of
581the use of dictionaries.
582
583The support of classes in Vim9 script is a "minimal common functionality" of
584class support in most languages. It works mostly like Java, which is the most
585popular programming language.
586
587
588
589 vim:tw=78:ts=8:noet:ft=help:norl: