blob: 21bc542a17ed45a35aa1627573df171ac12104b4 [file] [log] [blame]
Bram Moolenaardf069ee2020-06-22 23:02:51 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Jun 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
Bram Moolenaar7ceefb32020-05-01 16:07:38 +02009Vim9 script commands and expressions. *vim9*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010010
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
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020031Vim script has been growing over time, while preserving backwards
32compatibility. That means bad choices from the past often can't be changed
Bram Moolenaar73fef332020-06-21 22:12:03 +020033and compatibility with Vi restricts possible solutions. Execution is quite
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020034slow, each line is parsed every time it is executed.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010035
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020036The main goal of Vim9 script is to drastically improve performance. This is
37accomplished by compiling commands into instructions that can be efficiently
38executed. An increase in execution speed of 10 to 100 times can be expected.
39
40A secondary goal is to avoid Vim-specific constructs and get closer to
41commonly used programming languages, such as JavaScript, TypeScript and Java.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010042
43The performance improvements can only be achieved by not being 100% backwards
Bram Moolenaar388a5d42020-05-26 21:20:45 +020044compatible. For example, making function arguments available in the
45"a:" dictionary adds quite a lot of overhead. In a Vim9 function this
46dictionary is not available. Other differences are more subtle, such as how
47errors are handled.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010048
49The Vim9 script syntax and semantics are used in:
50- a function defined with the `:def` command
51- a script file where the first command is `vim9script`
52
53When using `:function` in a Vim9 script file the legacy syntax is used.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020054However, this can be confusing and is therefore discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010055
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020056Vim9 script and legacy Vim script can be mixed. There is no requirement to
57rewrite old scripts, they keep working as before.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010058
59==============================================================================
60
612. Differences from legacy Vim script *vim9-differences*
62
63THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
64
Bram Moolenaar2c330432020-04-13 14:41:35 +020065Comments starting with # ~
66
67In Vim script comments normally start with double quote. That can also be the
68start of a string, thus in many places it cannot be used. In Vim9 script a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020069comment can also start with #. In Vi this is a command to list text with
Bram Moolenaar2c330432020-04-13 14:41:35 +020070numbers, but you can also use `:number` for that. >
Bram Moolenaar73fef332020-06-21 22:12:03 +020071 let count = 0 # number of occurrences
Bram Moolenaar2c330432020-04-13 14:41:35 +020072
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020073To improve readability there must be a space between the command and the #
74that starts a comment. Note that #{ is the start of a dictionary, therefore
75it cannot start a comment.
76
Bram Moolenaar2c330432020-04-13 14:41:35 +020077
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010078Vim9 functions ~
79
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020080A function defined with `:def` is compiled. Execution is many times faster,
81often 10x to 100x times.
82
Bram Moolenaar388a5d42020-05-26 21:20:45 +020083Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020084The syntax is strict, to enforce code that is easy to read and understand.
85
Bram Moolenaar388a5d42020-05-26 21:20:45 +020086Compilation is done when the function is first called, or when the
87`:defcompile` command is encountered in the script where the function was
88defined.
89
90`:def` has no options like `:function` does: "range", "abort", "dict" or
91"closure". A `:def` function always aborts on an error, does not get a range
92passed and cannot be a "dict" function.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010093
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020094The argument types and return type need to be specified. The "any" type can
95be used, type checking will then be done at runtime, like with legacy
96functions.
97
98Arguments are accessed by name, without "a:". There is no "a:" dictionary or
99"a:000" list.
100
101Variable arguments are defined as the last argument, with a name and have a
102list type, similar to Typescript. For example, a list of numbers: >
103 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100104 for item in itemlist
105 ...
106
107
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200108Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200109 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200110When using `:function` or `:def` to specify a new function at the script level
111in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200112prefixed. Using the "s:" prefix is optional.
113
114To define or use a global function or variable the "g:" prefix must be used.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200115
116When using `:function` or `:def` to specify a new function inside a function,
117the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200118script-local function inside a function. It is possible to define a global
119function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200120
121When referring to a function and no "s:" or "g:" prefix is used, Vim will
122search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200123- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200124- Local to the current script file.
125- Imported functions, see `:import`.
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200126In all cases the function must be defined before used. That is when it is
127first called or when `:defcompile` causes the call to be compiled.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200128
129The result is that functions and variables without a namespace can always be
130found in the script, either defined there or imported. Global functions and
131variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200132
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200133Global functions can be still be defined and deleted at nearly any time. In
134Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200135and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200136
137
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100138Variable declarations with :let and :const ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200139 *vim9-declaration*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100140Local variables need to be declared with `:let`. Local constants need to be
141declared with `:const`. We refer to both as "variables".
142
143Variables can be local to a script, function or code block: >
144 vim9script
145 let script_var = 123
146 def SomeFunc()
147 let func_var = script_var
148 if cond
149 let block_var = func_var
150 ...
151
152The variables are only visible in the block where they are defined and nested
153blocks. Once the block ends the variable is no longer accessible: >
154 if cond
155 let inner = 5
156 else
157 let inner = 0
158 endif
159 echo inner " Error!
160
161The declaration must be done earlier: >
162 let inner: number
163 if cond
164 inner = 5
165 else
166 inner = 0
167 endif
168 echo inner
169
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200170To intentionally avoid a variable being available later, a block can be used:
171>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100172 {
173 let temp = 'temp'
174 ...
175 }
176 echo temp " Error!
177
Bram Moolenaar560979e2020-02-04 22:53:05 +0100178An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100179declaration. An exception is global variables: these can be both used with
180and without `:let`, because there is no rule about where they are declared.
181
182Variables cannot shadow previously defined variables.
183Variables may shadow Ex commands, rename the variable if needed.
184
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200185Global variables and user defined functions must be prefixed with "g:", also
186at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200187 vim9script
188 let script_local = 'text'
189 let g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200190 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200191
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100192Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
193used to repeat a `:substitute` command.
194
195
196Omitting :call and :eval ~
197
198Functions can be called without `:call`: >
199 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100200Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100201
202A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100203identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100204 myList->add(123) " works
205 g:myList->add(123) " works
206 [1, 2, 3]->Process() " works
207 #{a: 1, b: 2}->Process() " works
208 {'a': 1, 'b': 2}->Process() " works
209 "foobar"->Process() " does NOT work
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100210 ("foobar")->Process() " works
211 'foobar'->Process() " does NOT work
212 ('foobar')->Process() " works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100213
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100214In case there is ambiguity between a function name and an Ex command, use ":"
215to make clear you want to use the Ex command. For example, there is both the
216`:substitute` command and the `substitute()` function. When the line starts
217with `substitute(` this will use the function, prepend a colon to use the
218command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100219 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100220
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100221Note that while variables need to be defined before they can be used,
222functions can be called before being defined. This is required to be able
223have cyclic dependencies between functions. It is slightly less efficient,
224since the function has to be looked up by name. And a typo in the function
225name will only be found when the call is executed.
226
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100227
Bram Moolenaard1caa942020-04-10 22:10:56 +0200228Omitting function() ~
229
230A user defined function can be used as a function reference in an expression
231without `function()`. The argument types and return type will then be checked.
232The function must already have been defined. >
233
234 let Funcref = MyFunction
235
236When using `function()` the resulting type is "func", a function with any
237number of arguments and any return type. The function can be defined later.
238
239
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200240Automatic line continuation ~
241
242In many cases it is obvious that an expression continues on the next line. In
243those cases there is no need to prefix the line with a backslash. For
244example, when a list spans multiple lines: >
245 let mylist = [
246 'one',
247 'two',
248 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200249And when a dict spans multiple lines: >
250 let mydict = #{
251 one: 1,
252 two: 2,
253 }
254Function call: >
255 let result = Func(
256 arg1,
257 arg2
258 )
259
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200260For binary operators in expressions not in [], {} or () a line break is
261possible just before or after the operator. For example: >
262 let text = lead
263 .. middle
264 .. end
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200265 let total = start +
266 end -
267 correction
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200268 let result = positive
269 ? PosFunc(arg)
270 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200271
Bram Moolenaar73fef332020-06-21 22:12:03 +0200272 let result = GetBuilder()
273 ->BuilderSetWidth(333)
274 ->BuilderSetHeight(777)
275 ->BuilderBuild()
276
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200277< *E1050*
278To make it possible for the operator at the start of the line to be
279recognized, it is required to put a colon before a range. This will adde
280"start" and print: >
281 let result = start
282 + print
283This will assign "start" and print a line: >
284 let result = start
285 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200286
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200287It is also possible to split a function header over multiple lines, in between
288arguments: >
289 def MyFunc(
290 text: string,
291 separator = '-'
292 ): string
293
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200294Note that "enddef" cannot be used at the start of a continuation line, it ends
295the current function.
296
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200297
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100298No curly braces expansion ~
299
300|curly-braces-names| cannot be used.
301
302
Bram Moolenaar560979e2020-02-04 22:53:05 +0100303No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100304
Bram Moolenaar560979e2020-02-04 22:53:05 +0100305These commands are too quickly confused with local variable names.
306
307
308Comparators ~
309
310The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100311
312
313White space ~
314
315Vim9 script enforces proper use of white space. This is no longer allowed: >
316 let var=234 " Error!
317 let var= 234 " Error!
318 let var =234 " Error!
319There must be white space before and after the "=": >
320 let var = 234 " OK
Bram Moolenaar2c330432020-04-13 14:41:35 +0200321White space must also be put before the # that starts a comment: >
322 let var = 234# Error!
323 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100324
325White space is required around most operators.
326
327White space is not allowed:
328- Between a function name and the "(": >
329 call Func (arg) " Error!
330 call Func
331 \ (arg) " Error!
332 call Func(arg) " OK
333 call Func(
334 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100335 call Func(
336 \ arg " OK
337 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100338
339
340Conditions and expressions ~
341
342Conditions and expression are mostly working like they do in JavaScript. A
343difference is made where JavaScript does not work like most people expect.
344Specifically, an empty list is falsey.
345
346Any type of variable can be used as a condition, there is no error, not even
347for using a list or job. This is very much like JavaScript, but there are a
348few exceptions.
349
350 type TRUE when ~
351 bool v:true
352 number non-zero
353 float non-zero
354 string non-empty
355 blob non-empty
356 list non-empty (different from JavaScript)
357 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200358 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100359 special v:true
360 job when not NULL
361 channel when not NULL
362 class when not NULL
363 object when not NULL (TODO: when isTrue() returns v:true)
364
365The boolean operators "||" and "&&" do not change the value: >
366 8 || 2 == 8
367 0 || 2 == 2
368 0 || '' == ''
369 8 && 2 == 2
370 0 && 2 == 0
371 [] && 2 == []
372
373When using `..` for string concatenation the arguments are always converted to
374string. >
375 'hello ' .. 123 == 'hello 123'
376 'hello ' .. v:true == 'hello true'
377
378In Vim9 script one can use "true" for v:true and "false" for v:false.
379
380
381==============================================================================
382
3833. New style functions *fast-functions*
384
385THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
386
387 *:def*
388:def[!] {name}([arguments])[: {return-type}
389 Define a new function by the name {name}. The body of
390 the function follows in the next lines, until the
391 matching `:enddef`.
392
Bram Moolenaard77a8522020-04-03 21:59:57 +0200393 When {return-type} is omitted or is "void" the
394 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100395
396 {arguments} is a sequence of zero or more argument
397 declarations. There are three forms:
398 {name}: {type}
399 {name} = {value}
400 {name}: {type} = {value}
401 The first form is a mandatory argument, the caller
402 must always provide them.
403 The second and third form are optional arguments.
404 When the caller omits an argument the {value} is used.
405
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200406 The function will be compiled into instructions when
407 called, or when `:defcompile` is used. Syntax and
408 type errors will be produced at that time.
409
Bram Moolenaar560979e2020-02-04 22:53:05 +0100410 NOTE: It is possible to nest `:def` inside another
411 `:def`, but it is not possible to nest `:def` inside
412 `:function`, for backwards compatibility.
413
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200414 [!] is used as with `:function`. Note that in Vim9
415 script script-local functions cannot be deleted or
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200416 redefined later in the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100417
418 *:enddef*
419:enddef End of a function defined with `:def`.
420
421
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100422If the script the function is defined in is Vim9 script, then script-local
423variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200424before the function is compiled. If the script the function is defined in is
425legacy script, then script-local variables must be accessed with the "s:"
426prefix.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100427
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200428 *:defc* *:defcompile*
429:defc[ompile] Compile functions defined in the current script that
430 were not compiled yet.
431 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100432
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100433 *:disa* *:disassemble*
434:disa[ssemble] {func} Show the instructions generated for {func}.
435 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100436 Note that for command line completion of {func} you
437 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100438
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100439==============================================================================
440
4414. Types *vim9-types*
442
443THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
444
445The following builtin types are supported:
446 bool
447 number
448 float
449 string
450 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200451 list<{type}>
452 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100453 job
454 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100455 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200456 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200457 func({type}, ...)
458 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100459
460Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200461 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100462
Bram Moolenaard77a8522020-04-03 21:59:57 +0200463These types can be used in declarations, but no value will have this type:
464 {type}|{type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100465 void
466 any
467
Bram Moolenaard77a8522020-04-03 21:59:57 +0200468There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100469efficient implementation is used that avoids allocating lot of small pieces of
470memory.
471
Bram Moolenaard77a8522020-04-03 21:59:57 +0200472A partial and function can be declared in more or less specific ways:
473func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200474 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200475func: {type} any number and type of arguments with specific
476 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200477func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200478 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200479func({type}): {type} function with argument type and return type
480func(?{type}) function with type of optional argument, does
481 not return a value
482func(...{type}) function with type of variable number of
483 arguments, does not return a value
484func({type}, ?{type}, ...{type}): {type}
485 function with:
486 - type of mandatory argument
487 - type of optional argument
488 - type of variable number of arguments
489 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200490
491If the return type is "void" the function does not return a value.
492
493The reference can also be a |Partial|, in which case it stores extra arguments
494and/or a dictionary, which are not visible to the caller. Since they are
495called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100496
497Custom types can be defined with `:type`: >
498 :type MyList list<string>
499{not implemented yet}
500
501And classes and interfaces can be used as types: >
502 :class MyClass
503 :let mine: MyClass
504
505 :interface MyInterface
506 :let mine: MyInterface
507
508 :class MyTemplate<Targ>
509 :let mine: MyTemplate<number>
510 :let mine: MyTemplate<string>
511
512 :class MyInterface<Targ>
513 :let mine: MyInterface<number>
514 :let mine: MyInterface<string>
515{not implemented yet}
516
517
518Type inference *type-inference*
519
520In general: Whenever the type is clear it can be omitted. For example, when
521declaring a variable and giving it a value: >
522 let var = 0 " infers number type
523 let var = 'hello' " infers string type
524
525
526==============================================================================
527
5285. Namespace, Import and Export
529 *vim9script* *vim9-export* *vim9-import*
530
531THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
532
533A Vim9 script can be written to be imported. This means that everything in
534the script is local, unless exported. Those exported items, and only those
535items, can then be imported in another script.
536
537
538Namespace ~
539 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100540To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100541appear as the first statement in the file. It tells Vim to interpret the
542script in its own namespace, instead of the global namespace. If a file
543starts with: >
544 vim9script
545 let myvar = 'yes'
546Then "myvar" will only exist in this file. While without `vim9script` it would
547be available as `g:myvar` from any other script and function.
548
549The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200550variables in legacy Vim script, but the "s:" is omitted. And they cannot be
551deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100552
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200553In Vim9 script the global "g:" namespace can still be used as before. And the
554"w:", "b:" and "t:" namespaces. These have in common that variables are not
555declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100556
557A side effect of `:vim9script` is that the 'cpoptions' option is set to the
558Vim default value, like with: >
559 :set cpo&vim
560One of the effects is that |line-continuation| is always enabled.
561The original value of 'cpoptions' is restored at the end of the script.
562
563
564Export ~
565 *:export* *:exp*
566Exporting one item can be written as: >
567 export const EXPORTED_CONST = 1234
568 export let someValue = ...
569 export def MyFunc() ...
570 export class MyClass ...
571
572As this suggests, only constants, variables, `:def` functions and classes can
573be exported.
574
575Alternatively, an export statement can be used to export several already
576defined (otherwise script-local) items: >
577 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200578<
579 *E1042*
580`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100581
582
583Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +0200584 *:import* *:imp* *E1094*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100585The exported items can be imported individually in another Vim9 script: >
586 import EXPORTED_CONST from "thatscript.vim"
587 import MyClass from "myclass.vim"
588
589To import multiple items at the same time: >
590 import {someValue, MyClass} from "thatscript.vim"
591
Bram Moolenaar560979e2020-02-04 22:53:05 +0100592In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100593 import MyClass as ThatClass from "myclass.vim"
594 import {someValue, MyClass as ThatClass} from "myclass.vim"
595
596To import all exported items under a specific identifier: >
597 import * as That from 'thatscript.vim'
598
599Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
600to choose the name "That", but it is highly recommended to use the name of the
601script file to avoid confusion.
602
603The script name after `import` can be:
604- A relative path, starting "." or "..". This finds a file relative to the
605 location of the script file itself. This is useful to split up a large
606 plugin into several files.
607- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
608 will be rarely used.
609- A path not being relative or absolute. This will be found in the
610 "import" subdirectories of 'runtimepath' entries. The name will usually be
611 longer and unique, to avoid loading the wrong file.
612
613Once a vim9 script file has been imported, the result is cached and used the
614next time the same script is imported. It will not be read again.
615 *:import-cycle*
616The `import` commands are executed when encountered. If that script (directly
617or indirectly) imports the current script, then items defined after the
618`import` won't be processed yet. Therefore cyclic imports can exist, but may
619result in undefined items.
620
621
622Import in an autoload script ~
623
624For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100625actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100626
6271. In the plugin define user commands, functions and/or mappings that refer to
628 an autoload script. >
629 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
630
631< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
632
6332. In the autocommand script do the actual work. You can import items from
634 other files to split up functionality in appropriate pieces. >
635 vim9script
636 import FilterFunc from "../import/someother.vim"
637 def searchfor#Stuff(arg: string)
638 let filtered = FilterFunc(arg)
639 ...
640< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
641 must be exactly the same as the prefix for the function name, that is how
642 Vim finds the file.
643
6443. Other functionality, possibly shared between plugins, contains the exported
645 items and any private items. >
646 vim9script
647 let localVar = 'local'
648 export def FilterFunc(arg: string): string
649 ...
650< This goes in .../import/someother.vim.
651
652
653Import in legacy Vim script ~
654
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200655If an `import` statement is used in legacy Vim script, the script-local "s:"
656namespace will be used for the imported item, even when "s:" is not specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100657
658
659==============================================================================
660
6619. Rationale *vim9-rationale*
662
663The :def command ~
664
665Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100666shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100667impossible, because of the overhead involved with calling a function, setting
668up the local function scope and executing lines. There are many details that
669need to be handled, such as error messages and exceptions. The need to create
670a dictionary for a: and l: scopes, the a:000 list and several others add too
671much overhead that cannot be avoided.
672
673Therefore the `:def` method to define a new-style function had to be added,
674which allows for a function with different semantics. Most things still work
675as before, but some parts do not. A new way to define a function was
676considered the best way to separate the old-style code from Vim9 script code.
677
678Using "def" to define a function comes from Python. Other languages use
679"function" which clashes with legacy Vim script.
680
681
682Type checking ~
683
684When compiling lines of Vim commands into instructions as much as possible
685should be done at compile time. Postponing it to runtime makes the execution
686slower and means mistakes are found only later. For example, when
687encountering the "+" character and compiling this into a generic add
688instruction, at execution time the instruction would have to inspect the type
689of the arguments and decide what kind of addition to do. And when the
690type is dictionary throw an error. If the types are known to be numbers then
691an "add number" instruction can be used, which is faster. The error can be
692given at compile time, no error handling is needed at runtime.
693
694The syntax for types is similar to Java, since it is easy to understand and
695widely used. The type names are what was used in Vim before, with some
696additions such as "void" and "bool".
697
698
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200699Compiling functions early ~
700
701Functions are compiled when called or when `:defcompile` is used. Why not
702compile them early, so that syntax and type errors are reported early?
703
704The functions can't be compiled right away when encountered, because there may
705be forward references to functions defined later. Consider defining functions
706A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
707to reorder the functions to avoid forward references.
708
709An alternative would be to first scan through the file to locate items and
Bram Moolenaar73fef332020-06-21 22:12:03 +0200710figure out their type, so that forward references are found, and only then
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200711execute the script and compile the functions. This means the script has to be
712parsed twice, which is slower, and some conditions at the script level, such
713as checking if a feature is supported, are hard to use. An attempt was made
714to see if it works, but it turned out to be impossible to make work nicely.
715
716It would be possible to compile all the functions at the end of the script.
717The drawback is that if a function never gets called, the overhead of
718compiling it counts anyway. Since startup speed is very important, in most
719cases it's better to do it later and accept that syntax and type errors are
720only reported then. In case these errors should be found early, e.g. when
721testing, the `:defcompile` command will help out.
722
723
724TypeScript syntax and semantics ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100725
726Script writers have complained that the Vim script syntax is unexpectedly
727different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200728languages are used as an example. At the same time, we do not want to abandon
729the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100730
731Since Vim already uses `:let` and `:const` and optional type checking is
732desirable, the JavaScript/TypeScript syntax fits best for variable
733declarations. >
734 const greeting = 'hello' " string type is inferred
735 let name: string
736 ...
737 name = 'John'
738
739Expression evaluation was already close to what JavaScript and other languages
740are doing. Some details are unexpected and can be fixed. For example how the
741|| and && operators work. Legacy Vim script: >
742 let result = 44
743 ...
744 return result || 0 " returns 1
745
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200746Vim9 script works like JavaScript/Typescript, keep the value: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100747 let result = 44
748 ...
749 return result || 0 " returns 44
750
751On the other hand, overloading "+" to use both for addition and string
752concatenation goes against legacy Vim script and often leads to mistakes.
753For that reason we will keep using ".." for string concatenation. Lua also
754uses ".." this way.
755
756
757Import and Export ~
758
759A problem of legacy Vim script is that by default all functions and variables
760are global. It is possible to make them script-local, but then they are not
761available in other scripts.
762
763In Vim9 script a mechanism very similar to the Javascript import and export
764mechanism is supported. It is a variant to the existing `:source` command
765that works like one would expect:
766- Instead of making everything global by default, everything is script-local,
767 unless exported.
768- When importing a script the symbols that are imported are listed, avoiding
769 name conflicts and failures if later functionality is added.
770- The mechanism allows for writing a big, long script with a very clear API:
771 the exported function(s) and class(es).
772- By using relative paths loading can be much faster for an import inside of a
773 package, no need to search many directories.
774- Once an import has been used, it can be cached and loading it again can be
775 avoided.
776- The Vim-specific use of "s:" to make things script-local can be dropped.
777
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200778When sourcing a Vim9 script from a legacy script, only the items defined
779globally can be used, not the exported items. Alternatives considered:
780- All the exported items become available as script-local items. This makes
781 it uncontrollable what items get defined.
782- Use the exported items and make them global. Disadvantage is that it's then
783 not possible to avoid name clashes in the global namespace.
784- Completely disallow sourcing a Vim9 script, require using `:import`. That
785 makes it difficult to use scripts for testing, or sourcing them from the
786 command line to try them out.
787
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100788
789Classes ~
790
791Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
792these have never become widespread. When Vim 9 was designed a decision was
793made to phase out these interfaces and concentrate on Vim script, while
794encouraging plugin authors to write code in any language and run it as an
795external tool, using jobs and channels.
796
797Still, using an external tool has disadvantages. An alternative is to convert
798the tool into Vim script. For that to be possible without too much
799translation, and keeping the code fast at the same time, the constructs of the
800tool need to be supported. Since most languages support classes the lack of
801class support in Vim is then a problem.
802
803Previously Vim supported a kind-of object oriented programming by adding
804methods to a dictionary. With some care this could be made to work, but it
805does not look like real classes. On top of that, it's very slow, because of
806the use of dictionaries.
807
808The support of classes in Vim9 script is a "minimal common functionality" of
809class support in most languages. It works mostly like Java, which is the most
810popular programming language.
811
812
813
814 vim:tw=78:ts=8:noet:ft=help:norl: