blob: 0172dffe849154c3f37132b69eb55113dd165a41 [file] [log] [blame]
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001*vim9.txt* For Vim version 8.2. Last change: 2022 Jan 23
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 Moolenaar6f4754b2022-01-23 12:07:04 +0000193 *vim9-variable-arguments* *E1055*
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 Moolenaar6f4754b2022-01-23 12:07:04 +0000230< *E1058* *E1075*
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 Moolenaar6f4754b2022-01-23 12:07:04 +0000292 *vim9-declaration* *:var*
293 *E1017* *E1020* *E1054*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200294Local variables need to be declared with `:var`. Local constants need to be
295declared with `:final` or `:const`. We refer to both as "variables" in this
296section.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100297
298Variables can be local to a script, function or code block: >
299 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200300 var script_var = 123
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100301 def SomeFunc()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200302 var func_var = script_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100303 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200304 var block_var = func_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100305 ...
306
307The variables are only visible in the block where they are defined and nested
308blocks. Once the block ends the variable is no longer accessible: >
309 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200310 var inner = 5
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100311 else
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200312 var inner = 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100313 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200314 echo inner # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100315
316The declaration must be done earlier: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200317 var inner: number
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100318 if cond
319 inner = 5
320 else
321 inner = 0
322 endif
323 echo inner
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000324< *E1025*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200325To intentionally hide a variable from code that follows, a block can be
326used: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100327 {
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200328 var temp = 'temp'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100329 ...
330 }
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200331 echo temp # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100332
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200333This is especially useful in a user command: >
334
335 command -range Rename {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200336 var save = @a
337 @a = 'some expression'
338 echo 'do something with ' .. @a
339 @a = save
340 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200341
342And with autocommands: >
343
344 au BufWritePre *.go {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200345 var save = winsaveview()
346 silent! exe ':%! some formatting command'
347 winrestview(save)
348 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200349
350Although using a :def function probably works better.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000351 *E1022*
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200352Declaring a variable with a type but without an initializer will initialize to
Bram Moolenaar1f318c62021-12-26 18:09:31 +0000353false (for bool), empty (for string, list, dict, etc.) or zero (for number,
354any, etc.). This matters especially when using the "any" type, the value will
355default to the number zero.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000356 *E1016* *E1052* *E1066*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200357In Vim9 script `:let` cannot be used. An existing variable is assigned to
358without any command. The same for global, window, tab, buffer and Vim
Bram Moolenaar5da36052021-12-27 15:39:57 +0000359variables, because they are not really declared. Those can also be deleted
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200360with `:unlet`.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100361
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200362`:lockvar` does not work on local variables. Use `:const` and `:final`
363instead.
364
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200365The `exists()` and `exists_compiled()` functions do not work on local variables
366or arguments.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000367 *E1006* *E1041*
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100368Variables, functions and function arguments cannot shadow previously defined
369or imported variables and functions in the same script file.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100370Variables may shadow Ex commands, rename the variable if needed.
371
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200372Global variables must be prefixed with "g:", also at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200373 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200374 var script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200375 g:global = 'value'
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200376 var Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200377
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200378Global functions must be prefixed with "g:" when defining them, but can be
379called without "g:". >
380 vim9script
381 def g:GlobalFunc(): string
382 return 'text'
383 enddef
384 echo GlobalFunc()
385The "g:" prefix is not needed for auto-load functions.
386
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200387 *vim9-function-defined-later*
388Although global functions can be called without the "g:" prefix, they must
389exist when compiled. By adding the "g:" prefix the function can be defined
390later. Example: >
391 def CallPluginFunc()
392 if exists('g:loaded_plugin')
393 g:PluginFunc()
394 endif
395 enddef
396
Bram Moolenaarb79ee0c2022-01-01 12:17:00 +0000397If you do it like this, you get an error at compile time that "PluginFunc"
398does not exist, even when "g:loaded_plugin" does not exist: >
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200399 def CallPluginFunc()
400 if exists('g:loaded_plugin')
401 PluginFunc() # Error - function not found
402 endif
403 enddef
404
405You can use exists_compiled() to avoid the error, but then the function would
406not be called, even when "g:loaded_plugin" is defined later: >
407 def CallPluginFunc()
408 if exists_compiled('g:loaded_plugin')
409 PluginFunc() # Function may never be called
410 endif
411 enddef
412
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200413Since `&opt = value` is now assigning a value to option "opt", ":&" cannot be
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100414used to repeat a `:substitute` command.
Bram Moolenaar56994d22021-04-17 16:31:09 +0200415 *vim9-unpack-ignore*
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200416For an unpack assignment the underscore can be used to ignore a list item,
417similar to how a function argument can be ignored: >
418 [a, _, c] = theList
Bram Moolenaar56994d22021-04-17 16:31:09 +0200419To ignore any remaining items: >
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200420 [a, b; _] = longList
421
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200422Declaring more than one variable at a time, using the unpack notation, is
Bram Moolenaarab36e6a2021-11-30 16:14:49 +0000423possible. Each variable can have a type or infer it from the value: >
424 var [v1: number, v2] = GetValues()
425Use this only when there is a list with values, declaring one variable per
426line is much easier to read and change later.
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200427
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200428
429Constants ~
430 *vim9-const* *vim9-final*
431How constants work varies between languages. Some consider a variable that
432can't be assigned another value a constant. JavaScript is an example. Others
433also make the value immutable, thus when a constant uses a list, the list
434cannot be changed. In Vim9 we can use both.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000435 *E1021*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200436`:const` is used for making both the variable and the value a constant. Use
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200437this for composite structures that you want to make sure will not be modified.
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200438Example: >
439 const myList = [1, 2]
440 myList = [3, 4] # Error!
441 myList[0] = 9 # Error!
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100442 myList->add(3) # Error!
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200443< *:final*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200444`:final` is used for making only the variable a constant, the value can be
445changed. This is well known from Java. Example: >
446 final myList = [1, 2]
447 myList = [3, 4] # Error!
448 myList[0] = 9 # OK
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100449 myList->add(3) # OK
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200450
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200451It is common to write constants as ALL_CAPS, but you don't have to.
452
453The constant only applies to the value itself, not what it refers to. >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200454 final females = ["Mary"]
455 const NAMES = [["John", "Peter"], females]
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200456 NAMES[0] = ["Jack"] # Error!
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200457 NAMES[0][0] = "Jack" # Error!
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200458 NAMES[1] = ["Emma"] # Error!
Bram Moolenaar82be4842021-01-11 19:40:15 +0100459 NAMES[1][0] = "Emma" # OK, now females[0] == "Emma"
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200460
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100461
462Omitting :call and :eval ~
463
464Functions can be called without `:call`: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200465 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100466Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100467
468A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0289a092021-03-14 18:40:19 +0100469identifier or can't be an Ex command. For a function either "(" or "->" must
470be following, without a line break. Examples: >
Bram Moolenaarae616492020-07-28 20:07:27 +0200471 myList->add(123)
472 g:myList->add(123)
473 [1, 2, 3]->Process()
Bram Moolenaar2bede172020-11-19 18:53:18 +0100474 {a: 1, b: 2}->Process()
Bram Moolenaarae616492020-07-28 20:07:27 +0200475 "foobar"->Process()
476 ("foobar")->Process()
477 'foobar'->Process()
478 ('foobar')->Process()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100479
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200480In the rare case there is ambiguity between a function name and an Ex command,
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200481prepend ":" to make clear you want to use the Ex command. For example, there
482is both the `:substitute` command and the `substitute()` function. When the
483line starts with `substitute(` this will use the function. Prepend a colon to
484use the command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100485 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100486
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200487If the expression starts with "!" this is interpreted as a shell command, not
488negation of a condition. Thus this is a shell command: >
489 !shellCommand->something
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200490Put the expression in parentheses to use the "!" for negation: >
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200491 (!expression)->Method()
492
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100493Note that while variables need to be defined before they can be used,
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200494functions can be called before being defined. This is required to allow
495for cyclic dependencies between functions. It is slightly less efficient,
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100496since the function has to be looked up by name. And a typo in the function
Bram Moolenaarae616492020-07-28 20:07:27 +0200497name will only be found when the function is called.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100498
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100499
Bram Moolenaard1caa942020-04-10 22:10:56 +0200500Omitting function() ~
501
502A user defined function can be used as a function reference in an expression
503without `function()`. The argument types and return type will then be checked.
504The function must already have been defined. >
505
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200506 var Funcref = MyFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200507
508When using `function()` the resulting type is "func", a function with any
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200509number of arguments and any return type (including void). The function can be
Bram Moolenaarfa3b7232021-12-24 13:18:38 +0000510defined later if the argument is in quotes.
Bram Moolenaard1caa942020-04-10 22:10:56 +0200511
512
Bram Moolenaar2b327002020-12-26 15:39:31 +0100513Lambda using => instead of -> ~
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200514 *vim9-lambda*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100515In legacy script there can be confusion between using "->" for a method call
516and for a lambda. Also, when a "{" is found the parser needs to figure out if
517it is the start of a lambda or a dictionary, which is now more complicated
518because of the use of argument types.
519
520To avoid these problems Vim9 script uses a different syntax for a lambda,
Bram Moolenaar74235772021-06-12 14:53:05 +0200521which is similar to JavaScript: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100522 var Lambda = (arg) => expression
523
Bram Moolenaar2b327002020-12-26 15:39:31 +0100524No line break is allowed in the arguments of a lambda up to and including the
Bram Moolenaar4d8f4762021-06-27 15:18:56 +0200525"=>" (so that Vim can tell the difference between an expression in parentheses
Bram Moolenaar2346a632021-06-13 19:02:49 +0200526and lambda arguments). This is OK: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100527 filter(list, (k, v) =>
528 v > 0)
529This does not work: >
530 filter(list, (k, v)
531 => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100532This also does not work: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100533 filter(list, (k,
534 v) => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100535But you can use a backslash to concatenate the lines before parsing: >
536 filter(list, (k,
537 \ v)
538 \ => v > 0)
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200539< *vim9-lambda-arguments*
540In legacy script a lambda could be called with any number of extra arguments,
541there was no way to warn for not using them. In Vim9 script the number of
542arguments must match. If you do want to accept any arguments, or any further
543arguments, use "..._", which makes the function accept
544|vim9-variable-arguments|. Example: >
545 var Callback = (..._) => 'anything'
546 echo Callback(1, 2, 3) # displays "anything"
547
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200548< *inline-function*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100549Additionally, a lambda can contain statements in {}: >
550 var Lambda = (arg) => {
551 g:was_called = 'yes'
552 return expression
553 }
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200554This can be useful for a timer, for example: >
555 var count = 0
556 var timer = timer_start(500, (_) => {
557 count += 1
558 echom 'Handler called ' .. count
559 }, {repeat: 3})
560
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200561The ending "}" must be at the start of a line. It can be followed by other
562characters, e.g.: >
563 var d = mapnew(dict, (k, v): string => {
564 return 'value'
565 })
566No command can follow the "{", only a comment can be used there.
567
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000568 *command-block* *E1026*
Bram Moolenaar259f4432021-12-17 12:45:22 +0000569The block can also be used for defining a user command. Inside the block Vim9
570syntax will be used.
571
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000572If the statements include a dictionary, its closing bracket must not be
573written at the start of a line. Otherwise, it would be parsed as the end of
574the block. This does not work: >
575 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000576 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000577 'key': 'value',
578 } # ERROR: will be recognized as the end of the block
579 }
580Put the '}' after the last item to avoid this: >
581 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000582 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000583 'key': 'value' }
584 }
585
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200586Rationale: The "}" cannot be after a command because it would require parsing
587the commands to find it. For consistency with that no command can follow the
588"{". Unfortunately this means using "() => { command }" does not work, line
589breaks are always required.
Bram Moolenaar65c44152020-12-24 15:14:01 +0100590
Bram Moolenaare0e39172021-01-25 21:14:57 +0100591 *vim9-curly*
Bram Moolenaar2b327002020-12-26 15:39:31 +0100592To avoid the "{" of a dictionary literal to be recognized as a statement block
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100593wrap it in parentheses: >
Bram Moolenaar2b327002020-12-26 15:39:31 +0100594 var Lambda = (arg) => ({key: 42})
Bram Moolenaar65c44152020-12-24 15:14:01 +0100595
Bram Moolenaare0e39172021-01-25 21:14:57 +0100596Also when confused with the start of a command block: >
597 ({
598 key: value
599 })->method()
600
Bram Moolenaar65c44152020-12-24 15:14:01 +0100601
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200602Automatic line continuation ~
Bram Moolenaar5da36052021-12-27 15:39:57 +0000603 *vim9-line-continuation*
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200604In many cases it is obvious that an expression continues on the next line. In
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100605those cases there is no need to prefix the line with a backslash (see
606|line-continuation|). For example, when a list spans multiple lines: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200607 var mylist = [
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200608 'one',
609 'two',
610 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200611And when a dict spans multiple lines: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100612 var mydict = {
Bram Moolenaare6085c52020-04-12 20:19:16 +0200613 one: 1,
614 two: 2,
615 }
Bram Moolenaar74235772021-06-12 14:53:05 +0200616With a function call: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200617 var result = Func(
Bram Moolenaare6085c52020-04-12 20:19:16 +0200618 arg1,
619 arg2
620 )
621
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200622For binary operators in expressions not in [], {} or () a line break is
623possible just before or after the operator. For example: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200624 var text = lead
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200625 .. middle
626 .. end
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200627 var total = start +
Bram Moolenaar82be4842021-01-11 19:40:15 +0100628 end -
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200629 correction
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200630 var result = positive
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200631 ? PosFunc(arg)
632 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200633
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200634For a method call using "->" and a member using a dot, a line break is allowed
635before it: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200636 var result = GetBuilder()
Bram Moolenaar73fef332020-06-21 22:12:03 +0200637 ->BuilderSetWidth(333)
638 ->BuilderSetHeight(777)
639 ->BuilderBuild()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200640 var result = MyDict
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200641 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200642
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100643For commands that have an argument that is a list of commands, the | character
644at the start of the line indicates line continuation: >
645 autocmd BufNewFile *.match if condition
646 | echo 'match'
647 | endif
648
Bram Moolenaar22863042021-10-16 15:23:36 +0100649Note that this means that in heredoc the first line cannot start with a bar: >
Bram Moolenaar74235772021-06-12 14:53:05 +0200650 var lines =<< trim END
651 | this doesn't work
652 END
653Either use an empty line at the start or do not use heredoc. Or temporarily
654add the "C" flag to 'cpoptions': >
655 set cpo+=C
656 var lines =<< trim END
Bram Moolenaar22863042021-10-16 15:23:36 +0100657 | this works
Bram Moolenaar74235772021-06-12 14:53:05 +0200658 END
659 set cpo-=C
660If the heredoc is inside a function 'cpoptions' must be set before :def and
661restored after the :enddef.
662
663In places where line continuation with a backslash is still needed, such as
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200664splitting up a long Ex command, comments can start with '#\ ': >
665 syn region Text
Bram Moolenaar74235772021-06-12 14:53:05 +0200666 \ start='foo'
667 #\ comment
668 \ end='bar'
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200669Like with legacy script '"\ ' is used. This is also needed when line
670continuation is used without a backslash and a line starts with a bar: >
671 au CursorHold * echom 'BEFORE bar'
672 #\ some comment
673 | echom 'AFTER bar'
674<
675 *E1050*
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200676To make it possible for the operator at the start of the line to be
Bram Moolenaar74235772021-06-12 14:53:05 +0200677recognized, it is required to put a colon before a range. This example will
678add "start" and print: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200679 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200680 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200681Like this: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200682 var result = start + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200683
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200684This will assign "start" and print a line: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200685 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200686 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200687
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000688After the range an Ex command must follow. Without the colon you can call a
689function without `:call`, but after a range you do need it: >
690 MyFunc()
691 :% call MyFunc()
692
Bram Moolenaar23515b42020-11-29 14:36:24 +0100693Note that the colon is not required for the |+cmd| argument: >
694 edit +6 fname
695
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200696It is also possible to split a function header over multiple lines, in between
697arguments: >
698 def MyFunc(
699 text: string,
700 separator = '-'
701 ): string
702
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100703Since a continuation line cannot be easily recognized the parsing of commands
Bram Moolenaar65c44152020-12-24 15:14:01 +0100704has been made stricter. E.g., because of the error in the first line, the
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100705second line is seen as a separate command: >
706 popup_create(some invalid expression, {
707 exit_cb: Func})
708Now "exit_cb: Func})" is actually a valid command: save any changes to the
709file "_cb: Func})" and exit. To avoid this kind of mistake in Vim9 script
710there must be white space between most command names and the argument.
711
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100712However, the argument of a command that is a command won't be recognized. For
713example, after "windo echo expr" a line break inside "expr" will not be seen.
714
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100715
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200716Notes:
717- "enddef" cannot be used at the start of a continuation line, it ends the
718 current function.
719- No line break is allowed in the LHS of an assignment. Specifically when
720 unpacking a list |:let-unpack|. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200721 [var1, var2] =
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200722 Func()
723< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200724 [var1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200725 var2] =
726 Func()
727- No line break is allowed in between arguments of an `:echo`, `:execute` and
728 similar commands. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200729 echo [1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200730 2] [3,
731 4]
732< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200733 echo [1, 2]
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200734 [3, 4]
Bram Moolenaar74235772021-06-12 14:53:05 +0200735- In some cases it is difficult for Vim to parse a command, especially when
736 commands are used as an argument to another command, such as `windo`. In
737 those cases the line continuation with a backslash has to be used.
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200738
Bram Moolenaar4c295022021-05-02 17:19:11 +0200739
740White space ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000741 *E1004* *E1068* *E1069* *E1074*
Bram Moolenaar4c295022021-05-02 17:19:11 +0200742Vim9 script enforces proper use of white space. This is no longer allowed: >
743 var name=234 # Error!
744 var name= 234 # Error!
745 var name =234 # Error!
746There must be white space before and after the "=": >
747 var name = 234 # OK
748White space must also be put before the # that starts a comment after a
749command: >
750 var name = 234# Error!
751 var name = 234 # OK
752
753White space is required around most operators.
754
755White space is required in a sublist (list slice) around the ":", except at
756the start and end: >
757 otherlist = mylist[v : count] # v:count has a different meaning
758 otherlist = mylist[:] # make a copy of the List
759 otherlist = mylist[v :]
760 otherlist = mylist[: v]
761
762White space is not allowed:
763- Between a function name and the "(": >
764 Func (arg) # Error!
765 Func
766 \ (arg) # Error!
767 Func
768 (arg) # Error!
769 Func(arg) # OK
770 Func(
771 arg) # OK
772 Func(
773 arg # OK
774 )
775
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200776White space is not allowed in a `:set` command between the option name and a
777following "&", "!", "<", "=", "+=", "-=" or "^=".
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200778
Bram Moolenaar4c295022021-05-02 17:19:11 +0200779
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100780No curly braces expansion ~
781
782|curly-braces-names| cannot be used.
783
784
Bram Moolenaar2bede172020-11-19 18:53:18 +0100785Dictionary literals ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000786 *vim9-literal-dict* *E1014*
Bram Moolenaar2bede172020-11-19 18:53:18 +0100787Traditionally Vim has supported dictionary literals with a {} syntax: >
788 let dict = {'key': value}
789
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100790Later it became clear that using a simple text key is very common, thus
791literal dictionaries were introduced in a backwards compatible way: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100792 let dict = #{key: value}
793
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100794However, this #{} syntax is unlike any existing language. As it turns out
795that using a literal key is much more common than using an expression, and
Bram Moolenaar2bede172020-11-19 18:53:18 +0100796considering that JavaScript uses this syntax, using the {} form for dictionary
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100797literals is considered a much more useful syntax. In Vim9 script the {} form
Bram Moolenaar2bede172020-11-19 18:53:18 +0100798uses literal keys: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100799 var dict = {key: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100800
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100801This works for alphanumeric characters, underscore and dash. If you want to
802use another character, use a single or double quoted string: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100803 var dict = {'key with space': value}
804 var dict = {"key\twith\ttabs": value}
805 var dict = {'': value} # empty key
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100806
807In case the key needs to be an expression, square brackets can be used, just
808like in JavaScript: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100809 var dict = {["key" .. nr]: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100810
Bram Moolenaar2e5910b2021-02-03 17:41:24 +0100811The key type can be string, number, bool or float. Other types result in an
812error. A number can be given with and without the []: >
813 var dict = {123: 'without', [456]: 'with'}
814 echo dict
815 {'456': 'with', '123': 'without'}
816
Bram Moolenaar2bede172020-11-19 18:53:18 +0100817
Bram Moolenaar10b94212021-02-19 21:42:57 +0100818No :xit, :t, :k, :append, :change or :insert ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100819
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200820These commands are too easily confused with local variable names.
821Instead of `:x` or `:xit` you can use `:exit`.
822Instead of `:t` you can use `:copy`.
Bram Moolenaar10b94212021-02-19 21:42:57 +0100823Instead of `:k` you can use `:mark`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100824
825
826Comparators ~
827
828The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100829
830
Bram Moolenaar4c295022021-05-02 17:19:11 +0200831Abort after error ~
832
833In legacy script, when an error is encountered, Vim continues to execute
834following lines. This can lead to a long sequence of errors and need to type
835CTRL-C to stop it. In Vim9 script execution of commands stops at the first
836error. Example: >
837 vim9script
838 var x = does-not-exist
839 echo 'not executed'
840
841
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100842For loop ~
843
Bram Moolenaar47003982021-12-05 21:54:04 +0000844The loop variable must not be declared yet: >
Bram Moolenaar6304be62021-11-27 10:57:26 +0000845 var i = 1
846 for i in [1, 2, 3] # Error!
847
Bram Moolenaar47003982021-12-05 21:54:04 +0000848It is possible to use a global variable though: >
849 g:i = 1
850 for g:i in [1, 2, 3]
851 echo g:i
852 endfor
853
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100854Legacy Vim script has some tricks to make a for loop over a list handle
855deleting items at the current or previous item. In Vim9 script it just uses
856the index, if items are deleted then items in the list will be skipped.
857Example legacy script: >
858 let l = [1, 2, 3, 4]
859 for i in l
860 echo i
861 call remove(l, index(l, i))
862 endfor
863Would echo:
864 1
865 2
866 3
867 4
868In compiled Vim9 script you get:
869 1
870 3
871Generally, you should not change the list that is iterated over. Make a copy
872first if needed.
873
874
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100875Conditions and expressions ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000876 *vim9-boolean*
Bram Moolenaar13106602020-10-04 16:06:05 +0200877Conditions and expressions are mostly working like they do in other languages.
878Some values are different from legacy Vim script:
879 value legacy Vim script Vim9 script ~
880 0 falsy falsy
881 1 truthy truthy
882 99 truthy Error!
883 "0" falsy Error!
884 "99" truthy Error!
885 "text" falsy Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100886
Bram Moolenaar13106602020-10-04 16:06:05 +0200887For the "??" operator and when using "!" then there is no error, every value
888is either falsy or truthy. This is mostly like JavaScript, except that an
889empty list and dict is falsy:
890
891 type truthy when ~
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100892 bool true, v:true or 1
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100893 number non-zero
894 float non-zero
895 string non-empty
896 blob non-empty
897 list non-empty (different from JavaScript)
898 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200899 func when there is a function name
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100900 special true or v:true
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100901 job when not NULL
902 channel when not NULL
903 class when not NULL
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100904 object when not NULL (TODO: when isTrue() returns true)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100905
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200906The boolean operators "||" and "&&" expect the values to be boolean, zero or
907one: >
908 1 || false == true
909 0 || 1 == true
910 0 || false == false
911 1 && true == true
912 0 && 1 == false
913 8 || 0 Error!
914 'yes' && 0 Error!
915 [] || 99 Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100916
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200917When using "!" for inverting, there is no error for using any type and the
Bram Moolenaar13106602020-10-04 16:06:05 +0200918result is a boolean. "!!" can be used to turn any value into boolean: >
Bram Moolenaar82be4842021-01-11 19:40:15 +0100919 !'yes' == false
Bram Moolenaar13106602020-10-04 16:06:05 +0200920 !![] == false
Bram Moolenaar82be4842021-01-11 19:40:15 +0100921 !![1, 2, 3] == true
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200922
923When using "`.."` for string concatenation arguments of simple types are
Bram Moolenaar13106602020-10-04 16:06:05 +0200924always converted to string: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100925 'hello ' .. 123 == 'hello 123'
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100926 'hello ' .. v:true == 'hello true'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100927
Bram Moolenaar5da36052021-12-27 15:39:57 +0000928Simple types are Number, Float, Special and Bool. For other types |string()|
929should be used.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000930 *false* *true* *null* *E1034*
Bram Moolenaar67977822021-01-03 21:53:53 +0100931In Vim9 script one can use "true" for v:true, "false" for v:false and "null"
932for v:null. When converting a boolean to a string "false" and "true" are
933used, not "v:false" and "v:true" like in legacy script. "v:none" is not
934changed, it is only used in JSON and has no equivalent in other languages.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100935
Bram Moolenaar0289a092021-03-14 18:40:19 +0100936Indexing a string with [idx] or taking a slice with [idx : idx] uses character
937indexes instead of byte indexes. Composing characters are included.
938Example: >
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200939 echo 'bár'[1]
940In legacy script this results in the character 0xc3 (an illegal byte), in Vim9
941script this results in the string 'á'.
Bram Moolenaar82be4842021-01-11 19:40:15 +0100942A negative index is counting from the end, "[-1]" is the last character.
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100943To exclude the last character use |slice()|.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200944To count composing characters separately use |strcharpart()|.
Bram Moolenaar82be4842021-01-11 19:40:15 +0100945If the index is out of range then an empty string results.
946
947In legacy script "++var" and "--var" would be silently accepted and have no
948effect. This is an error in Vim9 script.
949
950Numbers starting with zero are not considered to be octal, only numbers
951starting with "0o" are octal: "0o744". |scriptversion-4|
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200952
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100953
Bram Moolenaare46a4402020-06-30 20:38:27 +0200954What to watch out for ~
955 *vim9-gotchas*
956Vim9 was designed to be closer to often used programming languages, but at the
957same time tries to support the legacy Vim commands. Some compromises had to
958be made. Here is a summary of what might be unexpected.
959
960Ex command ranges need to be prefixed with a colon. >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100961 -> legacy Vim: shifts the previous line to the right
962 ->func() Vim9: method call in a continuation line
963 :-> Vim9: shifts the previous line to the right
Bram Moolenaare46a4402020-06-30 20:38:27 +0200964
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100965 %s/a/b legacy Vim: substitute on all lines
Bram Moolenaare46a4402020-06-30 20:38:27 +0200966 x = alongname
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100967 % another Vim9: modulo operator in a continuation line
968 :%s/a/b Vim9: substitute on all lines
969 't legacy Vim: jump to mark t
970 'text'->func() Vim9: method call
971 :'t Vim9: jump to mark t
Bram Moolenaare46a4402020-06-30 20:38:27 +0200972
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200973Some Ex commands can be confused with assignments in Vim9 script: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100974 g:name = value # assignment
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100975 :g:pattern:cmd # :global command
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200976
Bram Moolenaar7b829262021-10-13 15:04:34 +0100977To avoid confusion between a `:global` or `:substitute` command and an
978expression or assignment, a few separators cannot be used when these commands
979are abbreviated to a single character: ':', '-' and '.'. >
980 g:pattern:cmd # invalid command - ERROR
981 s:pattern:repl # invalid command - ERROR
982 g-pattern-cmd # invalid command - ERROR
983 s-pattern-repl # invalid command - ERROR
984 g.pattern.cmd # invalid command - ERROR
985 s.pattern.repl # invalid command - ERROR
986
987Also, there cannot be a space between the command and the separator: >
988 g /pattern/cmd # invalid command - ERROR
989 s /pattern/repl # invalid command - ERROR
990
Bram Moolenaare46a4402020-06-30 20:38:27 +0200991Functions defined with `:def` compile the whole function. Legacy functions
992can bail out, and the following lines are not parsed: >
993 func Maybe()
994 if !has('feature')
995 return
996 endif
997 use-feature
998 endfunc
999Vim9 functions are compiled as a whole: >
1000 def Maybe()
1001 if !has('feature')
1002 return
1003 endif
Bram Moolenaar82be4842021-01-11 19:40:15 +01001004 use-feature # May give a compilation error
Bram Moolenaare46a4402020-06-30 20:38:27 +02001005 enddef
1006For a workaround, split it in two functions: >
1007 func Maybe()
1008 if has('feature')
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001009 call MaybeInner()
Bram Moolenaare46a4402020-06-30 20:38:27 +02001010 endif
1011 endfunc
1012 if has('feature')
1013 def MaybeInner()
1014 use-feature
1015 enddef
1016 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001017Or put the unsupported code inside an `if` with a constant expression that
Bram Moolenaar207f0092020-08-30 17:20:20 +02001018evaluates to false: >
1019 def Maybe()
1020 if has('feature')
1021 use-feature
1022 endif
1023 enddef
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001024The `exists_compiled()` function can also be used for this.
1025 *vim9-user-command*
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001026Another side effect of compiling a function is that the presence of a user
Bram Moolenaar82be4842021-01-11 19:40:15 +01001027command is checked at compile time. If the user command is defined later an
1028error will result. This works: >
1029 command -nargs=1 MyCommand echom <q-args>
1030 def Works()
1031 MyCommand 123
1032 enddef
1033This will give an error for "MyCommand" not being defined: >
1034 def Works()
1035 command -nargs=1 MyCommand echom <q-args>
1036 MyCommand 123
1037 enddef
1038A workaround is to invoke the command indirectly with `:execute`: >
1039 def Works()
1040 command -nargs=1 MyCommand echom <q-args>
1041 execute 'MyCommand 123'
1042 enddef
1043
Bram Moolenaar207f0092020-08-30 17:20:20 +02001044Note that for unrecognized commands there is no check for "|" and a following
1045command. This will give an error for missing `endif`: >
1046 def Maybe()
1047 if has('feature') | use-feature | endif
1048 enddef
Bram Moolenaare46a4402020-06-30 20:38:27 +02001049
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001050Other differences ~
1051
1052Patterns are used like 'magic' is set, unless explicitly overruled.
1053The 'edcompatible' option value is not used.
1054The 'gdefault' option value is not used.
1055
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001056You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaarc8cdf0f2021-03-13 13:28:13 +01001057Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001058
Bram Moolenaar4d8f4762021-06-27 15:18:56 +02001059 *:++* *:--*
1060The ++ and -- commands have been added. They are very similar to adding or
1061subtracting one: >
1062 ++var
1063 var += 1
1064 --var
1065 var -= 1
1066
1067Using ++var or --var in an expression is not supported yet.
1068
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001069==============================================================================
1070
10713. New style functions *fast-functions*
1072
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001073 *:def* *E1028*
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001074:def[!] {name}([arguments])[: {return-type}]
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001075 Define a new function by the name {name}. The body of
1076 the function follows in the next lines, until the
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001077 matching `:enddef`. *E1073*
1078 *E1011*
1079 The {name} must be less than 100 bytes long.
1080 *E1003* *E1027* *E1056* *E1059*
1081 The type of value used with `:return` must match
1082 {return-type}. When {return-type} is omitted or is
1083 "void" the function is not expected to return
1084 anything.
1085 *E1077*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001086 {arguments} is a sequence of zero or more argument
1087 declarations. There are three forms:
1088 {name}: {type}
1089 {name} = {value}
1090 {name}: {type} = {value}
1091 The first form is a mandatory argument, the caller
1092 must always provide them.
1093 The second and third form are optional arguments.
1094 When the caller omits an argument the {value} is used.
1095
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001096 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001097 called, or when `:disassemble` or `:defcompile` is
1098 used. Syntax and type errors will be produced at that
1099 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001100
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001101 It is possible to nest `:def` inside another `:def` or
1102 `:function` up to about 50 levels deep.
Bram Moolenaar560979e2020-02-04 22:53:05 +01001103
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001104 [!] is used as with `:function`. Note that
1105 script-local functions cannot be deleted or redefined
1106 later in Vim9 script. They can only be removed by
1107 reloading the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001108
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001109 *:enddef* *E1057*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001110:enddef End of a function defined with `:def`. It should be on
1111 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001112
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001113You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaar0289a092021-03-14 18:40:19 +01001114Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001115
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001116If the script the function is defined in is Vim9 script, then script-local
1117variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001118before the function is compiled. If the script the function is defined in is
1119legacy script, then script-local variables must be accessed with the "s:"
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001120prefix if they do not exist at the time of compiling.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001121
Bram Moolenaar388a5d42020-05-26 21:20:45 +02001122 *:defc* *:defcompile*
1123:defc[ompile] Compile functions defined in the current script that
1124 were not compiled yet.
1125 This will report errors found during the compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001126
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001127 *:disa* *:disassemble*
1128:disa[ssemble] {func} Show the instructions generated for {func}.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001129 This is for debugging and testing. *E1061*
Bram Moolenaarcc390ff2020-02-29 22:06:30 +01001130 Note that for command line completion of {func} you
1131 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001132
Bram Moolenaar2346a632021-06-13 19:02:49 +02001133:disa[ssemble] profile {func}
1134 Like `:disassemble` but with the instructions used for
Bram Moolenaare0e39172021-01-25 21:14:57 +01001135 profiling.
1136
Bram Moolenaar2346a632021-06-13 19:02:49 +02001137:disa[ssemble] debug {func}
1138 Like `:disassemble` but with the instructions used for
1139 debugging.
1140
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001141Limitations ~
1142
1143Local variables will not be visible to string evaluation. For example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001144 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001145 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001146 return range(1, 2)->map('list[v:val]')
1147 enddef
1148
1149The map argument is a string expression, which is evaluated without the
1150function scope. Instead, use a lambda: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001151 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001152 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar22863042021-10-16 15:23:36 +01001153 return range(1, 2)->map((_, v) => list[v])
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001154 enddef
1155
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001156For commands that are not compiled, such as `:edit`, backtick expansion can be
1157used and it can use the local scope. Example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001158 def Replace()
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001159 var fname = 'blah.txt'
1160 edit `=fname`
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001161 enddef
1162
Bram Moolenaardad44732021-03-31 20:07:33 +02001163Closures defined in a loop will share the same context. For example: >
1164 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001165 for i in range(5)
Bram Moolenaardad44732021-03-31 20:07:33 +02001166 var inloop = i
1167 flist[i] = () => inloop
1168 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001169 echo range(5)->map((i, _) => flist[i]())
1170 # Result: [4, 4, 4, 4, 4]
Bram Moolenaardad44732021-03-31 20:07:33 +02001171
1172The "inloop" variable will exist only once, all closures put in the list refer
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001173to the same instance, which in the end will have the value 4. This is
1174efficient, also when looping many times. If you do want a separate context
1175for each closure call a function to define it: >
1176 def GetClosure(i: number): func
1177 var infunc = i
1178 return () => infunc
Bram Moolenaardad44732021-03-31 20:07:33 +02001179 enddef
1180
1181 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001182 for i in range(5)
1183 flist[i] = GetClosure(i)
Bram Moolenaardad44732021-03-31 20:07:33 +02001184 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001185 echo range(5)->map((i, _) => flist[i]())
1186 # Result: [0, 1, 2, 3, 4]
Bram Moolenaardad44732021-03-31 20:07:33 +02001187
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001188==============================================================================
1189
11904. Types *vim9-types*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001191 *E1008* *E1009* *E1010* *E1012*
1192 *E1013* *E1029* *E1030*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001193The following builtin types are supported:
1194 bool
1195 number
1196 float
1197 string
1198 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +02001199 list<{type}>
1200 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001201 job
1202 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +01001203 func
Bram Moolenaard1caa942020-04-10 22:10:56 +02001204 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +02001205 func({type}, ...)
1206 func({type}, ...): {type}
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001207 void
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001208
1209Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +02001210 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001211
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001212These types can be used in declarations, but no simple value will actually
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001213have the "void" type. Trying to use a void (e.g. a function without a
1214return value) results in error *E1031* .
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001215
Bram Moolenaard77a8522020-04-03 21:59:57 +02001216There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001217efficient implementation is used that avoids allocating lot of small pieces of
1218memory.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001219 *E1005* *E1007*
Bram Moolenaard77a8522020-04-03 21:59:57 +02001220A partial and function can be declared in more or less specific ways:
1221func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +02001222 checking for arguments or return value
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001223func: void any number and type of arguments, no return
1224 value
Bram Moolenaard77a8522020-04-03 21:59:57 +02001225func: {type} any number and type of arguments with specific
1226 return type
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001227
1228func() function with no argument, does not return a
1229 value
1230func(): void same
1231func(): {type} function with no argument and return type
1232
Bram Moolenaard1caa942020-04-10 22:10:56 +02001233func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +02001234 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +02001235func({type}): {type} function with argument type and return type
1236func(?{type}) function with type of optional argument, does
1237 not return a value
1238func(...{type}) function with type of variable number of
1239 arguments, does not return a value
1240func({type}, ?{type}, ...{type}): {type}
1241 function with:
1242 - type of mandatory argument
1243 - type of optional argument
1244 - type of variable number of arguments
1245 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +02001246
1247If the return type is "void" the function does not return a value.
1248
1249The reference can also be a |Partial|, in which case it stores extra arguments
1250and/or a dictionary, which are not visible to the caller. Since they are
1251called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001252
1253Custom types can be defined with `:type`: >
1254 :type MyList list<string>
Bram Moolenaar127542b2020-08-09 17:22:04 +02001255Custom types must start with a capital letter, to avoid name clashes with
1256builtin types added later, similarly to user functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001257{not implemented yet}
1258
1259And classes and interfaces can be used as types: >
1260 :class MyClass
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001261 :var mine: MyClass
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001262
1263 :interface MyInterface
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001264 :var mine: MyInterface
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001265
1266 :class MyTemplate<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001267 :var mine: MyTemplate<number>
1268 :var mine: MyTemplate<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001269
1270 :class MyInterface<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001271 :var mine: MyInterface<number>
1272 :var mine: MyInterface<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001273{not implemented yet}
1274
1275
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001276Variable types and type casting ~
1277 *variable-types*
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001278Variables declared in Vim9 script or in a `:def` function have a type, either
1279specified explicitly or inferred from the initialization.
1280
1281Global, buffer, window and tab page variables do not have a specific type, the
1282value can be changed at any time, possibly changing the type. Therefore, in
1283compiled code the "any" type is assumed.
1284
1285This can be a problem when the "any" type is undesired and the actual type is
1286expected to always be the same. For example, when declaring a list: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001287 var l: list<number> = [1, g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001288At compile time Vim doesn't know the type of "g:two" and the expression type
1289becomes list<any>. An instruction is generated to check the list type before
1290doing the assignment, which is a bit inefficient.
1291 *type-casting*
1292To avoid this, use a type cast: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001293 var l: list<number> = [1, <number>g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001294The compiled code will then only check that "g:two" is a number and give an
1295error if it isn't. This is called type casting.
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001296
1297The syntax of a type cast is: "<" {type} ">". There cannot be white space
1298after the "<" or before the ">" (to avoid them being confused with
1299smaller-than and bigger-than operators).
1300
1301The semantics is that, if needed, a runtime type check is performed. The
1302value is not actually changed. If you need to change the type, e.g. to change
1303it to a string, use the |string()| function. Or use |str2nr()| to convert a
1304string to a number.
1305
1306
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001307Type inference ~
1308 *type-inference*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001309In general: Whenever the type is clear it can be omitted. For example, when
1310declaring a variable and giving it a value: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001311 var name = 0 # infers number type
1312 var name = 'hello' # infers string type
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001313
Bram Moolenaar127542b2020-08-09 17:22:04 +02001314The type of a list and dictionary comes from the common type of the values.
1315If the values all have the same type, that type is used for the list or
1316dictionary. If there is a mix of types, the "any" type is used. >
1317 [1, 2, 3] list<number>
1318 ['a', 'b', 'c'] list<string>
1319 [1, 'x', 3] list<any>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001320
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001321The common type of function references, if they do not all have the same
1322number of arguments, uses "(...)" to indicate the number of arguments is not
1323specified. For example: >
1324 def Foo(x: bool)
1325 enddef
1326 def Bar(x: bool, y: bool)
1327 enddef
1328 var funclist = [Foo, Bar]
1329 echo funclist->typename()
1330Results in:
1331 list<func(...)>
1332
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001333For script-local variables in Vim9 script the type is checked, also when the
1334variable was declared in a legacy function.
1335
Bram Moolenaar207f0092020-08-30 17:20:20 +02001336
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001337Stricter type checking ~
1338 *type-checking*
Bram Moolenaar207f0092020-08-30 17:20:20 +02001339In legacy Vim script, where a number was expected, a string would be
1340automatically converted to a number. This was convenient for an actual number
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001341such as "123", but leads to unexpected problems (and no error message) if the
Bram Moolenaar207f0092020-08-30 17:20:20 +02001342string doesn't start with a number. Quite often this leads to hard-to-find
1343bugs.
1344
1345In Vim9 script this has been made stricter. In most places it works just as
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001346before, if the value used matches the expected type. There will sometimes be
1347an error, thus breaking backwards compatibility. For example:
Bram Moolenaar207f0092020-08-30 17:20:20 +02001348- Using a number other than 0 or 1 where a boolean is expected. *E1023*
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001349- Using a string value when setting a number option.
Bram Moolenaar207f0092020-08-30 17:20:20 +02001350- Using a number where a string is expected. *E1024*
1351
Bram Moolenaar22863042021-10-16 15:23:36 +01001352One consequence is that the item type of a list or dict given to |map()| must
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001353not change. This will give an error in Vim9 script: >
Bram Moolenaar22863042021-10-16 15:23:36 +01001354 echo map([1, 2, 3], (i, v) => 'item ' .. i)
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001355 E1012: Type mismatch; expected number but got string
Bram Moolenaar22863042021-10-16 15:23:36 +01001356Instead use |mapnew()|: >
1357 echo mapnew([1, 2, 3], (i, v) => 'item ' .. i)
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001358 ['item 0', 'item 1', 'item 2']
1359
1360If the item type was determined to be "any" it can change to a more specific
Bram Moolenaar22863042021-10-16 15:23:36 +01001361type. E.g. when a list of mixed types gets changed to a list of strings: >
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001362 var mylist = [1, 2.0, '3']
1363 # typename(mylist) == "list<any>"
1364 map(mylist, (i, v) => 'item ' .. i)
1365 # typename(mylist) == "list<string>", no error
1366
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001367Same for |extend()|, use |extendnew()| instead, and for |flatten()|, use
1368|flattennew()| instead.
Bram Moolenaar82be4842021-01-11 19:40:15 +01001369
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001370==============================================================================
1371
Bram Moolenaar30fd8202020-09-26 15:09:30 +020013725. Namespace, Import and Export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001373 *vim9script* *vim9-export* *vim9-import*
1374
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001375A Vim9 script can be written to be imported. This means that some items are
1376intentionally exported, made available to other scripts. When the exporting
1377script is imported in another script, these exported items can then be used in
1378that script. All the other items remain script-local in the exporting script
1379and cannot be accessed by the importing script.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001380
1381This mechanism exists for writing a script that can be sourced (imported) by
1382other scripts, while making sure these other scripts only have access to what
1383you want them to. This also avoids using the global namespace, which has a
1384risc of name collisions. For example when you have two plugins with similar
1385functionality.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001386
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001387You can cheat by using the global namespace explicitly. That should be done
1388only for things that really are global.
Bram Moolenaar207f0092020-08-30 17:20:20 +02001389
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001390
1391Namespace ~
Bram Moolenaardcc58e02020-12-28 20:53:21 +01001392 *vim9-namespace*
Bram Moolenaar560979e2020-02-04 22:53:05 +01001393To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001394appear as the first statement in the file (see |vim9-mix| for an exception).
1395It tells Vim to interpret the script in its own namespace, instead of the
1396global namespace. If a file starts with: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001397 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001398 var myvar = 'yes'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001399Then "myvar" will only exist in this file. While without `vim9script` it would
1400be available as `g:myvar` from any other script and function.
1401
1402The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001403variables in legacy Vim script, but the "s:" is omitted. And they cannot be
1404deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001405
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001406In Vim9 script the global "g:" namespace can still be used as before. And the
1407"w:", "b:" and "t:" namespaces. These have in common that variables are not
1408declared and they can be deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001409
1410A side effect of `:vim9script` is that the 'cpoptions' option is set to the
1411Vim default value, like with: >
1412 :set cpo&vim
1413One of the effects is that |line-continuation| is always enabled.
Bram Moolenaar3e191692021-03-17 17:46:00 +01001414The original value of 'cpoptions' is restored at the end of the script, while
1415flags added or removed in the script are also added to or removed from the
1416original value to get the same effect. The order of flags may change.
Bram Moolenaar71eb3ad2021-12-26 12:07:30 +00001417In the |vimrc| file sourced on startup this does not happen.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001418
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001419 *vim9-mix*
1420There is one way to use both legacy and Vim9 syntax in one script file: >
1421 " comments may go here
1422 if !has('vim9script')
1423 " legacy script commands go here
1424 finish
1425 endif
1426 vim9script
1427 # Vim9 script commands go here
1428This allows for writing a script that takes advantage of the Vim9 script
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001429syntax if possible, but will also work on a Vim version without it.
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001430
1431This can only work in two ways:
14321. The "if" statement evaluates to false, the commands up to `endif` are
1433 skipped and `vim9script` is then the first command actually executed.
14342. The "if" statement evaluates to true, the commands up to `endif` are
1435 executed and `finish` bails out before reaching `vim9script`.
1436
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001437
1438Export ~
1439 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001440Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001441 export const EXPORTED_CONST = 1234
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001442 export var someValue = ...
1443 export final someValue = ...
1444 export const someValue = ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001445 export def MyFunc() ...
1446 export class MyClass ...
Bram Moolenaar74235772021-06-12 14:53:05 +02001447 export interface MyClass ...
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001448< *E1043* *E1044*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001449As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar74235772021-06-12 14:53:05 +02001450be exported. {not implemented yet: class, interface}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001451
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001452 *E1042*
1453`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001454
1455
1456Import ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001457 *:import* *:imp* *E1094* *E1047*
1458 *E1048* *E1049* *E1053* *E1071*
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001459The exported items can be imported in another Vim9 script: >
1460 import "myscript.vim"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001461
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001462This makes each item available as "myscript.item".
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001463 *:import-as*
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001464In case the name is long or ambiguous, another name can be specified: >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001465 import "thatscript.vim" as that
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001466< *E1060*
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001467Then you can use "that.EXPORTED_CONST", "that.someValue", etc. You are free
1468to choose the name "that". Use something that will be recognized as referring
1469to the imported script. Avoid command names and builtin function names,
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001470because the name will shadow them. If the name starts with a capital letter
1471it can also shadow global user commands and functions. Also, you cannot use
1472the name for something else in the script, such as a function or variable
1473name.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001474
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001475In case the dot in the name is undesired, a local reference can be made for a
1476function: >
1477 var LongFunc = that.LongFuncName
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001478
1479This also works for constants: >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001480 const MAXLEN = that.MAX_LEN_OF_NAME
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001481
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001482This does not work for variables, since the value would be copied once and
1483when changing the variable the copy will change, not the original variable.
1484You will need to use the full name, with the dot.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001485
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001486The full syntax of the command is:
1487 import {filename} [as {name}]
1488Where {filename} is an expression that must evaluate to a string. Without the
1489"as {name}" part it must end in ".vim". {name} must consist of letters,
1490digits and '_', like |internal-variables|.
1491
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001492`:import` can also be used in legacy Vim script. The imported items still
1493become script-local, even when the "s:" prefix is not given.
1494
Bram Moolenaar4db572e2021-07-18 18:21:38 +02001495`:import` can not be used in a function. Imported items are intended to exist
1496at the script level and only imported once.
1497
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001498The script name after `import` can be:
1499- A relative path, starting "." or "..". This finds a file relative to the
1500 location of the script file itself. This is useful to split up a large
1501 plugin into several files.
1502- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001503 will rarely be used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001504- A path not being relative or absolute. This will be found in the
1505 "import" subdirectories of 'runtimepath' entries. The name will usually be
1506 longer and unique, to avoid loading the wrong file.
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001507 Note that "after/import" is not used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001508
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001509If the name does not end in ".vim" then the use of "as name" is required.
1510
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001511Once a vim9 script file has been imported, the result is cached and used the
1512next time the same script is imported. It will not be read again.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001513
1514It is not allowed to import the same script twice, also when using two
1515different "as" names.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001516
1517When using the imported name the dot and the item name must be in the same
1518line, there can be no line break: >
1519 echo that.
1520 name # Error!
1521 echo that
1522 .name # Error!
1523< *:import-cycle*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001524The `import` commands are executed when encountered. If that script (directly
1525or indirectly) imports the current script, then items defined after the
1526`import` won't be processed yet. Therefore cyclic imports can exist, but may
1527result in undefined items.
1528
1529
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001530Importing an autoload script ~
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001531 *vim9-autoload*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001532For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001533actually needed. Using the autoload mechanism is recommended:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001534
15351. In the plugin define user commands, functions and/or mappings that refer to
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001536 items imported from an autoload script. >
1537 import autoload 'for/search.vim'
1538 command -nargs=1 SearchForStuff search.Stuff(<f-args>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001539
1540< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001541 The "SearchForStuff" command is now available to the user.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001542
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001543 The "autoload" argument to `:import` means that the script is not loaded
1544 until one of the items is actually used. The script will be found under
1545 the "autoload" directory in 'runtimepath' instead of the "import"
1546 directory.
1547
15482. In the autoload script put the bulk of the code. >
Bram Moolenaarfd218c82022-01-18 16:26:24 +00001549 vim9script
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001550 export def Stuff(arg: string)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001551 ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001552
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001553< This goes in .../autoload/for/search.vim.
1554
Bram Moolenaarfd218c82022-01-18 16:26:24 +00001555 Putting the "search.vim" script under the "/autoload/for/" directory has
1556 the effect that "for#search#" will be prefixed to every exported item. The
1557 prefix is obtained from the file name, as you would to manually in a
1558 legacy autoload script. Thus the exported function can be found with
1559 "for#search#Stuff", but you would normally use `import autoload` and not
1560 use the prefix.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001561
1562 You can split up the functionality and import other scripts from the
1563 autoload script as you like. This way you can share code between plugins.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001564
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001565For defining a mapping that uses the imported autoload script the special key
1566|<ScriptCmd>| is useful. It allows for a command in a mapping to use the
1567script context of where the mapping was defined.
1568
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001569When compiling a `:def` function and a function in an autoload script is
1570encountered, the script is not loaded until the `:def` function is called.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001571This also means you get any errors only at runtime, since the argument and
1572return types are not known yet.
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001573
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001574For testing the |test_override()| function can be used to have the
1575`import autoload` load the script right away, so that the items and types can
1576be checked without waiting for them to be actually used: >
1577 test_override('autoload', 1)
1578Reset it later with: >
1579 test_override('autoload', 0)
1580Or: >
1581 test_override('ALL', 0)
1582
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001583
1584Import in legacy Vim script ~
1585
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001586If an `import` statement is used in legacy Vim script, the script-local "s:"
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001587namespace will be used for the imported items, even when "s:" is not
1588specified.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001589
1590
1591==============================================================================
1592
Bram Moolenaar1d59aa12020-09-19 18:50:13 +020015936. Future work: classes *vim9-classes*
1594
1595Above "class" was mentioned a few times, but it has not been implemented yet.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001596Most of Vim9 script can be created without this functionality, and since
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001597implementing classes is going to be a lot of work, it is left for the future.
1598For now we'll just make sure classes can be added later.
1599
1600Thoughts:
Bram Moolenaar74235772021-06-12 14:53:05 +02001601- `class` / `endclass`, the whole class must be in one file
1602- Class names are always CamelCase (to avoid a name clash with builtin types)
1603- A single constructor called "constructor"
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001604- Single inheritance with `class ThisClass extends BaseClass`
Bram Moolenaar74235772021-06-12 14:53:05 +02001605- `abstract class` (class with incomplete implementation)
1606- `interface` / `endinterface` (abstract class without any implementation)
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001607- `class SomeClass implements SomeInterface`
1608- Generics for class: `class <Tkey, Tentry>`
1609- Generics for function: `def <Tkey> GetLast(key: Tkey)`
1610
Bram Moolenaar74235772021-06-12 14:53:05 +02001611Again, much of this is from TypeScript with a slightly different syntax.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001612
1613Some things that look like good additions:
1614- Use a class as an interface (like Dart)
1615- Extend a class with methods, using an import (like Dart)
Bram Moolenaar74235772021-06-12 14:53:05 +02001616- Mixins
1617- For testing: Mock mechanism
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001618
1619An important class that will be provided is "Promise". Since Vim is single
1620threaded, connecting asynchronous operations is a natural way of allowing
1621plugins to do their work without blocking the user. It's a uniform way to
1622invoke callbacks and handle timeouts and errors.
1623
Bram Moolenaar74235772021-06-12 14:53:05 +02001624Some examples: >
1625
1626 abstract class Person
1627 static const prefix = 'xxx'
1628 var name: string
1629
1630 def constructor(name: string)
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001631 this.name = name
Bram Moolenaar74235772021-06-12 14:53:05 +02001632 enddef
1633
1634 def display(): void
1635 echo name
1636 enddef
1637
1638 abstract def find(string): Person
1639 endclass
1640
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001641==============================================================================
1642
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010016439. Rationale *vim9-rationale*
1644
1645The :def command ~
1646
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001647Plugin writers have asked for much faster Vim script. Investigations have
Bram Moolenaar560979e2020-02-04 22:53:05 +01001648shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001649impossible, because of the overhead involved with calling a function, setting
1650up the local function scope and executing lines. There are many details that
1651need to be handled, such as error messages and exceptions. The need to create
1652a dictionary for a: and l: scopes, the a:000 list and several others add too
1653much overhead that cannot be avoided.
1654
1655Therefore the `:def` method to define a new-style function had to be added,
1656which allows for a function with different semantics. Most things still work
1657as before, but some parts do not. A new way to define a function was
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001658considered the best way to separate the legacy style code from Vim9 style code.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001659
1660Using "def" to define a function comes from Python. Other languages use
1661"function" which clashes with legacy Vim script.
1662
1663
1664Type checking ~
1665
1666When compiling lines of Vim commands into instructions as much as possible
1667should be done at compile time. Postponing it to runtime makes the execution
1668slower and means mistakes are found only later. For example, when
1669encountering the "+" character and compiling this into a generic add
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001670instruction, at runtime the instruction would have to inspect the type of the
1671arguments and decide what kind of addition to do. And when the type is
1672dictionary throw an error. If the types are known to be numbers then an "add
1673number" instruction can be used, which is faster. The error can be given at
1674compile time, no error handling is needed at runtime, since adding two numbers
1675cannot fail.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001676
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001677The syntax for types, using <type> for compound types, is similar to Java. It
1678is easy to understand and widely used. The type names are what were used in
1679Vim before, with some additions such as "void" and "bool".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001680
1681
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001682Removing clutter and weirdness ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001683
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001684Once decided that `:def` functions have different syntax than legacy functions,
1685we are free to add improvements to make the code more familiar for users who
1686know popular programming languages. In other words: remove weird things that
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001687only Vim does.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001688
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001689We can also remove clutter, mainly things that were done to make Vim script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001690backwards compatible with the good old Vi commands.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001691
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001692Examples:
1693- Drop `:call` for calling a function and `:eval` for manipulating data.
1694- Drop using a leading backslash for line continuation, automatically figure
1695 out where an expression ends.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001696
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001697However, this does require that some things need to change:
1698- Comments start with # instead of ", to avoid confusing them with strings.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001699 This is good anyway, it is known from several popular languages.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001700- Ex command ranges need to be prefixed with a colon, to avoid confusion with
1701 expressions (single quote can be a string or a mark, "/" can be divide or a
1702 search command, etc.).
1703
1704Goal is to limit the differences. A good criteria is that when the old syntax
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001705is accidentally used you are very likely to get an error message.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001706
1707
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001708Syntax and semantics from popular languages ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001709
1710Script writers have complained that the Vim script syntax is unexpectedly
1711different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001712languages are used as an example. At the same time, we do not want to abandon
1713the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001714
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001715For many things TypeScript is followed. It's a recent language that is
1716gaining popularity and has similarities with Vim script. It also has a
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001717mix of static typing (a variable always has a known value type) and dynamic
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001718typing (a variable can have different types, this changes at runtime). Since
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001719legacy Vim script is dynamically typed and a lot of existing functionality
1720(esp. builtin functions) depends on that, while static typing allows for much
1721faster execution, we need to have this mix in Vim9 script.
1722
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001723There is no intention to completely match TypeScript syntax and semantics. We
1724just want to take those parts that we can use for Vim and we expect Vim users
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001725will be happy with. TypeScript is a complex language with its own history,
1726advantages and disadvantages. To get an idea of the disadvantages read the
1727book: "JavaScript: The Good Parts". Or find the article "TypeScript: the good
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001728parts" and read the "Things to avoid" section.
1729
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001730People familiar with other languages (Java, Python, etc.) will also find
1731things in TypeScript that they do not like or do not understand. We'll try to
1732avoid those things.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001733
1734Specific items from TypeScript we avoid:
1735- Overloading "+", using it both for addition and string concatenation. This
1736 goes against legacy Vim script and often leads to mistakes. For that reason
1737 we will keep using ".." for string concatenation. Lua also uses ".." this
1738 way. And it allows for conversion to string for more values.
1739- TypeScript can use an expression like "99 || 'yes'" in a condition, but
1740 cannot assign the value to a boolean. That is inconsistent and can be
1741 annoying. Vim recognizes an expression with && or || and allows using the
Bram Moolenaar1f318c62021-12-26 18:09:31 +00001742 result as a bool. The |falsy-operator| was added for the mechanism to use a
1743 default value.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02001744- TypeScript considers an empty string as Falsy, but an empty list or dict as
1745 Truthy. That is inconsistent. In Vim an empty list and dict are also
1746 Falsy.
1747- TypeScript has various "Readonly" types, which have limited usefulness,
1748 since a type cast can remove the immutable nature. Vim locks the value,
1749 which is more flexible, but is only checked at runtime.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001750
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001751
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001752Declarations ~
1753
1754Legacy Vim script uses `:let` for every assignment, while in Vim9 declarations
1755are used. That is different, thus it's good to use a different command:
1756`:var`. This is used in many languages. The semantics might be slightly
1757different, but it's easily recognized as a declaration.
1758
Bram Moolenaar23515b42020-11-29 14:36:24 +01001759Using `:const` for constants is common, but the semantics varies. Some
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001760languages only make the variable immutable, others also make the value
1761immutable. Since "final" is well known from Java for only making the variable
1762immutable we decided to use that. And then `:const` can be used for making
1763both immutable. This was also used in legacy Vim script and the meaning is
1764almost the same.
1765
1766What we end up with is very similar to Dart: >
1767 :var name # mutable variable and value
1768 :final name # immutable variable, mutable value
1769 :const name # immutable variable and value
1770
1771Since legacy and Vim9 script will be mixed and global variables will be
1772shared, optional type checking is desirable. Also, type inference will avoid
1773the need for specifying the type in many cases. The TypeScript syntax fits
1774best for adding types to declarations: >
1775 var name: string # string type is specified
1776 ...
1777 name = 'John'
1778 const greeting = 'hello' # string type is inferred
1779
1780This is how we put types in a declaration: >
1781 var mylist: list<string>
1782 final mylist: list<string> = ['foo']
1783 def Func(arg1: number, arg2: string): bool
1784
1785Two alternatives were considered:
17861. Put the type before the name, like Dart: >
1787 var list<string> mylist
1788 final list<string> mylist = ['foo']
1789 def Func(number arg1, string arg2) bool
17902. Put the type after the variable name, but do not use a colon, like Go: >
1791 var mylist list<string>
1792 final mylist list<string> = ['foo']
1793 def Func(arg1 number, arg2 string) bool
1794
1795The first is more familiar for anyone used to C or Java. The second one
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001796doesn't really have an advantage over the first, so let's discard the second.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001797
1798Since we use type inference the type can be left out when it can be inferred
1799from the value. This means that after `var` we don't know if a type or a name
1800follows. That makes parsing harder, not only for Vim but also for humans.
1801Also, it will not be allowed to use a variable name that could be a type name,
1802using `var string string` is too confusing.
1803
1804The chosen syntax, using a colon to separate the name from the type, adds
1805punctuation, but it actually makes it easier to recognize the parts of a
1806declaration.
1807
1808
1809Expressions ~
1810
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001811Expression evaluation was already close to what other languages are doing.
1812Some details are unexpected and can be improved. For example a boolean
1813condition would accept a string, convert it to a number and check if the
1814number is non-zero. This is unexpected and often leads to mistakes, since
1815text not starting with a number would be converted to zero, which is
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001816considered false. Thus using a string for a condition would often not give an
1817error and be considered false. That is confusing.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001818
Bram Moolenaar23515b42020-11-29 14:36:24 +01001819In Vim9 type checking is stricter to avoid mistakes. Where a condition is
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001820used, e.g. with the `:if` command and the `||` operator, only boolean-like
1821values are accepted:
1822 true: `true`, `v:true`, `1`, `0 < 9`
1823 false: `false`, `v:false`, `0`, `0 > 9`
1824Note that the number zero is false and the number one is true. This is more
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001825permissive than most other languages. It was done because many builtin
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001826functions return these values.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001827
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001828If you have any type of value and want to use it as a boolean, use the `!!`
1829operator:
Bram Moolenaard2ea7cf2021-05-30 20:54:13 +02001830 true: `!!'text'`, `!![99]`, `!!{'x': 1}`, `!!99`
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02001831 false: `!!''`, `!![]`, `!!{}`
1832
1833From a language like JavaScript we have this handy construct: >
1834 GetName() || 'unknown'
1835However, this conflicts with only allowing a boolean for a condition.
1836Therefore the "??" operator was added: >
1837 GetName() ?? 'unknown'
1838Here you can explicitly express your intention to use the value as-is and not
1839result in a boolean. This is called the |falsy-operator|.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001840
1841
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001842Import and Export ~
1843
1844A problem of legacy Vim script is that by default all functions and variables
1845are global. It is possible to make them script-local, but then they are not
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001846available in other scripts. This defies the concept of a package that only
1847exports selected items and keeps the rest local.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001848
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001849In Vim9 script a mechanism very similar to the JavaScript import and export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001850mechanism is supported. It is a variant to the existing `:source` command
1851that works like one would expect:
1852- Instead of making everything global by default, everything is script-local,
1853 unless exported.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001854- When importing a script the symbols that are imported are explicitly listed,
1855 avoiding name conflicts and failures if functionality is added later.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001856- The mechanism allows for writing a big, long script with a very clear API:
1857 the exported function(s) and class(es).
1858- By using relative paths loading can be much faster for an import inside of a
1859 package, no need to search many directories.
1860- Once an import has been used, it can be cached and loading it again can be
1861 avoided.
1862- The Vim-specific use of "s:" to make things script-local can be dropped.
1863
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001864When sourcing a Vim9 script from a legacy script, only the items defined
1865globally can be used, not the exported items. Alternatives considered:
1866- All the exported items become available as script-local items. This makes
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001867 it uncontrollable what items get defined and likely soon leads to trouble.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001868- Use the exported items and make them global. Disadvantage is that it's then
1869 not possible to avoid name clashes in the global namespace.
1870- Completely disallow sourcing a Vim9 script, require using `:import`. That
1871 makes it difficult to use scripts for testing, or sourcing them from the
1872 command line to try them out.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001873Note that you can also use `:import` in legacy Vim script, see above.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001874
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001875
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001876Compiling functions early ~
1877
1878Functions are compiled when called or when `:defcompile` is used. Why not
1879compile them early, so that syntax and type errors are reported early?
1880
1881The functions can't be compiled right away when encountered, because there may
1882be forward references to functions defined later. Consider defining functions
1883A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
1884to reorder the functions to avoid forward references.
1885
1886An alternative would be to first scan through the file to locate items and
1887figure out their type, so that forward references are found, and only then
1888execute the script and compile the functions. This means the script has to be
1889parsed twice, which is slower, and some conditions at the script level, such
1890as checking if a feature is supported, are hard to use. An attempt was made
1891to see if it works, but it turned out to be impossible to make work nicely.
1892
1893It would be possible to compile all the functions at the end of the script.
1894The drawback is that if a function never gets called, the overhead of
1895compiling it counts anyway. Since startup speed is very important, in most
1896cases it's better to do it later and accept that syntax and type errors are
1897only reported then. In case these errors should be found early, e.g. when
1898testing, the `:defcompile` command will help out.
1899
1900
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001901Why not use an embedded language? ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001902
1903Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001904these interfaces have never become widely used, for various reasons. When
1905Vim9 was designed a decision was made to make these interfaces lower priority
1906and concentrate on Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001907
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001908Still, plugin writers may find other languages more familiar, want to use
1909existing libraries or see a performance benefit. We encourage plugin authors
1910to write code in any language and run it as an external tool, using jobs and
1911channels. We can try to make this easier somehow.
1912
1913Using an external tool also has disadvantages. An alternative is to convert
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001914the tool into Vim script. For that to be possible without too much
1915translation, and keeping the code fast at the same time, the constructs of the
1916tool need to be supported. Since most languages support classes the lack of
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001917support for classes in Vim is then a problem.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001918
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001919
1920Classes ~
1921
1922Vim supports a kind-of object oriented programming by adding methods to a
1923dictionary. With some care this can be made to work, but it does not look
1924like real classes. On top of that, it's quite slow, because of the use of
1925dictionaries.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001926
1927The support of classes in Vim9 script is a "minimal common functionality" of
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001928class support in most languages. It works much like Java, which is the most
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001929popular programming language.
1930
1931
1932
1933 vim:tw=78:ts=8:noet:ft=help:norl: