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