blob: e13feee467cab0d65cdda00dfdcf8f6db5d59c44 [file] [log] [blame]
Bram Moolenaar7db29e42022-12-11 15:53:04 +00001*vim9.txt* For Vim version 9.0. Last change: 2022 Dec 08
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 Moolenaarc1c365c2022-12-04 20:13:24 +0000196. Classes and interfaces |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 Moolenaar8a3b8052022-06-26 12:21:15 +010040compatible. For example, making function arguments available in the "a:"
41dictionary adds quite a lot of overhead. In a Vim9 function this dictionary
42is not available. Other differences are more subtle, such as how errors are
43handled.
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 Moolenaara2baa732022-02-04 16:09:54 +000059:vim9[cmd] {cmd} *:vim9* *:vim9cmd* *E1164*
Bram Moolenaar5b1d6e92022-02-11 20:33:48 +000060 Evaluate and execute {cmd} using Vim9 script syntax and
61 semantics. Useful when typing a command and in a legacy
62 script or function.
Bram Moolenaar39f3b142021-02-14 12:57:36 +010063
Bram Moolenaara2baa732022-02-04 16:09:54 +000064:leg[acy] {cmd} *:leg* *:legacy* *E1189* *E1234*
Bram Moolenaar5b1d6e92022-02-11 20:33:48 +000065 Evaluate and execute {cmd} using legacy script syntax and
66 semantics. Only useful in a Vim9 script or a :def function.
Bram Moolenaar96cf4ba2021-04-24 14:15:41 +020067 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 ~
Bram Moolenaara2baa732022-02-04 16:09:54 +000075 *E1146*
Bram Moolenaard58a3bf2020-09-28 21:48:16 +020076Brief 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 Moolenaarf10911e2022-01-29 22:20:48 +000085- Assign values without `:let` *E1126* , 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 Moolenaar63f32602022-06-09 20:45:54 +010089 final matches = [] # add to the list later
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 Moolenaar8acb9cc2022-03-08 13:18:55 +000097- You cannot use old Ex commands:
98 `:Print`
99 `:append`
100 `:change`
101 `:d` directly followed by 'd' or 'p'.
102 `:insert`
103 `:k`
104 `:mode`
105 `:open`
106 `:s` with only flags
107 `:t`
108 `:xit`
109- Some commands, especially those used for flow control, cannot be shortened.
Bram Moolenaar9712ff12022-09-18 13:04:22 +0100110 E.g., `:throw` cannot be written as `:th`. *vim9-no-shorten*
Bram Moolenaar22863042021-10-16 15:23:36 +0100111- You cannot use curly-braces names.
Bram Moolenaard58a3bf2020-09-28 21:48:16 +0200112- A range before a command must be prefixed with a colon: >
Bram Moolenaar82be4842021-01-11 19:40:15 +0100113 :%s/this/that
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200114- Executing a register with "@r" does not work, you can prepend a colon or use
115 `:exe`: >
116 :exe @a
Bram Moolenaar82be4842021-01-11 19:40:15 +0100117- Unless mentioned specifically, the highest |scriptversion| is used.
Bram Moolenaarfd31be22022-01-16 14:46:06 +0000118- When defining an expression mapping, the expression will be evaluated in the
119 context of the script where it was defined.
Bram Moolenaard58a3bf2020-09-28 21:48:16 +0200120
121
Bram Moolenaar2c330432020-04-13 14:41:35 +0200122Comments starting with # ~
123
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200124In legacy Vim script comments start with double quote. In Vim9 script
125comments start with #. >
126 # declarations
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200127 var count = 0 # number of occurrences
Bram Moolenaar2c330432020-04-13 14:41:35 +0200128
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200129The reason is that a double quote can also be the start of a string. In many
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200130places, especially halfway through an expression with a line break, it's hard
131to tell what the meaning is, since both a string and a comment can be followed
132by arbitrary text. To avoid confusion only # comments are recognized. This
133is the same as in shell scripts and Python programs.
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200134
135In Vi # is a command to list text with numbers. In Vim9 script you can use
136`:number` for that. >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +0000137 :101 number
Bram Moolenaarf5be8cd2020-07-17 20:36:00 +0200138
139To improve readability there must be a space between a command and the #
Bram Moolenaar2b327002020-12-26 15:39:31 +0100140that starts a comment: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100141 var name = value # comment
142 var name = value# error!
Bram Moolenaara2baa732022-02-04 16:09:54 +0000143< *E1170*
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200144Do not start a comment with #{, it looks like the legacy dictionary literal
145and produces an error where this might be confusing. #{{ or #{{{ are OK,
146these can be used to start a fold.
147
Bram Moolenaar5ed11532022-07-06 13:18:11 +0100148When starting to read a script file Vim doesn't know it is |Vim9| script until
149the `vim9script` command is found. Until that point you would need to use
150legacy comments: >
151 " legacy comment
152 vim9script
153 # Vim9 comment
154
155That looks ugly, better put `vim9script` in the very first line: >
156 vim9script
157 # Vim9 comment
158
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100159In legacy Vim script # is also used for the alternate file name. In Vim9
160script you need to use %% instead. Instead of ## use %%% (stands for all
161arguments).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200162
Bram Moolenaar2c330432020-04-13 14:41:35 +0200163
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100164Vim9 functions ~
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000165 *E1099*
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200166A function defined with `:def` is compiled. Execution is many times faster,
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200167often 10 to 100 times.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200168
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200169Many errors are already found when compiling, before the function is executed.
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200170The syntax is strict, to enforce code that is easy to read and understand.
171
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200172Compilation is done when any of these is encountered:
Bram Moolenaar1b884a02020-12-10 21:11:27 +0100173- the first time the function is called
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200174- when the `:defcompile` command is encountered in the script after the
Bram Moolenaar207f0092020-08-30 17:20:20 +0200175 function was defined
176- `:disassemble` is used for the function.
177- a function that is compiled calls the function or uses it as a function
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200178 reference (so that the argument and return types can be checked)
Bram Moolenaara2baa732022-02-04 16:09:54 +0000179 *E1091* *E1191*
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200180If compilation fails it is not tried again on the next call, instead this
181error is given: "E1091: Function is not compiled: {name}".
Bram Moolenaar4c295022021-05-02 17:19:11 +0200182Compilation will fail when encountering a user command that has not been
183created yet. In this case you can call `execute()` to invoke it at runtime. >
184 def MyFunc()
185 execute('DefinedLater')
186 enddef
Bram Moolenaar388a5d42020-05-26 21:20:45 +0200187
188`:def` has no options like `:function` does: "range", "abort", "dict" or
Bram Moolenaar1b884a02020-12-10 21:11:27 +0100189"closure". A `:def` function always aborts on an error (unless `:silent!` was
Bram Moolenaarfa3b7232021-12-24 13:18:38 +0000190used for the command or the error was caught a `:try` block), does not get a
Bram Moolenaar63f32602022-06-09 20:45:54 +0100191range passed, cannot be a "dict" function, and can always be a closure.
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200192 *vim9-no-dict-function*
Bram Moolenaar74235772021-06-12 14:53:05 +0200193Later classes will be added, which replaces the "dict function" mechanism.
194For now you will need to pass the dictionary explicitly: >
Bram Moolenaar63f32602022-06-09 20:45:54 +0100195 def DictFunc(self: dict<any>, arg: string)
196 echo self[arg]
Bram Moolenaar74235772021-06-12 14:53:05 +0200197 enddef
Bram Moolenaar46eea442022-03-30 10:51:39 +0100198 var ad = {item: 'value', func: DictFunc}
Bram Moolenaarcbaff5e2022-04-08 17:45:08 +0100199 ad.func(ad, 'item')
Bram Moolenaar74235772021-06-12 14:53:05 +0200200
Bram Moolenaar34cc7d82021-09-21 20:09:51 +0200201You can call a legacy dict function though: >
202 func Legacy() dict
203 echo self.value
204 endfunc
205 def CallLegacy()
206 var d = {func: Legacy, value: 'text'}
207 d.func()
208 enddef
Bram Moolenaara2baa732022-02-04 16:09:54 +0000209< *E1096* *E1174* *E1175*
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200210The argument types and return type need to be specified. The "any" type can
211be used, type checking will then be done at runtime, like with legacy
212functions.
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000213 *E1106*
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200214Arguments are accessed by name, without "a:", just like any other language.
215There is no "a:" dictionary or "a:000" list.
Bram Moolenaara2baa732022-02-04 16:09:54 +0000216 *vim9-variable-arguments* *E1055* *E1160* *E1180*
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200217Variable arguments are defined as the last argument, with a name and have a
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200218list type, similar to TypeScript. For example, a list of numbers: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200219 def MyFunc(...itemlist: list<number>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100220 for item in itemlist
221 ...
222
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200223When a function argument is optional (it has a default value) passing `v:none`
224as the argument results in using the default value. This is useful when you
225want to specify a value for an argument that comes after an argument that
226should use its default value. Example: >
Bram Moolenaar22863042021-10-16 15:23:36 +0100227 def MyFunc(one = 'one', last = 'last')
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200228 ...
229 enddef
230 MyFunc(v:none, 'LAST') # first argument uses default value 'one'
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200231<
Bram Moolenaara2baa732022-02-04 16:09:54 +0000232 *vim9-ignored-argument* *E1181*
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200233The argument "_" (an underscore) can be used to ignore the argument. This is
234most useful in callbacks where you don't need it, but do need to give an
235argument to match the call. E.g. when using map() two arguments are passed,
236the key and the value, to ignore the key: >
Bram Moolenaar63f32602022-06-09 20:45:54 +0100237 map(numberList, (_, v) => v * 2)
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200238There is no error for using the "_" argument multiple times. No type needs to
239be given.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200240
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100241
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200242Functions and variables are script-local by default ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +0200243 *vim9-scopes*
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200244When using `:function` or `:def` to specify a new function at the script level
Bram Moolenaar92f645b2022-02-11 13:29:40 +0000245in a Vim9 script, the function is local to the script. Like prefixing "s:" in
246legacy script. To define a global function or variable the "g:" prefix must
247be used. For functions in a script that is to be imported and in an autoload
Bram Moolenaar63f32602022-06-09 20:45:54 +0100248script "export" needs to be used for those to be used elsewhere. >
Bram Moolenaarea2d8d22020-07-29 22:11:05 +0200249 def ThisFunction() # script-local
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200250 def g:ThatFunction() # global
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000251 export def Function() # for import and import autoload
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000252< *E1058* *E1075*
Bram Moolenaar2bb26582020-10-03 22:52:39 +0200253When using `:function` or `:def` to specify a nested function inside a `:def`
Bram Moolenaar47003982021-12-05 21:54:04 +0000254function and no namespace was given, this nested function is local to the code
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000255block it is defined in. It cannot be used in `function()` with a string
256argument, pass the function reference itself: >
257 def Outer()
258 def Inner()
259 echo 'inner'
260 enddef
261 var Fok = function(Inner) # OK
262 var Fbad = function('Inner') # does not work
263
Bram Moolenaar63f32602022-06-09 20:45:54 +0100264Detail: this is because "Inner" will actually become a function reference to a
265function with a generated name.
266
267It is not possible to define a script-local function in a function. You can
268define a local function and assign it to a script-local funcref (it must have
269been declared at the script level). It is possible to define a global
270function by using the "g:" prefix.
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200271
272When referring to a function and no "s:" or "g:" prefix is used, Vim will
Bram Moolenaar13106602020-10-04 16:06:05 +0200273search for the function:
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +0200274- in the function scope, in block scopes
Bram Moolenaar63f32602022-06-09 20:45:54 +0100275- in the script scope
276
277Imported functions are found with the prefix from the `:import` command.
Bram Moolenaar13106602020-10-04 16:06:05 +0200278
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200279Since a script-local function reference can be used without "s:" the name must
Bram Moolenaardad44732021-03-31 20:07:33 +0200280start with an upper case letter even when using the "s:" prefix. In legacy
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200281script "s:funcref" could be used, because it could not be referred to with
282"funcref". In Vim9 script it can, therefore "s:Funcref" must be used to avoid
283that the name interferes with builtin functions.
Bram Moolenaar2ecbe532022-07-29 21:36:21 +0100284 *vim9-s-namespace* *E1268*
Bram Moolenaar92f645b2022-02-11 13:29:40 +0000285The use of the "s:" prefix is not supported at the Vim9 script level. All
286functions and variables without a prefix are script-local.
Bram Moolenaarafa048f2022-02-22 20:43:36 +0000287
288In :def functions the use of "s:" depends on the script: Script-local
289variables and functions in a legacy script do use "s:", while in a Vim9 script
290they do not use "s:". This matches what you see in the rest of the file.
291
Bram Moolenaar92f645b2022-02-11 13:29:40 +0000292In legacy functions the use of "s:" for script items is required, as before.
Bram Moolenaar63f32602022-06-09 20:45:54 +0100293No matter if the script is Vim9 or legacy.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200294
Bram Moolenaar13106602020-10-04 16:06:05 +0200295In all cases the function must be defined before used. That is when it is
Bram Moolenaarcb80aa22020-10-26 21:12:46 +0100296called, when `:defcompile` causes it to be compiled, or when code that calls
297it is being compiled (to figure out the return type).
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200298
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200299The result is that functions and variables without a namespace can usually be
Bram Moolenaar7ceefb32020-05-01 16:07:38 +0200300found in the script, either defined there or imported. Global functions and
Bram Moolenaar63f32602022-06-09 20:45:54 +0100301variables could be defined anywhere (good luck finding out where! You can
302often see where it was last set using |:verbose|).
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000303 *E1102*
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200304Global functions can still be defined and deleted at nearly any time. In
Bram Moolenaar2cfb4a22020-05-07 18:56:00 +0200305Vim9 script script-local functions are defined once when the script is sourced
Bram Moolenaar63f32602022-06-09 20:45:54 +0100306and cannot be deleted or replaced by itself (it can be by reloading the
307script).
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200308
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100309When compiling a function and a function call is encountered for a function
310that is not (yet) defined, the |FuncUndefined| autocommand is not triggered.
311You can use an autoload function if needed, or call a legacy function and have
312|FuncUndefined| triggered there.
313
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +0200314
Bram Moolenaar2b327002020-12-26 15:39:31 +0100315Reloading a Vim9 script clears functions and variables by default ~
Bram Moolenaara2baa732022-02-04 16:09:54 +0000316 *vim9-reload* *E1149* *E1150*
Bram Moolenaar2b327002020-12-26 15:39:31 +0100317When loading a legacy Vim script a second time nothing is removed, the
Bram Moolenaar30ab04e2022-05-14 13:33:50 +0100318commands will replace existing variables and functions, create new ones, and
319leave removed things hanging around.
Bram Moolenaar2b327002020-12-26 15:39:31 +0100320
321When loading a Vim9 script a second time all existing script-local functions
322and variables are deleted, thus you start with a clean slate. This is useful
323if you are developing a plugin and want to try a new version. If you renamed
324something you don't have to worry about the old name still hanging around.
325
326If you do want to keep items, use: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100327 vim9script noclear
Bram Moolenaar2b327002020-12-26 15:39:31 +0100328
329You want to use this in scripts that use a `finish` command to bail out at
Bram Moolenaar944697a2022-02-20 19:48:20 +0000330some point when loaded again. E.g. when a buffer local option is set to a
331function, the function does not need to be defined more than once: >
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100332 vim9script noclear
Bram Moolenaar2b327002020-12-26 15:39:31 +0100333 setlocal completefunc=SomeFunc
Bram Moolenaar944697a2022-02-20 19:48:20 +0000334 if exists('*SomeFunc')
Bram Moolenaar9da17d72022-02-09 21:50:44 +0000335 finish
336 endif
Bram Moolenaar944697a2022-02-20 19:48:20 +0000337 def SomeFunc()
Bram Moolenaar2b327002020-12-26 15:39:31 +0100338 ....
339
Bram Moolenaar2b327002020-12-26 15:39:31 +0100340
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200341Variable declarations with :var, :final and :const ~
Bram Moolenaar8acb9cc2022-03-08 13:18:55 +0000342 *vim9-declaration* *:var* *E1079*
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000343 *E1017* *E1020* *E1054* *E1087* *E1108* *E1124*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200344Local variables need to be declared with `:var`. Local constants need to be
345declared with `:final` or `:const`. We refer to both as "variables" in this
346section.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100347
348Variables can be local to a script, function or code block: >
349 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200350 var script_var = 123
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100351 def SomeFunc()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200352 var func_var = script_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100353 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200354 var block_var = func_var
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100355 ...
356
357The variables are only visible in the block where they are defined and nested
358blocks. Once the block ends the variable is no longer accessible: >
359 if cond
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200360 var inner = 5
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100361 else
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200362 var inner = 0
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100363 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200364 echo inner # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100365
366The declaration must be done earlier: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200367 var inner: number
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100368 if cond
369 inner = 5
370 else
371 inner = 0
372 endif
373 echo inner
Bram Moolenaar63f32602022-06-09 20:45:54 +0100374
375Although this is shorter and faster for simple values: >
376 var inner = 0
377 if cond
378 inner = 5
379 endif
380 echo inner
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000381< *E1025* *E1128*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200382To intentionally hide a variable from code that follows, a block can be
383used: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100384 {
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200385 var temp = 'temp'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100386 ...
387 }
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200388 echo temp # Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100389
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200390This is especially useful in a user command: >
391
392 command -range Rename {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200393 var save = @a
394 @a = 'some expression'
395 echo 'do something with ' .. @a
396 @a = save
397 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200398
399And with autocommands: >
400
401 au BufWritePre *.go {
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200402 var save = winsaveview()
403 silent! exe ':%! some formatting command'
404 winrestview(save)
405 }
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200406
407Although using a :def function probably works better.
Bram Moolenaar46eea442022-03-30 10:51:39 +0100408
Bram Moolenaara2baa732022-02-04 16:09:54 +0000409 *E1022* *E1103* *E1130* *E1131* *E1133*
Dominique Pelle7765f5c2022-04-10 11:26:53 +0100410 *E1134*
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200411Declaring a variable with a type but without an initializer will initialize to
Bram Moolenaar1f318c62021-12-26 18:09:31 +0000412false (for bool), empty (for string, list, dict, etc.) or zero (for number,
413any, etc.). This matters especially when using the "any" type, the value will
Bram Moolenaar46eea442022-03-30 10:51:39 +0100414default to the number zero. For example, when declaring a list, items can be
415added: >
416 var myList: list<number>
417 myList->add(7)
418
419Initializing a variable to a null value, e.g. `null_list`, differs from not
420initializing the variable. This throws an error: >
421 var myList = null_list
422 myList->add(7) # E1130: Cannot add to null list
423
424< *E1016* *E1052* *E1066*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200425In Vim9 script `:let` cannot be used. An existing variable is assigned to
426without any command. The same for global, window, tab, buffer and Vim
Bram Moolenaar5da36052021-12-27 15:39:57 +0000427variables, because they are not really declared. Those can also be deleted
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200428with `:unlet`.
Bram Moolenaar8acb9cc2022-03-08 13:18:55 +0000429 *E1065*
430You cannot use `:va` to declare a variable, it must be written with the full
431name `:var`. Just to make sure it is easy to read.
Bram Moolenaara2baa732022-02-04 16:09:54 +0000432 *E1178*
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200433`:lockvar` does not work on local variables. Use `:const` and `:final`
434instead.
435
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200436The `exists()` and `exists_compiled()` functions do not work on local variables
437or arguments.
Bram Moolenaara2baa732022-02-04 16:09:54 +0000438 *E1006* *E1041* *E1167* *E1168* *E1213*
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100439Variables, functions and function arguments cannot shadow previously defined
440or imported variables and functions in the same script file.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100441Variables may shadow Ex commands, rename the variable if needed.
442
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200443Global variables must be prefixed with "g:", also at the script level. >
Bram Moolenaard1caa942020-04-10 22:10:56 +0200444 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200445 var script_local = 'text'
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200446 g:global = 'value'
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200447 var Funcref = g:ThatFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200448
Bram Moolenaarc4573eb2022-01-31 15:40:56 +0000449Global functions must be prefixed with "g:": >
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200450 vim9script
451 def g:GlobalFunc(): string
452 return 'text'
453 enddef
Bram Moolenaarc4573eb2022-01-31 15:40:56 +0000454 echo g:GlobalFunc()
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200455The "g:" prefix is not needed for auto-load functions.
456
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200457 *vim9-function-defined-later*
458Although global functions can be called without the "g:" prefix, they must
459exist when compiled. By adding the "g:" prefix the function can be defined
460later. Example: >
461 def CallPluginFunc()
462 if exists('g:loaded_plugin')
463 g:PluginFunc()
464 endif
465 enddef
466
Bram Moolenaarb79ee0c2022-01-01 12:17:00 +0000467If you do it like this, you get an error at compile time that "PluginFunc"
468does not exist, even when "g:loaded_plugin" does not exist: >
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200469 def CallPluginFunc()
470 if exists('g:loaded_plugin')
471 PluginFunc() # Error - function not found
472 endif
473 enddef
474
475You can use exists_compiled() to avoid the error, but then the function would
476not be called, even when "g:loaded_plugin" is defined later: >
477 def CallPluginFunc()
478 if exists_compiled('g:loaded_plugin')
479 PluginFunc() # Function may never be called
480 endif
481 enddef
482
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200483Since `&opt = value` is now assigning a value to option "opt", ":&" cannot be
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100484used to repeat a `:substitute` command.
Bram Moolenaar56994d22021-04-17 16:31:09 +0200485 *vim9-unpack-ignore*
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200486For an unpack assignment the underscore can be used to ignore a list item,
487similar to how a function argument can be ignored: >
488 [a, _, c] = theList
Bram Moolenaar56994d22021-04-17 16:31:09 +0200489To ignore any remaining items: >
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200490 [a, b; _] = longList
Bram Moolenaar944697a2022-02-20 19:48:20 +0000491< *E1163* *E1080*
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200492Declaring more than one variable at a time, using the unpack notation, is
Bram Moolenaarab36e6a2021-11-30 16:14:49 +0000493possible. Each variable can have a type or infer it from the value: >
494 var [v1: number, v2] = GetValues()
495Use this only when there is a list with values, declaring one variable per
496line is much easier to read and change later.
Bram Moolenaarf93bbd02021-04-10 22:35:43 +0200497
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200498
499Constants ~
500 *vim9-const* *vim9-final*
501How constants work varies between languages. Some consider a variable that
502can't be assigned another value a constant. JavaScript is an example. Others
503also make the value immutable, thus when a constant uses a list, the list
504cannot be changed. In Vim9 we can use both.
Bram Moolenaarf269eab2022-10-03 18:04:35 +0100505 *E1021* *E1307*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200506`:const` is used for making both the variable and the value a constant. Use
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200507this for composite structures that you want to make sure will not be modified.
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200508Example: >
509 const myList = [1, 2]
510 myList = [3, 4] # Error!
511 myList[0] = 9 # Error!
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100512 myList->add(3) # Error!
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000513< *:final* *E1125*
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200514`:final` is used for making only the variable a constant, the value can be
515changed. This is well known from Java. Example: >
516 final myList = [1, 2]
517 myList = [3, 4] # Error!
518 myList[0] = 9 # OK
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100519 myList->add(3) # OK
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200520
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200521It is common to write constants as ALL_CAPS, but you don't have to.
522
523The constant only applies to the value itself, not what it refers to. >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200524 final females = ["Mary"]
525 const NAMES = [["John", "Peter"], females]
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200526 NAMES[0] = ["Jack"] # Error!
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200527 NAMES[0][0] = "Jack" # Error!
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200528 NAMES[1] = ["Emma"] # Error!
Bram Moolenaar82be4842021-01-11 19:40:15 +0100529 NAMES[1][0] = "Emma" # OK, now females[0] == "Emma"
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +0200530
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100531
532Omitting :call and :eval ~
Bram Moolenaara2baa732022-02-04 16:09:54 +0000533 *E1190*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100534Functions can be called without `:call`: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200535 writefile(lines, 'file')
Bram Moolenaar560979e2020-02-04 22:53:05 +0100536Using `:call` is still possible, but this is discouraged.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100537
538A method call without `eval` is possible, so long as the start is an
Bram Moolenaar0289a092021-03-14 18:40:19 +0100539identifier or can't be an Ex command. For a function either "(" or "->" must
540be following, without a line break. Examples: >
Bram Moolenaarae616492020-07-28 20:07:27 +0200541 myList->add(123)
542 g:myList->add(123)
543 [1, 2, 3]->Process()
Bram Moolenaar2bede172020-11-19 18:53:18 +0100544 {a: 1, b: 2}->Process()
Bram Moolenaarae616492020-07-28 20:07:27 +0200545 "foobar"->Process()
546 ("foobar")->Process()
547 'foobar'->Process()
548 ('foobar')->Process()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100549
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200550In the rare case there is ambiguity between a function name and an Ex command,
Bram Moolenaare7b1ea02020-08-07 19:54:59 +0200551prepend ":" to make clear you want to use the Ex command. For example, there
552is both the `:substitute` command and the `substitute()` function. When the
553line starts with `substitute(` this will use the function. Prepend a colon to
554use the command instead: >
Bram Moolenaar0c6ceaf2020-02-22 18:36:32 +0100555 :substitute(pattern (replacement (
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +0100556
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200557If the expression starts with "!" this is interpreted as a shell command, not
558negation of a condition. Thus this is a shell command: >
559 !shellCommand->something
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200560Put the expression in parentheses to use the "!" for negation: >
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200561 (!expression)->Method()
562
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100563Note that while variables need to be defined before they can be used,
Bram Moolenaar3d1cde82020-08-15 18:55:18 +0200564functions can be called before being defined. This is required to allow
565for cyclic dependencies between functions. It is slightly less efficient,
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100566since the function has to be looked up by name. And a typo in the function
Bram Moolenaarae616492020-07-28 20:07:27 +0200567name will only be found when the function is called.
Bram Moolenaarcc390ff2020-02-29 22:06:30 +0100568
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100569
Bram Moolenaard1caa942020-04-10 22:10:56 +0200570Omitting function() ~
571
572A user defined function can be used as a function reference in an expression
573without `function()`. The argument types and return type will then be checked.
574The function must already have been defined. >
575
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200576 var Funcref = MyFunction
Bram Moolenaard1caa942020-04-10 22:10:56 +0200577
578When using `function()` the resulting type is "func", a function with any
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200579number of arguments and any return type (including void). The function can be
Bram Moolenaarfa3b7232021-12-24 13:18:38 +0000580defined later if the argument is in quotes.
Bram Moolenaard1caa942020-04-10 22:10:56 +0200581
582
Bram Moolenaar2b327002020-12-26 15:39:31 +0100583Lambda using => instead of -> ~
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200584 *vim9-lambda*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100585In legacy script there can be confusion between using "->" for a method call
586and for a lambda. Also, when a "{" is found the parser needs to figure out if
587it is the start of a lambda or a dictionary, which is now more complicated
588because of the use of argument types.
589
590To avoid these problems Vim9 script uses a different syntax for a lambda,
Bram Moolenaar74235772021-06-12 14:53:05 +0200591which is similar to JavaScript: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100592 var Lambda = (arg) => expression
Bram Moolenaara2baa732022-02-04 16:09:54 +0000593 var Lambda = (arg): type => expression
594< *E1157*
Bram Moolenaar2b327002020-12-26 15:39:31 +0100595No line break is allowed in the arguments of a lambda up to and including the
Bram Moolenaar4d8f4762021-06-27 15:18:56 +0200596"=>" (so that Vim can tell the difference between an expression in parentheses
Bram Moolenaar2346a632021-06-13 19:02:49 +0200597and lambda arguments). This is OK: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100598 filter(list, (k, v) =>
599 v > 0)
600This does not work: >
601 filter(list, (k, v)
602 => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100603This also does not work: >
Bram Moolenaar65c44152020-12-24 15:14:01 +0100604 filter(list, (k,
605 v) => v > 0)
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100606But you can use a backslash to concatenate the lines before parsing: >
607 filter(list, (k,
608 \ v)
609 \ => v > 0)
Bram Moolenaara2baa732022-02-04 16:09:54 +0000610< *vim9-lambda-arguments* *E1172*
Bram Moolenaar962c43b2021-04-10 17:18:09 +0200611In legacy script a lambda could be called with any number of extra arguments,
612there was no way to warn for not using them. In Vim9 script the number of
613arguments must match. If you do want to accept any arguments, or any further
614arguments, use "..._", which makes the function accept
615|vim9-variable-arguments|. Example: >
616 var Callback = (..._) => 'anything'
617 echo Callback(1, 2, 3) # displays "anything"
618
Bram Moolenaara2baa732022-02-04 16:09:54 +0000619< *inline-function* *E1171*
Bram Moolenaar65c44152020-12-24 15:14:01 +0100620Additionally, a lambda can contain statements in {}: >
621 var Lambda = (arg) => {
622 g:was_called = 'yes'
623 return expression
624 }
Bram Moolenaar130cbfc2021-04-07 21:07:20 +0200625This can be useful for a timer, for example: >
626 var count = 0
627 var timer = timer_start(500, (_) => {
628 count += 1
629 echom 'Handler called ' .. count
630 }, {repeat: 3})
631
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200632The ending "}" must be at the start of a line. It can be followed by other
633characters, e.g.: >
634 var d = mapnew(dict, (k, v): string => {
635 return 'value'
636 })
637No command can follow the "{", only a comment can be used there.
638
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000639 *command-block* *E1026*
Bram Moolenaar259f4432021-12-17 12:45:22 +0000640The block can also be used for defining a user command. Inside the block Vim9
641syntax will be used.
642
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000643If the statements include a dictionary, its closing bracket must not be
644written at the start of a line. Otherwise, it would be parsed as the end of
645the block. This does not work: >
646 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000647 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000648 'key': 'value',
649 } # ERROR: will be recognized as the end of the block
650 }
651Put the '}' after the last item to avoid this: >
652 command NewCommand {
Bram Moolenaar259f4432021-12-17 12:45:22 +0000653 g:mydict = {
Bram Moolenaar0e6adf82021-12-16 14:41:10 +0000654 'key': 'value' }
655 }
656
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +0200657Rationale: The "}" cannot be after a command because it would require parsing
658the commands to find it. For consistency with that no command can follow the
659"{". Unfortunately this means using "() => { command }" does not work, line
660breaks are always required.
Bram Moolenaar65c44152020-12-24 15:14:01 +0100661
Bram Moolenaare0e39172021-01-25 21:14:57 +0100662 *vim9-curly*
Bram Moolenaar2b327002020-12-26 15:39:31 +0100663To avoid the "{" of a dictionary literal to be recognized as a statement block
Bram Moolenaar9faec4e2021-02-27 16:38:07 +0100664wrap it in parentheses: >
Bram Moolenaar2b327002020-12-26 15:39:31 +0100665 var Lambda = (arg) => ({key: 42})
Bram Moolenaar65c44152020-12-24 15:14:01 +0100666
Bram Moolenaare0e39172021-01-25 21:14:57 +0100667Also when confused with the start of a command block: >
668 ({
669 key: value
670 })->method()
671
Bram Moolenaar65c44152020-12-24 15:14:01 +0100672
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200673Automatic line continuation ~
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000674 *vim9-line-continuation* *E1097*
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200675In many cases it is obvious that an expression continues on the next line. In
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100676those cases there is no need to prefix the line with a backslash (see
677|line-continuation|). For example, when a list spans multiple lines: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200678 var mylist = [
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200679 'one',
680 'two',
681 ]
Bram Moolenaare6085c52020-04-12 20:19:16 +0200682And when a dict spans multiple lines: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100683 var mydict = {
Bram Moolenaare6085c52020-04-12 20:19:16 +0200684 one: 1,
685 two: 2,
686 }
Bram Moolenaar74235772021-06-12 14:53:05 +0200687With a function call: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200688 var result = Func(
Bram Moolenaare6085c52020-04-12 20:19:16 +0200689 arg1,
690 arg2
691 )
692
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200693For binary operators in expressions not in [], {} or () a line break is
694possible just before or after the operator. For example: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200695 var text = lead
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200696 .. middle
697 .. end
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200698 var total = start +
Bram Moolenaar82be4842021-01-11 19:40:15 +0100699 end -
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200700 correction
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200701 var result = positive
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200702 ? PosFunc(arg)
703 : NegFunc(arg)
Bram Moolenaar9c7e6dd2020-04-12 20:55:20 +0200704
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200705For a method call using "->" and a member using a dot, a line break is allowed
706before it: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200707 var result = GetBuilder()
Bram Moolenaar73fef332020-06-21 22:12:03 +0200708 ->BuilderSetWidth(333)
709 ->BuilderSetHeight(777)
710 ->BuilderBuild()
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200711 var result = MyDict
Bram Moolenaar2547aa92020-07-26 17:00:44 +0200712 .member
Bram Moolenaar73fef332020-06-21 22:12:03 +0200713
Bram Moolenaardcc58e02020-12-28 20:53:21 +0100714For commands that have an argument that is a list of commands, the | character
715at the start of the line indicates line continuation: >
716 autocmd BufNewFile *.match if condition
717 | echo 'match'
718 | endif
719
Bram Moolenaar22863042021-10-16 15:23:36 +0100720Note that this means that in heredoc the first line cannot start with a bar: >
Bram Moolenaar74235772021-06-12 14:53:05 +0200721 var lines =<< trim END
722 | this doesn't work
723 END
724Either use an empty line at the start or do not use heredoc. Or temporarily
725add the "C" flag to 'cpoptions': >
726 set cpo+=C
727 var lines =<< trim END
Bram Moolenaar22863042021-10-16 15:23:36 +0100728 | this works
Bram Moolenaar74235772021-06-12 14:53:05 +0200729 END
730 set cpo-=C
731If the heredoc is inside a function 'cpoptions' must be set before :def and
732restored after the :enddef.
733
734In places where line continuation with a backslash is still needed, such as
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200735splitting up a long Ex command, comments can start with '#\ ': >
736 syn region Text
Bram Moolenaar74235772021-06-12 14:53:05 +0200737 \ start='foo'
738 #\ comment
739 \ end='bar'
Bram Moolenaar90df4b92021-07-07 20:26:08 +0200740Like with legacy script '"\ ' is used. This is also needed when line
741continuation is used without a backslash and a line starts with a bar: >
742 au CursorHold * echom 'BEFORE bar'
743 #\ some comment
744 | echom 'AFTER bar'
745<
746 *E1050*
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200747To make it possible for the operator at the start of the line to be
Bram Moolenaar74235772021-06-12 14:53:05 +0200748recognized, it is required to put a colon before a range. This example will
749add "start" and print: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200750 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200751 + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200752Like this: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200753 var result = start + print
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200754
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200755This will assign "start" and print a line: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +0200756 var result = start
Bram Moolenaardf069ee2020-06-22 23:02:51 +0200757 :+ print
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200758
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000759After the range an Ex command must follow. Without the colon you can call a
760function without `:call`, but after a range you do need it: >
761 MyFunc()
762 :% call MyFunc()
763
Bram Moolenaar23515b42020-11-29 14:36:24 +0100764Note that the colon is not required for the |+cmd| argument: >
765 edit +6 fname
766
Bram Moolenaar5e774c72020-04-12 21:53:00 +0200767It is also possible to split a function header over multiple lines, in between
768arguments: >
769 def MyFunc(
770 text: string,
771 separator = '-'
772 ): string
773
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100774Since a continuation line cannot be easily recognized the parsing of commands
Bram Moolenaar65c44152020-12-24 15:14:01 +0100775has been made stricter. E.g., because of the error in the first line, the
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100776second line is seen as a separate command: >
777 popup_create(some invalid expression, {
778 exit_cb: Func})
779Now "exit_cb: Func})" is actually a valid command: save any changes to the
780file "_cb: Func})" and exit. To avoid this kind of mistake in Vim9 script
781there must be white space between most command names and the argument.
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000782*E1144*
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100783
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100784However, the argument of a command that is a command won't be recognized. For
785example, after "windo echo expr" a line break inside "expr" will not be seen.
786
Bram Moolenaar4072ba52020-12-23 13:56:35 +0100787
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200788Notes:
789- "enddef" cannot be used at the start of a continuation line, it ends the
790 current function.
791- No line break is allowed in the LHS of an assignment. Specifically when
792 unpacking a list |:let-unpack|. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200793 [var1, var2] =
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200794 Func()
795< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200796 [var1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200797 var2] =
798 Func()
799- No line break is allowed in between arguments of an `:echo`, `:execute` and
800 similar commands. This is OK: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200801 echo [1,
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200802 2] [3,
803 4]
804< This does not work: >
Bram Moolenaar1c6737b2020-09-07 22:18:52 +0200805 echo [1, 2]
Bram Moolenaar7ff78462020-07-10 22:00:53 +0200806 [3, 4]
Bram Moolenaar74235772021-06-12 14:53:05 +0200807- In some cases it is difficult for Vim to parse a command, especially when
808 commands are used as an argument to another command, such as `windo`. In
809 those cases the line continuation with a backslash has to be used.
Bram Moolenaar4fdae992020-04-12 16:38:57 +0200810
Bram Moolenaar4c295022021-05-02 17:19:11 +0200811
812White space ~
Bram Moolenaara2baa732022-02-04 16:09:54 +0000813 *E1004* *E1068* *E1069* *E1074* *E1127* *E1202*
Bram Moolenaar4c295022021-05-02 17:19:11 +0200814Vim9 script enforces proper use of white space. This is no longer allowed: >
815 var name=234 # Error!
816 var name= 234 # Error!
817 var name =234 # Error!
818There must be white space before and after the "=": >
819 var name = 234 # OK
820White space must also be put before the # that starts a comment after a
821command: >
822 var name = 234# Error!
823 var name = 234 # OK
824
825White space is required around most operators.
826
827White space is required in a sublist (list slice) around the ":", except at
828the start and end: >
829 otherlist = mylist[v : count] # v:count has a different meaning
830 otherlist = mylist[:] # make a copy of the List
831 otherlist = mylist[v :]
832 otherlist = mylist[: v]
833
834White space is not allowed:
835- Between a function name and the "(": >
836 Func (arg) # Error!
837 Func
838 \ (arg) # Error!
839 Func
840 (arg) # Error!
841 Func(arg) # OK
842 Func(
843 arg) # OK
844 Func(
845 arg # OK
846 )
Bram Moolenaara2baa732022-02-04 16:09:54 +0000847< *E1205*
Bram Moolenaar89a9c152021-08-29 21:55:35 +0200848White space is not allowed in a `:set` command between the option name and a
849following "&", "!", "<", "=", "+=", "-=" or "^=".
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +0200850
Bram Moolenaar4c295022021-05-02 17:19:11 +0200851
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100852No curly braces expansion ~
853
854|curly-braces-names| cannot be used.
855
856
Bram Moolenaara2baa732022-02-04 16:09:54 +0000857Command modifiers are not ignored ~
858 *E1176*
859Using a command modifier for a command that does not use it gives an error.
Bram Moolenaar2ecbe532022-07-29 21:36:21 +0100860 *E1082*
861Also, using a command modifier without a following command is now an error.
Bram Moolenaara2baa732022-02-04 16:09:54 +0000862
863
Bram Moolenaar2bede172020-11-19 18:53:18 +0100864Dictionary literals ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000865 *vim9-literal-dict* *E1014*
Bram Moolenaar2bede172020-11-19 18:53:18 +0100866Traditionally Vim has supported dictionary literals with a {} syntax: >
867 let dict = {'key': value}
868
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100869Later it became clear that using a simple text key is very common, thus
870literal dictionaries were introduced in a backwards compatible way: >
Bram Moolenaar2bede172020-11-19 18:53:18 +0100871 let dict = #{key: value}
872
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100873However, this #{} syntax is unlike any existing language. As it turns out
874that using a literal key is much more common than using an expression, and
Bram Moolenaar2bede172020-11-19 18:53:18 +0100875considering that JavaScript uses this syntax, using the {} form for dictionary
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100876literals is considered a much more useful syntax. In Vim9 script the {} form
Bram Moolenaar2bede172020-11-19 18:53:18 +0100877uses literal keys: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100878 var dict = {key: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100879
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100880This works for alphanumeric characters, underscore and dash. If you want to
881use another character, use a single or double quoted string: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100882 var dict = {'key with space': value}
883 var dict = {"key\twith\ttabs": value}
884 var dict = {'': value} # empty key
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000885< *E1139*
Bram Moolenaarc5e6a712020-12-04 19:12:14 +0100886In case the key needs to be an expression, square brackets can be used, just
887like in JavaScript: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100888 var dict = {["key" .. nr]: value}
Bram Moolenaar2bede172020-11-19 18:53:18 +0100889
Bram Moolenaar2e5910b2021-02-03 17:41:24 +0100890The key type can be string, number, bool or float. Other types result in an
Bram Moolenaard899e512022-05-07 21:54:03 +0100891error. Without using [] the value is used as a string, keeping leading zeros.
892An expression given with [] is evaluated and then converted to a string.
893Leading zeros will then be dropped: >
894 var dict = {000123: 'without', [000456]: 'with'}
Bram Moolenaar2e5910b2021-02-03 17:41:24 +0100895 echo dict
Bram Moolenaard899e512022-05-07 21:54:03 +0100896 {'456': 'with', '000123': 'without'}
897A float only works inside [] because the dot is not accepted otherwise: >
898 var dict = {[00.013]: 'float'}
899 echo dict
900 {'0.013': 'float'}
Bram Moolenaar2e5910b2021-02-03 17:41:24 +0100901
Bram Moolenaar2bede172020-11-19 18:53:18 +0100902
Bram Moolenaar10b94212021-02-19 21:42:57 +0100903No :xit, :t, :k, :append, :change or :insert ~
Bram Moolenaarf10911e2022-01-29 22:20:48 +0000904 *E1100*
Bram Moolenaarf5a48012020-08-01 17:00:03 +0200905These commands are too easily confused with local variable names.
906Instead of `:x` or `:xit` you can use `:exit`.
907Instead of `:t` you can use `:copy`.
Bram Moolenaar10b94212021-02-19 21:42:57 +0100908Instead of `:k` you can use `:mark`.
Bram Moolenaar560979e2020-02-04 22:53:05 +0100909
910
911Comparators ~
912
913The 'ignorecase' option is not used for comparators that use strings.
Bram Moolenaar944697a2022-02-20 19:48:20 +0000914Thus "=~" works like "=~#".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100915
Bram Moolenaare1f3fd12022-08-15 18:51:32 +0100916"is" and "isnot" (|expr-is| and |expr-isnot|) when used on strings now return
917false. In legacy script they just compare the strings, in |Vim9| script they
918check identity, and strings are copied when used, thus two strings are never
919the same (this might change some day if strings are not copied but reference
920counted).
921
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100922
Bram Moolenaar4c295022021-05-02 17:19:11 +0200923Abort after error ~
924
925In legacy script, when an error is encountered, Vim continues to execute
926following lines. This can lead to a long sequence of errors and need to type
927CTRL-C to stop it. In Vim9 script execution of commands stops at the first
928error. Example: >
929 vim9script
930 var x = does-not-exist
931 echo 'not executed'
932
933
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100934For loop ~
Bram Moolenaara2baa732022-02-04 16:09:54 +0000935 *E1254*
Bram Moolenaar47003982021-12-05 21:54:04 +0000936The loop variable must not be declared yet: >
Bram Moolenaar6304be62021-11-27 10:57:26 +0000937 var i = 1
938 for i in [1, 2, 3] # Error!
939
Bram Moolenaar47003982021-12-05 21:54:04 +0000940It is possible to use a global variable though: >
941 g:i = 1
942 for g:i in [1, 2, 3]
943 echo g:i
944 endfor
945
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100946Legacy Vim script has some tricks to make a for loop over a list handle
947deleting items at the current or previous item. In Vim9 script it just uses
948the index, if items are deleted then items in the list will be skipped.
949Example legacy script: >
950 let l = [1, 2, 3, 4]
951 for i in l
952 echo i
953 call remove(l, index(l, i))
954 endfor
955Would echo:
956 1
957 2
958 3
959 4
960In compiled Vim9 script you get:
961 1
962 3
963Generally, you should not change the list that is iterated over. Make a copy
964first if needed.
Bram Moolenaar7c6cd442022-10-11 21:54:04 +0100965When looping over a list of lists, the nested lists can be changed. The loop
966variable is "final", it cannot be changed but what its value can be changed.
Bram Moolenaar9fbdbb82022-09-27 17:30:34 +0100967 *E1306*
968The depth of loops, :for and :while loops added together, cannot exceed 10.
Bram Moolenaar98a29d02021-01-18 19:55:44 +0100969
970
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100971Conditions and expressions ~
Bram Moolenaar6f4754b2022-01-23 12:07:04 +0000972 *vim9-boolean*
Bram Moolenaar13106602020-10-04 16:06:05 +0200973Conditions and expressions are mostly working like they do in other languages.
974Some values are different from legacy Vim script:
975 value legacy Vim script Vim9 script ~
976 0 falsy falsy
977 1 truthy truthy
978 99 truthy Error!
979 "0" falsy Error!
980 "99" truthy Error!
981 "text" falsy Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100982
Bram Moolenaar13106602020-10-04 16:06:05 +0200983For the "??" operator and when using "!" then there is no error, every value
984is either falsy or truthy. This is mostly like JavaScript, except that an
985empty list and dict is falsy:
986
987 type truthy when ~
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100988 bool true, v:true or 1
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100989 number non-zero
990 float non-zero
991 string non-empty
992 blob non-empty
993 list non-empty (different from JavaScript)
994 dictionary non-empty (different from JavaScript)
Bram Moolenaard1caa942020-04-10 22:10:56 +0200995 func when there is a function name
Bram Moolenaar7e6a5152021-01-02 16:39:53 +0100996 special true or v:true
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100997 job when not NULL
998 channel when not NULL
999 class when not NULL
Bram Moolenaar7e6a5152021-01-02 16:39:53 +01001000 object when not NULL (TODO: when isTrue() returns true)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001001
Bram Moolenaar2bb26582020-10-03 22:52:39 +02001002The boolean operators "||" and "&&" expect the values to be boolean, zero or
1003one: >
1004 1 || false == true
1005 0 || 1 == true
1006 0 || false == false
1007 1 && true == true
1008 0 && 1 == false
1009 8 || 0 Error!
1010 'yes' && 0 Error!
1011 [] || 99 Error!
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001012
Bram Moolenaar2bb26582020-10-03 22:52:39 +02001013When using "!" for inverting, there is no error for using any type and the
Bram Moolenaar13106602020-10-04 16:06:05 +02001014result is a boolean. "!!" can be used to turn any value into boolean: >
Bram Moolenaar82be4842021-01-11 19:40:15 +01001015 !'yes' == false
Bram Moolenaar13106602020-10-04 16:06:05 +02001016 !![] == false
Bram Moolenaar82be4842021-01-11 19:40:15 +01001017 !![1, 2, 3] == true
Bram Moolenaar2bb26582020-10-03 22:52:39 +02001018
1019When using "`.."` for string concatenation arguments of simple types are
Bram Moolenaar13106602020-10-04 16:06:05 +02001020always converted to string: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001021 'hello ' .. 123 == 'hello 123'
Bram Moolenaar7e6a5152021-01-02 16:39:53 +01001022 'hello ' .. v:true == 'hello true'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001023
Bram Moolenaar5da36052021-12-27 15:39:57 +00001024Simple types are Number, Float, Special and Bool. For other types |string()|
1025should be used.
Bram Moolenaar7db29e42022-12-11 15:53:04 +00001026 *false* *true* *null* *null_blob* *null_channel*
1027 *null_dict* *null_function* *null_job* *null_list*
1028 *null_partial* *null_string* *E1034*
Bram Moolenaar8acb9cc2022-03-08 13:18:55 +00001029In Vim9 script one can use the following predefined values: >
1030 true
1031 false
1032 null
1033 null_blob
1034 null_channel
1035 null_dict
1036 null_function
1037 null_job
1038 null_list
1039 null_partial
1040 null_string
1041`true` is the same as `v:true`, `false` the same as `v:false`, `null` the same
1042as `v:null`.
1043
Bram Moolenaar76db9e02022-11-09 21:21:04 +00001044While `null` has the type "special", the other "null_" values have the type
Bram Moolenaar8acb9cc2022-03-08 13:18:55 +00001045indicated by their name. Quite often a null value is handled the same as an
1046empty value, but not always. The values can be useful to clear a script-local
1047variable, since they cannot be deleted with `:unlet`. E.g.: >
1048 var theJob = job_start(...)
1049 # let the job do its work
1050 theJob = null_job
1051
1052The values can also be useful as the default value for an argument: >
1053 def MyFunc(b: blob = null_blob)
1054 if b == null_blob
1055 # b argument was not given
1056
Bram Moolenaar47c532e2022-03-19 15:18:53 +00001057It is possible to compare `null` with any value, this will not give a type
1058error. However, comparing `null` with a number, float or bool will always
1059result in `false`. This is different from legacy script, where comparing
1060`null` with zero or `false` would return `true`.
1061
Bram Moolenaar8acb9cc2022-03-08 13:18:55 +00001062When converting a boolean to a string `false` and `true` are used, not
1063`v:false` and `v:true` like in legacy script. `v:none` has no `none`
1064replacement, it has no equivalent in other languages.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001065
Bram Moolenaar0289a092021-03-14 18:40:19 +01001066Indexing a string with [idx] or taking a slice with [idx : idx] uses character
1067indexes instead of byte indexes. Composing characters are included.
1068Example: >
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001069 echo 'bár'[1]
1070In legacy script this results in the character 0xc3 (an illegal byte), in Vim9
1071script this results in the string 'á'.
Bram Moolenaar82be4842021-01-11 19:40:15 +01001072A negative index is counting from the end, "[-1]" is the last character.
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001073To exclude the last character use |slice()|.
Bram Moolenaar38a3bfa2021-03-29 22:14:55 +02001074To count composing characters separately use |strcharpart()|.
Bram Moolenaar82be4842021-01-11 19:40:15 +01001075If the index is out of range then an empty string results.
1076
1077In legacy script "++var" and "--var" would be silently accepted and have no
1078effect. This is an error in Vim9 script.
1079
1080Numbers starting with zero are not considered to be octal, only numbers
1081starting with "0o" are octal: "0o744". |scriptversion-4|
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001082
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001083
Bram Moolenaare46a4402020-06-30 20:38:27 +02001084What to watch out for ~
1085 *vim9-gotchas*
1086Vim9 was designed to be closer to often used programming languages, but at the
1087same time tries to support the legacy Vim commands. Some compromises had to
1088be made. Here is a summary of what might be unexpected.
1089
1090Ex command ranges need to be prefixed with a colon. >
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001091 -> legacy Vim: shifts the previous line to the right
1092 ->func() Vim9: method call in a continuation line
1093 :-> Vim9: shifts the previous line to the right
Bram Moolenaare46a4402020-06-30 20:38:27 +02001094
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001095 %s/a/b legacy Vim: substitute on all lines
Bram Moolenaare46a4402020-06-30 20:38:27 +02001096 x = alongname
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001097 % another Vim9: modulo operator in a continuation line
1098 :%s/a/b Vim9: substitute on all lines
1099 't legacy Vim: jump to mark t
1100 'text'->func() Vim9: method call
1101 :'t Vim9: jump to mark t
Bram Moolenaare46a4402020-06-30 20:38:27 +02001102
Bram Moolenaare7b1ea02020-08-07 19:54:59 +02001103Some Ex commands can be confused with assignments in Vim9 script: >
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001104 g:name = value # assignment
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001105 :g:pattern:cmd # :global command
Bram Moolenaare7b1ea02020-08-07 19:54:59 +02001106
Bram Moolenaar7b829262021-10-13 15:04:34 +01001107To avoid confusion between a `:global` or `:substitute` command and an
1108expression or assignment, a few separators cannot be used when these commands
1109are abbreviated to a single character: ':', '-' and '.'. >
1110 g:pattern:cmd # invalid command - ERROR
1111 s:pattern:repl # invalid command - ERROR
1112 g-pattern-cmd # invalid command - ERROR
1113 s-pattern-repl # invalid command - ERROR
1114 g.pattern.cmd # invalid command - ERROR
1115 s.pattern.repl # invalid command - ERROR
1116
1117Also, there cannot be a space between the command and the separator: >
1118 g /pattern/cmd # invalid command - ERROR
1119 s /pattern/repl # invalid command - ERROR
1120
Bram Moolenaare46a4402020-06-30 20:38:27 +02001121Functions defined with `:def` compile the whole function. Legacy functions
1122can bail out, and the following lines are not parsed: >
1123 func Maybe()
1124 if !has('feature')
1125 return
1126 endif
1127 use-feature
1128 endfunc
1129Vim9 functions are compiled as a whole: >
1130 def Maybe()
1131 if !has('feature')
1132 return
1133 endif
Bram Moolenaar82be4842021-01-11 19:40:15 +01001134 use-feature # May give a compilation error
Bram Moolenaare46a4402020-06-30 20:38:27 +02001135 enddef
1136For a workaround, split it in two functions: >
1137 func Maybe()
1138 if has('feature')
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001139 call MaybeInner()
Bram Moolenaare46a4402020-06-30 20:38:27 +02001140 endif
1141 endfunc
1142 if has('feature')
1143 def MaybeInner()
1144 use-feature
1145 enddef
1146 endif
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001147Or put the unsupported code inside an `if` with a constant expression that
Bram Moolenaar207f0092020-08-30 17:20:20 +02001148evaluates to false: >
1149 def Maybe()
1150 if has('feature')
1151 use-feature
1152 endif
1153 enddef
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001154The `exists_compiled()` function can also be used for this.
1155 *vim9-user-command*
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001156Another side effect of compiling a function is that the presence of a user
Bram Moolenaar82be4842021-01-11 19:40:15 +01001157command is checked at compile time. If the user command is defined later an
1158error will result. This works: >
1159 command -nargs=1 MyCommand echom <q-args>
1160 def Works()
1161 MyCommand 123
1162 enddef
1163This will give an error for "MyCommand" not being defined: >
1164 def Works()
1165 command -nargs=1 MyCommand echom <q-args>
1166 MyCommand 123
1167 enddef
1168A workaround is to invoke the command indirectly with `:execute`: >
1169 def Works()
1170 command -nargs=1 MyCommand echom <q-args>
1171 execute 'MyCommand 123'
1172 enddef
1173
Bram Moolenaar207f0092020-08-30 17:20:20 +02001174Note that for unrecognized commands there is no check for "|" and a following
1175command. This will give an error for missing `endif`: >
1176 def Maybe()
1177 if has('feature') | use-feature | endif
1178 enddef
Bram Moolenaare46a4402020-06-30 20:38:27 +02001179
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001180Other differences ~
1181
1182Patterns are used like 'magic' is set, unless explicitly overruled.
1183The 'edcompatible' option value is not used.
1184The 'gdefault' option value is not used.
1185
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001186You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaarc8cdf0f2021-03-13 13:28:13 +01001187Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001188
Bram Moolenaar4d8f4762021-06-27 15:18:56 +02001189 *:++* *:--*
1190The ++ and -- commands have been added. They are very similar to adding or
1191subtracting one: >
1192 ++var
1193 var += 1
1194 --var
1195 var -= 1
1196
1197Using ++var or --var in an expression is not supported yet.
1198
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001199==============================================================================
1200
12013. New style functions *fast-functions*
1202
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001203 *:def* *E1028*
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02001204:def[!] {name}([arguments])[: {return-type}]
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001205 Define a new function by the name {name}. The body of
1206 the function follows in the next lines, until the
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001207 matching `:enddef`. *E1073*
1208 *E1011*
1209 The {name} must be less than 100 bytes long.
1210 *E1003* *E1027* *E1056* *E1059*
1211 The type of value used with `:return` must match
1212 {return-type}. When {return-type} is omitted or is
1213 "void" the function is not expected to return
1214 anything.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001215 *E1077* *E1123*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001216 {arguments} is a sequence of zero or more argument
1217 declarations. There are three forms:
1218 {name}: {type}
1219 {name} = {value}
1220 {name}: {type} = {value}
1221 The first form is a mandatory argument, the caller
1222 must always provide them.
1223 The second and third form are optional arguments.
1224 When the caller omits an argument the {value} is used.
1225
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001226 The function will be compiled into instructions when
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001227 called, or when `:disassemble` or `:defcompile` is
1228 used. Syntax and type errors will be produced at that
1229 time.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001230
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001231 It is possible to nest `:def` inside another `:def` or
1232 `:function` up to about 50 levels deep.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001233 *E1117*
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001234 [!] is used as with `:function`. Note that
1235 script-local functions cannot be deleted or redefined
1236 later in Vim9 script. They can only be removed by
1237 reloading the same script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001238
Bram Moolenaara2baa732022-02-04 16:09:54 +00001239 *:enddef* *E1057* *E1152* *E1173*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001240:enddef End of a function defined with `:def`. It should be on
1241 a line by its own.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001242
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001243You may also find this wiki useful. It was written by an early adopter of
Bram Moolenaar0289a092021-03-14 18:40:19 +01001244Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001245
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001246If the script the function is defined in is Vim9 script, then script-local
1247variables can be accessed without the "s:" prefix. They must be defined
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001248before the function is compiled. If the script the function is defined in is
1249legacy script, then script-local variables must be accessed with the "s:"
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001250prefix if they do not exist at the time of compiling.
Bram Moolenaar2ecbe532022-07-29 21:36:21 +01001251 *E1269*
1252Script-local variables in a |Vim9| script must be declared at the script
1253level. They cannot be created in a function, also not in a legacy function.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001254
Bram Moolenaar388a5d42020-05-26 21:20:45 +02001255 *:defc* *:defcompile*
1256:defc[ompile] Compile functions defined in the current script that
1257 were not compiled yet.
Bram Moolenaarf79d9dd2022-05-21 15:39:02 +01001258 This will report any errors found during compilation.
1259
1260:defc[ompile] {func}
1261:defc[ompile] debug {func}
1262:defc[ompile] profile {func}
1263 Compile function {func}, if needed. Use "debug" and
1264 "profile" to specify the compilation mode.
1265 This will report any errors found during compilation.
Bram Moolenaar5b1c8fe2020-02-21 18:42:43 +01001266
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001267 *:disa* *:disassemble*
1268:disa[ssemble] {func} Show the instructions generated for {func}.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001269 This is for debugging and testing. *E1061*
Bram Moolenaarcc390ff2020-02-29 22:06:30 +01001270 Note that for command line completion of {func} you
1271 can prepend "s:" to find script-local functions.
Bram Moolenaarebdf3c92020-02-15 21:41:42 +01001272
Bram Moolenaar2346a632021-06-13 19:02:49 +02001273:disa[ssemble] profile {func}
1274 Like `:disassemble` but with the instructions used for
Bram Moolenaare0e39172021-01-25 21:14:57 +01001275 profiling.
1276
Bram Moolenaar2346a632021-06-13 19:02:49 +02001277:disa[ssemble] debug {func}
1278 Like `:disassemble` but with the instructions used for
1279 debugging.
1280
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001281Limitations ~
1282
1283Local variables will not be visible to string evaluation. For example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001284 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001285 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001286 return range(1, 2)->map('list[v:val]')
1287 enddef
1288
1289The map argument is a string expression, which is evaluated without the
1290function scope. Instead, use a lambda: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001291 def MapList(): list<string>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001292 var list = ['aa', 'bb', 'cc', 'dd']
Bram Moolenaar22863042021-10-16 15:23:36 +01001293 return range(1, 2)->map((_, v) => list[v])
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001294 enddef
1295
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001296For commands that are not compiled, such as `:edit`, backtick expansion can be
1297used and it can use the local scope. Example: >
Bram Moolenaar2b327002020-12-26 15:39:31 +01001298 def Replace()
Bram Moolenaar3d2e0312021-12-01 09:27:20 +00001299 var fname = 'blah.txt'
1300 edit `=fname`
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001301 enddef
1302
Bram Moolenaardad44732021-03-31 20:07:33 +02001303Closures defined in a loop will share the same context. For example: >
1304 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001305 for i in range(5)
Bram Moolenaardad44732021-03-31 20:07:33 +02001306 var inloop = i
1307 flist[i] = () => inloop
1308 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001309 echo range(5)->map((i, _) => flist[i]())
1310 # Result: [4, 4, 4, 4, 4]
Bram Moolenaar47c532e2022-03-19 15:18:53 +00001311< *E1271*
1312A closure must be compiled in the context that it is defined in, so that
1313variables in that context can be found. This mostly happens correctly, except
1314when a function is marked for debugging with `breakadd` after it was compiled.
Bram Moolenaar46eea442022-03-30 10:51:39 +01001315Make sure to define the breakpoint before compiling the outer function.
Bram Moolenaardad44732021-03-31 20:07:33 +02001316
1317The "inloop" variable will exist only once, all closures put in the list refer
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001318to the same instance, which in the end will have the value 4. This is
1319efficient, also when looping many times. If you do want a separate context
Bram Moolenaar71b6d332022-09-10 13:13:14 +01001320for each closure, call a function to define it: >
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001321 def GetClosure(i: number): func
1322 var infunc = i
1323 return () => infunc
Bram Moolenaardad44732021-03-31 20:07:33 +02001324 enddef
1325
1326 var flist: list<func>
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001327 for i in range(5)
1328 flist[i] = GetClosure(i)
Bram Moolenaardad44732021-03-31 20:07:33 +02001329 endfor
Bram Moolenaar53f7fcc2021-07-28 20:10:16 +02001330 echo range(5)->map((i, _) => flist[i]())
1331 # Result: [0, 1, 2, 3, 4]
Bram Moolenaardad44732021-03-31 20:07:33 +02001332
Bram Moolenaara2baa732022-02-04 16:09:54 +00001333In some situations, especially when calling a Vim9 closure from legacy
1334context, the evaluation will fail. *E1248*
1335
Bram Moolenaar71b6d332022-09-10 13:13:14 +01001336Note that at the script level the loop variable will be invalid after the
1337loop, also when used in a closure that is called later, e.g. with a timer.
1338This will generate error |E1302|: >
1339 for n in range(4)
1340 timer_start(500 * n, (_) => {
1341 echowin n
1342 })
1343 endfor
1344
Bram Moolenaar9712ff12022-09-18 13:04:22 +01001345You need to use a block and define a variable there, and use that one in the
1346closure: >
Bram Moolenaar71b6d332022-09-10 13:13:14 +01001347 for n in range(4)
Bram Moolenaar9712ff12022-09-18 13:04:22 +01001348 {
1349 var nr = n
1350 timer_start(500 * n, (_) => {
1351 echowin nr
1352 })
1353 }
Bram Moolenaar71b6d332022-09-10 13:13:14 +01001354 endfor
1355
1356Using `echowindow` is useful in a timer, the messages go into a popup and will
1357not interfere with what the user is doing when it triggers.
1358
Bram Moolenaara2baa732022-02-04 16:09:54 +00001359
1360Converting a function from legacy to Vim9 ~
1361 *convert_legacy_function_to_vim9*
1362These are the most changes that need to be made to convert a legacy function
1363to a Vim9 function:
1364
1365- Change `func` or `function` to `def`.
1366- Change `endfunc` or `endfunction` to `enddef`.
1367- Add types to the function arguments.
1368- If the function returns something, add the return type.
1369- Change comments to start with # instead of ".
1370
1371 For example, a legacy function: >
1372 func MyFunc(text)
1373 " function body
1374 endfunc
1375< Becomes: >
1376 def MyFunc(text: string): number
1377 # function body
1378 enddef
1379
1380- Remove "a:" used for arguments. E.g.: >
1381 return len(a:text)
1382< Becomes: >
1383 return len(text)
1384
1385- Change `let` used to declare a variable to `var`.
1386- Remove `let` used to assign a value to a variable. This is for local
1387 variables already declared and b: w: g: and t: variables.
1388
1389 For example, legacy function: >
1390 let lnum = 1
1391 let lnum += 3
1392 let b:result = 42
1393< Becomes: >
1394 var lnum = 1
1395 lnum += 3
1396 b:result = 42
1397
1398- Insert white space in expressions where needed.
1399- Change "." used for concatenation to "..".
1400
1401 For example, legacy function: >
1402 echo line(1).line(2)
1403< Becomes: >
1404 echo line(1) .. line(2)
1405
1406- line continuation does not always require a backslash: >
1407 echo ['one',
1408 \ 'two',
1409 \ 'three'
1410 \ ]
1411< Becomes: >
1412 echo ['one',
1413 'two',
1414 'three'
1415 ]
1416
Bram Moolenaar87b4e5c2022-10-01 15:32:46 +01001417
1418Calling a function in an expr option ~
1419 *expr-option-function*
Bram Moolenaarf269eab2022-10-03 18:04:35 +01001420The value of a few options, such as 'foldexpr', is an expression that is
1421evaluated to get a value. The evaluation can have quite a bit of overhead.
1422One way to minimize the overhead, and also to keep the option value very
1423simple, is to define a compiled function and set the option to call it
1424without arguments. Example: >
Bram Moolenaar87b4e5c2022-10-01 15:32:46 +01001425 vim9script
1426 def MyFoldFunc(): any
1427 ... compute fold level for line v:lnum
1428 return level
1429 enddef
1430 set foldexpr=s:MyFoldFunc()
1431
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001432==============================================================================
1433
14344. Types *vim9-types*
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001435 *E1008* *E1009* *E1010* *E1012*
1436 *E1013* *E1029* *E1030*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001437The following builtin types are supported:
1438 bool
1439 number
1440 float
1441 string
1442 blob
Bram Moolenaard77a8522020-04-03 21:59:57 +02001443 list<{type}>
1444 dict<{type}>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001445 job
1446 channel
Bram Moolenaarb17893a2020-03-14 08:19:51 +01001447 func
Bram Moolenaard1caa942020-04-10 22:10:56 +02001448 func: {type}
Bram Moolenaard77a8522020-04-03 21:59:57 +02001449 func({type}, ...)
1450 func({type}, ...): {type}
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001451 void
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001452
1453Not supported yet:
Bram Moolenaard77a8522020-04-03 21:59:57 +02001454 tuple<a: {type}, b: {type}, ...>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001455
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001456These types can be used in declarations, but no simple value will actually
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001457have the "void" type. Trying to use a void (e.g. a function without a
Bram Moolenaara2baa732022-02-04 16:09:54 +00001458return value) results in error *E1031* *E1186* .
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001459
Bram Moolenaard77a8522020-04-03 21:59:57 +02001460There is no array type, use list<{type}> instead. For a list constant an
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001461efficient implementation is used that avoids allocating lot of small pieces of
1462memory.
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001463 *E1005* *E1007*
Bram Moolenaard77a8522020-04-03 21:59:57 +02001464A partial and function can be declared in more or less specific ways:
1465func any kind of function reference, no type
Bram Moolenaard1caa942020-04-10 22:10:56 +02001466 checking for arguments or return value
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001467func: void any number and type of arguments, no return
1468 value
Bram Moolenaard77a8522020-04-03 21:59:57 +02001469func: {type} any number and type of arguments with specific
1470 return type
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001471
1472func() function with no argument, does not return a
1473 value
1474func(): void same
1475func(): {type} function with no argument and return type
1476
Bram Moolenaard1caa942020-04-10 22:10:56 +02001477func({type}) function with argument type, does not return
Bram Moolenaard77a8522020-04-03 21:59:57 +02001478 a value
Bram Moolenaard1caa942020-04-10 22:10:56 +02001479func({type}): {type} function with argument type and return type
1480func(?{type}) function with type of optional argument, does
1481 not return a value
1482func(...{type}) function with type of variable number of
1483 arguments, does not return a value
1484func({type}, ?{type}, ...{type}): {type}
1485 function with:
1486 - type of mandatory argument
1487 - type of optional argument
1488 - type of variable number of arguments
1489 - return type
Bram Moolenaard77a8522020-04-03 21:59:57 +02001490
1491If the return type is "void" the function does not return a value.
1492
1493The reference can also be a |Partial|, in which case it stores extra arguments
1494and/or a dictionary, which are not visible to the caller. Since they are
1495called in the same way the declaration is the same.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001496
1497Custom types can be defined with `:type`: >
1498 :type MyList list<string>
Bram Moolenaar127542b2020-08-09 17:22:04 +02001499Custom types must start with a capital letter, to avoid name clashes with
1500builtin types added later, similarly to user functions.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001501{not implemented yet}
1502
1503And classes and interfaces can be used as types: >
1504 :class MyClass
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001505 :var mine: MyClass
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001506
1507 :interface MyInterface
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001508 :var mine: MyInterface
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001509
1510 :class MyTemplate<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001511 :var mine: MyTemplate<number>
1512 :var mine: MyTemplate<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001513
1514 :class MyInterface<Targ>
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001515 :var mine: MyInterface<number>
1516 :var mine: MyInterface<string>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001517{not implemented yet}
1518
1519
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001520Variable types and type casting ~
1521 *variable-types*
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001522Variables declared in Vim9 script or in a `:def` function have a type, either
1523specified explicitly or inferred from the initialization.
1524
1525Global, buffer, window and tab page variables do not have a specific type, the
1526value can be changed at any time, possibly changing the type. Therefore, in
1527compiled code the "any" type is assumed.
1528
1529This can be a problem when the "any" type is undesired and the actual type is
1530expected to always be the same. For example, when declaring a list: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001531 var l: list<number> = [1, g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001532At compile time Vim doesn't know the type of "g:two" and the expression type
1533becomes list<any>. An instruction is generated to check the list type before
1534doing the assignment, which is a bit inefficient.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001535 *type-casting* *E1104*
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001536To avoid this, use a type cast: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001537 var l: list<number> = [1, <number>g:two]
Bram Moolenaar4072ba52020-12-23 13:56:35 +01001538The compiled code will then only check that "g:two" is a number and give an
1539error if it isn't. This is called type casting.
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001540
1541The syntax of a type cast is: "<" {type} ">". There cannot be white space
1542after the "<" or before the ">" (to avoid them being confused with
1543smaller-than and bigger-than operators).
1544
1545The semantics is that, if needed, a runtime type check is performed. The
1546value is not actually changed. If you need to change the type, e.g. to change
1547it to a string, use the |string()| function. Or use |str2nr()| to convert a
1548string to a number.
1549
Bram Moolenaar2ecbe532022-07-29 21:36:21 +01001550If a type is given where it is not expected you can get *E1272* .
1551
Bram Moolenaar64d662d2020-08-09 19:02:50 +02001552
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001553Type inference ~
1554 *type-inference*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001555In general: Whenever the type is clear it can be omitted. For example, when
1556declaring a variable and giving it a value: >
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001557 var name = 0 # infers number type
1558 var name = 'hello' # infers string type
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001559
Bram Moolenaar127542b2020-08-09 17:22:04 +02001560The type of a list and dictionary comes from the common type of the values.
1561If the values all have the same type, that type is used for the list or
1562dictionary. If there is a mix of types, the "any" type is used. >
1563 [1, 2, 3] list<number>
1564 ['a', 'b', 'c'] list<string>
1565 [1, 'x', 3] list<any>
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001566
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001567The common type of function references, if they do not all have the same
1568number of arguments, uses "(...)" to indicate the number of arguments is not
1569specified. For example: >
1570 def Foo(x: bool)
1571 enddef
1572 def Bar(x: bool, y: bool)
1573 enddef
1574 var funclist = [Foo, Bar]
1575 echo funclist->typename()
1576Results in:
1577 list<func(...)>
1578
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001579For script-local variables in Vim9 script the type is checked, also when the
1580variable was declared in a legacy function.
1581
Bram Moolenaar9da17d72022-02-09 21:50:44 +00001582When a type has been declared this is attached to a List or Dictionary. When
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001583later some expression attempts to change the type an error will be given: >
1584 var ll: list<number> = [1, 2, 3]
Bram Moolenaarc4573eb2022-01-31 15:40:56 +00001585 ll->extend(['x']) # Error, 'x' is not a number
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001586
Bram Moolenaar9da17d72022-02-09 21:50:44 +00001587If the type is not declared then it is allowed to change: >
Bram Moolenaarc4573eb2022-01-31 15:40:56 +00001588 [1, 2, 3]->extend(['x']) # result: [1, 2, 3, 'x']
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001589
Bram Moolenaar9da17d72022-02-09 21:50:44 +00001590For a variable declaration an inferred type matters: >
1591 var ll = [1, 2, 3]
1592 ll->extend(['x']) # Error, 'x' is not a number
1593That is because the declaration looks like a list of numbers, thus is
1594equivalent to: >
1595 var ll: list<number> = [1, 2, 3]
1596If you do want a more permissive list you need to declare the type: >
1597 var ll: list<any = [1, 2, 3]
1598 ll->extend(['x']) # OK
1599
Bram Moolenaar207f0092020-08-30 17:20:20 +02001600
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001601Stricter type checking ~
1602 *type-checking*
Bram Moolenaar207f0092020-08-30 17:20:20 +02001603In legacy Vim script, where a number was expected, a string would be
1604automatically converted to a number. This was convenient for an actual number
Bram Moolenaar130cbfc2021-04-07 21:07:20 +02001605such as "123", but leads to unexpected problems (and no error message) if the
Bram Moolenaar207f0092020-08-30 17:20:20 +02001606string doesn't start with a number. Quite often this leads to hard-to-find
Bram Moolenaar944697a2022-02-20 19:48:20 +00001607bugs. e.g.: >
1608 echo 123 == '123'
1609< 1 ~
1610With an accidental space: >
1611 echo 123 == ' 123'
1612< 0 ~
Bram Moolenaara2baa732022-02-04 16:09:54 +00001613 *E1206* *E1210* *E1212*
Bram Moolenaar207f0092020-08-30 17:20:20 +02001614In Vim9 script this has been made stricter. In most places it works just as
Bram Moolenaar944697a2022-02-20 19:48:20 +00001615before if the value used matches the expected type. There will sometimes be
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02001616an error, thus breaking backwards compatibility. For example:
Bram Moolenaar207f0092020-08-30 17:20:20 +02001617- Using a number other than 0 or 1 where a boolean is expected. *E1023*
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001618- Using a string value when setting a number option.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001619- Using a number where a string is expected. *E1024* *E1105*
Bram Moolenaar207f0092020-08-30 17:20:20 +02001620
Bram Moolenaar22863042021-10-16 15:23:36 +01001621One consequence is that the item type of a list or dict given to |map()| must
Bram Moolenaar944697a2022-02-20 19:48:20 +00001622not change, if the type was declared. This will give an error in Vim9
1623script: >
1624 var mylist: list<number> = [1, 2, 3]
1625 echo map(mylist, (i, v) => 'item ' .. i)
1626< E1012: Type mismatch; expected number but got string in map() ~
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001627
Bram Moolenaar944697a2022-02-20 19:48:20 +00001628Instead use |mapnew()|, it creates a new list: >
1629 var mylist: list<number> = [1, 2, 3]
1630 echo mapnew(mylist, (i, v) => 'item ' .. i)
1631< ['item 0', 'item 1', 'item 2'] ~
1632
1633If the item type was not declared or determined to be "any" it can change to a
1634more specific type. E.g. when a list of mixed types gets changed to a list of
1635strings: >
Bram Moolenaar90df4b92021-07-07 20:26:08 +02001636 var mylist = [1, 2.0, '3']
1637 # typename(mylist) == "list<any>"
1638 map(mylist, (i, v) => 'item ' .. i)
1639 # typename(mylist) == "list<string>", no error
Bram Moolenaar944697a2022-02-20 19:48:20 +00001640
1641There is a subtle difference between using a list constant directly and
Bram Moolenaarafa048f2022-02-22 20:43:36 +00001642through a variable declaration. Because of type inference, when using a list
Bram Moolenaar944697a2022-02-20 19:48:20 +00001643constant to initialize a variable, this also sets the declared type: >
1644 var mylist = [1, 2, 3]
1645 # typename(mylist) == "list<number>"
1646 echo map(mylist, (i, v) => 'item ' .. i) # Error!
1647
1648When using the list constant directly, the type is not declared and is allowed
1649to change: >
1650 echo map([1, 2, 3], (i, v) => 'item ' .. i) # OK
1651
1652The reasoning behind this is that when a type is declared and the list is
1653passed around and changed, the declaration must always hold. So that you can
1654rely on the type to match the declared type. For a constant this is not
1655needed.
1656
1657 *E1158*
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001658Same for |extend()|, use |extendnew()| instead, and for |flatten()|, use
Bram Moolenaar944697a2022-02-20 19:48:20 +00001659|flattennew()| instead. Since |flatten()| is intended to always change the
1660type, it can not be used in Vim9 script.
1661
Bram Moolenaara2baa732022-02-04 16:09:54 +00001662 *E1211* *E1217* *E1218* *E1219* *E1220* *E1221*
1663 *E1222* *E1223* *E1224* *E1225* *E1226* *E1227*
1664 *E1228* *E1238* *E1250* *E1251* *E1252* *E1253*
Bram Moolenaar71b6d332022-09-10 13:13:14 +01001665 *E1256* *E1297* *E1298* *E1301*
Bram Moolenaara2baa732022-02-04 16:09:54 +00001666Types are checked for most builtin functions to make it easier to spot
1667mistakes.
Bram Moolenaar82be4842021-01-11 19:40:15 +01001668
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001669==============================================================================
1670
Bram Moolenaar30fd8202020-09-26 15:09:30 +020016715. Namespace, Import and Export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001672 *vim9script* *vim9-export* *vim9-import*
1673
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001674A Vim9 script can be written to be imported. This means that some items are
1675intentionally exported, made available to other scripts. When the exporting
1676script is imported in another script, these exported items can then be used in
1677that script. All the other items remain script-local in the exporting script
1678and cannot be accessed by the importing script.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001679
1680This mechanism exists for writing a script that can be sourced (imported) by
1681other scripts, while making sure these other scripts only have access to what
1682you want them to. This also avoids using the global namespace, which has a
Bram Moolenaar6ba83ba2022-06-12 22:15:57 +01001683risk of name collisions. For example when you have two plugins with similar
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001684functionality.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001685
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001686You can cheat by using the global namespace explicitly. That should be done
1687only for things that really are global.
Bram Moolenaar207f0092020-08-30 17:20:20 +02001688
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001689
1690Namespace ~
Bram Moolenaardcc58e02020-12-28 20:53:21 +01001691 *vim9-namespace*
Bram Moolenaar560979e2020-02-04 22:53:05 +01001692To recognize a file that can be imported the `vim9script` statement must
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001693appear as the first statement in the file (see |vim9-mix| for an exception).
1694It tells Vim to interpret the script in its own namespace, instead of the
1695global namespace. If a file starts with: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001696 vim9script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001697 var myvar = 'yes'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001698Then "myvar" will only exist in this file. While without `vim9script` it would
1699be available as `g:myvar` from any other script and function.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00001700 *E1101*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001701The variables at the file level are very much like the script-local "s:"
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001702variables in legacy Vim script, but the "s:" is omitted. And they cannot be
1703deleted.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001704
Bram Moolenaar2c7f8c52020-04-20 19:52:53 +02001705In Vim9 script the global "g:" namespace can still be used as before. And the
1706"w:", "b:" and "t:" namespaces. These have in common that variables are not
Bram Moolenaar9712ff12022-09-18 13:04:22 +01001707declared, have no specific type and they can be deleted. *E1304*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001708
1709A side effect of `:vim9script` is that the 'cpoptions' option is set to the
1710Vim default value, like with: >
1711 :set cpo&vim
1712One of the effects is that |line-continuation| is always enabled.
Bram Moolenaar3e191692021-03-17 17:46:00 +01001713The original value of 'cpoptions' is restored at the end of the script, while
1714flags added or removed in the script are also added to or removed from the
1715original value to get the same effect. The order of flags may change.
Bram Moolenaar71eb3ad2021-12-26 12:07:30 +00001716In the |vimrc| file sourced on startup this does not happen.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001717
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001718 *vim9-mix*
1719There is one way to use both legacy and Vim9 syntax in one script file: >
1720 " comments may go here
1721 if !has('vim9script')
1722 " legacy script commands go here
1723 finish
1724 endif
1725 vim9script
1726 # Vim9 script commands go here
1727This allows for writing a script that takes advantage of the Vim9 script
Bram Moolenaar9faec4e2021-02-27 16:38:07 +01001728syntax if possible, but will also work on a Vim version without it.
Bram Moolenaard3f8a9e2021-02-17 21:57:03 +01001729
1730This can only work in two ways:
17311. The "if" statement evaluates to false, the commands up to `endif` are
1732 skipped and `vim9script` is then the first command actually executed.
17332. The "if" statement evaluates to true, the commands up to `endif` are
1734 executed and `finish` bails out before reaching `vim9script`.
1735
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001736
1737Export ~
1738 *:export* *:exp*
Bram Moolenaar2547aa92020-07-26 17:00:44 +02001739Exporting an item can be written as: >
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001740 export const EXPORTED_CONST = 1234
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001741 export var someValue = ...
1742 export final someValue = ...
1743 export const someValue = ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001744 export def MyFunc() ...
1745 export class MyClass ...
Bram Moolenaar74235772021-06-12 14:53:05 +02001746 export interface MyClass ...
Bram Moolenaar6f4754b2022-01-23 12:07:04 +00001747< *E1043* *E1044*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001748As this suggests, only constants, variables, `:def` functions and classes can
Bram Moolenaar74235772021-06-12 14:53:05 +02001749be exported. {not implemented yet: class, interface}
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001750
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001751 *E1042*
1752`:export` can only be used in Vim9 script, at the script level.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001753
1754
1755Import ~
Bram Moolenaar2ecbe532022-07-29 21:36:21 +01001756 *:import* *:imp* *E1094* *E1047* *E1262*
1757 *E1048* *E1049* *E1053* *E1071* *E1088* *E1236*
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001758The exported items can be imported in another script. The import syntax has
1759two forms. The simple form: >
1760 import {filename}
1761<
1762Where {filename} is an expression that must evaluate to a string. In this
1763form the filename should end in ".vim" and the portion before ".vim" will
1764become the script local name of the namespace. For example: >
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001765 import "myscript.vim"
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001766<
1767This makes each exported item in "myscript.vim" available as "myscript.item".
Bram Moolenaara2baa732022-02-04 16:09:54 +00001768 *:import-as* *E1257* *E1261*
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001769In case the name is long or ambiguous, this form can be used to specify
1770another name: >
1771 import {longfilename} as {name}
1772<
1773In this form {name} becomes a specific script local name for the imported
1774namespace. Therefore {name} must consist of letters, digits and '_', like
1775|internal-variables|. The {longfilename} expression must evaluate to any
1776filename. For example: >
1777 import "thatscript.vim.v2" as that
Bram Moolenaara2baa732022-02-04 16:09:54 +00001778< *E1060* *E1258* *E1259* *E1260*
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001779Then you can use "that.item", etc. You are free to choose the name "that".
1780Use something that will be recognized as referring to the imported script.
1781Avoid command names, command modifiers and builtin function names, because the
1782name will shadow them. Better not start the name starts with a capital
1783letter, since it can then also shadow global user commands and functions.
1784Also, you cannot use the name for something else in the script, such as a
1785function or variable name.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001786
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001787In case the dot in the name is undesired, a local reference can be made for a
1788function: >
1789 var LongFunc = that.LongFuncName
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001790
1791This also works for constants: >
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001792 const MAXLEN = that.MAX_LEN_OF_NAME
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001793
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001794This does not work for variables, since the value would be copied once and
1795when changing the variable the copy will change, not the original variable.
1796You will need to use the full name, with the dot.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001797
Bram Moolenaar4db572e2021-07-18 18:21:38 +02001798`:import` can not be used in a function. Imported items are intended to exist
1799at the script level and only imported once.
1800
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001801The script name after `import` can be:
1802- A relative path, starting "." or "..". This finds a file relative to the
1803 location of the script file itself. This is useful to split up a large
1804 plugin into several files.
1805- An absolute path, starting with "/" on Unix or "D:/" on MS-Windows. This
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001806 will rarely be used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001807- A path not being relative or absolute. This will be found in the
1808 "import" subdirectories of 'runtimepath' entries. The name will usually be
1809 longer and unique, to avoid loading the wrong file.
Bram Moolenaar6aa57292021-08-14 21:25:52 +02001810 Note that "after/import" is not used.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001811
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001812If the name does not end in ".vim" then the use of "as name" is required.
1813
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001814Once a vim9 script file has been imported, the result is cached and used the
1815next time the same script is imported. It will not be read again.
Bram Moolenaard5f400c2022-01-06 21:10:28 +00001816
1817It is not allowed to import the same script twice, also when using two
1818different "as" names.
Bram Moolenaar2f0936c2022-01-08 21:51:59 +00001819
1820When using the imported name the dot and the item name must be in the same
1821line, there can be no line break: >
1822 echo that.
1823 name # Error!
1824 echo that
1825 .name # Error!
Bram Moolenaar48c3f4e2022-08-08 15:42:38 +01001826< *import-map*
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001827When you've imported a function from one script into a vim9 script you can
1828refer to the imported function in a mapping by prefixing it with |<SID>|: >
Bram Moolenaar89445512022-04-14 12:58:23 +01001829 noremap <silent> ,a :call <SID>name.Function()<CR>
1830
1831When the mapping is defined "<SID>name." will be replaced with <SNR> and the
1832script ID of the imported script.
Bram Moolenaar6ba83ba2022-06-12 22:15:57 +01001833An even simpler solution is using |<ScriptCmd>|: >
1834 noremap ,a <ScriptCmd>name.Function()<CR>
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001835
1836Note that this does not work for variables, only for functions.
1837
1838 *import-legacy* *legacy-import*
1839`:import` can also be used in legacy Vim script. The imported namespace still
1840becomes script-local, even when the "s:" prefix is not given. For example: >
1841 import "myfile.vim"
1842 call s:myfile.MyFunc()
1843
1844And using the "as name" form: >
1845 import "otherfile.vim9script" as that
1846 call s:that.OtherFunc()
1847
Bram Moolenaar9712ff12022-09-18 13:04:22 +01001848However, the namespace cannot be resolved on its own: >
Bram Moolenaar5ed11532022-07-06 13:18:11 +01001849 import "that.vim"
1850 echo s:that
1851 " ERROR: E1060: Expected dot after name: s:that
1852<
1853This also affects the use of |<SID>| in the legacy mapping context. Since
1854|<SID>| is only a valid prefix for a function and NOT for a namespace, you
1855cannot use it
1856to scope a function in a script local namespace. Instead of prefixing the
1857function with |<SID>| you should use|<ScriptCmd>|. For example: >
1858 noremap ,a <ScriptCmd>:call s:that.OtherFunc()<CR>
Bram Moolenaar6ba83ba2022-06-12 22:15:57 +01001859<
Bram Moolenaar89445512022-04-14 12:58:23 +01001860 *:import-cycle*
Bram Moolenaara2baa732022-02-04 16:09:54 +00001861The `import` commands are executed when encountered. If script A imports
1862script B, and B (directly or indirectly) imports A, this will be skipped over.
1863At this point items in A after "import B" will not have been processed and
1864defined yet. Therefore cyclic imports can exist and not result in an error
1865directly, but may result in an error for items in A after "import B" not being
1866defined. This does not apply to autoload imports, see the next section.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001867
1868
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001869Importing an autoload script ~
Bram Moolenaarfd999452022-08-24 18:30:14 +01001870 *vim9-autoload* *import-autoload*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001871For optimal startup speed, loading scripts should be postponed until they are
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001872actually needed. Using the autoload mechanism is recommended:
Bram Moolenaara2baa732022-02-04 16:09:54 +00001873 *E1264*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010018741. In the plugin define user commands, functions and/or mappings that refer to
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001875 items imported from an autoload script. >
1876 import autoload 'for/search.vim'
1877 command -nargs=1 SearchForStuff search.Stuff(<f-args>)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001878
1879< This goes in .../plugin/anyname.vim. "anyname.vim" can be freely chosen.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001880 The "SearchForStuff" command is now available to the user.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001881
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001882 The "autoload" argument to `:import` means that the script is not loaded
1883 until one of the items is actually used. The script will be found under
1884 the "autoload" directory in 'runtimepath' instead of the "import"
Bram Moolenaarcbaff5e2022-04-08 17:45:08 +01001885 directory. Alternatively a relative or absolute name can be used, see
1886 below.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001887
18882. In the autoload script put the bulk of the code. >
Bram Moolenaarfd218c82022-01-18 16:26:24 +00001889 vim9script
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001890 export def Stuff(arg: string)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001891 ...
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001892
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001893< This goes in .../autoload/for/search.vim.
1894
Bram Moolenaarfd218c82022-01-18 16:26:24 +00001895 Putting the "search.vim" script under the "/autoload/for/" directory has
1896 the effect that "for#search#" will be prefixed to every exported item. The
1897 prefix is obtained from the file name, as you would to manually in a
1898 legacy autoload script. Thus the exported function can be found with
1899 "for#search#Stuff", but you would normally use `import autoload` and not
Bram Moolenaar47c532e2022-03-19 15:18:53 +00001900 use the prefix (which has the side effect of loading the autoload script
1901 when compiling a function that encounters this name).
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001902
1903 You can split up the functionality and import other scripts from the
1904 autoload script as you like. This way you can share code between plugins.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001905
Bram Moolenaarcbaff5e2022-04-08 17:45:08 +01001906Searching for the autoload script in all entries in 'runtimepath' can be a bit
1907slow. If the plugin knows where the script is located, quite often a relative
1908path can be used. This avoids the search and should be quite a bit faster.
1909Another advantage is that the script name does not need to be unique. An
1910absolute path is also possible. Examples: >
1911 import autoload '../lib/implement.vim'
1912 import autoload MyScriptsDir .. '/lib/implement.vim'
1913
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001914For defining a mapping that uses the imported autoload script the special key
1915|<ScriptCmd>| is useful. It allows for a command in a mapping to use the
1916script context of where the mapping was defined.
1917
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001918When compiling a `:def` function and a function in an autoload script is
1919encountered, the script is not loaded until the `:def` function is called.
Bram Moolenaardc4451d2022-01-09 21:36:37 +00001920This also means you get any errors only at runtime, since the argument and
Bram Moolenaar47c532e2022-03-19 15:18:53 +00001921return types are not known yet. If you would use the name with '#' characters
1922then the autoload script IS loaded.
1923
1924Be careful to not refer to an item in an autoload script that does trigger
1925loading it unintentionally. For example, when setting an option that takes a
1926function name, make sure to use a string, not a function reference: >
1927 import autoload 'qftf.vim'
1928 &quickfixtextfunc = 'qftf.Func' # autoload script NOT loaded
1929 &quickfixtextfunc = qftf.Func # autoload script IS loaded
1930On the other hand, it can be useful to load the script early, at a time when
1931any errors should be given.
Bram Moolenaar418f1df2020-08-12 21:34:49 +02001932
Bram Moolenaarfd31be22022-01-16 14:46:06 +00001933For testing the |test_override()| function can be used to have the
1934`import autoload` load the script right away, so that the items and types can
1935be checked without waiting for them to be actually used: >
1936 test_override('autoload', 1)
1937Reset it later with: >
1938 test_override('autoload', 0)
1939Or: >
1940 test_override('ALL', 0)
1941
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001942
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001943==============================================================================
1944
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000019456. Classes and interfaces *vim9-classes*
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001946
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001947In legacy script a Dictionary could be used as a kind-of object, by adding
1948members that are functions. However, this is quite inefficient and requires
1949the writer to do the work of making sure all the objects have the right
1950members. See |Dictionary-function|.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001951
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001952In |Vim9| script you can have classes, objects and interfaces like in most
1953popular object-oriented programming languages. Since this is a lot of
1954functionality it is located in a separate help file: |vim9class.txt|.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001955
Bram Moolenaar74235772021-06-12 14:53:05 +02001956
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001957==============================================================================
1958
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010019599. Rationale *vim9-rationale*
1960
1961The :def command ~
1962
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001963Plugin writers have asked for much faster Vim script. Investigations have
Bram Moolenaar560979e2020-02-04 22:53:05 +01001964shown that keeping the existing semantics of function calls make this close to
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001965impossible, because of the overhead involved with calling a function, setting
1966up the local function scope and executing lines. There are many details that
1967need to be handled, such as error messages and exceptions. The need to create
1968a dictionary for a: and l: scopes, the a:000 list and several others add too
1969much overhead that cannot be avoided.
1970
1971Therefore the `:def` method to define a new-style function had to be added,
1972which allows for a function with different semantics. Most things still work
1973as before, but some parts do not. A new way to define a function was
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001974considered the best way to separate the legacy style code from Vim9 style code.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001975
1976Using "def" to define a function comes from Python. Other languages use
1977"function" which clashes with legacy Vim script.
1978
1979
1980Type checking ~
1981
1982When compiling lines of Vim commands into instructions as much as possible
1983should be done at compile time. Postponing it to runtime makes the execution
1984slower and means mistakes are found only later. For example, when
1985encountering the "+" character and compiling this into a generic add
Bram Moolenaar98a29d02021-01-18 19:55:44 +01001986instruction, at runtime the instruction would have to inspect the type of the
1987arguments and decide what kind of addition to do. And when the type is
1988dictionary throw an error. If the types are known to be numbers then an "add
1989number" instruction can be used, which is faster. The error can be given at
1990compile time, no error handling is needed at runtime, since adding two numbers
1991cannot fail.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001992
Bram Moolenaar30fd8202020-09-26 15:09:30 +02001993The syntax for types, using <type> for compound types, is similar to Java. It
1994is easy to understand and widely used. The type names are what were used in
1995Vim before, with some additions such as "void" and "bool".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001996
1997
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02001998Removing clutter and weirdness ~
Bram Moolenaar65e0d772020-06-14 17:29:55 +02001999
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002000Once decided that `:def` functions have different syntax than legacy functions,
2001we are free to add improvements to make the code more familiar for users who
2002know popular programming languages. In other words: remove weird things that
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002003only Vim does.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002004
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002005We can also remove clutter, mainly things that were done to make Vim script
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002006backwards compatible with the good old Vi commands.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002007
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002008Examples:
Bram Moolenaar63f32602022-06-09 20:45:54 +01002009- Drop `:call` for calling a function and `:eval` for evaluating an
2010 expression.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002011- Drop using a leading backslash for line continuation, automatically figure
2012 out where an expression ends.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002013
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002014However, this does require that some things need to change:
2015- Comments start with # instead of ", to avoid confusing them with strings.
Bram Moolenaar63f32602022-06-09 20:45:54 +01002016 This is good anyway, it is also used by several popular languages.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002017- Ex command ranges need to be prefixed with a colon, to avoid confusion with
2018 expressions (single quote can be a string or a mark, "/" can be divide or a
2019 search command, etc.).
2020
2021Goal is to limit the differences. A good criteria is that when the old syntax
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002022is accidentally used you are very likely to get an error message.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002023
2024
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002025Syntax and semantics from popular languages ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002026
2027Script writers have complained that the Vim script syntax is unexpectedly
2028different from what they are used to. To reduce this complaint popular
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002029languages are used as an example. At the same time, we do not want to abandon
2030the well-known parts of legacy Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002031
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002032For many things TypeScript is followed. It's a recent language that is
2033gaining popularity and has similarities with Vim script. It also has a
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002034mix of static typing (a variable always has a known value type) and dynamic
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002035typing (a variable can have different types, this changes at runtime). Since
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002036legacy Vim script is dynamically typed and a lot of existing functionality
2037(esp. builtin functions) depends on that, while static typing allows for much
2038faster execution, we need to have this mix in Vim9 script.
2039
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002040There is no intention to completely match TypeScript syntax and semantics. We
2041just want to take those parts that we can use for Vim and we expect Vim users
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002042will be happy with. TypeScript is a complex language with its own history,
2043advantages and disadvantages. To get an idea of the disadvantages read the
2044book: "JavaScript: The Good Parts". Or find the article "TypeScript: the good
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02002045parts" and read the "Things to avoid" section.
2046
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002047People familiar with other languages (Java, Python, etc.) will also find
2048things in TypeScript that they do not like or do not understand. We'll try to
2049avoid those things.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02002050
2051Specific items from TypeScript we avoid:
2052- Overloading "+", using it both for addition and string concatenation. This
2053 goes against legacy Vim script and often leads to mistakes. For that reason
2054 we will keep using ".." for string concatenation. Lua also uses ".." this
2055 way. And it allows for conversion to string for more values.
2056- TypeScript can use an expression like "99 || 'yes'" in a condition, but
2057 cannot assign the value to a boolean. That is inconsistent and can be
2058 annoying. Vim recognizes an expression with && or || and allows using the
Bram Moolenaar1f318c62021-12-26 18:09:31 +00002059 result as a bool. The |falsy-operator| was added for the mechanism to use a
2060 default value.
Bram Moolenaar0b4c66c2020-09-14 21:39:44 +02002061- TypeScript considers an empty string as Falsy, but an empty list or dict as
2062 Truthy. That is inconsistent. In Vim an empty list and dict are also
2063 Falsy.
2064- TypeScript has various "Readonly" types, which have limited usefulness,
2065 since a type cast can remove the immutable nature. Vim locks the value,
2066 which is more flexible, but is only checked at runtime.
Bram Moolenaarf10911e2022-01-29 22:20:48 +00002067- TypeScript has a complicated "import" statement that does not match how the
2068 Vim import mechanism works. A much simpler mechanism is used instead, which
2069 matches that the imported script is only sourced once.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002070
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002071
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002072Declarations ~
2073
2074Legacy Vim script uses `:let` for every assignment, while in Vim9 declarations
2075are used. That is different, thus it's good to use a different command:
2076`:var`. This is used in many languages. The semantics might be slightly
2077different, but it's easily recognized as a declaration.
2078
Bram Moolenaar23515b42020-11-29 14:36:24 +01002079Using `:const` for constants is common, but the semantics varies. Some
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002080languages only make the variable immutable, others also make the value
2081immutable. Since "final" is well known from Java for only making the variable
2082immutable we decided to use that. And then `:const` can be used for making
2083both immutable. This was also used in legacy Vim script and the meaning is
2084almost the same.
2085
2086What we end up with is very similar to Dart: >
2087 :var name # mutable variable and value
2088 :final name # immutable variable, mutable value
2089 :const name # immutable variable and value
2090
2091Since legacy and Vim9 script will be mixed and global variables will be
2092shared, optional type checking is desirable. Also, type inference will avoid
2093the need for specifying the type in many cases. The TypeScript syntax fits
2094best for adding types to declarations: >
2095 var name: string # string type is specified
2096 ...
2097 name = 'John'
2098 const greeting = 'hello' # string type is inferred
2099
2100This is how we put types in a declaration: >
2101 var mylist: list<string>
2102 final mylist: list<string> = ['foo']
2103 def Func(arg1: number, arg2: string): bool
2104
2105Two alternatives were considered:
21061. Put the type before the name, like Dart: >
2107 var list<string> mylist
2108 final list<string> mylist = ['foo']
2109 def Func(number arg1, string arg2) bool
21102. Put the type after the variable name, but do not use a colon, like Go: >
2111 var mylist list<string>
2112 final mylist list<string> = ['foo']
2113 def Func(arg1 number, arg2 string) bool
2114
2115The first is more familiar for anyone used to C or Java. The second one
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02002116doesn't really have an advantage over the first, so let's discard the second.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002117
2118Since we use type inference the type can be left out when it can be inferred
2119from the value. This means that after `var` we don't know if a type or a name
2120follows. That makes parsing harder, not only for Vim but also for humans.
2121Also, it will not be allowed to use a variable name that could be a type name,
2122using `var string string` is too confusing.
2123
2124The chosen syntax, using a colon to separate the name from the type, adds
2125punctuation, but it actually makes it easier to recognize the parts of a
2126declaration.
2127
2128
2129Expressions ~
2130
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02002131Expression evaluation was already close to what other languages are doing.
2132Some details are unexpected and can be improved. For example a boolean
2133condition would accept a string, convert it to a number and check if the
2134number is non-zero. This is unexpected and often leads to mistakes, since
2135text not starting with a number would be converted to zero, which is
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01002136considered false. Thus using a string for a condition would often not give an
2137error and be considered false. That is confusing.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002138
Bram Moolenaar23515b42020-11-29 14:36:24 +01002139In Vim9 type checking is stricter to avoid mistakes. Where a condition is
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02002140used, e.g. with the `:if` command and the `||` operator, only boolean-like
2141values are accepted:
2142 true: `true`, `v:true`, `1`, `0 < 9`
2143 false: `false`, `v:false`, `0`, `0 > 9`
2144Note that the number zero is false and the number one is true. This is more
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01002145permissive than most other languages. It was done because many builtin
Bram Moolenaar63f32602022-06-09 20:45:54 +01002146functions return these values, and changing that causes more problems than it
2147solves. After using this for a while it turned out to work well.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002148
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02002149If you have any type of value and want to use it as a boolean, use the `!!`
2150operator:
Bram Moolenaar63f32602022-06-09 20:45:54 +01002151 true: `!!'text'` `!![99]` `!!{'x': 1}` `!!99`
2152 false: `!!''` `!![]` `!!{}`
Bram Moolenaar4f4d51a2020-10-11 13:57:40 +02002153
2154From a language like JavaScript we have this handy construct: >
2155 GetName() || 'unknown'
2156However, this conflicts with only allowing a boolean for a condition.
2157Therefore the "??" operator was added: >
2158 GetName() ?? 'unknown'
2159Here you can explicitly express your intention to use the value as-is and not
2160result in a boolean. This is called the |falsy-operator|.
Bram Moolenaar30fd8202020-09-26 15:09:30 +02002161
2162
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002163Import and Export ~
2164
2165A problem of legacy Vim script is that by default all functions and variables
2166are global. It is possible to make them script-local, but then they are not
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002167available in other scripts. This defies the concept of a package that only
2168exports selected items and keeps the rest local.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002169
Bram Moolenaar3d1cde82020-08-15 18:55:18 +02002170In Vim9 script a mechanism very similar to the JavaScript import and export
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002171mechanism is supported. It is a variant to the existing `:source` command
2172that works like one would expect:
2173- Instead of making everything global by default, everything is script-local,
Bram Moolenaar63f32602022-06-09 20:45:54 +01002174 some of these are exported.
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002175- When importing a script the symbols that are imported are explicitly listed,
2176 avoiding name conflicts and failures if functionality is added later.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002177- The mechanism allows for writing a big, long script with a very clear API:
Bram Moolenaar63f32602022-06-09 20:45:54 +01002178 the exported functions, variables and classes.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002179- By using relative paths loading can be much faster for an import inside of a
2180 package, no need to search many directories.
Bram Moolenaar63f32602022-06-09 20:45:54 +01002181- Once an import has been used, its items are cached and loading it again is
2182 not needed.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002183- The Vim-specific use of "s:" to make things script-local can be dropped.
2184
Bram Moolenaar63f32602022-06-09 20:45:54 +01002185When sourcing a Vim9 script (from a Vim9 or legacy script), only the items
2186defined globally can be used, not the exported items. Alternatives
2187considered:
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002188- All the exported items become available as script-local items. This makes
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002189 it uncontrollable what items get defined and likely soon leads to trouble.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002190- Use the exported items and make them global. Disadvantage is that it's then
2191 not possible to avoid name clashes in the global namespace.
2192- Completely disallow sourcing a Vim9 script, require using `:import`. That
2193 makes it difficult to use scripts for testing, or sourcing them from the
2194 command line to try them out.
Bram Moolenaar63f32602022-06-09 20:45:54 +01002195Note that you CAN also use `:import` in legacy Vim script, see above.
Bram Moolenaar65e0d772020-06-14 17:29:55 +02002196
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002197
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002198Compiling functions early ~
2199
2200Functions are compiled when called or when `:defcompile` is used. Why not
2201compile them early, so that syntax and type errors are reported early?
2202
2203The functions can't be compiled right away when encountered, because there may
2204be forward references to functions defined later. Consider defining functions
2205A, B and C, where A calls B, B calls C, and C calls A again. It's impossible
2206to reorder the functions to avoid forward references.
2207
2208An alternative would be to first scan through the file to locate items and
2209figure out their type, so that forward references are found, and only then
2210execute the script and compile the functions. This means the script has to be
2211parsed twice, which is slower, and some conditions at the script level, such
2212as checking if a feature is supported, are hard to use. An attempt was made
Bram Moolenaar63f32602022-06-09 20:45:54 +01002213to see if it works, but it turned out to be impossible to make work well.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002214
2215It would be possible to compile all the functions at the end of the script.
2216The drawback is that if a function never gets called, the overhead of
2217compiling it counts anyway. Since startup speed is very important, in most
2218cases it's better to do it later and accept that syntax and type errors are
2219only reported then. In case these errors should be found early, e.g. when
Bram Moolenaar63f32602022-06-09 20:45:54 +01002220testing, a `:defcompile` command at the end of the script will help out.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002221
2222
Bram Moolenaar63f32602022-06-09 20:45:54 +01002223Why not use an existing embedded language? ~
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002224
2225Vim supports interfaces to Perl, Python, Lua, Tcl and a few others. But
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002226these interfaces have never become widely used, for various reasons. When
2227Vim9 was designed a decision was made to make these interfaces lower priority
2228and concentrate on Vim script.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002229
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002230Still, plugin writers may find other languages more familiar, want to use
2231existing libraries or see a performance benefit. We encourage plugin authors
Bram Moolenaar63f32602022-06-09 20:45:54 +01002232to write code in any language and run it as an external process, using jobs
2233and channels. We can try to make this easier somehow.
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002234
2235Using an external tool also has disadvantages. An alternative is to convert
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002236the tool into Vim script. For that to be possible without too much
2237translation, and keeping the code fast at the same time, the constructs of the
2238tool need to be supported. Since most languages support classes the lack of
Bram Moolenaar1c6737b2020-09-07 22:18:52 +02002239support for classes in Vim is then a problem.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002240
Bram Moolenaar1d59aa12020-09-19 18:50:13 +02002241
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002242
2243 vim:tw=78:ts=8:noet:ft=help:norl: