blob: 94a505773f21a000f9fd96694d5739873c5b4471 [file] [log] [blame]
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001*vim9.txt* For Vim version 8.2. Last change: 2022 Jan 15
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
Bram Moolenaardcc58e02020-12-28 20:53:21 +01007Vim9 script commands and expressions. *Vim9* *vim9*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01008
9Most expression help is in |eval.txt|. This file is about the new syntax and
10features in Vim9 script.
11
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010012
13
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100141. What is Vim9 script? |Vim9-script|
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100152. Differences |vim9-differences|
163. New style functions |fast-functions|
174. Types |vim9-types|
185. Namespace, Import and Export |vim9script|
Bram Moolenaar1d59aa12020-09-19 18:50:13 +0200196. Future work: classes |vim9-classes|
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010020
219. Rationale |vim9-rationale|
22
23==============================================================================
24
Bram Moolenaar2b327002020-12-26 15:39:31 +0100251. What is Vim9 script? *Vim9-script*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010026
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020027Vim script has been growing over time, while preserving backwards
28compatibility. That means bad choices from the past often can't be changed
Bram Moolenaar73fef332020-06-21 22:12:03 +020029and compatibility with Vi restricts possible solutions. Execution is quite
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020030slow, each line is parsed every time it is executed.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010031
Bram Moolenaar7ceefb32020-05-01 16:07:38 +020032The main goal of Vim9 script is to drastically improve performance. This is
33accomplished by compiling commands into instructions that can be efficiently
34executed. An increase in execution speed of 10 to 100 times can be expected.
35
36A secondary goal is to avoid Vim-specific constructs and get closer to
37commonly used programming languages, such as JavaScript, TypeScript and Java.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010038
39The performance improvements can only be achieved by not being 100% backwards
Bram Moolenaar388a5d42020-05-26 21:20:45 +020040compatible. For example, making function arguments available in the
41"a:" dictionary adds quite a lot of overhead. In a Vim9 function this
42dictionary is not available. Other differences are more subtle, such as how
43errors are handled.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010044
45The Vim9 script syntax and semantics are used in:
46- a function defined with the `:def` command
47- a script file where the first command is `vim9script`
Bram Moolenaar1d59aa12020-09-19 18:50:13 +020048- an autocommand defined in the context of the above
Bram Moolenaar39f3b142021-02-14 12:57:36 +010049- a command prefixed with the `vim9cmd` command modifier
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010050
Bram Moolenaar82be4842021-01-11 19:40:15 +010051When using `:function` in a Vim9 script file the legacy syntax is used, with
52the highest |scriptversion|. However, this can be confusing and is therefore
53discouraged.
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
Bram Moolenaar1d59aa12020-09-19 18:50:13 +020056rewrite old scripts, they keep working as before. You may want to use a few
57`:def` functions for code that needs to be fast.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010058
Bram Moolenaar96cf4ba2021-04-24 14:15:41 +020059:vim9[cmd] {cmd} *:vim9* *:vim9cmd*
Bram Moolenaar39f3b142021-02-14 12:57:36 +010060 Execute {cmd} using Vim9 script syntax and semantics.
61 Useful when typing a command and in a legacy script or
62 function.
63
Bram Moolenaar96cf4ba2021-04-24 14:15:41 +020064:leg[acy] {cmd} *:leg* *:legacy*
65 Execute {cmd} using legacy script syntax and semantics. Only
66 useful in a Vim9 script or a :def function.
67 Note that {cmd} cannot use local variables, since it is parsed
68 with legacy expression syntax.
69
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010070==============================================================================
71
722. Differences from legacy Vim script *vim9-differences*
73
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020074Overview ~
75
76Brief summary of the differences you will most often encounter when using Vim9
77script and `:def` functions; details are below:
78- Comments start with #, not ": >
Bram Moolenaar82be4842021-01-11 19:40:15 +010079 echo "hello" # comment
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020080- Using a backslash for line continuation is hardly ever needed: >
Bram Moolenaar82be4842021-01-11 19:40:15 +010081 echo "hello "
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020082 .. yourName
83 .. ", how are you?"
Bram Moolenaar5da36052021-12-27 15:39:57 +000084- White space is required in many places to improve readability.
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020085- Assign values without `:let`, declare variables with `:var`: >
Bram Moolenaar82be4842021-01-11 19:40:15 +010086 var count = 0
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020087 count += 3
88- Constants can be declared with `:final` and `:const`: >
Bram Moolenaar82be4842021-01-11 19:40:15 +010089 final matches = [] # add matches
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020090 const names = ['Betty', 'Peter'] # cannot be changed
91- `:final` cannot be used as an abbreviation of `:finally`.
92- Variables and functions are script-local by default.
93- Functions are declared with argument types and return type: >
94 def CallMe(count: number, message: string): bool
95- Call functions without `:call`: >
Bram Moolenaar82be4842021-01-11 19:40:15 +010096 writefile(['done'], 'file.txt')
Bram Moolenaar5da36052021-12-27 15:39:57 +000097- You cannot use old Ex commands `:xit`, `:t`, `:k`, `:append`, `:change`,
98 `:insert`, `:open`, and `:s` or `:d` with only flags.
Bram Moolenaar22863042021-10-16 15:23:36 +010099- You cannot use curly-braces names.
Bram Moolenaard58a3bf2020-09-28 21:48:16 +0200100- A range before a command must be prefixed with a colon: >
Bram Moolenaar82be4842021-01-11 19:40:15 +0100101 :%s/this/that
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200102- Executing a register with "@r" does not work, you can prepend a colon or use
103 `:exe`: >
104 :exe @a
Bram Moolenaar82be4842021-01-11 19:40:15 +0100105- Unless mentioned specifically, the highest |scriptversion| is used.
Bram Moolenaarfd31be22022-01-16 14:46:06 +0000106- When defining an expression mapping, the expression will be evaluated in the
107 context of the script where it was defined.
Bram Moolenaard58a3bf2020-09-28 21:48:16 +0200108
109
Bram Moolenaar2c330432020-04-13 14:41:35 +0200110Comments starting with # ~
111
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200112In legacy Vim script comments start with double quote. In Vim9 script
113comments start with #. >
114 # declarations
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200115 var count = 0 # number of occurrences
Bram Moolenaar2c330432020-04-13 14:41:35 +0200116
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200117The reason is that a double quote can also be the start of a string. In many
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200118places, especially halfway through an expression with a line break, it's hard
119to tell what the meaning is, since both a string and a comment can be followed
120by arbitrary text. To avoid confusion only # comments are recognized. This
121is the same as in shell scripts and Python programs.
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200122
123In Vi # is a command to list text with numbers. In Vim9 script you can use
124`:number` for that. >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +0000125 :101 number
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200126
127To improve readability there must be a space between a command and the #
Bram Moolenaar2b327002020-12-26 15:39:31 +0100128that starts a comment: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100129 var name = value # comment
130 var name = value# error!
Bram Moolenaar2b327002020-12-26 15:39:31 +0100131
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200132Do not start a comment with #{, it looks like the legacy dictionary literal
133and produces an error where this might be confusing. #{{ or #{{{ are OK,
134these can be used to start a fold.
135
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100136In legacy Vim script # is also used for the alternate file name. In Vim9
137script you need to use %% instead. Instead of ## use %%% (stands for all
138arguments).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200139
Bram Moolenaar2c330432020-04-13 14:41:35 +0200140
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100141Vim9 functions ~
142
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200143A function defined with `:def` is compiled. Execution is many times faster,
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200144often 10 to 100 times.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200145
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200146Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200147The syntax is strict, to enforce code that is easy to read and understand.
148
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200149Compilation is done when any of these is encountered:
Bram Moolenaar1b884a02020-12-10 21:11:27 +0100150- the first time the function is called
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200151- when the `:defcompile` command is encountered in the script after the
Bram Moolenaar207f0092020-08-30 17:20:20 +0200152 function was defined
153- `:disassemble` is used for the function.
154- a function that is compiled calls the function or uses it as a function
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200155 reference (so that the argument and return types can be checked)
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200156 *E1091*
157If compilation fails it is not tried again on the next call, instead this
158error is given: "E1091: Function is not compiled: {name}".
Bram Moolenaar4c295022021-05-02 17:19:11 +0200159Compilation will fail when encountering a user command that has not been
160created yet. In this case you can call `execute()` to invoke it at runtime. >
161 def MyFunc()
162 execute('DefinedLater')
163 enddef
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200164
165`:def` has no options like `:function` does: "range", "abort", "dict" or
Bram Moolenaar1b884a02020-12-10 21:11:27 +0100166"closure". A `:def` function always aborts on an error (unless `:silent!` was
Bram Moolenaarfa3b7232021-12-24 13:18:38 +0000167used for the command or the error was caught a `:try` block), does not get a
168range passed cannot be a "dict" function, and can always be a closure.
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200169 *vim9-no-dict-function*
Bram Moolenaar74235772021-06-12 14:53:05 +0200170Later classes will be added, which replaces the "dict function" mechanism.
171For now you will need to pass the dictionary explicitly: >
172 def DictFunc(d: dict<any>, arg: string)
173 echo d[arg]
174 enddef
175 var d = {item: 'value', func: DictFunc}
176 d.func(d, 'item')
177
Bram Moolenaar34cc7d82021-09-21 20:09:51 +0200178You can call a legacy dict function though: >
179 func Legacy() dict
180 echo self.value
181 endfunc
182 def CallLegacy()
183 var d = {func: Legacy, value: 'text'}
184 d.func()
185 enddef
186
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200187The argument types and return type need to be specified. The "any" type can
188be used, type checking will then be done at runtime, like with legacy
189functions.
190
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200191Arguments are accessed by name, without "a:", just like any other language.
192There is no "a:" dictionary or "a:000" list.
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200193 *vim9-variable-arguments*
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200194Variable arguments are defined as the last argument, with a name and have a
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200195list type, similar to TypeScript. For example, a list of numbers: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200196 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100197 for item in itemlist
198 ...
199
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200200When a function argument is optional (it has a default value) passing `v:none`
201as the argument results in using the default value. This is useful when you
202want to specify a value for an argument that comes after an argument that
203should use its default value. Example: >
Bram Moolenaar22863042021-10-16 15:23:36 +0100204 def MyFunc(one = 'one', last = 'last')
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200205 ...
206 enddef
207 MyFunc(v:none, 'LAST') # first argument uses default value 'one'
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200208<
209 *vim9-ignored-argument*
210The argument "_" (an underscore) can be used to ignore the argument. This is
211most useful in callbacks where you don't need it, but do need to give an
212argument to match the call. E.g. when using map() two arguments are passed,
213the key and the value, to ignore the key: >
214 map(myList, (_, v) => v * 2)
215There is no error for using the "_" argument multiple times. No type needs to
216be given.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200217
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100218
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200219Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200220 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200221When using `:function` or `:def` to specify a new function at the script level
222in a Vim9 script, the function is local to the script, as if "s:" was
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200223prefixed. Using the "s:" prefix is optional. To define a global function or
224variable the "g:" prefix must be used. For functions in an autoload script
225the "name#" prefix is sufficient. >
Bram Moolenaarea2d8d22020-07-29 22:11:05 +0200226 def ThisFunction() # script-local
227 def s:ThisFunction() # script-local
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200228 def g:ThatFunction() # global
Bram Moolenaarea2d8d22020-07-29 22:11:05 +0200229 def scriptname#function() # autoload
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200230
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200231When using `:function` or `:def` to specify a nested function inside a `:def`
Bram Moolenaar47003982021-12-05 21:54:04 +0000232function and no namespace was given, this nested function is local to the code
233block it is defined in. In a `:def` function it is not possible to define a
234script-local function. It is possible to define a global function by using
235the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200236
237When referring to a function and no "s:" or "g:" prefix is used, Vim will
Bram Moolenaar13106602020-10-04 16:06:05 +0200238search for the function:
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +0200239- in the function scope, in block scopes
Bram Moolenaar13106602020-10-04 16:06:05 +0200240- in the script scope, possibly imported
241- in the list of global functions
242However, it is recommended to always use "g:" to refer to a global function
243for clarity.
244
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200245Since a script-local function reference can be used without "s:" the name must
Bram Moolenaardad44732021-03-31 20:07:33 +0200246start with an upper case letter even when using the "s:" prefix. In legacy
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200247script "s:funcref" could be used, because it could not be referred to with
248"funcref". In Vim9 script it can, therefore "s:Funcref" must be used to avoid
249that the name interferes with builtin functions.
250
Bram Moolenaar13106602020-10-04 16:06:05 +0200251In all cases the function must be defined before used. That is when it is
Bram Moolenaarcb80aa22020-10-26 21:12:46 +0100252called, when `:defcompile` causes it to be compiled, or when code that calls
253it is being compiled (to figure out the return type).
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200254
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200255The result is that functions and variables without a namespace can usually be
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200256found in the script, either defined there or imported. Global functions and
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200257variables could be defined anywhere (good luck finding out where!).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200258
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200259Global functions can still be defined and deleted at nearly any time. In
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200260Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200261and cannot be deleted or replaced.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200262
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100263When compiling a function and a function call is encountered for a function
264that is not (yet) defined, the |FuncUndefined| autocommand is not triggered.
265You can use an autoload function if needed, or call a legacy function and have
266|FuncUndefined| triggered there.
267
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200268
Bram Moolenaar2b327002020-12-26 15:39:31 +0100269Reloading a Vim9 script clears functions and variables by default ~
270 *vim9-reload*
271When loading a legacy Vim script a second time nothing is removed, the
272commands will replace existing variables and functions and create new ones.
273
274When loading a Vim9 script a second time all existing script-local functions
275and variables are deleted, thus you start with a clean slate. This is useful
276if you are developing a plugin and want to try a new version. If you renamed
277something you don't have to worry about the old name still hanging around.
278
279If you do want to keep items, use: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100280 vim9script noclear
Bram Moolenaar2b327002020-12-26 15:39:31 +0100281
282You want to use this in scripts that use a `finish` command to bail out at
283some point when loaded again. E.g. when a buffer local option is set: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100284 vim9script noclear
Bram Moolenaar2b327002020-12-26 15:39:31 +0100285 setlocal completefunc=SomeFunc
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100286 if exists('*g:SomeFunc') | finish | endif
Bram Moolenaar2b327002020-12-26 15:39:31 +0100287 def g:SomeFunc()
288 ....
289
Bram Moolenaar2b327002020-12-26 15:39:31 +0100290
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200291Variable declarations with :var, :final and :const ~
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200292 *vim9-declaration* *:var*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200293Local variables need to be declared with `:var`. Local constants need to be
294declared with `:final` or `:const`. We refer to both as "variables" in this
295section.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100296
297Variables can be local to a script, function or code block: >
298 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200299 var script_var = 123
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100300 def SomeFunc()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200301 var func_var = script_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100302 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200303 var block_var = func_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100304 ...
305
306The variables are only visible in the block where they are defined and nested
307blocks. Once the block ends the variable is no longer accessible: >
308 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200309 var inner = 5
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100310 else
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200311 var inner = 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100312 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200313 echo inner # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100314
315The declaration must be done earlier: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200316 var inner: number
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100317 if cond
318 inner = 5
319 else
320 inner = 0
321 endif
322 echo inner
323
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200324To intentionally hide a variable from code that follows, a block can be
325used: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100326 {
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200327 var temp = 'temp'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100328 ...
329 }
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200330 echo temp # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100331
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200332This is especially useful in a user command: >
333
334 command -range Rename {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200335 var save = @a
336 @a = 'some expression'
337 echo 'do something with ' .. @a
338 @a = save
339 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200340
341And with autocommands: >
342
343 au BufWritePre *.go {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200344 var save = winsaveview()
345 silent! exe ':%! some formatting command'
346 winrestview(save)
347 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200348
349Although using a :def function probably works better.
350
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200351Declaring a variable with a type but without an initializer will initialize to
Bram Moolenaar1f318c62021-12-26 18:09:31 +0000352false (for bool), empty (for string, list, dict, etc.) or zero (for number,
353any, etc.). This matters especially when using the "any" type, the value will
354default to the number zero.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200355
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200356In Vim9 script `:let` cannot be used. An existing variable is assigned to
357without any command. The same for global, window, tab, buffer and Vim
Bram Moolenaar5da36052021-12-27 15:39:57 +0000358variables, because they are not really declared. Those can also be deleted
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200359with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100360
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200361`:lockvar` does not work on local variables. Use `:const` and `:final`
362instead.
363
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200364The `exists()` and `exists_compiled()` functions do not work on local variables
365or arguments.
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200366
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100367Variables, functions and function arguments cannot shadow previously defined
368or imported variables and functions in the same script file.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100369Variables may shadow Ex commands, rename the variable if needed.
370
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200371Global variables must be prefixed with "g:", also at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200372 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200373 var script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200374 g:global = 'value'
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200375 var Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200376
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200377Global functions must be prefixed with "g:" when defining them, but can be
378called without "g:". >
379 vim9script
380 def g:GlobalFunc(): string
381 return 'text'
382 enddef
383 echo GlobalFunc()
384The "g:" prefix is not needed for auto-load functions.
385
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200386 *vim9-function-defined-later*
387Although global functions can be called without the "g:" prefix, they must
388exist when compiled. By adding the "g:" prefix the function can be defined
389later. Example: >
390 def CallPluginFunc()
391 if exists('g:loaded_plugin')
392 g:PluginFunc()
393 endif
394 enddef
395
Bram Moolenaarb79ee0c2022-01-01 12:17:00 +0000396If you do it like this, you get an error at compile time that "PluginFunc"
397does not exist, even when "g:loaded_plugin" does not exist: >
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200398 def CallPluginFunc()
399 if exists('g:loaded_plugin')
400 PluginFunc() # Error - function not found
401 endif
402 enddef
403
404You can use exists_compiled() to avoid the error, but then the function would
405not be called, even when "g:loaded_plugin" is defined later: >
406 def CallPluginFunc()
407 if exists_compiled('g:loaded_plugin')
408 PluginFunc() # Function may never be called
409 endif
410 enddef
411
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200412Since `&opt = value` is now assigning a value to option "opt", ":&" cannot be
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100413used to repeat a `:substitute` command.
Bram Moolenaar56994d22021-04-17 16:31:09 +0200414 *vim9-unpack-ignore*
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200415For an unpack assignment the underscore can be used to ignore a list item,
416similar to how a function argument can be ignored: >
417 [a, _, c] = theList
Bram Moolenaar56994d22021-04-17 16:31:09 +0200418To ignore any remaining items: >
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200419 [a, b; _] = longList
420
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200421Declaring more than one variable at a time, using the unpack notation, is
Bram Moolenaarab36e6a2021-11-30 16:14:49 +0000422possible. Each variable can have a type or infer it from the value: >
423 var [v1: number, v2] = GetValues()
424Use this only when there is a list with values, declaring one variable per
425line is much easier to read and change later.
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200426
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200427
428Constants ~
429 *vim9-const* *vim9-final*
430How constants work varies between languages. Some consider a variable that
431can't be assigned another value a constant. JavaScript is an example. Others
432also make the value immutable, thus when a constant uses a list, the list
433cannot be changed. In Vim9 we can use both.
434
435`:const` is used for making both the variable and the value a constant. Use
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200436this for composite structures that you want to make sure will not be modified.
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200437Example: >
438 const myList = [1, 2]
439 myList = [3, 4] # Error!
440 myList[0] = 9 # Error!
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100441 myList->add(3) # Error!
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200442< *:final*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200443`:final` is used for making only the variable a constant, the value can be
444changed. This is well known from Java. Example: >
445 final myList = [1, 2]
446 myList = [3, 4] # Error!
447 myList[0] = 9 # OK
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100448 myList->add(3) # OK
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200449
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200450It is common to write constants as ALL_CAPS, but you don't have to.
451
452The constant only applies to the value itself, not what it refers to. >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200453 final females = ["Mary"]
454 const NAMES = [["John", "Peter"], females]
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200455 NAMES[0] = ["Jack"] # Error!
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200456 NAMES[0][0] = "Jack" # Error!
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200457 NAMES[1] = ["Emma"] # Error!
Bram Moolenaar82be4842021-01-11 19:40:15 +0100458 NAMES[1][0] = "Emma" # OK, now females[0] == "Emma"
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200459
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100460
461Omitting :call and :eval ~
462
463Functions can be called without `:call`: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200464 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100465Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100466
467A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0289a092021-03-14 18:40:19 +0100468identifier or can't be an Ex command. For a function either "(" or "->" must
469be following, without a line break. Examples: >
Bram Moolenaarae616492020-07-28 20:07:27 +0200470 myList->add(123)
471 g:myList->add(123)
472 [1, 2, 3]->Process()
Bram Moolenaar2bede172020-11-19 18:53:18 +0100473 {a: 1, b: 2}->Process()
Bram Moolenaarae616492020-07-28 20:07:27 +0200474 "foobar"->Process()
475 ("foobar")->Process()
476 'foobar'->Process()
477 ('foobar')->Process()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100478
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200479In the rare case there is ambiguity between a function name and an Ex command,
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200480prepend ":" to make clear you want to use the Ex command. For example, there
481is both the `:substitute` command and the `substitute()` function. When the
482line starts with `substitute(` this will use the function. Prepend a colon to
483use the command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100484 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100485
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200486If the expression starts with "!" this is interpreted as a shell command, not
487negation of a condition. Thus this is a shell command: >
488 !shellCommand->something
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200489Put the expression in parentheses to use the "!" for negation: >
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200490 (!expression)->Method()
491
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100492Note that while variables need to be defined before they can be used,
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200493functions can be called before being defined. This is required to allow
494for cyclic dependencies between functions. It is slightly less efficient,
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100495since the function has to be looked up by name. And a typo in the function
Bram Moolenaarae616492020-07-28 20:07:27 +0200496name will only be found when the function is called.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100497
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100498
Bram Moolenaard1caa942020-04-10 22:10:56 +0200499Omitting function() ~
500
501A user defined function can be used as a function reference in an expression
502without `function()`. The argument types and return type will then be checked.
503The function must already have been defined. >
504
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200505 var Funcref = MyFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200506
507When using `function()` the resulting type is "func", a function with any
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200508number of arguments and any return type (including void). The function can be
Bram Moolenaarfa3b7232021-12-24 13:18:38 +0000509defined later if the argument is in quotes.
Bram Moolenaard1caa942020-04-10 22:10:56 +0200510
511
Bram Moolenaar2b327002020-12-26 15:39:31 +0100512Lambda using => instead of -> ~
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200513 *vim9-lambda*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100514In legacy script there can be confusion between using "->" for a method call
515and for a lambda. Also, when a "{" is found the parser needs to figure out if
516it is the start of a lambda or a dictionary, which is now more complicated
517because of the use of argument types.
518
519To avoid these problems Vim9 script uses a different syntax for a lambda,
Bram Moolenaar74235772021-06-12 14:53:05 +0200520which is similar to JavaScript: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100521 var Lambda = (arg) => expression
522
Bram Moolenaar2b327002020-12-26 15:39:31 +0100523No line break is allowed in the arguments of a lambda up to and including the
Bram Moolenaar4d8f4762021-06-27 15:18:56 +0200524"=>" (so that Vim can tell the difference between an expression in parentheses
Bram Moolenaar2346a632021-06-13 19:02:49 +0200525and lambda arguments). This is OK: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100526 filter(list, (k, v) =>
527 v > 0)
528This does not work: >
529 filter(list, (k, v)
530 => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100531This also does not work: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100532 filter(list, (k,
533 v) => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100534But you can use a backslash to concatenate the lines before parsing: >
535 filter(list, (k,
536 \ v)
537 \ => v > 0)
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200538< *vim9-lambda-arguments*
539In legacy script a lambda could be called with any number of extra arguments,
540there was no way to warn for not using them. In Vim9 script the number of
541arguments must match. If you do want to accept any arguments, or any further
542arguments, use "..._", which makes the function accept
543|vim9-variable-arguments|. Example: >
544 var Callback = (..._) => 'anything'
545 echo Callback(1, 2, 3) # displays "anything"
546
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200547< *inline-function*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100548Additionally, a lambda can contain statements in {}: >
549 var Lambda = (arg) => {
550 g:was_called = 'yes'
551 return expression
552 }
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200553This can be useful for a timer, for example: >
554 var count = 0
555 var timer = timer_start(500, (_) => {
556 count += 1
557 echom 'Handler called ' .. count
558 }, {repeat: 3})
559
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200560The ending "}" must be at the start of a line. It can be followed by other
561characters, e.g.: >
562 var d = mapnew(dict, (k, v): string => {
563 return 'value'
564 })
565No command can follow the "{", only a comment can be used there.
566
Bram Moolenaar259f4432021-12-17 12:45:22 +0000567 *command-block*
568The block can also be used for defining a user command. Inside the block Vim9
569syntax will be used.
570
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000571If the statements include a dictionary, its closing bracket must not be
572written at the start of a line. Otherwise, it would be parsed as the end of
573the block. This does not work: >
574 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000575 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000576 'key': 'value',
577 } # ERROR: will be recognized as the end of the block
578 }
579Put the '}' after the last item to avoid this: >
580 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000581 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000582 'key': 'value' }
583 }
584
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200585Rationale: The "}" cannot be after a command because it would require parsing
586the commands to find it. For consistency with that no command can follow the
587"{". Unfortunately this means using "() => { command }" does not work, line
588breaks are always required.
Bram Moolenaar65c44152020-12-24 15:14:01 +0100589
Bram Moolenaare0e39172021-01-25 21:14:57 +0100590 *vim9-curly*
Bram Moolenaar2b327002020-12-26 15:39:31 +0100591To avoid the "{" of a dictionary literal to be recognized as a statement block
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100592wrap it in parentheses: >
Bram Moolenaar2b327002020-12-26 15:39:31 +0100593 var Lambda = (arg) => ({key: 42})
Bram Moolenaar65c44152020-12-24 15:14:01 +0100594
Bram Moolenaare0e39172021-01-25 21:14:57 +0100595Also when confused with the start of a command block: >
596 ({
597 key: value
598 })->method()
599
Bram Moolenaar65c44152020-12-24 15:14:01 +0100600
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200601Automatic line continuation ~
Bram Moolenaar5da36052021-12-27 15:39:57 +0000602 *vim9-line-continuation*
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200603In many cases it is obvious that an expression continues on the next line. In
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100604those cases there is no need to prefix the line with a backslash (see
605|line-continuation|). For example, when a list spans multiple lines: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200606 var mylist = [
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200607 'one',
608 'two',
609 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200610And when a dict spans multiple lines: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100611 var mydict = {
Bram Moolenaare6085c52020-04-12 20:19:16 +0200612 one: 1,
613 two: 2,
614 }
Bram Moolenaar74235772021-06-12 14:53:05 +0200615With a function call: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200616 var result = Func(
Bram Moolenaare6085c52020-04-12 20:19:16 +0200617 arg1,
618 arg2
619 )
620
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200621For binary operators in expressions not in [], {} or () a line break is
622possible just before or after the operator. For example: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200623 var text = lead
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200624 .. middle
625 .. end
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200626 var total = start +
Bram Moolenaar82be4842021-01-11 19:40:15 +0100627 end -
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200628 correction
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200629 var result = positive
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200630 ? PosFunc(arg)
631 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200632
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200633For a method call using "->" and a member using a dot, a line break is allowed
634before it: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200635 var result = GetBuilder()
Bram Moolenaar73fef332020-06-21 22:12:03 +0200636 ->BuilderSetWidth(333)
637 ->BuilderSetHeight(777)
638 ->BuilderBuild()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200639 var result = MyDict
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200640 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200641
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100642For commands that have an argument that is a list of commands, the | character
643at the start of the line indicates line continuation: >
644 autocmd BufNewFile *.match if condition
645 | echo 'match'
646 | endif
647
Bram Moolenaar22863042021-10-16 15:23:36 +0100648Note that this means that in heredoc the first line cannot start with a bar: >
Bram Moolenaar74235772021-06-12 14:53:05 +0200649 var lines =<< trim END
650 | this doesn't work
651 END
652Either use an empty line at the start or do not use heredoc. Or temporarily
653add the "C" flag to 'cpoptions': >
654 set cpo+=C
655 var lines =<< trim END
Bram Moolenaar22863042021-10-16 15:23:36 +0100656 | this works
Bram Moolenaar74235772021-06-12 14:53:05 +0200657 END
658 set cpo-=C
659If the heredoc is inside a function 'cpoptions' must be set before :def and
660restored after the :enddef.
661
662In places where line continuation with a backslash is still needed, such as
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200663splitting up a long Ex command, comments can start with '#\ ': >
664 syn region Text
Bram Moolenaar74235772021-06-12 14:53:05 +0200665 \ start='foo'
666 #\ comment
667 \ end='bar'
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200668Like with legacy script '"\ ' is used. This is also needed when line
669continuation is used without a backslash and a line starts with a bar: >
670 au CursorHold * echom 'BEFORE bar'
671 #\ some comment
672 | echom 'AFTER bar'
673<
674 *E1050*
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200675To make it possible for the operator at the start of the line to be
Bram Moolenaar74235772021-06-12 14:53:05 +0200676recognized, it is required to put a colon before a range. This example will
677add "start" and print: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200678 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200679 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200680Like this: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200681 var result = start + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200682
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200683This will assign "start" and print a line: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200684 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200685 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200686
Bram Moolenaar23515b42020-11-29 14:36:24 +0100687Note that the colon is not required for the |+cmd| argument: >
688 edit +6 fname
689
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200690It is also possible to split a function header over multiple lines, in between
691arguments: >
692 def MyFunc(
693 text: string,
694 separator = '-'
695 ): string
696
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100697Since a continuation line cannot be easily recognized the parsing of commands
Bram Moolenaar65c44152020-12-24 15:14:01 +0100698has been made stricter. E.g., because of the error in the first line, the
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100699second line is seen as a separate command: >
700 popup_create(some invalid expression, {
701 exit_cb: Func})
702Now "exit_cb: Func})" is actually a valid command: save any changes to the
703file "_cb: Func})" and exit. To avoid this kind of mistake in Vim9 script
704there must be white space between most command names and the argument.
705
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100706However, the argument of a command that is a command won't be recognized. For
707example, after "windo echo expr" a line break inside "expr" will not be seen.
708
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100709
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200710Notes:
711- "enddef" cannot be used at the start of a continuation line, it ends the
712 current function.
713- No line break is allowed in the LHS of an assignment. Specifically when
714 unpacking a list |:let-unpack|. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200715 [var1, var2] =
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200716 Func()
717< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200718 [var1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200719 var2] =
720 Func()
721- No line break is allowed in between arguments of an `:echo`, `:execute` and
722 similar commands. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200723 echo [1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200724 2] [3,
725 4]
726< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200727 echo [1, 2]
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200728 [3, 4]
Bram Moolenaar74235772021-06-12 14:53:05 +0200729- In some cases it is difficult for Vim to parse a command, especially when
730 commands are used as an argument to another command, such as `windo`. In
731 those cases the line continuation with a backslash has to be used.
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200732
Bram Moolenaar4c295022021-05-02 17:19:11 +0200733
734White space ~
735
736Vim9 script enforces proper use of white space. This is no longer allowed: >
737 var name=234 # Error!
738 var name= 234 # Error!
739 var name =234 # Error!
740There must be white space before and after the "=": >
741 var name = 234 # OK
742White space must also be put before the # that starts a comment after a
743command: >
744 var name = 234# Error!
745 var name = 234 # OK
746
747White space is required around most operators.
748
749White space is required in a sublist (list slice) around the ":", except at
750the start and end: >
751 otherlist = mylist[v : count] # v:count has a different meaning
752 otherlist = mylist[:] # make a copy of the List
753 otherlist = mylist[v :]
754 otherlist = mylist[: v]
755
756White space is not allowed:
757- Between a function name and the "(": >
758 Func (arg) # Error!
759 Func
760 \ (arg) # Error!
761 Func
762 (arg) # Error!
763 Func(arg) # OK
764 Func(
765 arg) # OK
766 Func(
767 arg # OK
768 )
769
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200770White space is not allowed in a `:set` command between the option name and a
771following "&", "!", "<", "=", "+=", "-=" or "^=".
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200772
Bram Moolenaar4c295022021-05-02 17:19:11 +0200773
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100774No curly braces expansion ~
775
776|curly-braces-names| cannot be used.
777
778
Bram Moolenaar2bede172020-11-19 18:53:18 +0100779Dictionary literals ~
Bram Moolenaar5da36052021-12-27 15:39:57 +0000780 *vim9-literal-dict*
Bram Moolenaar2bede172020-11-19 18:53:18 +0100781Traditionally Vim has supported dictionary literals with a {} syntax: >
782 let dict = {'key': value}
783
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100784Later it became clear that using a simple text key is very common, thus
785literal dictionaries were introduced in a backwards compatible way: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100786 let dict = #{key: value}
787
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100788However, this #{} syntax is unlike any existing language. As it turns out
789that using a literal key is much more common than using an expression, and
Bram Moolenaar2bede172020-11-19 18:53:18 +0100790considering that JavaScript uses this syntax, using the {} form for dictionary
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100791literals is considered a much more useful syntax. In Vim9 script the {} form
Bram Moolenaar2bede172020-11-19 18:53:18 +0100792uses literal keys: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100793 var dict = {key: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100794
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100795This works for alphanumeric characters, underscore and dash. If you want to
796use another character, use a single or double quoted string: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100797 var dict = {'key with space': value}
798 var dict = {"key\twith\ttabs": value}
799 var dict = {'': value} # empty key
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100800
801In case the key needs to be an expression, square brackets can be used, just
802like in JavaScript: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100803 var dict = {["key" .. nr]: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100804
Bram Moolenaar2e5910b2021-02-03 17:41:24 +0100805The key type can be string, number, bool or float. Other types result in an
806error. A number can be given with and without the []: >
807 var dict = {123: 'without', [456]: 'with'}
808 echo dict
809 {'456': 'with', '123': 'without'}
810
Bram Moolenaar2bede172020-11-19 18:53:18 +0100811
Bram Moolenaar10b94212021-02-19 21:42:57 +0100812No :xit, :t, :k, :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100813
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200814These commands are too easily confused with local variable names.
815Instead of `:x` or `:xit` you can use `:exit`.
816Instead of `:t` you can use `:copy`.
Bram Moolenaar10b94212021-02-19 21:42:57 +0100817Instead of `:k` you can use `:mark`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100818
819
820Comparators ~
821
822The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100823
824
Bram Moolenaar4c295022021-05-02 17:19:11 +0200825Abort after error ~
826
827In legacy script, when an error is encountered, Vim continues to execute
828following lines. This can lead to a long sequence of errors and need to type
829CTRL-C to stop it. In Vim9 script execution of commands stops at the first
830error. Example: >
831 vim9script
832 var x = does-not-exist
833 echo 'not executed'
834
835
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100836For loop ~
837
Bram Moolenaar47003982021-12-05 21:54:04 +0000838The loop variable must not be declared yet: >
Bram Moolenaar6304be62021-11-27 10:57:26 +0000839 var i = 1
840 for i in [1, 2, 3] # Error!
841
Bram Moolenaar47003982021-12-05 21:54:04 +0000842It is possible to use a global variable though: >
843 g:i = 1
844 for g:i in [1, 2, 3]
845 echo g:i
846 endfor
847
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100848Legacy Vim script has some tricks to make a for loop over a list handle
849deleting items at the current or previous item. In Vim9 script it just uses
850the index, if items are deleted then items in the list will be skipped.
851Example legacy script: >
852 let l = [1, 2, 3, 4]
853 for i in l
854 echo i
855 call remove(l, index(l, i))
856 endfor
857Would echo:
858 1
859 2
860 3
861 4
862In compiled Vim9 script you get:
863 1
864 3
865Generally, you should not change the list that is iterated over. Make a copy
866first if needed.
867
868
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100869Conditions and expressions ~
Bram Moolenaar5da36052021-12-27 15:39:57 +0000870 *vim9-boolean*
Bram Moolenaar13106602020-10-04 16:06:05 +0200871Conditions and expressions are mostly working like they do in other languages.
872Some values are different from legacy Vim script:
873 value legacy Vim script Vim9 script ~
874 0 falsy falsy
875 1 truthy truthy
876 99 truthy Error!
877 "0" falsy Error!
878 "99" truthy Error!
879 "text" falsy Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100880
Bram Moolenaar13106602020-10-04 16:06:05 +0200881For the "??" operator and when using "!" then there is no error, every value
882is either falsy or truthy. This is mostly like JavaScript, except that an
883empty list and dict is falsy:
884
885 type truthy when ~
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100886 bool true, v:true or 1
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100887 number non-zero
888 float non-zero
889 string non-empty
890 blob non-empty
891 list non-empty (different from JavaScript)
892 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200893 func when there is a function name
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100894 special true or v:true
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100895 job when not NULL
896 channel when not NULL
897 class when not NULL
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100898 object when not NULL (TODO: when isTrue() returns true)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100899
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200900The boolean operators "||" and "&&" expect the values to be boolean, zero or
901one: >
902 1 || false == true
903 0 || 1 == true
904 0 || false == false
905 1 && true == true
906 0 && 1 == false
907 8 || 0 Error!
908 'yes' && 0 Error!
909 [] || 99 Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100910
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200911When using "!" for inverting, there is no error for using any type and the
Bram Moolenaar13106602020-10-04 16:06:05 +0200912result is a boolean. "!!" can be used to turn any value into boolean: >
Bram Moolenaar82be4842021-01-11 19:40:15 +0100913 !'yes' == false
Bram Moolenaar13106602020-10-04 16:06:05 +0200914 !![] == false
Bram Moolenaar82be4842021-01-11 19:40:15 +0100915 !![1, 2, 3] == true
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200916
917When using "`.."` for string concatenation arguments of simple types are
Bram Moolenaar13106602020-10-04 16:06:05 +0200918always converted to string: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100919 'hello ' .. 123 == 'hello 123'
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100920 'hello ' .. v:true == 'hello true'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100921
Bram Moolenaar5da36052021-12-27 15:39:57 +0000922Simple types are Number, Float, Special and Bool. For other types |string()|
923should be used.
Bram Moolenaar67977822021-01-03 21:53:53 +0100924 *false* *true* *null*
925In Vim9 script one can use "true" for v:true, "false" for v:false and "null"
926for v:null. When converting a boolean to a string "false" and "true" are
927used, not "v:false" and "v:true" like in legacy script. "v:none" is not
928changed, it is only used in JSON and has no equivalent in other languages.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100929
Bram Moolenaar0289a092021-03-14 18:40:19 +0100930Indexing a string with [idx] or taking a slice with [idx : idx] uses character
931indexes instead of byte indexes. Composing characters are included.
932Example: >
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200933 echo 'bár'[1]
934In legacy script this results in the character 0xc3 (an illegal byte), in Vim9
935script this results in the string 'á'.
Bram Moolenaar82be4842021-01-11 19:40:15 +0100936A negative index is counting from the end, "[-1]" is the last character.
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100937To exclude the last character use |slice()|.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200938To count composing characters separately use |strcharpart()|.
Bram Moolenaar82be4842021-01-11 19:40:15 +0100939If the index is out of range then an empty string results.
940
941In legacy script "++var" and "--var" would be silently accepted and have no
942effect. This is an error in Vim9 script.
943
944Numbers starting with zero are not considered to be octal, only numbers
945starting with "0o" are octal: "0o744". |scriptversion-4|
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200946
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100947
Bram Moolenaare46a4402020-06-30 20:38:27 +0200948What to watch out for ~
949 *vim9-gotchas*
950Vim9 was designed to be closer to often used programming languages, but at the
951same time tries to support the legacy Vim commands. Some compromises had to
952be made. Here is a summary of what might be unexpected.
953
954Ex command ranges need to be prefixed with a colon. >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100955 -> legacy Vim: shifts the previous line to the right
956 ->func() Vim9: method call in a continuation line
957 :-> Vim9: shifts the previous line to the right
Bram Moolenaare46a4402020-06-30 20:38:27 +0200958
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100959 %s/a/b legacy Vim: substitute on all lines
Bram Moolenaare46a4402020-06-30 20:38:27 +0200960 x = alongname
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100961 % another Vim9: modulo operator in a continuation line
962 :%s/a/b Vim9: substitute on all lines
963 't legacy Vim: jump to mark t
964 'text'->func() Vim9: method call
965 :'t Vim9: jump to mark t
Bram Moolenaare46a4402020-06-30 20:38:27 +0200966
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200967Some Ex commands can be confused with assignments in Vim9 script: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100968 g:name = value # assignment
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100969 :g:pattern:cmd # :global command
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200970
Bram Moolenaar7b829262021-10-13 15:04:34 +0100971To avoid confusion between a `:global` or `:substitute` command and an
972expression or assignment, a few separators cannot be used when these commands
973are abbreviated to a single character: ':', '-' and '.'. >
974 g:pattern:cmd # invalid command - ERROR
975 s:pattern:repl # invalid command - ERROR
976 g-pattern-cmd # invalid command - ERROR
977 s-pattern-repl # invalid command - ERROR
978 g.pattern.cmd # invalid command - ERROR
979 s.pattern.repl # invalid command - ERROR
980
981Also, there cannot be a space between the command and the separator: >
982 g /pattern/cmd # invalid command - ERROR
983 s /pattern/repl # invalid command - ERROR
984
Bram Moolenaare46a4402020-06-30 20:38:27 +0200985Functions defined with `:def` compile the whole function. Legacy functions
986can bail out, and the following lines are not parsed: >
987 func Maybe()
988 if !has('feature')
989 return
990 endif
991 use-feature
992 endfunc
993Vim9 functions are compiled as a whole: >
994 def Maybe()
995 if !has('feature')
996 return
997 endif
Bram Moolenaar82be4842021-01-11 19:40:15 +0100998 use-feature # May give a compilation error
Bram Moolenaare46a4402020-06-30 20:38:27 +0200999 enddef
1000For a workaround, split it in two functions: >
1001 func Maybe()
1002 if has('feature')
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001003 call MaybeInner()
Bram Moolenaare46a4402020-06-30 20:38:27 +02001004 endif
1005 endfunc
1006 if has('feature')
1007 def MaybeInner()
1008 use-feature
1009 enddef
1010 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001011Or put the unsupported code inside an `if` with a constant expression that
Bram Moolenaar207f0092020-08-30 17:20:20 +02001012evaluates to false: >
1013 def Maybe()
1014 if has('feature')
1015 use-feature
1016 endif
1017 enddef
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001018The `exists_compiled()` function can also be used for this.
1019 *vim9-user-command*
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001020Another side effect of compiling a function is that the presence of a user
Bram Moolenaar82be4842021-01-11 19:40:15 +01001021command is checked at compile time. If the user command is defined later an
1022error will result. This works: >
1023 command -nargs=1 MyCommand echom <q-args>
1024 def Works()
1025 MyCommand 123
1026 enddef
1027This will give an error for "MyCommand" not being defined: >
1028 def Works()
1029 command -nargs=1 MyCommand echom <q-args>
1030 MyCommand 123
1031 enddef
1032A workaround is to invoke the command indirectly with `:execute`: >
1033 def Works()
1034 command -nargs=1 MyCommand echom <q-args>
1035 execute 'MyCommand 123'
1036 enddef
1037
Bram Moolenaar207f0092020-08-30 17:20:20 +02001038Note that for unrecognized commands there is no check for "|" and a following
1039command. This will give an error for missing `endif`: >
1040 def Maybe()
1041 if has('feature') | use-feature | endif
1042 enddef
Bram Moolenaare46a4402020-06-30 20:38:27 +02001043
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001044Other differences ~
1045
1046Patterns are used like 'magic' is set, unless explicitly overruled.
1047The 'edcompatible' option value is not used.
1048The 'gdefault' option value is not used.
1049
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001050You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaarc8cdf0f2021-03-13 13:28:13 +01001051Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001052
Bram Moolenaar4d8f4762021-06-27 15:18:56 +02001053 *:++* *:--*
1054The ++ and -- commands have been added. They are very similar to adding or
1055subtracting one: >
1056 ++var
1057 var += 1
1058 --var
1059 var -= 1
1060
1061Using ++var or --var in an expression is not supported yet.
1062
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001063==============================================================================
1064
10653. New style functions *fast-functions*
1066
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001067 *:def*
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001068:def[!] {name}([arguments])[: {return-type}]
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001069 Define a new function by the name {name}. The body of
1070 the function follows in the next lines, until the
1071 matching `:enddef`.
1072
Bram Moolenaard77a8522020-04-03 21:59:57 +02001073 When {return-type} is omitted or is "void" the
1074 function is not expected to return anything.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001075
1076 {arguments} is a sequence of zero or more argument
1077 declarations. There are three forms:
1078 {name}: {type}
1079 {name} = {value}
1080 {name}: {type} = {value}
1081 The first form is a mandatory argument, the caller
1082 must always provide them.
1083 The second and third form are optional arguments.
1084 When the caller omits an argument the {value} is used.
1085
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001086 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001087 called, or when `:disassemble` or `:defcompile` is
1088 used. Syntax and type errors will be produced at that
1089 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001090
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001091 It is possible to nest `:def` inside another `:def` or
1092 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +01001093
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001094 [!] is used as with `:function`. Note that
1095 script-local functions cannot be deleted or redefined
1096 later in Vim9 script. They can only be removed by
1097 reloading the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001098
1099 *:enddef*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001100:enddef End of a function defined with `:def`. It should be on
1101 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001102
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001103You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaar0289a092021-03-14 18:40:19 +01001104Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001105
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001106If the script the function is defined in is Vim9 script, then script-local
1107variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001108before the function is compiled. If the script the function is defined in is
1109legacy script, then script-local variables must be accessed with the "s:"
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001110prefix if they do not exist at the time of compiling.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001111
Bram Moolenaar388a5d42020-05-26 21:20:45 +02001112 *:defc* *:defcompile*
1113:defc[ompile] Compile functions defined in the current script that
1114 were not compiled yet.
1115 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001116
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001117 *:disa* *:disassemble*
1118:disa[ssemble] {func} Show the instructions generated for {func}.
1119 This is for debugging and testing.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +01001120 Note that for command line completion of {func} you
1121 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001122
Bram Moolenaar2346a632021-06-13 19:02:49 +02001123:disa[ssemble] profile {func}
1124 Like `:disassemble` but with the instructions used for
Bram Moolenaare0e39172021-01-25 21:14:57 +01001125 profiling.
1126
Bram Moolenaar2346a632021-06-13 19:02:49 +02001127:disa[ssemble] debug {func}
1128 Like `:disassemble` but with the instructions used for
1129 debugging.
1130
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001131Limitations ~
1132
1133Local variables will not be visible to string evaluation. For example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001134 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001135 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001136 return range(1, 2)->map('list[v:val]')
1137 enddef
1138
1139The map argument is a string expression, which is evaluated without the
1140function scope. Instead, use a lambda: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001141 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001142 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar22863042021-10-16 15:23:36 +01001143 return range(1, 2)->map((_, v) => list[v])
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001144 enddef
1145
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001146For commands that are not compiled, such as `:edit`, backtick expansion can be
1147used and it can use the local scope. Example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001148 def Replace()
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001149 var fname = 'blah.txt'
1150 edit `=fname`
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001151 enddef
1152
Bram Moolenaardad44732021-03-31 20:07:33 +02001153Closures defined in a loop will share the same context. For example: >
1154 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001155 for i in range(5)
Bram Moolenaardad44732021-03-31 20:07:33 +02001156 var inloop = i
1157 flist[i] = () => inloop
1158 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001159 echo range(5)->map((i, _) => flist[i]())
1160 # Result: [4, 4, 4, 4, 4]
Bram Moolenaardad44732021-03-31 20:07:33 +02001161
1162The "inloop" variable will exist only once, all closures put in the list refer
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001163to the same instance, which in the end will have the value 4. This is
1164efficient, also when looping many times. If you do want a separate context
1165for each closure call a function to define it: >
1166 def GetClosure(i: number): func
1167 var infunc = i
1168 return () => infunc
Bram Moolenaardad44732021-03-31 20:07:33 +02001169 enddef
1170
1171 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001172 for i in range(5)
1173 flist[i] = GetClosure(i)
Bram Moolenaardad44732021-03-31 20:07:33 +02001174 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001175 echo range(5)->map((i, _) => flist[i]())
1176 # Result: [0, 1, 2, 3, 4]
Bram Moolenaardad44732021-03-31 20:07:33 +02001177
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001178==============================================================================
1179
11804. Types *vim9-types*
1181
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001182The following builtin types are supported:
1183 bool
1184 number
1185 float
1186 string
1187 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +02001188 list<{type}>
1189 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001190 job
1191 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +01001192 func
Bram Moolenaard1caa942020-04-10 22:10:56 +02001193 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +02001194 func({type}, ...)
1195 func({type}, ...): {type}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001196
1197Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +02001198 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001199
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001200These types can be used in declarations, but no simple value will actually
1201have the "void" type.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001202
Bram Moolenaard77a8522020-04-03 21:59:57 +02001203There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001204efficient implementation is used that avoids allocating lot of small pieces of
1205memory.
1206
Bram Moolenaard77a8522020-04-03 21:59:57 +02001207A partial and function can be declared in more or less specific ways:
1208func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +02001209 checking for arguments or return value
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001210func: void any number and type of arguments, no return
1211 value
Bram Moolenaard77a8522020-04-03 21:59:57 +02001212func: {type} any number and type of arguments with specific
1213 return type
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001214
1215func() function with no argument, does not return a
1216 value
1217func(): void same
1218func(): {type} function with no argument and return type
1219
Bram Moolenaard1caa942020-04-10 22:10:56 +02001220func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +02001221 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +02001222func({type}): {type} function with argument type and return type
1223func(?{type}) function with type of optional argument, does
1224 not return a value
1225func(...{type}) function with type of variable number of
1226 arguments, does not return a value
1227func({type}, ?{type}, ...{type}): {type}
1228 function with:
1229 - type of mandatory argument
1230 - type of optional argument
1231 - type of variable number of arguments
1232 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +02001233
1234If the return type is "void" the function does not return a value.
1235
1236The reference can also be a |Partial|, in which case it stores extra arguments
1237and/or a dictionary, which are not visible to the caller. Since they are
1238called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001239
1240Custom types can be defined with `:type`: >
1241 :type MyList list<string>
Bram Moolenaar127542b2020-08-09 17:22:04 +02001242Custom types must start with a capital letter, to avoid name clashes with
1243builtin types added later, similarly to user functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001244{not implemented yet}
1245
1246And classes and interfaces can be used as types: >
1247 :class MyClass
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001248 :var mine: MyClass
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001249
1250 :interface MyInterface
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001251 :var mine: MyInterface
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001252
1253 :class MyTemplate<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001254 :var mine: MyTemplate<number>
1255 :var mine: MyTemplate<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001256
1257 :class MyInterface<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001258 :var mine: MyInterface<number>
1259 :var mine: MyInterface<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001260{not implemented yet}
1261
1262
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001263Variable types and type casting ~
1264 *variable-types*
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001265Variables declared in Vim9 script or in a `:def` function have a type, either
1266specified explicitly or inferred from the initialization.
1267
1268Global, buffer, window and tab page variables do not have a specific type, the
1269value can be changed at any time, possibly changing the type. Therefore, in
1270compiled code the "any" type is assumed.
1271
1272This can be a problem when the "any" type is undesired and the actual type is
1273expected to always be the same. For example, when declaring a list: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001274 var l: list<number> = [1, g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001275At compile time Vim doesn't know the type of "g:two" and the expression type
1276becomes list<any>. An instruction is generated to check the list type before
1277doing the assignment, which is a bit inefficient.
1278 *type-casting*
1279To avoid this, use a type cast: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001280 var l: list<number> = [1, <number>g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001281The compiled code will then only check that "g:two" is a number and give an
1282error if it isn't. This is called type casting.
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001283
1284The syntax of a type cast is: "<" {type} ">". There cannot be white space
1285after the "<" or before the ">" (to avoid them being confused with
1286smaller-than and bigger-than operators).
1287
1288The semantics is that, if needed, a runtime type check is performed. The
1289value is not actually changed. If you need to change the type, e.g. to change
1290it to a string, use the |string()| function. Or use |str2nr()| to convert a
1291string to a number.
1292
1293
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001294Type inference ~
1295 *type-inference*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001296In general: Whenever the type is clear it can be omitted. For example, when
1297declaring a variable and giving it a value: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001298 var name = 0 # infers number type
1299 var name = 'hello' # infers string type
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001300
Bram Moolenaar127542b2020-08-09 17:22:04 +02001301The type of a list and dictionary comes from the common type of the values.
1302If the values all have the same type, that type is used for the list or
1303dictionary. If there is a mix of types, the "any" type is used. >
1304 [1, 2, 3] list<number>
1305 ['a', 'b', 'c'] list<string>
1306 [1, 'x', 3] list<any>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001307
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001308The common type of function references, if they do not all have the same
1309number of arguments, uses "(...)" to indicate the number of arguments is not
1310specified. For example: >
1311 def Foo(x: bool)
1312 enddef
1313 def Bar(x: bool, y: bool)
1314 enddef
1315 var funclist = [Foo, Bar]
1316 echo funclist->typename()
1317Results in:
1318 list<func(...)>
1319
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001320For script-local variables in Vim9 script the type is checked, also when the
1321variable was declared in a legacy function.
1322
Bram Moolenaar207f0092020-08-30 17:20:20 +02001323
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001324Stricter type checking ~
1325 *type-checking*
Bram Moolenaar207f0092020-08-30 17:20:20 +02001326In legacy Vim script, where a number was expected, a string would be
1327automatically converted to a number. This was convenient for an actual number
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001328such as "123", but leads to unexpected problems (and no error message) if the
Bram Moolenaar207f0092020-08-30 17:20:20 +02001329string doesn't start with a number. Quite often this leads to hard-to-find
1330bugs.
1331
1332In Vim9 script this has been made stricter. In most places it works just as
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001333before, if the value used matches the expected type. There will sometimes be
1334an error, thus breaking backwards compatibility. For example:
Bram Moolenaar207f0092020-08-30 17:20:20 +02001335- Using a number other than 0 or 1 where a boolean is expected. *E1023*
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001336- Using a string value when setting a number option.
Bram Moolenaar207f0092020-08-30 17:20:20 +02001337- Using a number where a string is expected. *E1024*
1338
Bram Moolenaar22863042021-10-16 15:23:36 +01001339One consequence is that the item type of a list or dict given to |map()| must
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001340not change. This will give an error in Vim9 script: >
Bram Moolenaar22863042021-10-16 15:23:36 +01001341 echo map([1, 2, 3], (i, v) => 'item ' .. i)
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001342 E1012: Type mismatch; expected number but got string
Bram Moolenaar22863042021-10-16 15:23:36 +01001343Instead use |mapnew()|: >
1344 echo mapnew([1, 2, 3], (i, v) => 'item ' .. i)
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001345 ['item 0', 'item 1', 'item 2']
1346
1347If the item type was determined to be "any" it can change to a more specific
Bram Moolenaar22863042021-10-16 15:23:36 +01001348type. E.g. when a list of mixed types gets changed to a list of strings: >
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001349 var mylist = [1, 2.0, '3']
1350 # typename(mylist) == "list<any>"
1351 map(mylist, (i, v) => 'item ' .. i)
1352 # typename(mylist) == "list<string>", no error
1353
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001354Same for |extend()|, use |extendnew()| instead, and for |flatten()|, use
1355|flattennew()| instead.
Bram Moolenaar82be4842021-01-11 19:40:15 +01001356
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001357==============================================================================
1358
Bram Moolenaar30fd8202020-09-26 15:09:30 +020013595. Namespace, Import and Export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001360 *vim9script* *vim9-export* *vim9-import*
1361
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001362A Vim9 script can be written to be imported. This means that some items are
1363intentionally exported, made available to other scripts. When the exporting
1364script is imported in another script, these exported items can then be used in
1365that script. All the other items remain script-local in the exporting script
1366and cannot be accessed by the importing script.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001367
1368This mechanism exists for writing a script that can be sourced (imported) by
1369other scripts, while making sure these other scripts only have access to what
1370you want them to. This also avoids using the global namespace, which has a
1371risc of name collisions. For example when you have two plugins with similar
1372functionality.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001373
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001374You can cheat by using the global namespace explicitly. That should be done
1375only for things that really are global.
Bram Moolenaar207f0092020-08-30 17:20:20 +02001376
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001377
1378Namespace ~
Bram Moolenaardcc58e02020-12-28 20:53:21 +01001379 *vim9-namespace*
Bram Moolenaar560979e2020-02-04 22:53:05 +01001380To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001381appear as the first statement in the file (see |vim9-mix| for an exception).
1382It tells Vim to interpret the script in its own namespace, instead of the
1383global namespace. If a file starts with: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001384 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001385 var myvar = 'yes'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001386Then "myvar" will only exist in this file. While without `vim9script` it would
1387be available as `g:myvar` from any other script and function.
1388
1389The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001390variables in legacy Vim script, but the "s:" is omitted. And they cannot be
1391deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001392
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001393In Vim9 script the global "g:" namespace can still be used as before. And the
1394"w:", "b:" and "t:" namespaces. These have in common that variables are not
1395declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001396
1397A side effect of `:vim9script` is that the 'cpoptions' option is set to the
1398Vim default value, like with: >
1399 :set cpo&vim
1400One of the effects is that |line-continuation| is always enabled.
Bram Moolenaar3e191692021-03-17 17:46:00 +01001401The original value of 'cpoptions' is restored at the end of the script, while
1402flags added or removed in the script are also added to or removed from the
1403original value to get the same effect. The order of flags may change.
Bram Moolenaar71eb3ad2021-12-26 12:07:30 +00001404In the |vimrc| file sourced on startup this does not happen.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001405
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001406 *vim9-mix*
1407There is one way to use both legacy and Vim9 syntax in one script file: >
1408 " comments may go here
1409 if !has('vim9script')
1410 " legacy script commands go here
1411 finish
1412 endif
1413 vim9script
1414 # Vim9 script commands go here
1415This allows for writing a script that takes advantage of the Vim9 script
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001416syntax if possible, but will also work on a Vim version without it.
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001417
1418This can only work in two ways:
14191. The "if" statement evaluates to false, the commands up to `endif` are
1420 skipped and `vim9script` is then the first command actually executed.
14212. The "if" statement evaluates to true, the commands up to `endif` are
1422 executed and `finish` bails out before reaching `vim9script`.
1423
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001424
1425Export ~
1426 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001427Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001428 export const EXPORTED_CONST = 1234
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001429 export var someValue = ...
1430 export final someValue = ...
1431 export const someValue = ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001432 export def MyFunc() ...
1433 export class MyClass ...
Bram Moolenaar74235772021-06-12 14:53:05 +02001434 export interface MyClass ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001435
1436As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar74235772021-06-12 14:53:05 +02001437be exported. {not implemented yet: class, interface}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001438
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001439 *E1042*
1440`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001441
1442
1443Import ~
Bram Moolenaar73fef332020-06-21 22:12:03 +02001444 *:import* *:imp* *E1094*
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001445The exported items can be imported in another Vim9 script: >
1446 import "myscript.vim"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001447
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001448This makes each item available as "myscript.item".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001449
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001450In case the name is long or ambiguous, another name can be specified: >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001451 import "thatscript.vim" as that
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001452
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001453Then you can use "that.EXPORTED_CONST", "that.someValue", etc. You are free
1454to choose the name "that". Use something that will be recognized as referring
1455to the imported script. Avoid command names and builtin function names,
1456because the name will shadow them.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001457
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001458In case the dot in the name is undesired, a local reference can be made for a
1459function: >
1460 var LongFunc = that.LongFuncName
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001461
1462This also works for constants: >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001463 const MAXLEN = that.MAX_LEN_OF_NAME
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001464
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001465This does not work for variables, since the value would be copied once and
1466when changing the variable the copy will change, not the original variable.
1467You will need to use the full name, with the dot.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001468
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001469`:import` can also be used in legacy Vim script. The imported items still
1470become script-local, even when the "s:" prefix is not given.
1471
Bram Moolenaar4db572e2021-07-18 18:21:38 +02001472`:import` can not be used in a function. Imported items are intended to exist
1473at the script level and only imported once.
1474
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001475The script name after `import` can be:
1476- A relative path, starting "." or "..". This finds a file relative to the
1477 location of the script file itself. This is useful to split up a large
1478 plugin into several files.
1479- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001480 will rarely be used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001481- A path not being relative or absolute. This will be found in the
1482 "import" subdirectories of 'runtimepath' entries. The name will usually be
1483 longer and unique, to avoid loading the wrong file.
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001484 Note that "after/import" is not used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001485
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001486If the name does not end in ".vim" then the use of "as name" is required.
1487
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001488Once a vim9 script file has been imported, the result is cached and used the
1489next time the same script is imported. It will not be read again.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001490
1491It is not allowed to import the same script twice, also when using two
1492different "as" names.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001493
1494When using the imported name the dot and the item name must be in the same
1495line, there can be no line break: >
1496 echo that.
1497 name # Error!
1498 echo that
1499 .name # Error!
1500< *:import-cycle*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001501The `import` commands are executed when encountered. If that script (directly
1502or indirectly) imports the current script, then items defined after the
1503`import` won't be processed yet. Therefore cyclic imports can exist, but may
1504result in undefined items.
1505
1506
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001507Importing an autoload script ~
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001508 *vim9-autoload*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001509For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001510actually needed. Using the autoload mechanism is recommended:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001511
15121. In the plugin define user commands, functions and/or mappings that refer to
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001513 items imported from an autoload script. >
1514 import autoload 'for/search.vim'
1515 command -nargs=1 SearchForStuff search.Stuff(<f-args>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001516
1517< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001518 The "SearchForStuff" command is now available to the user.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001519
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001520 The "autoload" argument to `:import` means that the script is not loaded
1521 until one of the items is actually used. The script will be found under
1522 the "autoload" directory in 'runtimepath' instead of the "import"
1523 directory.
1524
15252. In the autoload script put the bulk of the code. >
1526 vim9script autoload
1527 export def Stuff(arg: string)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001528 ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001529
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001530< This goes in .../autoload/for/search.vim.
1531
1532 Adding "autoload" to `:vim9script` has the effect that "for#search#" will
1533 be prefixed to every exported item. The prefix is obtained from the file
1534 name, as you would to manually in a legacy autoload script. Thus the
1535 exported function can be found with "for#search#Stuff", but you would
1536 normally use `import autoload` and not need to specify the prefix.
1537
1538 You can split up the functionality and import other scripts from the
1539 autoload script as you like. This way you can share code between plugins.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001540
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001541For defining a mapping that uses the imported autoload script the special key
1542|<ScriptCmd>| is useful. It allows for a command in a mapping to use the
1543script context of where the mapping was defined.
1544
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001545When compiling a `:def` function and a function in an autoload script is
1546encountered, the script is not loaded until the `:def` function is called.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001547This also means you get any errors only at runtime, since the argument and
1548return types are not known yet.
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001549
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001550For testing the |test_override()| function can be used to have the
1551`import autoload` load the script right away, so that the items and types can
1552be checked without waiting for them to be actually used: >
1553 test_override('autoload', 1)
1554Reset it later with: >
1555 test_override('autoload', 0)
1556Or: >
1557 test_override('ALL', 0)
1558
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001559
1560Import in legacy Vim script ~
1561
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001562If an `import` statement is used in legacy Vim script, the script-local "s:"
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001563namespace will be used for the imported items, even when "s:" is not
1564specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001565
1566
1567==============================================================================
1568
Bram Moolenaar1d59aa12020-09-19 18:50:13 +020015696. Future work: classes *vim9-classes*
1570
1571Above "class" was mentioned a few times, but it has not been implemented yet.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001572Most of Vim9 script can be created without this functionality, and since
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001573implementing classes is going to be a lot of work, it is left for the future.
1574For now we'll just make sure classes can be added later.
1575
1576Thoughts:
Bram Moolenaar74235772021-06-12 14:53:05 +02001577- `class` / `endclass`, the whole class must be in one file
1578- Class names are always CamelCase (to avoid a name clash with builtin types)
1579- A single constructor called "constructor"
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001580- Single inheritance with `class ThisClass extends BaseClass`
Bram Moolenaar74235772021-06-12 14:53:05 +02001581- `abstract class` (class with incomplete implementation)
1582- `interface` / `endinterface` (abstract class without any implementation)
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001583- `class SomeClass implements SomeInterface`
1584- Generics for class: `class <Tkey, Tentry>`
1585- Generics for function: `def <Tkey> GetLast(key: Tkey)`
1586
Bram Moolenaar74235772021-06-12 14:53:05 +02001587Again, much of this is from TypeScript with a slightly different syntax.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001588
1589Some things that look like good additions:
1590- Use a class as an interface (like Dart)
1591- Extend a class with methods, using an import (like Dart)
Bram Moolenaar74235772021-06-12 14:53:05 +02001592- Mixins
1593- For testing: Mock mechanism
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001594
1595An important class that will be provided is "Promise". Since Vim is single
1596threaded, connecting asynchronous operations is a natural way of allowing
1597plugins to do their work without blocking the user. It's a uniform way to
1598invoke callbacks and handle timeouts and errors.
1599
Bram Moolenaar74235772021-06-12 14:53:05 +02001600Some examples: >
1601
1602 abstract class Person
1603 static const prefix = 'xxx'
1604 var name: string
1605
1606 def constructor(name: string)
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001607 this.name = name
Bram Moolenaar74235772021-06-12 14:53:05 +02001608 enddef
1609
1610 def display(): void
1611 echo name
1612 enddef
1613
1614 abstract def find(string): Person
1615 endclass
1616
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001617==============================================================================
1618
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010016199. Rationale *vim9-rationale*
1620
1621The :def command ~
1622
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001623Plugin writers have asked for much faster Vim script. Investigations have
Bram Moolenaar560979e2020-02-04 22:53:05 +01001624shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001625impossible, because of the overhead involved with calling a function, setting
1626up the local function scope and executing lines. There are many details that
1627need to be handled, such as error messages and exceptions. The need to create
1628a dictionary for a: and l: scopes, the a:000 list and several others add too
1629much overhead that cannot be avoided.
1630
1631Therefore the `:def` method to define a new-style function had to be added,
1632which allows for a function with different semantics. Most things still work
1633as before, but some parts do not. A new way to define a function was
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001634considered the best way to separate the legacy style code from Vim9 style code.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001635
1636Using "def" to define a function comes from Python. Other languages use
1637"function" which clashes with legacy Vim script.
1638
1639
1640Type checking ~
1641
1642When compiling lines of Vim commands into instructions as much as possible
1643should be done at compile time. Postponing it to runtime makes the execution
1644slower and means mistakes are found only later. For example, when
1645encountering the "+" character and compiling this into a generic add
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001646instruction, at runtime the instruction would have to inspect the type of the
1647arguments and decide what kind of addition to do. And when the type is
1648dictionary throw an error. If the types are known to be numbers then an "add
1649number" instruction can be used, which is faster. The error can be given at
1650compile time, no error handling is needed at runtime, since adding two numbers
1651cannot fail.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001652
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001653The syntax for types, using <type> for compound types, is similar to Java. It
1654is easy to understand and widely used. The type names are what were used in
1655Vim before, with some additions such as "void" and "bool".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001656
1657
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001658Removing clutter and weirdness ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001659
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001660Once decided that `:def` functions have different syntax than legacy functions,
1661we are free to add improvements to make the code more familiar for users who
1662know popular programming languages. In other words: remove weird things that
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001663only Vim does.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001664
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001665We can also remove clutter, mainly things that were done to make Vim script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001666backwards compatible with the good old Vi commands.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001667
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001668Examples:
1669- Drop `:call` for calling a function and `:eval` for manipulating data.
1670- Drop using a leading backslash for line continuation, automatically figure
1671 out where an expression ends.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001672
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001673However, this does require that some things need to change:
1674- Comments start with # instead of ", to avoid confusing them with strings.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001675 This is good anyway, it is known from several popular languages.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001676- Ex command ranges need to be prefixed with a colon, to avoid confusion with
1677 expressions (single quote can be a string or a mark, "/" can be divide or a
1678 search command, etc.).
1679
1680Goal is to limit the differences. A good criteria is that when the old syntax
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001681is accidentally used you are very likely to get an error message.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001682
1683
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001684Syntax and semantics from popular languages ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001685
1686Script writers have complained that the Vim script syntax is unexpectedly
1687different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001688languages are used as an example. At the same time, we do not want to abandon
1689the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001690
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001691For many things TypeScript is followed. It's a recent language that is
1692gaining popularity and has similarities with Vim script. It also has a
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001693mix of static typing (a variable always has a known value type) and dynamic
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001694typing (a variable can have different types, this changes at runtime). Since
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001695legacy Vim script is dynamically typed and a lot of existing functionality
1696(esp. builtin functions) depends on that, while static typing allows for much
1697faster execution, we need to have this mix in Vim9 script.
1698
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001699There is no intention to completely match TypeScript syntax and semantics. We
1700just want to take those parts that we can use for Vim and we expect Vim users
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001701will be happy with. TypeScript is a complex language with its own history,
1702advantages and disadvantages. To get an idea of the disadvantages read the
1703book: "JavaScript: The Good Parts". Or find the article "TypeScript: the good
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001704parts" and read the "Things to avoid" section.
1705
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001706People familiar with other languages (Java, Python, etc.) will also find
1707things in TypeScript that they do not like or do not understand. We'll try to
1708avoid those things.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001709
1710Specific items from TypeScript we avoid:
1711- Overloading "+", using it both for addition and string concatenation. This
1712 goes against legacy Vim script and often leads to mistakes. For that reason
1713 we will keep using ".." for string concatenation. Lua also uses ".." this
1714 way. And it allows for conversion to string for more values.
1715- TypeScript can use an expression like "99 || 'yes'" in a condition, but
1716 cannot assign the value to a boolean. That is inconsistent and can be
1717 annoying. Vim recognizes an expression with && or || and allows using the
Bram Moolenaar1f318c62021-12-26 18:09:31 +00001718 result as a bool. The |falsy-operator| was added for the mechanism to use a
1719 default value.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001720- TypeScript considers an empty string as Falsy, but an empty list or dict as
1721 Truthy. That is inconsistent. In Vim an empty list and dict are also
1722 Falsy.
1723- TypeScript has various "Readonly" types, which have limited usefulness,
1724 since a type cast can remove the immutable nature. Vim locks the value,
1725 which is more flexible, but is only checked at runtime.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001726
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001727
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001728Declarations ~
1729
1730Legacy Vim script uses `:let` for every assignment, while in Vim9 declarations
1731are used. That is different, thus it's good to use a different command:
1732`:var`. This is used in many languages. The semantics might be slightly
1733different, but it's easily recognized as a declaration.
1734
Bram Moolenaar23515b42020-11-29 14:36:24 +01001735Using `:const` for constants is common, but the semantics varies. Some
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001736languages only make the variable immutable, others also make the value
1737immutable. Since "final" is well known from Java for only making the variable
1738immutable we decided to use that. And then `:const` can be used for making
1739both immutable. This was also used in legacy Vim script and the meaning is
1740almost the same.
1741
1742What we end up with is very similar to Dart: >
1743 :var name # mutable variable and value
1744 :final name # immutable variable, mutable value
1745 :const name # immutable variable and value
1746
1747Since legacy and Vim9 script will be mixed and global variables will be
1748shared, optional type checking is desirable. Also, type inference will avoid
1749the need for specifying the type in many cases. The TypeScript syntax fits
1750best for adding types to declarations: >
1751 var name: string # string type is specified
1752 ...
1753 name = 'John'
1754 const greeting = 'hello' # string type is inferred
1755
1756This is how we put types in a declaration: >
1757 var mylist: list<string>
1758 final mylist: list<string> = ['foo']
1759 def Func(arg1: number, arg2: string): bool
1760
1761Two alternatives were considered:
17621. Put the type before the name, like Dart: >
1763 var list<string> mylist
1764 final list<string> mylist = ['foo']
1765 def Func(number arg1, string arg2) bool
17662. Put the type after the variable name, but do not use a colon, like Go: >
1767 var mylist list<string>
1768 final mylist list<string> = ['foo']
1769 def Func(arg1 number, arg2 string) bool
1770
1771The first is more familiar for anyone used to C or Java. The second one
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001772doesn't really have an advantage over the first, so let's discard the second.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001773
1774Since we use type inference the type can be left out when it can be inferred
1775from the value. This means that after `var` we don't know if a type or a name
1776follows. That makes parsing harder, not only for Vim but also for humans.
1777Also, it will not be allowed to use a variable name that could be a type name,
1778using `var string string` is too confusing.
1779
1780The chosen syntax, using a colon to separate the name from the type, adds
1781punctuation, but it actually makes it easier to recognize the parts of a
1782declaration.
1783
1784
1785Expressions ~
1786
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001787Expression evaluation was already close to what other languages are doing.
1788Some details are unexpected and can be improved. For example a boolean
1789condition would accept a string, convert it to a number and check if the
1790number is non-zero. This is unexpected and often leads to mistakes, since
1791text not starting with a number would be converted to zero, which is
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001792considered false. Thus using a string for a condition would often not give an
1793error and be considered false. That is confusing.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001794
Bram Moolenaar23515b42020-11-29 14:36:24 +01001795In Vim9 type checking is stricter to avoid mistakes. Where a condition is
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001796used, e.g. with the `:if` command and the `||` operator, only boolean-like
1797values are accepted:
1798 true: `true`, `v:true`, `1`, `0 < 9`
1799 false: `false`, `v:false`, `0`, `0 > 9`
1800Note that the number zero is false and the number one is true. This is more
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001801permissive than most other languages. It was done because many builtin
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001802functions return these values.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001803
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001804If you have any type of value and want to use it as a boolean, use the `!!`
1805operator:
Bram Moolenaard2ea7cf2021-05-30 20:54:13 +02001806 true: `!!'text'`, `!![99]`, `!!{'x': 1}`, `!!99`
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001807 false: `!!''`, `!![]`, `!!{}`
1808
1809From a language like JavaScript we have this handy construct: >
1810 GetName() || 'unknown'
1811However, this conflicts with only allowing a boolean for a condition.
1812Therefore the "??" operator was added: >
1813 GetName() ?? 'unknown'
1814Here you can explicitly express your intention to use the value as-is and not
1815result in a boolean. This is called the |falsy-operator|.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001816
1817
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001818Import and Export ~
1819
1820A problem of legacy Vim script is that by default all functions and variables
1821are global. It is possible to make them script-local, but then they are not
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001822available in other scripts. This defies the concept of a package that only
1823exports selected items and keeps the rest local.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001824
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001825In Vim9 script a mechanism very similar to the JavaScript import and export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001826mechanism is supported. It is a variant to the existing `:source` command
1827that works like one would expect:
1828- Instead of making everything global by default, everything is script-local,
1829 unless exported.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001830- When importing a script the symbols that are imported are explicitly listed,
1831 avoiding name conflicts and failures if functionality is added later.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001832- The mechanism allows for writing a big, long script with a very clear API:
1833 the exported function(s) and class(es).
1834- By using relative paths loading can be much faster for an import inside of a
1835 package, no need to search many directories.
1836- Once an import has been used, it can be cached and loading it again can be
1837 avoided.
1838- The Vim-specific use of "s:" to make things script-local can be dropped.
1839
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001840When sourcing a Vim9 script from a legacy script, only the items defined
1841globally can be used, not the exported items. Alternatives considered:
1842- All the exported items become available as script-local items. This makes
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001843 it uncontrollable what items get defined and likely soon leads to trouble.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001844- Use the exported items and make them global. Disadvantage is that it's then
1845 not possible to avoid name clashes in the global namespace.
1846- Completely disallow sourcing a Vim9 script, require using `:import`. That
1847 makes it difficult to use scripts for testing, or sourcing them from the
1848 command line to try them out.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001849Note that you can also use `:import` in legacy Vim script, see above.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001850
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001851
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001852Compiling functions early ~
1853
1854Functions are compiled when called or when `:defcompile` is used. Why not
1855compile them early, so that syntax and type errors are reported early?
1856
1857The functions can't be compiled right away when encountered, because there may
1858be forward references to functions defined later. Consider defining functions
1859A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
1860to reorder the functions to avoid forward references.
1861
1862An alternative would be to first scan through the file to locate items and
1863figure out their type, so that forward references are found, and only then
1864execute the script and compile the functions. This means the script has to be
1865parsed twice, which is slower, and some conditions at the script level, such
1866as checking if a feature is supported, are hard to use. An attempt was made
1867to see if it works, but it turned out to be impossible to make work nicely.
1868
1869It would be possible to compile all the functions at the end of the script.
1870The drawback is that if a function never gets called, the overhead of
1871compiling it counts anyway. Since startup speed is very important, in most
1872cases it's better to do it later and accept that syntax and type errors are
1873only reported then. In case these errors should be found early, e.g. when
1874testing, the `:defcompile` command will help out.
1875
1876
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001877Why not use an embedded language? ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001878
1879Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001880these interfaces have never become widely used, for various reasons. When
1881Vim9 was designed a decision was made to make these interfaces lower priority
1882and concentrate on Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001883
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001884Still, plugin writers may find other languages more familiar, want to use
1885existing libraries or see a performance benefit. We encourage plugin authors
1886to write code in any language and run it as an external tool, using jobs and
1887channels. We can try to make this easier somehow.
1888
1889Using an external tool also has disadvantages. An alternative is to convert
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001890the tool into Vim script. For that to be possible without too much
1891translation, and keeping the code fast at the same time, the constructs of the
1892tool need to be supported. Since most languages support classes the lack of
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001893support for classes in Vim is then a problem.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001894
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001895
1896Classes ~
1897
1898Vim supports a kind-of object oriented programming by adding methods to a
1899dictionary. With some care this can be made to work, but it does not look
1900like real classes. On top of that, it's quite slow, because of the use of
1901dictionaries.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001902
1903The support of classes in Vim9 script is a "minimal common functionality" of
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001904class support in most languages. It works much like Java, which is the most
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001905popular programming language.
1906
1907
1908
1909 vim:tw=78:ts=8:noet:ft=help:norl: