blob: 525393dacb4d4e104dcd18421e5afa09114a76d6 [file] [log] [blame]
Bram Moolenaar7ceefb32020-05-01 16:07:38 +02001*vim9.txt* For Vim version 8.2. Last change: 2020 Apr 30
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
8
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
33and compability with Vi restricts possible solutions. Execution is quite
34slow, 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
44compatible. For example, in a function the arguments are not available in the
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020045"a:" dictionary, because creating that dictionary adds quite a lot of
46overhead. Other differences are more subtle, such as how errors are handled.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010047
48The Vim9 script syntax and semantics are used in:
49- a function defined with the `:def` command
50- a script file where the first command is `vim9script`
51
52When using `:function` in a Vim9 script file the legacy syntax is used.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020053However, this can be confusing and is therefore discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010054
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020055Vim9 script and legacy Vim script can be mixed. There is no requirement to
56rewrite old scripts, they keep working as before.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010057
58==============================================================================
59
602. Differences from legacy Vim script *vim9-differences*
61
62THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
63
Bram Moolenaar2c330432020-04-13 14:41:35 +020064Comments starting with # ~
65
66In Vim script comments normally start with double quote. That can also be the
67start of a string, thus in many places it cannot be used. In Vim9 script a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020068comment can also start with #. In Vi this is a command to list text with
Bram Moolenaar2c330432020-04-13 14:41:35 +020069numbers, but you can also use `:number` for that. >
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020070 let count = 0 # number of occurences
Bram Moolenaar2c330432020-04-13 14:41:35 +020071
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +020072To improve readability there must be a space between the command and the #
73that starts a comment. Note that #{ is the start of a dictionary, therefore
74it cannot start a comment.
75
Bram Moolenaar2c330432020-04-13 14:41:35 +020076
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010077Vim9 functions ~
78
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020079A function defined with `:def` is compiled. Execution is many times faster,
80often 10x to 100x times.
81
82Many errors are already found when compiling, before the function is called.
83The syntax is strict, to enforce code that is easy to read and understand.
84
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010085`:def` has no extra arguments like `:function` does: "range", "abort", "dict"
86or "closure". A `:def` function always aborts on an error, does not get a
87range passed and cannot be a "dict" function.
88
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020089The argument types and return type need to be specified. The "any" type can
90be used, type checking will then be done at runtime, like with legacy
91functions.
92
93Arguments are accessed by name, without "a:". There is no "a:" dictionary or
94"a:000" list.
95
96Variable arguments are defined as the last argument, with a name and have a
97list type, similar to Typescript. For example, a list of numbers: >
98 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010099 for item in itemlist
100 ...
101
102
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200103Functions and variables are script-local by default ~
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200104
105When using `:function` or `:def` to specify a new function at the script level
106in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200107prefixed. Using the "s:" prefix is optional.
108
109To define or use a global function or variable the "g:" prefix must be used.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200110
111When using `:function` or `:def` to specify a new function inside a function,
112the function is local to the function. It is not possible to define a
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200113script-local function inside a function. It is possible to define a global
114function, using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200115
116When referring to a function and no "s:" or "g:" prefix is used, Vim will
117search for the function in this order:
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200118- Local to the current scope and outer scopes up to the function scope.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200119- Local to the current script file.
120- Imported functions, see `:import`.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200121In all cases the function must be defined before used. To make a call cycle a
122global function needs to be used. (TODO: can we fix this?)
123
124The result is that functions and variables without a namespace can always be
125found in the script, either defined there or imported. Global functions and
126variables could be defined anywhere (good luck finding where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200127
128Global functions can be defined and deleted at nearly any time. In Vim9
129script script-local functions are defined once when the script is sourced and
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200130cannot be deleted. Except that when the same script is sourced again all
131existing script-local functions and variables are deleted.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200132
133
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100134Variable declarations with :let and :const ~
135
136Local variables need to be declared with `:let`. Local constants need to be
137declared with `:const`. We refer to both as "variables".
138
139Variables can be local to a script, function or code block: >
140 vim9script
141 let script_var = 123
142 def SomeFunc()
143 let func_var = script_var
144 if cond
145 let block_var = func_var
146 ...
147
148The variables are only visible in the block where they are defined and nested
149blocks. Once the block ends the variable is no longer accessible: >
150 if cond
151 let inner = 5
152 else
153 let inner = 0
154 endif
155 echo inner " Error!
156
157The declaration must be done earlier: >
158 let inner: number
159 if cond
160 inner = 5
161 else
162 inner = 0
163 endif
164 echo inner
165
166To intentionally use a variable that won't be available later, a block can be
167used: >
168 {
169 let temp = 'temp'
170 ...
171 }
172 echo temp " Error!
173
Bram Moolenaar560979e2020-02-04 22:53:05 +0100174An existing variable cannot be assigned to with `:let`, since that implies a
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100175declaration. An exception is global variables: these can be both used with
176and without `:let`, because there is no rule about where they are declared.
177
178Variables cannot shadow previously defined variables.
179Variables may shadow Ex commands, rename the variable if needed.
180
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200181Global variables and user defined functions must be prefixed with "g:", also
182at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200183 vim9script
184 let script_local = 'text'
185 let g:global = 'value'
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200186 let Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200187
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100188Since "&opt = value" is now assigning a value to option "opt", ":&" cannot be
189used to repeat a `:substitute` command.
190
191
192Omitting :call and :eval ~
193
194Functions can be called without `:call`: >
195 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100196Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100197
198A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100199identifier or can't be an Ex command. It does NOT work for string constants: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100200 myList->add(123) " works
201 g:myList->add(123) " works
202 [1, 2, 3]->Process() " works
203 #{a: 1, b: 2}->Process() " works
204 {'a': 1, 'b': 2}->Process() " works
205 "foobar"->Process() " does NOT work
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100206 ("foobar")->Process() " works
207 'foobar'->Process() " does NOT work
208 ('foobar')->Process() " works
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100209
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100210In case there is ambiguity between a function name and an Ex command, use ":"
211to make clear you want to use the Ex command. For example, there is both the
212`:substitute` command and the `substitute()` function. When the line starts
213with `substitute(` this will use the function, prepend a colon to use the
214command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100215 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100216
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100217Note that while variables need to be defined before they can be used,
218functions can be called before being defined. This is required to be able
219have cyclic dependencies between functions. It is slightly less efficient,
220since the function has to be looked up by name. And a typo in the function
221name will only be found when the call is executed.
222
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100223
Bram Moolenaard1caa942020-04-10 22:10:56 +0200224Omitting function() ~
225
226A user defined function can be used as a function reference in an expression
227without `function()`. The argument types and return type will then be checked.
228The function must already have been defined. >
229
230 let Funcref = MyFunction
231
232When using `function()` the resulting type is "func", a function with any
233number of arguments and any return type. The function can be defined later.
234
235
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200236Automatic line continuation ~
237
238In many cases it is obvious that an expression continues on the next line. In
239those cases there is no need to prefix the line with a backslash. For
240example, when a list spans multiple lines: >
241 let mylist = [
242 'one',
243 'two',
244 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200245And when a dict spans multiple lines: >
246 let mydict = #{
247 one: 1,
248 two: 2,
249 }
250Function call: >
251 let result = Func(
252 arg1,
253 arg2
254 )
255
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200256For binary operators iin expressions not in [], {} or () a line break is
257possible AFTER the operators. For example: >
258 let text = lead ..
259 middle ..
260 end
261 let total = start +
262 end -
263 correction
264 let result = positive ?
265 PosFunc(arg) :
266 NegFunc(arg)
267
Bram Moolenaare6085c52020-04-12 20:19:16 +0200268Note that "enddef" cannot be used at the start of a continuation line, it ends
269the current function.
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200270
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200271It is also possible to split a function header over multiple lines, in between
272arguments: >
273 def MyFunc(
274 text: string,
275 separator = '-'
276 ): string
277
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200278
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100279No curly braces expansion ~
280
281|curly-braces-names| cannot be used.
282
283
Bram Moolenaar560979e2020-02-04 22:53:05 +0100284No :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100285
Bram Moolenaar560979e2020-02-04 22:53:05 +0100286These commands are too quickly confused with local variable names.
287
288
289Comparators ~
290
291The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100292
293
294White space ~
295
296Vim9 script enforces proper use of white space. This is no longer allowed: >
297 let var=234 " Error!
298 let var= 234 " Error!
299 let var =234 " Error!
300There must be white space before and after the "=": >
301 let var = 234 " OK
Bram Moolenaar2c330432020-04-13 14:41:35 +0200302White space must also be put before the # that starts a comment: >
303 let var = 234# Error!
304 let var = 234 # OK
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100305
306White space is required around most operators.
307
308White space is not allowed:
309- Between a function name and the "(": >
310 call Func (arg) " Error!
311 call Func
312 \ (arg) " Error!
313 call Func(arg) " OK
314 call Func(
315 \ arg) " OK
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100316 call Func(
317 \ arg " OK
318 \ )
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100319
320
321Conditions and expressions ~
322
323Conditions and expression are mostly working like they do in JavaScript. A
324difference is made where JavaScript does not work like most people expect.
325Specifically, an empty list is falsey.
326
327Any type of variable can be used as a condition, there is no error, not even
328for using a list or job. This is very much like JavaScript, but there are a
329few exceptions.
330
331 type TRUE when ~
332 bool v:true
333 number non-zero
334 float non-zero
335 string non-empty
336 blob non-empty
337 list non-empty (different from JavaScript)
338 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200339 func when there is a function name
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100340 special v:true
341 job when not NULL
342 channel when not NULL
343 class when not NULL
344 object when not NULL (TODO: when isTrue() returns v:true)
345
346The boolean operators "||" and "&&" do not change the value: >
347 8 || 2 == 8
348 0 || 2 == 2
349 0 || '' == ''
350 8 && 2 == 2
351 0 && 2 == 0
352 [] && 2 == []
353
354When using `..` for string concatenation the arguments are always converted to
355string. >
356 'hello ' .. 123 == 'hello 123'
357 'hello ' .. v:true == 'hello true'
358
359In Vim9 script one can use "true" for v:true and "false" for v:false.
360
361
362==============================================================================
363
3643. New style functions *fast-functions*
365
366THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
367
368 *:def*
369:def[!] {name}([arguments])[: {return-type}
370 Define a new function by the name {name}. The body of
371 the function follows in the next lines, until the
372 matching `:enddef`.
373
Bram Moolenaard77a8522020-04-03 21:59:57 +0200374 When {return-type} is omitted or is "void" the
375 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100376
377 {arguments} is a sequence of zero or more argument
378 declarations. There are three forms:
379 {name}: {type}
380 {name} = {value}
381 {name}: {type} = {value}
382 The first form is a mandatory argument, the caller
383 must always provide them.
384 The second and third form are optional arguments.
385 When the caller omits an argument the {value} is used.
386
Bram Moolenaar560979e2020-02-04 22:53:05 +0100387 NOTE: It is possible to nest `:def` inside another
388 `:def`, but it is not possible to nest `:def` inside
389 `:function`, for backwards compatibility.
390
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100391 [!] is used as with `:function`.
392
393 *:enddef*
394:enddef End of a function defined with `:def`.
395
396
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100397If the script the function is defined in is Vim9 script, then script-local
398variables can be accessed without the "s:" prefix. They must be defined
399before the function. If the script the function is defined in is legacy
400script, then script-local variables must be accessed with the "s:" prefix.
401
402
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100403 *:disa* *:disassemble*
404:disa[ssemble] {func} Show the instructions generated for {func}.
405 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100406 Note that for command line completion of {func} you
407 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +0100408
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100409==============================================================================
410
4114. Types *vim9-types*
412
413THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
414
415The following builtin types are supported:
416 bool
417 number
418 float
419 string
420 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +0200421 list<{type}>
422 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100423 job
424 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +0100425 func
Bram Moolenaard1caa942020-04-10 22:10:56 +0200426 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +0200427 func({type}, ...)
428 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100429
430Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +0200431 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100432
Bram Moolenaard77a8522020-04-03 21:59:57 +0200433These types can be used in declarations, but no value will have this type:
434 {type}|{type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100435 void
436 any
437
Bram Moolenaard77a8522020-04-03 21:59:57 +0200438There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100439efficient implementation is used that avoids allocating lot of small pieces of
440memory.
441
Bram Moolenaard77a8522020-04-03 21:59:57 +0200442A partial and function can be declared in more or less specific ways:
443func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200444 checking for arguments or return value
Bram Moolenaard77a8522020-04-03 21:59:57 +0200445func: {type} any number and type of arguments with specific
446 return type
Bram Moolenaard1caa942020-04-10 22:10:56 +0200447func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +0200448 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +0200449func({type}): {type} function with argument type and return type
450func(?{type}) function with type of optional argument, does
451 not return a value
452func(...{type}) function with type of variable number of
453 arguments, does not return a value
454func({type}, ?{type}, ...{type}): {type}
455 function with:
456 - type of mandatory argument
457 - type of optional argument
458 - type of variable number of arguments
459 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +0200460
461If the return type is "void" the function does not return a value.
462
463The reference can also be a |Partial|, in which case it stores extra arguments
464and/or a dictionary, which are not visible to the caller. Since they are
465called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100466
467Custom types can be defined with `:type`: >
468 :type MyList list<string>
469{not implemented yet}
470
471And classes and interfaces can be used as types: >
472 :class MyClass
473 :let mine: MyClass
474
475 :interface MyInterface
476 :let mine: MyInterface
477
478 :class MyTemplate<Targ>
479 :let mine: MyTemplate<number>
480 :let mine: MyTemplate<string>
481
482 :class MyInterface<Targ>
483 :let mine: MyInterface<number>
484 :let mine: MyInterface<string>
485{not implemented yet}
486
487
488Type inference *type-inference*
489
490In general: Whenever the type is clear it can be omitted. For example, when
491declaring a variable and giving it a value: >
492 let var = 0 " infers number type
493 let var = 'hello' " infers string type
494
495
496==============================================================================
497
4985. Namespace, Import and Export
499 *vim9script* *vim9-export* *vim9-import*
500
501THIS IS STILL UNDER DEVELOPMENT - ANYTHING CAN BREAK - ANYTHING CAN CHANGE
502
503A Vim9 script can be written to be imported. This means that everything in
504the script is local, unless exported. Those exported items, and only those
505items, can then be imported in another script.
506
507
508Namespace ~
509 *:vim9script* *:vim9*
Bram Moolenaar560979e2020-02-04 22:53:05 +0100510To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100511appear as the first statement in the file. It tells Vim to interpret the
512script in its own namespace, instead of the global namespace. If a file
513starts with: >
514 vim9script
515 let myvar = 'yes'
516Then "myvar" will only exist in this file. While without `vim9script` it would
517be available as `g:myvar` from any other script and function.
518
519The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200520variables in legacy Vim script, but the "s:" is omitted. And they cannot be
521deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100522
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200523In Vim9 script the global "g:" namespace can still be used as before. And the
524"w:", "b:" and "t:" namespaces. These have in common that variables are not
525declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100526
527A side effect of `:vim9script` is that the 'cpoptions' option is set to the
528Vim default value, like with: >
529 :set cpo&vim
530One of the effects is that |line-continuation| is always enabled.
531The original value of 'cpoptions' is restored at the end of the script.
532
533
534Export ~
535 *:export* *:exp*
536Exporting one item can be written as: >
537 export const EXPORTED_CONST = 1234
538 export let someValue = ...
539 export def MyFunc() ...
540 export class MyClass ...
541
542As this suggests, only constants, variables, `:def` functions and classes can
543be exported.
544
545Alternatively, an export statement can be used to export several already
546defined (otherwise script-local) items: >
547 export {EXPORTED_CONST, someValue, MyFunc, MyClass}
548
549
550Import ~
551 *:import* *:imp*
552The exported items can be imported individually in another Vim9 script: >
553 import EXPORTED_CONST from "thatscript.vim"
554 import MyClass from "myclass.vim"
555
556To import multiple items at the same time: >
557 import {someValue, MyClass} from "thatscript.vim"
558
Bram Moolenaar560979e2020-02-04 22:53:05 +0100559In case the name is ambiguous, another name can be specified: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100560 import MyClass as ThatClass from "myclass.vim"
561 import {someValue, MyClass as ThatClass} from "myclass.vim"
562
563To import all exported items under a specific identifier: >
564 import * as That from 'thatscript.vim'
565
566Then you can use "That.EXPORTED_CONST", "That.someValue", etc. You are free
567to choose the name "That", but it is highly recommended to use the name of the
568script file to avoid confusion.
569
570The script name after `import` can be:
571- A relative path, starting "." or "..". This finds a file relative to the
572 location of the script file itself. This is useful to split up a large
573 plugin into several files.
574- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
575 will be rarely used.
576- A path not being relative or absolute. This will be found in the
577 "import" subdirectories of 'runtimepath' entries. The name will usually be
578 longer and unique, to avoid loading the wrong file.
579
580Once a vim9 script file has been imported, the result is cached and used the
581next time the same script is imported. It will not be read again.
582 *:import-cycle*
583The `import` commands are executed when encountered. If that script (directly
584or indirectly) imports the current script, then items defined after the
585`import` won't be processed yet. Therefore cyclic imports can exist, but may
586result in undefined items.
587
588
589Import in an autoload script ~
590
591For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaar560979e2020-02-04 22:53:05 +0100592actually needed. A recommended mechanism:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100593
5941. In the plugin define user commands, functions and/or mappings that refer to
595 an autoload script. >
596 command -nargs=1 SearchForStuff call searchfor#Stuff(<f-args>)
597
598< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
599
6002. In the autocommand script do the actual work. You can import items from
601 other files to split up functionality in appropriate pieces. >
602 vim9script
603 import FilterFunc from "../import/someother.vim"
604 def searchfor#Stuff(arg: string)
605 let filtered = FilterFunc(arg)
606 ...
607< This goes in .../autoload/searchfor.vim. "searchfor" in the file name
608 must be exactly the same as the prefix for the function name, that is how
609 Vim finds the file.
610
6113. Other functionality, possibly shared between plugins, contains the exported
612 items and any private items. >
613 vim9script
614 let localVar = 'local'
615 export def FilterFunc(arg: string): string
616 ...
617< This goes in .../import/someother.vim.
618
619
620Import in legacy Vim script ~
621
622If an `import` statement is used in legacy Vim script, for identifier the
623script-local "s:" namespace will be used, even when "s:" is not specified.
624
625
626==============================================================================
627
6289. Rationale *vim9-rationale*
629
630The :def command ~
631
632Plugin writers have asked for a much faster Vim script. Investigation have
Bram Moolenaar560979e2020-02-04 22:53:05 +0100633shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100634impossible, because of the overhead involved with calling a function, setting
635up the local function scope and executing lines. There are many details that
636need to be handled, such as error messages and exceptions. The need to create
637a dictionary for a: and l: scopes, the a:000 list and several others add too
638much overhead that cannot be avoided.
639
640Therefore the `:def` method to define a new-style function had to be added,
641which allows for a function with different semantics. Most things still work
642as before, but some parts do not. A new way to define a function was
643considered the best way to separate the old-style code from Vim9 script code.
644
645Using "def" to define a function comes from Python. Other languages use
646"function" which clashes with legacy Vim script.
647
648
649Type checking ~
650
651When compiling lines of Vim commands into instructions as much as possible
652should be done at compile time. Postponing it to runtime makes the execution
653slower and means mistakes are found only later. For example, when
654encountering the "+" character and compiling this into a generic add
655instruction, at execution time the instruction would have to inspect the type
656of the arguments and decide what kind of addition to do. And when the
657type is dictionary throw an error. If the types are known to be numbers then
658an "add number" instruction can be used, which is faster. The error can be
659given at compile time, no error handling is needed at runtime.
660
661The syntax for types is similar to Java, since it is easy to understand and
662widely used. The type names are what was used in Vim before, with some
663additions such as "void" and "bool".
664
665
666JavaScript/TypeScript syntax and semantics ~
667
668Script writers have complained that the Vim script syntax is unexpectedly
669different from what they are used to. To reduce this complaint popular
670languages will be used as an example. At the same time, we do not want to
Bram Moolenaar560979e2020-02-04 22:53:05 +0100671abandon the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100672
673Since Vim already uses `:let` and `:const` and optional type checking is
674desirable, the JavaScript/TypeScript syntax fits best for variable
675declarations. >
676 const greeting = 'hello' " string type is inferred
677 let name: string
678 ...
679 name = 'John'
680
681Expression evaluation was already close to what JavaScript and other languages
682are doing. Some details are unexpected and can be fixed. For example how the
683|| and && operators work. Legacy Vim script: >
684 let result = 44
685 ...
686 return result || 0 " returns 1
687
688Vim9 script works like JavaScript, keep the value: >
689 let result = 44
690 ...
691 return result || 0 " returns 44
692
693On the other hand, overloading "+" to use both for addition and string
694concatenation goes against legacy Vim script and often leads to mistakes.
695For that reason we will keep using ".." for string concatenation. Lua also
696uses ".." this way.
697
698
699Import and Export ~
700
701A problem of legacy Vim script is that by default all functions and variables
702are global. It is possible to make them script-local, but then they are not
703available in other scripts.
704
705In Vim9 script a mechanism very similar to the Javascript import and export
706mechanism is supported. It is a variant to the existing `:source` command
707that works like one would expect:
708- Instead of making everything global by default, everything is script-local,
709 unless exported.
710- When importing a script the symbols that are imported are listed, avoiding
711 name conflicts and failures if later functionality is added.
712- The mechanism allows for writing a big, long script with a very clear API:
713 the exported function(s) and class(es).
714- By using relative paths loading can be much faster for an import inside of a
715 package, no need to search many directories.
716- Once an import has been used, it can be cached and loading it again can be
717 avoided.
718- The Vim-specific use of "s:" to make things script-local can be dropped.
719
720
721Classes ~
722
723Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
724these have never become widespread. When Vim 9 was designed a decision was
725made to phase out these interfaces and concentrate on Vim script, while
726encouraging plugin authors to write code in any language and run it as an
727external tool, using jobs and channels.
728
729Still, using an external tool has disadvantages. An alternative is to convert
730the tool into Vim script. For that to be possible without too much
731translation, and keeping the code fast at the same time, the constructs of the
732tool need to be supported. Since most languages support classes the lack of
733class support in Vim is then a problem.
734
735Previously Vim supported a kind-of object oriented programming by adding
736methods to a dictionary. With some care this could be made to work, but it
737does not look like real classes. On top of that, it's very slow, because of
738the use of dictionaries.
739
740The support of classes in Vim9 script is a "minimal common functionality" of
741class support in most languages. It works mostly like Java, which is the most
742popular programming language.
743
744
745
746 vim:tw=78:ts=8:noet:ft=help:norl: