comparison runtime/doc/vim9.txt @ 19181:94eda51ba9ba v8.2.0149

patch 8.2.0149: maintaining a Vim9 branch separately is more work Commit: https://github.com/vim/vim/commit/8a7d6542b33e5d2b352262305c3bfdb2d14e1cf8 Author: Bram Moolenaar <Bram@vim.org> Date: Sun Jan 26 15:56:19 2020 +0100 patch 8.2.0149: maintaining a Vim9 branch separately is more work Problem: Maintaining a Vim9 branch separately is more work. Solution: Merge the Vim9 script changes.
author Bram Moolenaar <Bram@vim.org>
date Sun, 26 Jan 2020 16:00:05 +0100
parents
children 51bc26d4a393
comparison
equal deleted inserted replaced
19180:8edf0aeb71b9 19181:94eda51ba9ba
1 *vim9.txt* For Vim version 8.2. Last change: 2019 Dec 06
2
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
8
9 Vim9 script commands and expressions.
10
11 Most expression help is in |eval.txt|. This file is about the new syntax and
12 features in Vim9 script.
13
14 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
15
16
17 1 What is Vim9 script? |vim9-script|
18 2. Differences |vim9-differences|
19 3. New style functions |fast-functions|
20 4. Types |vim9-types|
21 5. Namespace, Import and Export |vim9script|
22
23 9. Rationale |vim9-rationale|
24
25 ==============================================================================
26
27 1. What is Vim9 script? *vim9-script*
28
29 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
30
31 Vim script has been growing over time, while keeping backwards compatibility.
32 That means bad choices from the past often can't be changed. Execution is
33 quite slow, every line is parsed every time it is executed.
34
35 The main goal of Vim9 script is to drastically improve performance. An
36 increase in execution speed of 10 to 100 times can be expected. A secondary
37 goal is to avoid Vim-specific constructs and get closer to commonly used
38 programming languages, such as JavaScript, TypeScript and Java.
39
40 The performance improvements can only be achieved by not being 100% backwards
41 compatible. 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.
43 Other differences are more subtle, such as how errors are handled.
44
45 The 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
49 When using `:function` in a Vim9 script file the legacy syntax is used.
50 However, this is discouraged.
51
52 Vim9 script and legacy Vim script can be mixed. There is no need to rewrite
53 old scripts, they keep working as before.
54
55 ==============================================================================
56
57 2. Differences from legacy Vim script *vim9-differences*
58
59 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
60
61 Vim9 functions ~
62
63 `:def` has no extra arguments like `:function` does: "range", "abort", "dict"
64 or "closure". A `:def` function always aborts on an error, does not get a
65 range passed and cannot be a "dict" function.
66
67 In 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
76 Variable declarations with :let and :const ~
77
78 Local variables need to be declared with `:let`. Local constants need to be
79 declared with `:const`. We refer to both as "variables".
80
81 Variables 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
90 The variables are only visible in the block where they are defined and nested
91 blocks. 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
99 The 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
108 To intentionally use a variable that won't be available later, a block can be
109 used: >
110 {
111 let temp = 'temp'
112 ...
113 }
114 echo temp " Error!
115
116 An existing variable cannot be assigend to with `:let`, since that implies a
117 declaration. An exception is global variables: these can be both used with
118 and without `:let`, because there is no rule about where they are declared.
119
120 Variables cannot shadow previously defined variables.
121 Variables may shadow Ex commands, rename the variable if needed.
122
123 Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
124 used to repeat a `:substitute` command.
125
126
127 Omitting :call and :eval ~
128
129 Functions can be called without `:call`: >
130 writefile(lines, 'file')
131 Using `:call` is still posible, but this is discouraged.
132
133 A method call without `eval` is possible, so long as the start is an
134 identifier 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
144 No curly braces expansion ~
145
146 |curly-braces-names| cannot be used.
147
148
149 Comperators ~
150
151 The 'ignorecase' option is not used for comperators that use strings.
152
153
154 White space ~
155
156 Vim9 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!
160 There must be white space before and after the "=": >
161 let var = 234 " OK
162
163 White space is required around most operators.
164
165 White 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
175 Conditions and expressions ~
176
177 Conditions and expression are mostly working like they do in JavaScript. A
178 difference is made where JavaScript does not work like most people expect.
179 Specifically, an empty list is falsey.
180
181 Any type of variable can be used as a condition, there is no error, not even
182 for using a list or job. This is very much like JavaScript, but there are a
183 few 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
201 The 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
209 When using `..` for string concatenation the arguments are always converted to
210 string. >
211 'hello ' .. 123 == 'hello 123'
212 'hello ' .. v:true == 'hello true'
213
214 In Vim9 script one can use "true" for v:true and "false" for v:false.
215
216
217 ==============================================================================
218
219 3. New style functions *fast-functions*
220
221 THIS 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
253 4. Types *vim9-types*
254
255 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
256
257 The 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
269 Not supported yet:
270 tuple<a: type, b: type, ...>
271
272 These types can be used in declarations, but no variable will have this type:
273 type|type
274 void
275 any
276
277 There is no array type, use list<type> instead. For a list constant an
278 efficient implementation is used that avoids allocating lot of small pieces of
279 memory.
280
281 A function defined with `:def` must declare the return type. If there is no
282 type then the function doesn't return anything. "void" is used in type
283 declarations.
284
285 Custom types can be defined with `:type`: >
286 :type MyList list<string>
287 {not implemented yet}
288
289 And 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
306 Type inference *type-inference*
307
308 In general: Whenever the type is clear it can be omitted. For example, when
309 declaring 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
316 5. Namespace, Import and Export
317 *vim9script* *vim9-export* *vim9-import*
318
319 THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
320
321 A Vim9 script can be written to be imported. This means that everything in
322 the script is local, unless exported. Those exported items, and only those
323 items, can then be imported in another script.
324
325
326 Namespace ~
327 *:vim9script* *:vim9*
328 To recognize an file that can be imported the `vim9script` statement must
329 appear as the first statement in the file. It tells Vim to interpret the
330 script in its own namespace, instead of the global namespace. If a file
331 starts with: >
332 vim9script
333 let myvar = 'yes'
334 Then "myvar" will only exist in this file. While without `vim9script` it would
335 be available as `g:myvar` from any other script and function.
336
337 The variables at the file level are very much like the script-local "s:"
338 variables in legacy Vim script, but the "s:" is omitted.
339
340 In Vim9 script the global "g:" namespace can still be used as before.
341
342 A side effect of `:vim9script` is that the 'cpoptions' option is set to the
343 Vim default value, like with: >
344 :set cpo&vim
345 One of the effects is that |line-continuation| is always enabled.
346 The original value of 'cpoptions' is restored at the end of the script.
347
348
349 Export ~
350 *:export* *:exp*
351 Exporting 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
357 As this suggests, only constants, variables, `:def` functions and classes can
358 be exported.
359
360 Alternatively, an export statement can be used to export several already
361 defined (otherwise script-local) items: >
362 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
363
364
365 Import ~
366 *:import* *:imp*
367 The exported items can be imported individually in another Vim9 script: >
368 import EXPORTED_CONST from "thatscript.vim"
369 import MyClass from "myclass.vim"
370
371 To import multiple items at the same time: >
372 import {someValue, MyClass} from "thatscript.vim"
373
374 In 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
378 To import all exported items under a specific identifier: >
379 import * as That from 'thatscript.vim'
380
381 Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
382 to choose the name "That", but it is highly recommended to use the name of the
383 script file to avoid confusion.
384
385 The 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
395 Once a vim9 script file has been imported, the result is cached and used the
396 next time the same script is imported. It will not be read again.
397 *:import-cycle*
398 The `import` commands are executed when encountered. If that script (directly
399 or indirectly) imports the current script, then items defined after the
400 `import` won't be processed yet. Therefore cyclic imports can exist, but may
401 result in undefined items.
402
403
404 Import in an autoload script ~
405
406 For optimal startup speed, loading scripts should be postponed until they are
407 actually needed. A recommended mechamism:
408
409 1. 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
415 2. 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
426 3. 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
435 Import in legacy Vim script ~
436
437 If an `import` statement is used in legacy Vim script, for identifier the
438 script-local "s:" namespace will be used, even when "s:" is not specified.
439
440
441 ==============================================================================
442
443 9. Rationale *vim9-rationale*
444
445 The :def command ~
446
447 Plugin writers have asked for a much faster Vim script. Investigation have
448 shown that keeping the existing semantics of funtion calls make this close to
449 impossible, because of the overhead involved with calling a function, setting
450 up the local function scope and executing lines. There are many details that
451 need to be handled, such as error messages and exceptions. The need to create
452 a dictionary for a: and l: scopes, the a:000 list and several others add too
453 much overhead that cannot be avoided.
454
455 Therefore the `:def` method to define a new-style function had to be added,
456 which allows for a function with different semantics. Most things still work
457 as before, but some parts do not. A new way to define a function was
458 considered the best way to separate the old-style code from Vim9 script code.
459
460 Using "def" to define a function comes from Python. Other languages use
461 "function" which clashes with legacy Vim script.
462
463
464 Type checking ~
465
466 When compiling lines of Vim commands into instructions as much as possible
467 should be done at compile time. Postponing it to runtime makes the execution
468 slower and means mistakes are found only later. For example, when
469 encountering the "+" character and compiling this into a generic add
470 instruction, at execution time the instruction would have to inspect the type
471 of the arguments and decide what kind of addition to do. And when the
472 type is dictionary throw an error. If the types are known to be numbers then
473 an "add number" instruction can be used, which is faster. The error can be
474 given at compile time, no error handling is needed at runtime.
475
476 The syntax for types is similar to Java, since it is easy to understand and
477 widely used. The type names are what was used in Vim before, with some
478 additions such as "void" and "bool".
479
480
481 JavaScript/TypeScript syntax and semantics ~
482
483 Script writers have complained that the Vim script syntax is unexpectedly
484 different from what they are used to. To reduce this complaint popular
485 languages will be used as an example. At the same time, we do not want to
486 abondon the well-known parts of legacy Vim script.
487
488 Since Vim already uses `:let` and `:const` and optional type checking is
489 desirable, the JavaScript/TypeScript syntax fits best for variable
490 declarations. >
491 const greeting = 'hello' " string type is inferred
492 let name: string
493 ...
494 name = 'John'
495
496 Expression evaluation was already close to what JavaScript and other languages
497 are 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
503 Vim9 script works like JavaScript, keep the value: >
504 let result = 44
505 ...
506 return result || 0 " returns 44
507
508 On the other hand, overloading "+" to use both for addition and string
509 concatenation goes against legacy Vim script and often leads to mistakes.
510 For that reason we will keep using ".." for string concatenation. Lua also
511 uses ".." this way.
512
513
514 Import and Export ~
515
516 A problem of legacy Vim script is that by default all functions and variables
517 are global. It is possible to make them script-local, but then they are not
518 available in other scripts.
519
520 In Vim9 script a mechanism very similar to the Javascript import and export
521 mechanism is supported. It is a variant to the existing `:source` command
522 that 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
536 Classes ~
537
538 Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
539 these have never become widespread. When Vim 9 was designed a decision was
540 made to phase out these interfaces and concentrate on Vim script, while
541 encouraging plugin authors to write code in any language and run it as an
542 external tool, using jobs and channels.
543
544 Still, using an external tool has disadvantages. An alternative is to convert
545 the tool into Vim script. For that to be possible without too much
546 translation, and keeping the code fast at the same time, the constructs of the
547 tool need to be supported. Since most languages support classes the lack of
548 class support in Vim is then a problem.
549
550 Previously Vim supported a kind-of object oriented programming by adding
551 methods to a dictionary. With some care this could be made to work, but it
552 does not look like real classes. On top of that, it's very slow, because of
553 the use of dictionaries.
554
555 The support of classes in Vim9 script is a "minimal common functionality" of
556 class support in most languages. It works mostly like Java, which is the most
557 popular programming language.
558
559
560
561 vim:tw=78:ts=8:noet:ft=help:norl: