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