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