vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

vim9.txt (218529B)


      1 *vim9.txt*	For Vim version 9.2.  Last change: 2026 Oct 13
      2 
      3 
      4 		  VIM REFERENCE MANUAL	  by Bram Moolenaar
      5 
      6 
      7 Vim9 script commands and expressions.			*Vim9* *vim9*
      8 
      9 Most expression help is in |eval.txt|.  This file is about the new syntax and
     10 features in Vim9 script, including more than 200 sourceable scripts.
     11 
     12 For a short primer on Vim9 script, other resources may be helpful too, e.g.,
     13 https://learnxinyminutes.com/vim9script/.
     14 
     15 
     16 1.  What is Vim9 script?		|Vim9-script|
     17 2.  Differences				|vim9-differences|
     18 3.  New style functions			|fast-functions|
     19 4.  Types				|vim9-types|
     20 5.  Generic functions			|generic-functions|
     21 6.  Namespace, Import and Export	|vim9script|
     22 7.  Classes and interfaces		|vim9-classes|
     23 8.  Rationale				|vim9-rationale|
     24 
     25 
     26 ------------------------------------------------------------------------------
     27 
     28 NOTE: In this vim9.txt help file, the Vim9 script code blocks beginning with
     29 `vim9script` (and individual lines starting with `vim9cmd`) are Vim9 script
     30 syntax highlighted.  Also, they are sourceable, meaning you can run them to
     31 see what they output.  To source them, use `:'<,'>source` (see |:source-range|),
     32 which is done by visually selecting the line(s) with |V| and typing `:so`.
     33 For example, try it on the following Vim9 script:
     34 >vim9
     35 	vim9script
     36 	echowindow "Welcome to Vim9 script!"
     37 <
     38 There are also code examples that should not be sourced - they explain
     39 concepts that don't require a sourceable example.  Such code blocks appear
     40 in generic code syntax highlighting, like this:
     41 >
     42 	def ThisFunction()          # script-local
     43 	def g:ThatFunction()        # global
     44 	export def Function()       # for import and import autoload
     45 <
     46 
     47 ==============================================================================
     48 
     49 
     50 1. What is Vim9 script?					*Vim9-script*
     51 
     52 Vim script has been growing over time, while preserving backwards
     53 compatibility.  That means bad choices from the past often can't be changed
     54 and compatibility with Vi restricts possible solutions.  Execution is quite
     55 slow, each line is parsed every time it is executed.
     56 
     57 The main goal of Vim9 script is to drastically improve performance.  This is
     58 accomplished by compiling commands into instructions that can be efficiently
     59 executed.  An increase in execution speed of 10 to 100 times can be expected.
     60 
     61 A secondary goal is to avoid Vim-specific constructs and get closer to
     62 commonly used programming languages, such as JavaScript, TypeScript and Java.
     63 
     64 The performance improvements can only be achieved by not being 100% backwards
     65 compatible.  For example, making function arguments available in the "a:"
     66 dictionary adds quite a lot of overhead.  In a Vim9 function this dictionary
     67 is not available.  Other differences are more subtle, such as how errors are
     68 handled.
     69 
     70 Vim9 script syntax, semantics, and behavior apply in:
     71 - a function defined with the `:def` command
     72 - a script file where the first command is `vim9script`
     73 - an autocommand defined in the context of the above
     74 - a command prefixed with the `vim9cmd` command modifier
     75 
     76 When using `:function` in a Vim9 script file the legacy syntax is used, with
     77 the highest |scriptversion|.  However, this can be confusing and is therefore
     78 discouraged.
     79 
     80 Vim9 script and legacy Vim script can be mixed.  There is no requirement to
     81 rewrite old scripts, they keep working as before.  You may want to use a few
     82 `:def` functions for code that needs to be fast.
     83 
     84 :vim9[cmd] {cmd}					*:vim9* *:vim9cmd*
     85 		Evaluate and execute {cmd} using Vim9 script syntax,
     86 		semantics, and behavior.  Useful when typing a command,
     87 		in a `:function`, or a legacy Vim script.
     88 
     89 		The following short example shows how a legacy Vim script
     90 		command and a :vim9cmd (so Vim9 script context) may appear
     91 		similar, though may differ not just syntactically, but also
     92 		semantically and behaviorally.
     93 >vim
     94 			call popup_notification('entrée'[5:]
     95 			  \ ->str2list()->string(), #{time: 7000})
     96 			vim9cmd popup_notification('entrée'[5 :]
     97 			    ->str2list()->string(), {time: 7000})
     98 <
     99 		Notes: 1. The reason for the different output is Vim9 script
    100 		uses character indexing whereas legacy Vim script uses byte
    101 		indexing - see |vim9-string-index|.
    102 		2. Syntax is different too.  In Vim9 script:
    103 		- The space in "[5 :]" is mandatory (see |vim9-white-space|).
    104 		- Line continuation with "\" is not required.
    105 		- The "#" (to avoid putting quotes around dictionary keys) is
    106 		  neither required nor allowed - see |#{}|.
    107 
    108 							*E1164*
    109 		`:vim9cmd` cannot stand alone; it must be followed by a command.
    110 
    111 :leg[acy] {cmd}						*:leg* *:legacy*
    112 		Evaluate and execute {cmd} using legacy Vim script syntax,
    113 		semantics, and behavior.  It is only applicable in a Vim9
    114 		script or a `:def` function.  Using an equivalent script to
    115 		the one, above (see its notes for why the output differs):
    116 >vim9
    117 			vim9script
    118 			# In legacy Vim script context the popup is [769, 101]
    119 			legacy call popup_notification('entrée'[5:]
    120 			  \ ->str2list()->string(), #{time: 7000})
    121 			# In Vim9 script context the popup is [101]
    122 			popup_notification('entrée'[5 :]
    123 			  ->str2list()->string(), {time: 7000})
    124 <
    125 		Vim9 script's script-local variables may be used by prefixing
    126 		"s:", like in legacy Vim script.  This example shows the
    127 		difference in syntax: "k" for the script-local variable in
    128 		Vim9 script, "s:k" in the legacy Vim script context.
    129 >vim9
    130 			vim9script
    131 			var k: string = "Okay"
    132 			echo k
    133 			legacy echo s:k
    134 <
    135 							*E1189*
    136 		Using `:legacy` is not allowed in compiled Vim9 script
    137 		control flow contexts. For example:
    138 >vim9
    139 			vim9script
    140 			def F_1189()
    141 			  if v:version == 900
    142 			  # E1189: Cannot use :legacy with this command: endif
    143 			  legacy endif
    144 			enddef
    145 			F_1189()
    146 <							*E1234*
    147 		`:legacy` cannot stand alone; it must be followed by a command.
    148 
    149 
    150 ==============================================================================
    151 
    152 2. Differences from legacy Vim script			*vim9-differences*
    153 
    154 Overview ~
    155 							*E1146*
    156 The following list is a brief summary of some key differences between legacy
    157 Vim script and Vim9 script, including `:def` functions:
    158 
    159 - Comments start with #, not ":
    160 >vim9
    161 	vim9script
    162 	# Comments start with a number sign (#), not a quotation mark (")
    163 <
    164 - Using a backslash (i.e., \, a reverse solidus) for line continuation is
    165   rarely needed:
    166 >vim9
    167 	vim9script
    168 	echo $"Your $HOME directory is {$HOME}\n" ..
    169 	  $"Your $VIMRUNTIME environment variable is {$VIMRUNTIME}"
    170 <
    171 - White space is required in many places, improving readability.
    172   See |vim9-white-space|.
    173 							*E1126*
    174 - Declare variables with `:var` and assign values without `:let` (which is
    175   not allowed):
    176 >vim9
    177 	vim9script
    178 	var count = 0
    179 	count += 3		# 3
    180 	echo count
    181 	let E1126 = count	# E1126: Cannot use :let in Vim9 script
    182 <
    183 - Constants can be declared with `:final` and `:const`:
    184 >vim9
    185 	vim9script
    186 	final matches = ['Peter']	# adding to this list later is okay
    187 	const NAMES = ['Paul', 'Mary']	# NAMES constant cannot be changed
    188 	matches->extend(NAMES)
    189 	echo matches			# ['Peter', 'Paul', 'Mary']
    190 <
    191 - Variables and functions are script-local by default (see |vim9-scopes|).
    192 
    193 - Functions are declared with argument types and return type:
    194 >vim9
    195 	vim9script
    196 	def Cubed(n: float): string  # float arg, string returned
    197 	  return $"\n{n} cubed is {n->pow(3)}"
    198 	enddef
    199 	echo Cubed(input("Enter a float to cube: ")->str2float())
    200 <
    201 - Calling functions does not require `:call`.  Although it is deprecated, using
    202   it does not give an error:
    203 >vim9
    204 	vim9script
    205 	popup_notification("Builtin function called WITHOUT :call", {})
    206 	call popup_notification("Builtin function called WITH :call", {})
    207 <
    208 						*vim9-invalid-Ex-commands*
    209 - You cannot use these Ex commands:
    210 
    211 	`:Print` (or shortened forms like `:Pr`)
    212 	`:append` (or shortened forms like `:a`)
    213 	`:change` (or shortened forms like `:c`)
    214 	`:dp`
    215 	`:insert` (or shortened forms like `:i`)
    216 	`:k`
    217 	`:mode` (or the shortened form `:mod`)
    218 	`:open` (or shortened forms like `:o`)
    219 	`:sce`	`:scg`	`:sci`	`:scI`	`:scl`	`:scn`	`:scp`
    220 	`:sg`	`:sgc`	`:sge`	`:sgi`	`:sgI`	`:sgl`	`:sgn`	`:sgp`	`:sgr`
    221 	`:sic`	`:sie`	`:siI`	`:sin`	`:sip`	`:sir`
    222 	`:sI`	`:sIc`	`:sIe`	`:sIg`	`:sIi`	`:sIl`	`:sIn`	`:sIp`	`:sIr`
    223 	`:src`	`:srg`	`:sri`	`:srI`	`:srl`	`:srn`	`:srp`
    224 	`:t`
    225 	`:xit` (or shortened forms `:x` and `:xi`)
    226 
    227 	Note: There are some commands that do not give errors but behave
    228 	differently in Vim9 script.  One is `:dl`, which is an abbreviation of
    229 	`:dlist` (whereas it is `:delete` in legacy Vim script).  Others are
    230 	`:sc`, `:si`, and `:sr`, which in legacy Vim script are short substitute
    231 	commands (like the 38 others listed above).  However, in Vim9 script
    232 	they are shortened forms of `:scriptnames`, `:simalt`, and `:srewind`
    233 	respectively.
    234 						*vim9-no-shorten* *E1065*
    235 - Many commands cannot be shortened.  Trying to use a shortened command will
    236   give E1065.  Specifically, these commands' full names must be used:
    237 
    238   - Flow control commands: `:break`, `:catch`, `:continue`, `:else`, `:elseif`, `:endfor`,
    239     `:endif`, `:endtry`, `:endwhile`, `:finally`, `:finish`, `:return`, `:throw`, `:while`
    240   - Declaration keywords: `:abstract`, `:class`, `:const`, `:def`, `:endclass`, `:enddef`,
    241     `:endenum`, `:endinterface`, `:enum`, `:export`, `:final`, `:import`, `:interface`,
    242     `:public`, `:static`, `:this`, `:type`, `:var`
    243 
    244 - `:final` cannot be used as a shortened form of `:finally`.  That is because
    245   it means |:final| in Vim9 script.  By itself, `:final` lists all variables,
    246   the same as a bare `:let` in legacy Vim script.
    247 
    248 - You cannot use |curly-braces-names| like `my_{&background}_message`.
    249 
    250 - A range before a command must be prefixed with a colon, for example:
    251 >vim9
    252 	vim9script
    253 	# The following line displays lines containing the word 'colon'
    254 	:-3,+2g/colon
    255 	# The following line gives E1050: colon required before a range
    256 	-3,+2g/colon
    257 <
    258 - Executing a register with "@" doesn't work; prepend either a colon or
    259   use `:execute`:
    260 >vim9
    261 	vim9script
    262 	@a = 'echo "Works"'
    263 	:@a		# Works
    264 	execute @a	# Works
    265 	@a		# E1207: Expression without an effect @a
    266 <
    267 - Unless mentioned specifically, the highest |scriptversion| is used.
    268 
    269 - When defining an expression mapping, the expression will be evaluated in
    270   the context of the script where it was defined.
    271 
    272 - When indexing a string, the index is counted in characters, not bytes.
    273   For implications and examples, see |vim9-string-index|.
    274 
    275 - There are some possibly unexpected differences - see |vim9-gotchas|.
    276 
    277 
    278 Comments starting with # ~
    279 							*vim9-comments*
    280 In legacy Vim script, comments start with a quotation mark (").  In Vim9
    281 script, comments start with a number sign (#).
    282 >vim9
    283 	vim9script
    284 	# This is a comment
    285 	'Vim9 script uses #, not "'->popup_notification({})  # Another comment
    286 <
    287 The reason is that a quotation mark can also start a string.  In many places,
    288 especially halfway through an expression with a line break, it is hard to tell
    289 what the meaning is because both a string and a comment can be followed by
    290 arbitrary text.  To avoid confusion, only # comments are recognized.  This is
    291 the same as in shell scripts and Python.
    292 
    293 In Vi, # is a command to list text with numbers.  In Vim9 script, `:number`
    294 may be used.  For example, the following one-line script prints this
    295 paragraph.
    296 >vim9
    297 	vim9cmd :-4,-2number
    298 <
    299 To improve readability, there must be at least one space or tab between a
    300 command and the # starting a comment.  With 'syntax' set, syntax highlighting
    301 also helps to show where an invalid comment is used.  For example:
    302 >vim9
    303 	vim9script
    304 	const OKAY: bool = true # A valid comment (white space before the #)
    305 	echo OKAY		# true
    306 	try
    307 	  const NO: bool = false# THIS IS AN INVALID COMMENT!
    308 	catch
    309 	  echo v:exception	# E121: Undefined variable: false#
    310 	endtry
    311 <							*E1170*
    312 You cannot not start a comment with `#{` - it looks like the legacy dictionary
    313 literal and produces an error where this might be confusing, for example:
    314 >vim9
    315 	vim9script
    316 	#{ E1170: Cannot use #{ to start a comment:
    317 <
    318 A |fold-marker| (i.e., `#{{{`) used to start a fold, is still okay.
    319 
    320 When reading a script, Vim doesn't know whether it is |Vim9| script before
    321 finding the `vim9script` command.  Before it, comments must use legacy
    322 syntax, so a quotation mark:
    323 >vim9
    324 	" legacy Vim script comment before vim9script
    325 	vim9script
    326 	# Vim9 script comment
    327 <
    328 That looks ugly (especially with the syntax highlighting not treating the
    329 initial Vim script comment in Comment highlight group as a command).
    330 It is better having the `vim9script` command as the first line:
    331 >vim9
    332 	vim9script
    333 	# Vim9 script comment
    334 <
    335 In legacy Vim script, # is also used for the alternate file name.  In Vim9
    336 script you must use %% instead.  Instead of ##, use %%%, which stands for
    337 all arguments.  See |c_%%| and |c_%%%#|.
    338 
    339 
    340 Vim9 functions ~
    341 							*vim9-functions*
    342 
    343 A function defined with `:def` is compiled.  Execution is many times faster,
    344 often 10 to 100 times.
    345 
    346 Many errors are already found when compiling, before the function is executed.
    347 The syntax is strict, to enforce code that is easy to read and understand.
    348 
    349 Compilation is done when any of these is encountered:
    350 - the first time the function is called
    351 - when the `:defcompile` command is encountered in the script after the
    352   function was defined
    353 - `:disassemble` is used for the function, or
    354 - a function that is compiled calls the function or uses it as a function
    355   reference (so that the argument and return types can be checked).
    356 
    357 							*E1099*
    358 "Unknown error", E1099, may occur while executing.  If reproducible, it may be
    359 reported at https://github.com/vim/vim/issues as it is now likely to be a
    360 rare, unhandled error worth reporting.
    361 							*E1091*
    362 If compilation fails it is not tried again on the next call, instead this
    363 error is given: "E1091: Function is not compiled: {name}".  For example:
    364 >vim9
    365 	vim9script
    366 	def g:Broken(): string
    367 	  echo 'a' .. []
    368 	enddef
    369 	g:Broken()		# E1105: Cannot convert list to string
    370 <
    371 	Compilation failed.  Now, attempting to call "g:Broken" gives E1091:
    372 >vim9
    373 	vim9cmd g:Broken()	# E1091: Function is not compiled: Broken
    374 <
    375 							*E1191*
    376 Trying to call a function which failed to compile may also return:
    377 "E1191: Call to function that failed to compile".  For example:
    378 >vim9
    379 	vim9script
    380 	def Set_hlsearch()
    381 	  &hlsearch = 9  # NB: 'hlsearch' is bool, so would give E1012
    382 	enddef
    383 	def D_Set_hlsearch()
    384 	  Set_hlsearch()
    385 	enddef
    386 	# With 'silent!', this call does not abort, despite the E1012 error
    387 	silent! Set_hlsearch()
    388 	# Trying to use the function that failed to compile gives E1191:
    389 	D_Set_hlsearch()  # E1191: Call to function that failed to compile
    390 <
    391 Compilation will fail when attempting to execute a user command that
    392 does not exist at either compile or execution time.  So, this fails:
    393 >vim9
    394 	vim9cmd YeahNah()  # E117: Unknown function: YeahNah
    395 <
    396 However, a user command contained in a function, which itself is not yet
    397 compiled, does not fail.  For example, this script can be sourced
    398 without error even though neither command in either of the functions exists:
    399 >vim9
    400 	vim9script
    401 	def g:Late1()
    402 	  DefinedLate1
    403 	enddef
    404 	def g:Late2()
    405 	  execute('DefinedLate2')
    406 	enddef
    407 <
    408 Further, if the functions, above, are subsequently called before the commands
    409 DefinedLate1 and DefinedLate2 exist, compilation fails.  So, after sourcing
    410 the script, above, when the following script is sourced, either |E476| or
    411 |E492| are given:
    412 >vim9
    413 	vim9cmd g:Late1()	# E476: Invalid command: DefinedLate1
    414 	vim9cmd g:Late2()	# E492: Not an editor command: DefinedLate2
    415 <
    416 Although those calls fail, and for different reasons, the point is that any
    417 commands must exist when they are executed.  So, the following script works
    418 because the commands are defined prior to being executed (Note: The script
    419 defining the two global functions must be re-sourced before sourcing this
    420 script):
    421 >vim9
    422 	vim9script
    423 	command DefinedLate1 @a = "One"
    424 	command DefinedLate2 @b = "Two"
    425 	g:Late1()
    426 	g:Late2()
    427 	echo (@a, @b)	# ('One', 'Two')
    428 <
    429 A `:def` function has no options like `:function` (i.e., "abort", "range",
    430 "closure", or "dict").  A `:def` function:
    431 - always aborts on an error unless the error is caught by a `:try` block or
    432   `:silent!` is used calling the function (for an example, see the first
    433   script under |E1191|),
    434 - may not have a range passed,
    435 - automatically supports closures (for an example, see |vim9-closure|), and
    436 - cannot be a "dict" function (see |vim9-no-dict-function|, which follows).
    437 
    438 							*vim9-no-dict-function*
    439 Neither the "dict" option nor "dict" functions are supported in a `:def`
    440 function.  To illustrate, first consider this working legacy Vim script:
    441 >vim
    442 	" legacy Vim script dict function
    443 	let dic = {'ln': [0, 1, 2, 3]}
    444 	function! dic.Len() dict
    445 	  return len(self.ln)
    446 	endfunction
    447 	echo dic.Len() | " 4
    448 <							*E1182*
    449 In Vim9 script, trying to do something similar gives E1182:
    450 >vim9
    451 	vim9script
    452 	var dic: dict<list<number>> = {'ln': [0, 1, 2, 3]}
    453 	def dic.len(): number  # E1182: Cannot define a dict function in Vim9…
    454 	  return len(self.ln)
    455 	enddef
    456 <
    457 Instead of using a "dict" function, in Vim9 script, there are a few options:
    458 
    459 - Use a Vim9 Class (see |Vim9-class|):
    460 >vim9
    461 	vim9script
    462 	class MyClass
    463 	  var ln: list<number>
    464 	  def Len(): number
    465 	    return this.ln->len()
    466 	  enddef
    467 	endclass
    468 	var obj = MyClass.new([0, 1, 2, 3])
    469 	echo obj.Len()	# 4
    470 <
    471 - Pass the dictionary explicitly:
    472 >vim9
    473 	vim9script
    474 	def DicLen(self: dict<any>, arg: string): number
    475 	  return self[arg]->len()
    476 	enddef
    477 	var da: dict<any> = {func: DicLen, item: [0, 1, 2, 3]}
    478 	echo da.func(da, 'item')	# 4
    479 <
    480 - Call a legacy Vim script dict function (|Dictionary-function|):
    481 >vim9
    482 	vim9script
    483 	function LegDicLen() dict
    484 	  return self.item->len()
    485 	endfunc
    486 	def CallLegDicLen(): number
    487 	  var da: dict<any> = {func: LegDicLen, item: [0, 1, 2, 3]}
    488 	  return da.func()
    489 	enddef
    490 	echo CallLegDicLen()	# 4
    491 <
    492 The argument types and return type need to be specified and match - various
    493 errors may occur when they do not.  See |fast-functions| and |type-checking|.
    494 
    495 							*vim9-any-type*
    496 The "any" type can be used, type checking will then be done at runtime, like
    497 with legacy functions, and allows the type to change.  For example:
    498 >vim9
    499 	vim9script
    500 	var avar: any
    501 	echo avar->typename()	# number
    502 	avar = 'A string'
    503 	echo avar->typename()	# string
    504 	avar = [['A', 'list'], ['of', 'lists']]
    505 	echo avar->typename()	# list<list<string>>
    506 <
    507 	Warning: The "any" type defaults to the number type and 0.  Operations
    508 	demanding a specific type may produce unexpected results or errors if
    509 	that is not factored.  Further, unlike a variable explicitly declared
    510 	as a number, direct assignment of any other type means the variable's
    511 	type is re-inferred, which can occur multiple times at runtime.  For
    512 	example:
    513 >vim9
    514 	vim9script
    515 	var n1: any
    516 	echo n1->typename()	# number
    517 	n1 ..= 'zero'
    518 	echo n1			# 0zero (that is, the default 0 and "zero")
    519 	echo n1->typename()	# string
    520 	n1 = true
    521 	echo n1->typename()	# bool
    522 	var n2: any
    523 	n2->extend(['item'])	# E712: Argument of extend() must be a List o…
    524 <
    525 Arguments are accessed by name, without "a:", just like any other language.
    526 There is no "a:" dictionary or "a:000" list.  This example shows not only "a:"
    527 but also valid extreme white space minimization in a legacy Vim script:
    528 >vim
    529 	function! MyFirst(s,d,n,...)
    530 	  return a:s.a:d[a:n].a:000[1]
    531 	endfunction
    532 	let MyDict={1:'one',2:'two'}
    533 	echo MyFirst('The value of key 2 of MyDict is ',
    534 	      \ MyDict,2,v:null,'!',9999)
    535 <
    536 The equivalent, in Vim9 script:
    537 >vim9
    538 	vim9script
    539 	def MyFirst(s: string, d: dict<string>, n: number,
    540 	    ...l: list<any>): string
    541 	  return s .. d[n] .. l[1]
    542 	enddef
    543 	var MyDict: dict<string> = {1: 'one', 2: 'two'}
    544 	echo MyFirst('The value of key 2 of MyDict is ',
    545 	  MyDict, 2, null, '!', 9999)
    546 <
    547 	Note: In this Vim9 script, an error would occur if omitting spaces:
    548 	- after any of the commas
    549 	- after any of the colons in 'key: value' or 'variable: type'
    550 	- before/after instances of '..', and
    551 	- before/after '='.
    552 						*vim9-variable-arguments*
    553 The previous example shows variable arguments ("...l: list<any>") defined as
    554 the last argument.  In Vim9 script, variable arguments require a name and
    555 list<type>, similar to TypeScript.  This example iterates a variadic list
    556 of numbers:
    557 >vim9
    558 	vim9script
    559 	def MyProduct(...ln: list<number>): number
    560 	  var prod: number = 1
    561 	  for num in ln
    562 	    prod *= num
    563 	  endfor
    564 	  return prod
    565 	enddef
    566 	echo MyProduct(10, 10)	# 100
    567 	echo MyProduct(5, 4, 5)	# 100
    568 <
    569 Errors may occur when variadic arguments are not declared or passed correctly:
    570 
    571 							*E1055*
    572 - Failing to provide the name to a variable argument:
    573 >vim9
    574 	vim9script
    575 	def F1055(n: number, ...): void  # E1055: Missing name after ...
    576 	enddef
    577 <							*E1160*
    578 - Trying to use a default for a variable argument:
    579 >vim9
    580 	vim9script
    581 	def F1160(...l = []): void  # E1160: Cannot use a default for variabl…
    582 	enddef
    583 <							*E1180*
    584 - Failing to declare a variable argument as a list<type>:
    585 >vim9
    586 	vim9script
    587 	def F1180(...l: string): void  # E1180: Variable arguments type must…
    588 	enddef
    589 <
    590 When a function argument is optional (that is, it has a default value),
    591 passing `v:none` as the argument results in using the default value.  This is
    592 useful when you want to specify a value for an argument that comes after an
    593 argument that should use its default value.  For example:
    594 >vim9
    595 	vim9script
    596 	def F(pi: float = 3.14, ra: float = 1.0): float
    597 	  return pi * ra->pow(2)
    598 	enddef
    599 	echo F(v:none, 2.0)	# 12.56 (using default 'pi' value, 3.14)
    600 <
    601 							*E1106*
    602 When too many arguments are passed, either an |E176| or E1106 error occurs.
    603 An E1106 example:
    604 >vim9
    605 	vim9script
    606 	var ln: list<number> = [1, 2, 4, 8]
    607 	foreach(ln, (val) => {
    608 	  echo val
    609 	})  # E1106: One argument too many (the Lambda has only one argument)
    610 <
    611 	Note: `foreach()` passes two arguments to its callback: for a list,
    612 	they are the list's index and value.  Vim9 lambdas must have both
    613 	(technically, "matching arity"), even when only one appears to be
    614 	required.  So, "(val)" should be "(_, val)", explained below.
    615 
    616 							*vim9-ignored-argument*
    617 The argument "_" (an underscore) can be used to ignore the argument.  This is
    618 most useful in callbacks where you don't need it, but do need to give an
    619 argument to match the call.  For example, when using |map()| with a list, two
    620 arguments are passed, the index and the value.  The following script
    621 first demonstrates ignoring the indexes, then ignoring the values:
    622 >vim9
    623 	vim9script
    624 	final nl: list<number> = [1, 2, 4, 8]
    625 	map(nl, (_, val) => val * 2)	# '_' ignores the indexes
    626 	echo nl				# [2, 4, 8, 16]
    627 	map(nl, (idx, _) => idx * 2)	# '_' ignores the values
    628 	echo nl				# [0, 2, 4, 6]
    629 <
    630 The "_" argument can be used multiple times, and no type is needed.
    631 >vim9
    632 	vim9script
    633 	var count: number
    634 	def In20s(_, _, year: number): void
    635 	  count += year >= 2020 ? 1 : 0
    636 	enddef
    637 	var data = [['Bo', 'A', 2026], ['Mo', 'B', 2018], ['Jo', 'A', 2022]]
    638 	for staff in data
    639 	  In20s->call(staff)
    640 	endfor
    641 	echo $"There are {count} staff members in the 2020s."
    642 <
    643 	Note: This script uses |call()|, not to be confused with |:call|.
    644 
    645 							*E1181*
    646 Using "_" in a disallowed context gives error E1181.  For example:
    647 >vim9
    648 	vim9script
    649 	def F1181(_): string
    650 	  return _	# E1181: Cannot use an underscore here
    651 	enddef
    652 	echo F1181("No")
    653 <
    654 
    655 Functions and variables are script-local by default ~
    656 							*vim9-scopes*
    657 When using `:function` or `:def` to specify a new function at the script level
    658 in a Vim9 script, the function is local to the script (like prefixing "s:" in
    659 legacy Vim script).  To define a global function or variable, the "g:" prefix
    660 must be used.  For functions in a script that is to be imported, and in an
    661 autoload script, `:export` needs to be used for those to be used elsewhere.
    662 >
    663 	def ThisFunction()	# script-local
    664 	def g:ThatFunction()	# global
    665 	export def Function()	# for import and import autoload
    666 <
    667 							*E1075*
    668 Using "s:" (like in a legacy Vim script function), is not allowed.  If used in
    669 a script level `:def` function, |E1268| is given, and, if used in a nested `:def`
    670 function, E1075.  For example:
    671 >vim9
    672 	vim9script
    673 	def F1075(): void
    674 	  def s:Inner()  # E1075: Namespace not supported: s:Inner()
    675 	  enddef
    676 	enddef
    677 	F1075()
    678 <
    679 When using `:function` or `:def` to specify a nested function inside a `:def`
    680 function and no namespace was given, the nested function is local to the code
    681 block it is defined in.  It cannot be used in a `function()` with a string
    682 argument.  Instead, pass the function reference itself:
    683 >vim9
    684 	vim9script
    685 	def Outer(): void
    686 	  def Inner(): string
    687 	    return 'Inner() successfully called'
    688 	  enddef
    689 	  var Okay = function(Inner)
    690 	  echo Okay()		# Inner() successfully called
    691 	  try
    692 	    var Bad = function("Inner")
    693 	  catch
    694 	    echo v:exception	# Vim:E700: Unknown function: Inner
    695 	  endtry
    696 	enddef
    697 	Outer()
    698 <
    699 	Note: Passing the string argument fails because "Inner" becomes a
    700 	function reference to a function with a generated internal name,
    701 	which could be shown with "funcref(Inner)".
    702 
    703 It is not possible to define a script-local function in a function.  You can
    704 define a local function and assign it to a script-local |Funcref|, though it
    705 must first have been declared at the script level.
    706 >vim9
    707 	vim9script
    708 	var ScriptLocalFuncref: func
    709 	def Outer(): void
    710 	  def Inner(): string
    711 	    return "Hi from ScriptLocalFuncref!"
    712 	  enddef
    713 	  ScriptLocalFuncref = Inner
    714 	enddef
    715 	Outer()
    716 	echo ScriptLocalFuncref()
    717 <
    718 When referring to an unprefixed function (i.e., without either a "g:" or "s:"
    719 prefix), Vim will search for the function in the function scope, in block
    720 scopes, and in the script scope.
    721 
    722 Imported functions are found with the prefix from the `:import` command.
    723 Exporting and importing is explained at |vim9-import|.
    724 
    725 In Vim9 script, a script-local function reference must start with an uppercase
    726 letter.  Consequently, even in scenarios where "s:" is required (within legacy
    727 Vim script scopes), "s:Funcref" must be used, avoiding potential ambiguity
    728 with builtin functions.  Consider the following legacy Vim script and Vim9
    729 script examples.
    730 
    731 - First, legacy Vim script, showing that "s:" may be used in a legacy Vim
    732   script to define a function, which would otherwise interfere with a
    733   builtin function (in this instance, the builtin, |cos()|):
    734 >vim
    735 	function! s:cos()
    736 	  echo 's:cos() works'
    737 	endfunction
    738 	call s:cos()		" s:cos() works
    739 <
    740 - Second, Vim9 scripts, showing that legacy functions:
    741   1. Must start with an uppercase letter (otherwise |E1267| is given),
    742   2. Cannot be defined with "s:" in a Vim9 script-local scope (|E1268|), and
    743   3. Within the legacy scope of a function, "s:" is required but, for the
    744     reasons, above, must be "s:" and an uppercase letter (|E117|):
    745 >vim9
    746 	vim9script
    747 	execute ('function cos()')  # E1267: Function name must start with a …
    748 < >vim9
    749 	vim9script
    750 	execute ('function s:cos()')  # E1268: Cannot use s: in Vim9 script: …
    751 < >vim9
    752 	vim9script
    753 	function Cos()
    754 	  echo 'This works: now we are in Cos().'
    755 	endfunction
    756 	function Call_Cos()
    757 	  call s:Cos()	" Requires the 's:'
    758 	  call Cos()	" E117: Unknown function: Cos
    759 	endfunction
    760 	Call_Cos()
    761 <							*vim9-s-namespace* *E1268*
    762 Within a Vim9 script's `:def` function, "s:" cannot be used.  Compare these
    763 two scripts: first, legacy Vim script where "s:" may be used in a `:def` then,
    764 second, Vim9 script where E1268 is given:
    765 >vim
    766 	" Legacy Vim script - s: working in a :def, though it is optional
    767 	let s:leg = 'okay'
    768 	def Ok_def_s(): void
    769 	  # Note that either leg or s:leg are valid here
    770 	  echo leg .. ', ' .. s:leg	# okay, okay
    771 	enddef
    772 	call Ok_def_s()
    773 < >vim9
    774 	vim9script
    775 	var nine: string
    776 	def F1268(): void
    777 	  echo s:nine	# E1268: Cannot use s: in Vim9 script: s:nine
    778 	enddef
    779 	F1268()
    780 <
    781 The use of the "s:" prefix is not supported in the Vim9 script-local scope.
    782 Functions and variables without a prefix are always script-local.  This
    783 includes calling legacy functions:
    784 >vim9
    785 	vim9script
    786 	function ScriptLevel(str)
    787 	  echo a:str
    788 	endfunction
    789 	ScriptLevel('okay')
    790 	# The following gives E1268: Cannot use s: in Vim9 script
    791 	s:ScriptLevel('not okay')
    792 <
    793 Within legacy functions, using "s:" for script-local variables is always
    794 required:
    795 >vim9
    796 	vim9script
    797 	var local: string = 'script-local :var'
    798 	function Legacy_requires_s()
    799 	  echo s:local
    800 	  " Without 's:', 'local' gives E121:
    801 	  echo local
    802 	endfunction
    803 	Legacy_requires_s()
    804 <
    805 In all cases the function must be defined before it is used.  That is, either
    806 when it is called explicitly (including if `:defcompile` causes it to be
    807 compiled), or when code that calls it is being compiled, inferring the return
    808 type.
    809 
    810 The result is that functions and variables without a namespace can usually be
    811 found in the script, either defined there or imported.  Global functions and
    812 variables could be defined anywhere.  (Good luck finding out where!  You can
    813 often see where it was last set using |:verbose|).
    814 
    815 
    816 Deleting functions in a Vim9 script ~
    817 							*E1084*
    818 In Vim9 script, script-local functions (either `:function` or `:def`) are
    819 defined once when the script is sourced and cannot be deleted or replaced by
    820 the script itself:
    821 >vim9
    822 	vim9script
    823 	def MyDef(): void
    824 	enddef
    825 	delfunction MyDef  # E1084: Cannot delete Vim9 script function MyDef
    826 <
    827 	Note: A script-local function may be replaced by reloading the script.
    828 	See |vim9-reload|.
    829 
    830 Global functions ("g:" prefixed) can still be defined and deleted at nearly
    831 any time, though deleting a global function in Vim9 script has a distinction
    832 between |function()| and |funcref()|.  When a global function is deleted and
    833 redefined, the replacement global function is updated dynamically in any
    834 variables calling it whereas the function reference is persistent (unless the
    835 variable itself is redeclared).  This is an important distinction, differing
    836 from legacy Vim script behavior, where deleting a function deletes the funcref
    837 too.  To illustrate:
    838 >vim9
    839 	vim9script
    840 	def g:F(): string
    841 	  return 'one'
    842 	enddef
    843 	var Function = function(g:F)
    844 	var Funcref = funcref(g:F)
    845 	echo (Function(), Funcref())	# ('one', 'one')
    846 	delfunction g:F
    847 	def g:F(): string
    848 	  return 'two'
    849 	enddef
    850 	echo (Function(), Funcref())	# ('two', 'one')
    851 	Funcref = funcref(g:F)		# Redeclare Funcref
    852 	echo (Function(), Funcref())	# ('two', 'two')
    853 <
    854 	Note: This persistent behavior of |funcref()| may be regarded as a
    855 	feature, or may be unexpected if not understood.
    856 
    857 When compiling a function, and a function call is encountered for a function
    858 that is not (yet) defined, the |FuncUndefined| autocommand is not triggered.
    859 You can use an autoload function if needed, or call a legacy function and have
    860 |FuncUndefined| triggered there.
    861 
    862 
    863 Reloading a Vim9 script clears functions and variables by default ~
    864 						*vim9-reload* *vim9-noclear*
    865 When loading a legacy Vim script a second or subsequent time, nothing is
    866 removed.  Commands will replace existing variables and functions, create new
    867 ones, and leave removed things hanging around.
    868 
    869 When loading a Vim9 script a second or subsequent time, the default is that
    870 all existing script-local functions and variables are deleted.  So, you start
    871 with a clean slate.  This is useful if you are developing a plugin and want to
    872 try a new version.  If you renamed something you don't have to worry about the
    873 old name persisting.
    874 
    875 The exported functions and variables of an autoload script live in the global
    876 namespace with the autoload prefix.  When such a script is sourced again they
    877 are likewise given a clean slate, so an autoload script can be sourced more
    878 than once.  A class or enum in an autoload script is an exception: it cannot
    879 be redefined this way and |E1041| is given, because objects created from the
    880 previous definition would keep referring to it.  Restart Vim to load a changed
    881 class or enum in an autoload script.  In other scripts a class or enum is
    882 cleared like everything else, so it can be redefined.
    883 
    884 If you do want to keep script-local functions and variables, use "noclear".
    885 To illustrate, source this script a few times; every time it is sourced,
    886 another 9 is added to MyList:
    887 >vim9
    888 	vim9script noclear
    889 	var MyList: list<number> = !exists('MyList') ? [9] : MyList->add(9)
    890 	echo MyList
    891 <
    892 You want to use this in scripts that use a `finish` command to bail out at
    893 some point when loaded again.  For example, when a buffer local option is set
    894 to a function, the function does not need to be defined more than once:
    895 >vim9
    896 	vim9script noclear
    897 	# 'We are in SomeFunc()' is echoed only the first time this script is
    898 	# sourced.  Subsequent times, you are told, 'SomeFunc exists already'.
    899 	setlocal completefunc=SomeFunc
    900 	if exists('*SomeFunc')
    901 	  popup_notification('SomeFunc() exists already', {time: 4000})
    902 	  finish
    903 	endif
    904 	def SomeFunc()
    905 	  popup_notification('We are in SomeFunc()', {time: 4000})
    906 	enddef
    907 	SomeFunc()
    908 <							*E1149*
    909 An important consequence of cleared script-local functions and variables is
    910 that idiomatic practices, such as finishing when "g:loaded_{plugin_name}"
    911 exists, means it's important to remember that variables and functions do not
    912 persist.  To illustrate, source the following Vim9 script.  Then source it
    913 again.  The first time in it will echo "Okay...."  The second/subsequent times
    914 it gives an E1149 error:
    915 >vim9
    916 	vim9script
    917 	:+7,+15source
    918 	echo g:GetName()
    919 	# The second and subsequent times it is sourced, this error is given:
    920 	# E1149: Script variable is invalid after reload in function GetName
    921 < >
    922 	" DO NOT SOURCE THIS SCRIPT: TO FOLLOW THIS DEMO, SOURCE THE ONE ABOVE
    923 	vim9script
    924 	if exists('g:loaded_E1149')
    925 	  finish
    926 	endif
    927 	g:loaded_E1149 = true
    928 	var name: string = 'Okay (declared only the first time sourced!)'
    929 	def g:GetName(): string
    930 	  return name
    931 	enddef
    932 <
    933 	Note: If you want to re-run this, use `:unlet` g:loaded_E1149 to
    934 	remove the global variable.
    935 
    936 							*E1150*
    937 Variables' types are not cleared when using `noclear` (|vim9-noclear|).  If you
    938 try to change a variable's type, E1150 may be given.  For example, if you
    939 source the following script it echoes "string".  If you then source the second
    940 script it gives E1150:
    941 >vim9
    942 	vim9script
    943 	var my_var: string = "string"
    944 	def g:Get_myvar(): void
    945 	  echo my_var
    946 	enddef
    947 	g:Get_myvar()
    948 < >vim9
    949 	vim9script noclear
    950 	my_var = false		# This changes my_var to a bool
    951 	echo my_var		# false
    952 	echo my_var->typename()	# bool
    953 	g:Get_myvar()		# E1150: Script variable type changed
    954 <
    955 							*E1190*
    956 When reloading with `noclear`, compiled function calls are preserved.  If a
    957 called function's signature changes, argument mismatches will occur.  For
    958 example, when sourced for the first time, the following script echoes "9".
    959 However, when sourced subsequently, the changed function signature change
    960 means there is one argument too few and E1190 is given:
    961 >vim9
    962 	vim9script noclear
    963 	if !exists('g:loaded_E1190')
    964 	  def Echo(n: number): void
    965 	    echo n
    966 	  enddef
    967 	  def CallEcho(n: number): void
    968 	    Echo(n)
    969 	  enddef
    970 	else
    971 	  # Redefine Echo() with a second argument
    972 	  def Echo(n: number, x: number)
    973 	    echo n * x
    974 	  enddef
    975 	endif
    976 	CallEcho(9)  # First time, 9.  Second, E1190: One argument too few.
    977 	g:loaded_E1190 = true
    978 <
    979 
    980 Variable declarations with :var, :final, and :const ~
    981 							*vim9-declaration* *:var*
    982 Local variables need to be declared with `:var`.  Local constants need to be
    983 declared with either `:final` or `:const`.  Collectively they are referred to
    984 as "variables" in this section.  Shortening `:var`, `:final`, or `:const` is not
    985 allowed - see |vim9-no-shorten|.
    986 
    987 Variables can be local to a script, function, or code block.  The following
    988 example demonstrates all three:
    989 >vim9
    990 	vim9script
    991 	var s: string = 'script'
    992 	def Func(): void
    993 	  var f: string = 'function'
    994 	  {
    995 	    var b: string = 'block'
    996 	    echo $"Visible: {s}, {f}, and {b}"
    997 	  }
    998 	  echo $"Visible: {s} and {f}"	# b: invisible outside the {...} block
    999 	enddef
   1000 	Func()
   1001 	echo $"Visible: {s} only"	# f and b: invisible outside the :def
   1002 <
   1003 	Note: See |vim9-exists()| for limitations in determining whether a
   1004 	variable exists.
   1005 							*vim9-block*
   1006 Variables are only visible in the block where they are defined, including any
   1007 nested blocks.  Once the block ends the variable is no longer accessible and,
   1008 if you try to use it, gives E121.  So, for example, to intentionally "hide" a
   1009 variable from code which follows it, a block may be used to make the variable
   1010 only accessible within the block's scope:
   1011 >vim9
   1012 	vim9script
   1013 	{
   1014 	  var inblock: string = 'inblock is not visible outside the block!'
   1015 	}
   1016 	echo inblock	# E121: Undefined variable: inblock
   1017 <
   1018 For the variable "inblock" to be visible, it needs to be declared earlier:
   1019 >vim9
   1020 	vim9script
   1021 	var inblock: string
   1022 	{
   1023 	  inblock = 'when defined earlier, inblock is visible outside'
   1024 	}
   1025 	echo inblock
   1026 <
   1027 A block is especially useful in a user command (see also |command-block|).  In
   1028 the following example, the SAVE constant is assigned the value of the unnamed
   1029 register and later it is used to revert the unnamed register.  The SAVE
   1030 constant is invisible outside the user command:
   1031 >vim9
   1032 	vim9script
   1033 	# Create the YankHelpGrep command (to :helpgrep a visual selection)
   1034 	command -register YankHelpGrep {
   1035 	  const SAVE = @"
   1036 	  normal! y
   1037 	  execute $"helpgrep {getreg('<register>')}"
   1038 	  @" = SAVE
   1039 	  copen
   1040 	}
   1041 	# Map YH in Visual mode to YankLhelpGrep
   1042 	xnoremap YH <ScriptCmd>YankHelpGrep "<CR>
   1043 <
   1044 A block can also be useful with autocommands (see |:autocmd-block|).
   1045 
   1046 Although a block may be useful and terse, using a `:def` function works better
   1047 in many instances, and often is more readable.
   1048 							*E1025* *E1128*
   1049 A block with a missing left curly bracket may give E1025 or E1128.  Examples:
   1050 >vim9
   1051 	vim9script
   1052 	def F1025()
   1053 	  }
   1054 	enddef
   1055 	defcompile F1025  # E1025: Using } outside of a block scope
   1056 <and >vim9
   1057 	vim9cmd }  # E1128: } without {
   1058 <
   1059 Errors given when incorrectly declaring or initializing a variable include:
   1060 
   1061 							*E1017*  >vim9
   1062 	vim9script
   1063 	var F1017: func = (): void => {
   1064 	  var a: any
   1065 	  var a = 'error'  # E1017: Variable already declared: a
   1066 	}
   1067 <							*E1020*  >vim9
   1068 	vim9script
   1069 	var x += 4  # E1020: Cannot use an operator on a new variable: x += 4
   1070 <
   1071 							*E1022*  >vim9
   1072 	vim9script
   1073 	var x  # E1022: Type or initialization required
   1074 <
   1075 							*E1034*  >vim9
   1076 	vim9script
   1077 	var this = 'reserved'	# E1034: Cannot use reserved name this
   1078 <
   1079 							*E1054*  >vim9
   1080 	vim9script
   1081 	var x: bool
   1082 	var F1054: func = (): void => {
   1083 	  var x = 'no'	# E1054: Variable already declared in the script: x
   1084 	}
   1085 <							*E1087*  >vim9
   1086 	vim9script
   1087 	var F1087: func = (): void => {
   1088 	  var x.y = 0	# E1087: Cannot use an index when declaring a variable
   1089 	}
   1090 <							*E1124*  >vim9
   1091 	vim9script
   1092 	function F1124()
   1093 	  var x = 'E1124: ":var" cannot be used in legacy Vim script'
   1094 	endfunction
   1095 	F1124()
   1096 <							*E1079*
   1097 A variable cannot be declared in Command-line mode or Ex mode.  For example:
   1098 >vim9
   1099 	vim9script
   1100 	feedkeys(":vim9cmd var x = 0\<CR>")
   1101 	# E1079: Cannot declare a variable on the command line
   1102 <
   1103 Declaring a variable with a type, but without an initializer, defaults to:
   1104 - `false` for bool
   1105 - 0 for number and "any"
   1106 - 0.0 for float, and
   1107 - empty (for all other types that can be declared without an initializer).
   1108 To illustrate:
   1109 >vim9
   1110 	vim9script
   1111 	var a: any | var b: bool | var n: number | var f: float
   1112 	echo [a, b, f, n]				# [0, false, 0.0, 0]
   1113 	var s: string | var F: func | var l: list<any> | var d: dict<any> |
   1114 	      \ var j: job | var c: channel | var z: blob | var t: tuple<any>
   1115 	echo empty(s) && empty(F) && empty(l) && empty(d) && empty(j) &&
   1116 	      \ empty(c) && empty(z) && empty(t)	# true
   1117 <
   1118 	Note: Take care using the "any" type given its default is 0.  For
   1119 	implications, see |vim9-any-type|.
   1120 
   1121 Uninitialized container types can be added to.  For example:
   1122 >vim9
   1123 	vim9script
   1124 	var myDict: dict<list<number>>
   1125 	var myList: list<number>
   1126 	myList->add(9)
   1127 	myDict['version'] = myList
   1128 	echo myDict  # {'version': [9]}
   1129 <
   1130 Initializing a variable to a null value differs from initializing a variable
   1131 with "null_<type>".  Particularly, `null_dict`, `null_list`, and `null_blob`
   1132 give errors when trying to add to/extend variables initialized to them:
   1133 
   1134 - `null_dict`:
   1135 							*E1103*  >vim9
   1136 	vim9script
   1137 	var nd = null_dict
   1138 	def F1103(): void
   1139 	  nd['a'] = 'fail'		# E1103: Dictionary not set
   1140 	enddef
   1141 	F1103()
   1142 <							*E1133*  >vim9
   1143 	vim9script
   1144 	var ed: dict<string>		# An empty dict can be extended
   1145 	ed->extend({'a': 'okay'})
   1146 	echo ed				# {'a': 'okay'}
   1147 	var nd: dict<string> = null_dict
   1148 	nd->extend({'a': 'fail'})	# E1133: Cannot extend a null_dict
   1149 <
   1150 - `null_list`:
   1151 							*E1147*  >vim9
   1152 	vim9script
   1153 	var nl = null_list
   1154 	def F1147(): void
   1155 	  nl[0] = 'fail'		# E1147: List not set
   1156 	enddef
   1157 	F1147()
   1158 <							*E1130*  >vim9
   1159 	vim9script
   1160 	var el: list<string>		# An empty list can be added to
   1161 	el->add('okay')
   1162 	echo el				# ['okay']
   1163 	var nl: list<string> = null_list
   1164 	nl->add('fail')			# E1130: Cannot add to null_list
   1165 <
   1166 							*E1134*  >vim9
   1167 	vim9script
   1168 	var el: list<string>		# An empty list can be extended
   1169 	el->extend(['okay'])
   1170 	echo el				# ['okay']
   1171 	var nl: list<string> = null_list
   1172 	nl->extend(['fail'])		# E1134: Cannot extend a null_list
   1173 <
   1174 - `null_blob`:
   1175 							*E1581*  >vim9
   1176 	vim9script
   1177 	var eb: blob			# An empty blob can be extended
   1178 	eb->extend(0zF09F988A)
   1179 	echo eb->blob2str()		# ['😊']
   1180 	var nb: blob = null_blob
   1181 	nb->extend(0zF09F988A)		# E1581: Cannot extend a null_blob
   1182 <
   1183 							*E1131*  >vim9
   1184 	vim9script
   1185 	var eb: blob			# An empty blob can be added to
   1186 	eb->add(0xF0)->add(0x9F)->add(0x98)->add(0x8A)
   1187 	echo eb->blob2str()		# ['😊']
   1188 	var nb: blob = null_blob
   1189 	nb->add(0xF0)			# E1131: Cannot add to null_blob
   1190 <
   1191 Note: Similar errors should not be encountered with:
   1192 - `null_tuple` (because |Tuples| are immutable, neither adding to nor
   1193   extending them is permitted), and
   1194 - `null_string` (which is one of the |null-anomalies|), for example:
   1195 >vim9
   1196 	vim9script
   1197 	var ns: string = null_string
   1198 	ns ..= 'Okay!'
   1199 	echo ns		# Okay!
   1200 <
   1201 Using |:let| is not allowed in Vim9 script.  Trying to do so gives |E1226|.
   1202 An existing variable is assigned to without any command.  The same applies to
   1203 global, window, tab, buffer and Vim variables, because they are not really
   1204 declared.  They can also be deleted with |:unlet|, for example:
   1205 >vim9
   1206 	vim9script
   1207 	g:v = "global"
   1208 	b:v = "buffer local"
   1209 	t:v = "tab local"
   1210 	w:v = "window local"
   1211 	echo [g:v, b:v, w:v, t:v]
   1212 	unlet g:v | unlet b:v | unlet w:v | unlet t:v
   1213 	# Now none of the 'v' variables exist, so this echoes [0, 0, 0, 0]
   1214 	echo [exists('g:v'), exists('b:v'), exists('w:v'), exists('t:v')]
   1215 <
   1216 Declaring any of the following with `:var` gives an error:
   1217 - a global, buffer, tab, or window variable
   1218 - an option, or
   1219 - a register.
   1220 Examples:
   1221 							*E1016*  >vim9
   1222 	vim9script
   1223 	var t:err = 'err'  # E1016: Cannot declare a tab variable: t:err
   1224 <
   1225 							*E1052*  >vim9
   1226 	vim9script
   1227 	var &ts = 8  # E1052: Cannot declare an option: &ts = 8
   1228 <
   1229 							*E1066*   >vim9
   1230 	vim9script
   1231 	var @a = 'no'  # E1066: Cannot declare a register: @a = 'no'
   1232 <
   1233 							*E1178*
   1234 Use `:const` or `:final` instead of `:lockvar`, which does not work on local
   1235 variables.
   1236 >vim9
   1237 	vim9script
   1238 	def F1178(): void
   1239 	  var x: any
   1240 	  lockvar x
   1241 	enddef
   1242 	F1178()  # E1178: Cannot lock or unlock a local variable
   1243 <
   1244 Even though `:lockvar` works with script-local variables, using `:const` or
   1245 `:final` usually is better for those too, except where locked/unlocked
   1246 toggling is wanted, which is shown in this example:
   1247 >vim9
   1248 	vim9script
   1249 	var n: number = 8
   1250 	lockvar n
   1251 	try
   1252 	  n = 9
   1253 	catch
   1254 	  echo v:exception	# E741: Value is locked: n
   1255 	finally
   1256 	  unlockvar n
   1257 	endtry
   1258 	n = 9
   1259 	echo n			# 9
   1260 <
   1261 							*vim9-exists()*
   1262 The `exists()` (and `exists_compiled()`) function does not work on local
   1263 arguments or variables declared in a compiled function.  It always returns 0.
   1264 However, `exists()` works in both non-compiled Vim9 script and on variables
   1265 tested from within a compiled function where the variable is declared
   1266 already in a non-compiled scope.  To illustrate:
   1267 >vim9
   1268 	vim9script
   1269 	var script: any
   1270 	var MyCompiled: func = (arg: any): void => {
   1271 	  var compiled: any
   1272 	  echo exists('arg')		# 0 (compiled, local argument)
   1273 	  echo exists('compiled')	# 0 (compiled, local variable)
   1274 	  echo exists('script')		# 1 (compiled, script-local variable)
   1275 	  }
   1276 	MyCompiled(true)
   1277 	echo exists('script')		# 1 (script-local scope and variable)
   1278 <
   1279 Also, `exists()` works in a Vim9 script for arguments and variables in a
   1280 legacy function, including those declared with `:var`.  For example:
   1281 >vim9
   1282 	vim9script
   1283 	function Legacy(arg = 'yes')
   1284 	  let local = 'yes'
   1285 	  vim9cmd var vlocal: string = 'yes'
   1286 	  return [exists('a:arg'), exists('local'), exists('vlocal')]
   1287 	endfunction
   1288 	echo Legacy()  # [1, 1, 1]
   1289 <							*vim9-no-shadowing*
   1290 Variables, functions and function arguments cannot shadow previously defined
   1291 or imported variables and functions in the same script file.  However,
   1292 variables can shadow Ex commands, so rename the variable if necessary.
   1293 The following are examples of errors given when trying to shadow:
   1294 
   1295 							*E1006*  >vim9
   1296 	vim9script
   1297 	def F1006(n: number): void
   1298 	  var n: number = 10  # E1006: n is used as an argument
   1299 	enddef
   1300 	F1006(9)
   1301 <							*E1041*  >vim9
   1302 	vim9script
   1303 	def X(): void
   1304 	enddef
   1305 	var X: number	# E1041: Redefining script item: "X"
   1306 <
   1307 							*E1167*  >vim9
   1308 	vim9script
   1309 	var ll: list<number> = [2, 3, 1]
   1310 	def F1167(): void
   1311 	  var x: number = 1
   1312 	  echo ll->sort((x, y) => x - y)
   1313 	enddef
   1314 	F1167()  # E1167: Argument name shadows existing variable: x
   1315 <
   1316 							*E1168*  >vim9
   1317 	vim9script
   1318 	var ll: list<number> = [2, 3, 1]
   1319 	var x: number
   1320 	echo ll->sort((x, y) => x - y)	# E1168: Argument already declared in…
   1321 <
   1322 							*E1213*
   1323 Attempting to redefine an imported script's name will give E1213 (see also
   1324 |:import|).  For example, the following script will write a temporary file,
   1325 which is then imported as "Imp" and its variable, "y", echoed.  Subsequently,
   1326 E1213 is given because "Imp" is the {name} of the imported script:
   1327 >vim9
   1328 	vim9script
   1329 	const TMP: string = tempname()
   1330 	var lines: list<string> = ['vim9script', 'export var y = "Success!"']
   1331 	lines->writefile(TMP)
   1332 	import TMP as Imp
   1333 	echo Imp.y		# Success!
   1334 	var Imp: string		# E1213: Redefining imported item "Imp"
   1335 <
   1336 Global variables and global functions must be prefixed with "g:", including at
   1337 the script level.  That is because a variable or function is script-local when
   1338 it does not have a prefix in a Vim9 script-local scope.  An example (noting
   1339 this will appear to do nothing until you source the subsequent script):
   1340 >vim9
   1341 	vim9script
   1342 	var scriptvar: string = 'scriptvar is a script-local variable'
   1343 	def Sfunc(): string
   1344 	  return 'Sfunc() is a script-local function'
   1345 	enddef
   1346 	g:globalvar = 'g:globalvar is a global variable'
   1347 	def g:Gfunc(): string
   1348 	  return 'g:Gfunc() is a global function'
   1349 	enddef
   1350 <
   1351 	Now source the following script.  The first two will echo the
   1352 	"g:...is a global..." strings whereas the unprefixed variable and
   1353 	function will give |E121| (undefined variable) and |E117| (unknown
   1354 	function) respectively.
   1355 >vim
   1356 	echo g:globalvar
   1357 	echo g:Gfunc()
   1358 	echo scriptvar
   1359 	echo Sfunc()
   1360 <
   1361 The "g:" prefix is not needed for |autoload| functions.
   1362 
   1363 						*vim9-function-defined-later*
   1364 In a Vim9 script, it is possible to call a global function before it exists
   1365 provided it is called from within an `exists()` conditional.  For example:
   1366 >vim9
   1367 	vim9script
   1368 	def Later(arg: number): void
   1369 	  if exists('g:ExLater')
   1370 	    g:ExLater(arg)
   1371 	  endif
   1372 	enddef
   1373 	Later(1)
   1374 	def g:ExLater(arg: number): void
   1375 	  popup_notification($'Called g:ExLater() - {arg}', {})
   1376 	enddef
   1377 	Later(2)
   1378 <
   1379 When sourced initially, "Later(1)" does nothing because the `exists()`
   1380 conditional skips calling "g:ExLater(arg)" (since it doesn't exist, yet).
   1381 When sourced again, the "g:ExLater()" function exists, and both popups,
   1382 "Called g:ExLater() - 1" and "Called g:ExLater() - 2", are generated.
   1383 
   1384 You could use `exists_compiled()` to avoid the error, however, then the
   1385 function would not be called, even when it is defined later.  To illustrate,
   1386 in the following script neither of the "LaterCompiled()" calls generate
   1387 the popup when sourced initially but, when sourced a second time, two popups
   1388 are generated:
   1389 >vim9
   1390 	vim9script
   1391 	def LaterCompiled(arg: number): void
   1392 	  if exists_compiled('g:ExCompLater')
   1393 	    g:ExCompLater(arg)
   1394 	  endif
   1395 	enddef
   1396 	LaterCompiled(1)
   1397 	def g:ExCompLater(arg: number): void
   1398 	  popup_notification($'Called g:ExCompLater() with {arg}', {})
   1399 	enddef
   1400 	LaterCompiled(2)
   1401 <
   1402 Since `&opt = value` is now assigning a value to option "opt", "&" by itself
   1403 cannot be used to repeat a `:substitute` command.  A ":" needs to precede the
   1404 "&" to distinguish it as the repeat command.  The following script
   1405 demonstrates this.  It creates a modifiable buffer in a new split, appends
   1406 "princess", then replaces the "s" twice, resulting in "prince":
   1407 >vim9
   1408 	vim9script
   1409 	:sp | enew
   1410 	append(0, 'princess')
   1411 	:1substitute/s//
   1412 	:&
   1413 <
   1414 Note: If you did use "&" instead of ":&" in this script it would give |E112|.
   1415 >
   1416 <							*vim9-unpack-ignore*
   1417 For unpack assignment (destructuring), the underscore can be used to ignore
   1418 a list item, similar to how a function argument can be ignored:
   1419 >vim9
   1420 	vim9script
   1421 	var theList: list<string> = ['A', 'M', 'Z']
   1422 	var [first, _, last] = theList	# ignore the second item
   1423 	echo $"{first} to {last}"
   1424 <
   1425 To ignore any remaining items, use "; _":
   1426 >vim9
   1427 	vim9script
   1428 	def GetNameCountry(): list<string>
   1429 	  return ['Kamoga', 'Kibaale', 'Uganda', '9', 'M']
   1430 	enddef
   1431 	# Unpack, ignoring second and all items after the third:
   1432 	var [name, _, country; _] = GetNameCountry()
   1433 	echo $"{name} lives in {country}"
   1434 <
   1435 Aside from declaring more than one variable at a time using unpack notation,
   1436 each variable can either have a declared type or infer it from its value:
   1437 >vim9
   1438 	vim9script
   1439 	var one: tuple<...list<any>> = (1, 'I', 'one', 'tahi', '١', '๑')
   1440 	var [d: number, _, _, m; _] = one
   1441 	echo $'Digit {d} is "{m}" in Māori.'
   1442 <
   1443 This approach should be used only where there is a list with values.
   1444 Declaring one variable per line usually is easier to understand.
   1445 
   1446 The type of a variable that does not have a declared type is the type of the
   1447 value it gets.  The variable after the ";" gets the remaining items: for a
   1448 list this is a list of the same member type, for a tuple this is a tuple of
   1449 the types of the remaining items:
   1450 >vim9
   1451 	vim9script
   1452 	var [v1; v2] = [8, 9, 10]	  # v2 has type list<number>
   1453 	var [v3; v4] = (null, 'a', true)  # v4 has type tuple<string, bool>
   1454 	echo "    Variable  has type\n    --------  --------"
   1455 	echo $"{v1->printf('%12S')}  {v1->typename()}"
   1456 	echo $"{v2->printf('%12S')}  {v2->typename()}"
   1457 	echo $"{v3->printf('%12S')}  {v3->typename()}"
   1458 	echo $"{v4->printf('%12S')}  {v4->typename()}"
   1459 <
   1460 When the value has type "any" the item types are not known and every variable
   1461 gets type "any".
   1462 
   1463 							*E1163*
   1464 When unpacking, type mismatches give E1163.  For example, the builtin function
   1465 `getpos()` returns four numbers (bufnum, lnum, col, off) so "col" in this
   1466 script is a type mismatch:
   1467 >vim9
   1468 	vim9script
   1469 	def F1163(): void
   1470 	  var lin: number
   1471 	  var col: bool
   1472 	  [lin, col] = getpos('w0')[1 : 2]  # E1163: Variable 2: type mismatc…
   1473 	enddef
   1474 	F1163()
   1475 <							*E1080*
   1476 And E1080, which is the function-scope equivalent of |E452| at the script
   1477 level, is given in a `:def` function if ";" is used more than once:
   1478 >vim9
   1479 	vim9script
   1480 	def F1080(): void
   1481 	  var [b; l; c] = getpos('w0')[0 : 2]	# E1080: Invalid assignment
   1482 	enddef
   1483 	F1080()
   1484 <
   1485 
   1486 Constants ~
   1487 							*vim9-const* *vim9-final*
   1488 How constants work varies between languages.  Some consider a variable that
   1489 can't be assigned another value a constant.  JavaScript is an example.  Others
   1490 also make the value immutable, thus when a constant uses a list, the list
   1491 cannot be changed.  Both can be used in Vim9 script.
   1492 
   1493 							*E1021* *E1307*
   1494 `:const` is used for making both the variable and the value a constant.  Use
   1495 this for composite structures that you want to make sure will not be modified.
   1496 The following script shows:
   1497 - That a constant must have a value, otherwise E1021 is given, and
   1498 - Attempts to change a constant fail, with E1307.
   1499 >vim9
   1500 	vim9script
   1501 	try
   1502 	  const MISSING_VAL: any
   1503 	catch
   1504 	  echo v:exception # E1021: Const requires a value
   1505 	endtry
   1506 	def F1307(): void
   1507 	  const L: list<number> = [7, 8]
   1508 	  L->add(9) # E1307: Argument 1: Trying to modify a const list<number>
   1509 	enddef
   1510 	F1307()
   1511 <
   1512 Errors |E46| and |E741| may also be given if you try to modify a constant in
   1513 the script-local scope.
   1514 
   1515 Note: It is common to write constants in ALL_CAPS, as has been done in the
   1516 examples in this help file, though you do not have to.
   1517 
   1518 							*:final* *E1125*
   1519 `:final` is used for making only the variable a constant, but with the
   1520 variable's values mutable.  This is well known from Java.  This example shows
   1521 how a variable declared with final can have its values changed and concludes
   1522 with another variable declared with final giving E1125 because it has no
   1523 value:
   1524 >vim9
   1525 	vim9script
   1526 	final ln: list<number> = [7]
   1527 	ln[1] = 9		# Adds an item to the list (okay with :final)
   1528 	ln->add(10)		# Alternative way to add to the list
   1529 	ln->extend([11, 12])	# Extending the list with a list
   1530 	ln[0] = 8		# Changing the values is fine too
   1531 	echo ln			# [8, 9, 10, 11, 12]
   1532 	final f1125: list<any>	# E1125: Final requires a value
   1533 <
   1534 The constant only applies to the value itself, not to what it refers to.
   1535 An example, showing that all items are constant/locked except for those within
   1536 the "females" list:
   1537 >vim9
   1538 	vim9script
   1539 	final females: list<string> = ['Martha']
   1540 	const NAMES: list<list<string>> = [['Peter', 'Paul'], females]
   1541 	NAMES[1][0] = 'Mary'
   1542 	echo NAMES->flattennew()	# ['Peter', 'Paul', 'Mary']
   1543 	NAMES[1] = ["Mary"]		# E741: Value is locked
   1544 <
   1545 
   1546 Omitting :call and :eval ~
   1547 							*vim9-omitting-:call*
   1548 Functions can be called without `:call`.  Using `:call`, as the following
   1549 example shows, is allowed (though it's discouraged).
   1550 >vim9
   1551 	vim9script
   1552 	popup_create("Call functions without using :call", {time: 3000})
   1553 	call popup_create(":call works, but isn't needed", {time: 6000})
   1554 <
   1555 							*vim9-omitting-:eval*
   1556 Method calls can be made without `:eval` provided the evaluated expression is
   1557 unequivocally an expression.  Each `->` must be followed by a function name,
   1558 and without a line break, otherwise |E260| is given.  Likewise, the "(" of a
   1559 function call cannot have a line break before it, otherwise |E107| is given.
   1560 Consider the following script-local methods where in legacy script `:eval`
   1561 would be mandatory.  In Vim9 script, it is unnecessary:
   1562 >vim9
   1563 	vim9script
   1564 	def Pop(arg: any): void
   1565 	  arg->popup_notification({time: 7000})
   1566 	enddef
   1567 	b:list = []
   1568 	b:list->add('1')->add('2')->Pop()	# 1 and 2 (on separate lines)
   1569 	{a: 1, b: 2}->string()->Pop()		# {'a': 1, 'b': 2}
   1570 	(8, 9)->typename()->Pop()		# tuple<number, number>
   1571 	'single quoted ''string'''->Pop()	# single quoted 'string'
   1572 	"double quoted \"string\""->Pop()	# double quoted "string"
   1573 	(85 >> 1 == 42)->string()->Pop()	# true
   1574 	# The following gives E260: Missing name after ->
   1575 	b:list->add('3')->
   1576 	Pop()
   1577 <
   1578 In the rare case there is ambiguity between a function name and an Ex command,
   1579 prepend ":" to ensure the Ex command is executed.  For example, there is the
   1580 `:substitute` command and `substitute()` function, the `:glob` shortened
   1581 command and `glob()` function, and so on.  Consequently, when the ":" is not
   1582 present the "(" is inferred by Vim to be the left parenthesis before a
   1583 function's arguments, not a |pattern-delimiter|.  So, prepending a colon will
   1584 ensure the command is executed with "(" as the delimiter.  For example:
   1585 >vim9
   1586 	vim9script
   1587 	# Synonymous with ":glob/delimiter)" (and prints these lines)
   1588 	:glob(delimiter)
   1589 	# Literally calls the "glob()" function (and gives E121/E116)
   1590 	glob(delimiter)
   1591 <
   1592 If an expression starts with "!" it is interpreted as a shell command, not
   1593 negation of a condition.  So, this is interpreted as a shell command:
   1594 >vim9
   1595 	vim9cmd !(900 == v:version)
   1596 <
   1597 Put the expression in parentheses to use the "!" for negation:
   1598 >vim9
   1599 	vim9cmd (!(900 == v:version))->string()->popup_notification({})
   1600 <
   1601 Note that while variables need to be defined before they can be used,
   1602 functions may be called before being defined - |vim9-function-defined-later|.
   1603 This is required to allow for cyclic dependencies between functions.  It is
   1604 slightly less efficient, since the function has to be looked up by name.
   1605 Also, a typographical error in the function name will only be found when the
   1606 function is called.
   1607 
   1608 
   1609 Omitting function() ~
   1610 
   1611 A user defined function can be used as a function reference in an expression
   1612 without `function()`, though the function must already be defined.  Argument
   1613 types and the return type will then be checked.  An example, demonstrating
   1614 that `function()` is optional:
   1615 >vim9
   1616 	vim9script
   1617 	def IsASCII(c: string): string
   1618 	  return $"{c} is{char2nr(c) > 127 ? ' not' : ''} an ASCII character"
   1619 	enddef
   1620 	const ASCII: func(string): string = IsASCII
   1621 	const F_ASCII: func(string): string = function(IsASCII)
   1622 	popup_notification(['K'->ASCII(), '§'->F_ASCII()], {time: 7000})
   1623 <
   1624 In the script-local scope, as above, both direct assignment and using
   1625 `function()` require a function to be defined already when used in a function
   1626 reference.
   1627 
   1628 Inside a `:def` function, both direct assignment and `function()` are allowed
   1629 as forward references because they are evaluated at runtime.  For example:
   1630 >vim9
   1631 	vim9script
   1632 	# IsASCII forward reference
   1633 	def ASCII(arg: string): string
   1634 	  var Forward_IsASCII: func(string): string = IsASCII
   1635 	  return Forward_IsASCII(arg)
   1636 	enddef
   1637 	# function(IsASCII) forward reference
   1638 	def Func_ASCII(arg: string): string
   1639 	  var Forward_funcIsASCII: func(string): string = function(IsASCII)
   1640 	  return Forward_funcIsASCII(arg)
   1641 	enddef
   1642 	# The forward-referenced function from the two functions above
   1643 	def IsASCII(c: string): string
   1644 	   return $"{c} is{char2nr(c) > 127 ? ' not' : ''} an ASCII character"
   1645 	enddef
   1646 	popup_notification(['K'->ASCII(), '§'->Func_ASCII()], {time: 7000})
   1647 <
   1648 
   1649 Lambda using => instead of -> ~
   1650 							*vim9-lambda*
   1651 In legacy Vim script there can be confusion between using "->" for method
   1652 calling/chaining and for a |lambda|.  Also, when a "{" is found the parser
   1653 needs to figure out whether it is the start of a lambda or a dictionary, which
   1654 is more complicated in Vim9 script because of the use of argument types.
   1655 
   1656 To avoid these problems, Vim9 script uses a different syntax for a lambda,
   1657 similar to JavaScript, which in its simplest form is:
   1658 >
   1659 	(args) => expr1
   1660 <
   1661 This syntax produces a func type (|vim9-func-type|) with args of "any" type,
   1662 and return type "any".  Examples:
   1663 >vim9
   1664 	vim9script
   1665 	# Vim9 lambda as expr2 of filter()
   1666 	echo [8, -2, 9]->filter((_, val) => val > 0)	# [8, 9]
   1667 	# Vim9 lambda as a func type
   1668 	var Increment = (n) => n + 1
   1669 	echo Increment(8)		# 9
   1670 	echo Increment->typename()	# func(any): any
   1671 <
   1672 A Vim9 script lambda can have its arguments and/or its return value strictly
   1673 typed.  For example, using the filtering example, these all echo [8, 9]:
   1674 >vim9
   1675 	vim9script
   1676 	echo [8, -2, 9]->filter((_, val: number) => val > 0)
   1677 	echo [8, -2, 9]->filter((_, val): bool => val > 0)
   1678 	echo [8, -2, 9]->filter((_, val: number): bool => val > 0)
   1679 <
   1680 When used as a func type in a |Funcref| variable, fourteen valid forms are
   1681 possible.  They are demonstrated in this example:
   1682 >vim9
   1683 	vim9script
   1684 	const I01 = (n) => n + 1
   1685 	const I02 = (n): number => n + 1
   1686 	const I03 = (n: number) => n + 1
   1687 	const I04 = (n: number): number => n + 1
   1688 	const I05: func = (n) => n + 1
   1689 	const I06: func = (n: number) => n + 1
   1690 	const I07: func = (n): number => n + 1
   1691 	const I08: func = (n: number): number => n + 1
   1692 	const I09: func: number = (n: number) => n + 1
   1693 	const I10: func: number = (n): number => n + 1
   1694 	const I11: func: number = (n: number): number => n + 1
   1695 	const I12: func(number): number = (n): number => n + 1
   1696 	const I13: func(number): number = (n: number) => n + 1
   1697 	const I14: func(number): number = (n: number): number => n + 1
   1698 	echo 0->I01()->I02()->I03()->I04()->I05()->I06()->I07()->I08()
   1699 	  ->I09()->I10()->I11()->I12()->I13()->I14()	# 14
   1700 <
   1701 	Notes:
   1702 	1. Return types use the most specific type from either the variable's
   1703 	declaration or the lambda's return type (i.e., if ": {type}" appears
   1704 	in either, that will be the lambda's return type).  Further, the
   1705 	variable's declaration cannot mismatch - it must be either the
   1706 	lambda's explicit or inferred return type, be "any", or be omitted.
   1707 	If the lambda's return type is not declared, it may be inferred from
   1708 	the lambda's expression (e.g., I03 inferred as "number").
   1709 	2. Arguments' types are determined from the lambda's parameter
   1710 	declaration (not from the variable's type declaration, if specified).
   1711 	So, the `typename()` of I02, I07, I10, and I12 is "func(any): number".
   1712 	Those forms should be avoided because, although they appear to accept
   1713 	"any" type arguments they don't (and consequently type mismatches can
   1714 	easily occur).
   1715 	3. The following are examples of invalid lambdas giving |E1012|.
   1716 	They are invalid because either (a and b) the variable declaration is
   1717 	for a number return type, but the lambda's return type is "any", or
   1718 	(c) because the form "func({type}) =" is always invalid.
   1719 >vim9
   1720 	vim9cmd var a: func: number = (n) => n + 1
   1721 	# E1012: ...; expected func(...): number but got func(any): any
   1722 
   1723 	vim9cmd var b: func(number): number = (n) => n + 1
   1724 	# E1012: ...; expected func(number): number but got func(any): any
   1725 
   1726 	vim9cmd var c: func(number) = (n) => n + 1
   1727 	# E1012: ...; expected func(number) but got func(any): any
   1728 <
   1729 The "Increment" lambda, shown in the first example, with `func` declared and
   1730 the lambda's argument type and return type specified (like I08 in the
   1731 example above), is:
   1732 >vim9
   1733 	vim9script
   1734 	var Increment: func = (n: number): number => n + 1
   1735 	echo Increment(0)		# 1
   1736 	echo Increment->typename()	# func(number): number
   1737 <
   1738 Note: Specifying the func type explicitly may appear redundant, though it does
   1739 make it clearer up front that the variable is a func and, for reasons outlined
   1740 above, specifying a lambda's return type and arguments' types is prudent.  It
   1741 is also more performant at runtime because "any" type checking is not required
   1742 (which can be verified using |:disassemble|).  Many of the examples in this
   1743 help file use that form.
   1744 
   1745 							*E1157*
   1746 Although specifying a lambda's return type is not mandatory, including the
   1747 colon means the return type must be specified:
   1748 >vim9
   1749 	vim9script
   1750 	var Minimal = (n) => n / 2
   1751 	var Missing = (n): => n / 2  # E1157: Missing return type
   1752 <
   1753 No line break is allowed in the arguments of a lambda up to and including the
   1754 "=>" (so that Vim can tell the difference between an expression in parentheses
   1755 and lambda arguments).  This is okay:
   1756 >vim9
   1757 	vim9script
   1758 	var list: list<number> = [1, -2, 2, -3, -1, 3]
   1759 	filter(list, (_, val): bool =>
   1760 	  val > 0)
   1761 	echowindow list
   1762 <
   1763 This would not work (|E121| and |E116|): >
   1764 	filter(list, (ind, val): bool
   1765 			=> val > 0)
   1766 And this would not work (|E121| and |E116|): >
   1767 	filter(list, (ind,
   1768 			val): bool => val > 0)
   1769 Nor would this (|E1157|): >
   1770 	filter(list, (ind, val):
   1771 		bool => val > 0)
   1772 
   1773 However, you can use a backslash to concatenate the lines before parsing.
   1774 This script also shows the lambda's "val" parameter typed:
   1775 >vim9
   1776 	vim9script
   1777 	var list: list<number> = [1, -2, 2, -3, -1, 3]
   1778 	filter(list,
   1779 	      \ (_,
   1780 	      \ val: number):
   1781 	      \ bool
   1782 	      \ => val > 0)
   1783 	echowindow list
   1784 <							*E1172*
   1785 Default values are not allowed in a lambda:
   1786 >vim9
   1787 	vim9script
   1788 	var F_1172 = (n = 1) => n + 1	# E1172: Cannot use default values in…
   1789 <
   1790 							*vim9-lambda-arguments*
   1791 In legacy Vim script, a lambda could be called with any number of extra
   1792 arguments and there was no way to warn for not using them.  In Vim9 script the
   1793 number of arguments must match.  If you want to accept either any arguments or
   1794 any additional arguments, use "..._", which enables |vim9-variable-arguments|.
   1795 For example:
   1796 >vim9
   1797 	vim9script
   1798 	b:fruits = ['apple', 'apricot', 'avocado']
   1799 	def Complete(..._): list<string>
   1800 	  const K: string = getcmdline()[: getcmdpos() - 2]->matchstr('\S*$')
   1801 	  return b:fruits->filter((_, val) => val =~ K)
   1802 	enddef
   1803 	var fruit = input('> ', '', $"customlist,{Complete->string()}")
   1804 	# (e.g., entering p<Tab> will present apple and apricot)
   1805 	echowindow $"Your choice was {fruit}"
   1806 <
   1807 	Note: Without "..._", the function will fail.  The {completion}
   1808 	argument of |input()| has three list items (ArgLead, CmdLine, and
   1809 	CursorPos).  None are required to build the output list, so it is
   1810 	preferable to use "..._", though it works with "...l: list<any>" too).
   1811 	See |:command-completion-custom|.
   1812 
   1813 							*inline-function*
   1814 A |lambda| can contain statements in a {} block.  The following example
   1815 reports on three "local to buffer" options:
   1816 >vim9
   1817 	vim9script
   1818 	var Get_bv: func = (...args: list<string>): dict<any> => {
   1819 	  var opts: dict<any>
   1820 	  for arg in args
   1821 	    opts[arg] = getbufvar(bufname(), $'&{arg}')
   1822 	  endfor
   1823 	  return opts
   1824 	}
   1825 	echowindow Get_bv('modifiable', 'tabstop', 'textwidth')
   1826 <
   1827 This is also useful for a |Channel|, |Job|, or |timer|.  This is a timer example:
   1828 >vim9
   1829 	vim9script
   1830 	echowindow "Handler calling..."
   1831 	var count: number
   1832 	var timer: number = timer_start(700, (_): void => {
   1833 	    count += 1
   1834 	    echowindow $'Handler called {count}'
   1835 	  }, {repeat: 3})
   1836 <
   1837 	Note: In this example, |timer_start()| requires {callback}, the
   1838 	function to call, as its second parameter.  When the timer triggers,
   1839 	Vim calls the callback function, passing the timer ID to it as a
   1840 	mandatory argument.  The "(_)" syntax in the lambda enables passing
   1841 	that ID without needing explicitly either to name it or to reference
   1842 	it - see |vim9-ignored-argument|.
   1843 
   1844 The ending "}" of the block must be at the start of a line, excluding
   1845 leading space or tab characters.  It can be followed by other characters too.
   1846 No command can follow the "{", though a comment can be used there.
   1847 These points are shown in this example:
   1848 >vim9
   1849 	vim9script
   1850 	var numbers: list<number> = [1, 2, 3, 4, 5]
   1851 	var Square: func = (ln: list<number>): list<number> => ln
   1852 	  ->mapnew((_, val) => {  # Comment is okay after the { of the block
   1853 	    return val * val
   1854 	  })  # The } of the block starting a new line (excl. white space)
   1855 	echowindow Square(numbers)
   1856 <							*E1171*
   1857 Omitting the closing "}" of an inline-function's code block gives E1171:
   1858 >vim9
   1859 	vim9script
   1860 	var F_1171 = (): bool => {
   1861 	  return false  # E1171: missing } after inline function
   1862 <
   1863 							*command-block*
   1864 A block can also be used for defining a user command.  Inside the block, Vim9
   1865 script syntax applies.  This example uses a heredoc (see |:let-heredoc|):
   1866 >vim9
   1867 	vim9script
   1868 	command MyHeredoc {
   1869 	  var someVar: list<string> =<< trim eval END
   1870 	    Life, the universe, and everything
   1871 	    {6 * 7}
   1872 	  END
   1873 	  echowindow someVar
   1874 	}
   1875 	MyHeredoc
   1876 <
   1877 	Note: "eval" is required after the "=<<" so that "{6 * 7}" is
   1878 	evaluated and not treated as a |literal-string|.  This is different to
   1879 	|vim9-omitting-:eval|, even though the command block is Vim9 script.
   1880 
   1881 If the statements include a dictionary, the dictionary's closing bracket must
   1882 not be written at the start of a line, otherwise it will be parsed as the end
   1883 of the block.  So, this does not work (the last line gives |E1128|), because
   1884 the penultimate "}" is recognized as the end of the block:
   1885 >vim9
   1886 	command FailingNewCommand {
   1887 	  g:mydict = {
   1888 	    'k1': 'v1',
   1889 	    'k2': 'v2'
   1890 	    }
   1891 	  }
   1892 <
   1893 To avoid this, place the dictionary's "}" after the last item:
   1894 >vim9
   1895 	vim9script
   1896 	command WorkingNewCommand {
   1897 	  g:mydict = {
   1898 	    'k1': 'v1',
   1899 	    'k2': 'v2' }
   1900 	  g:mydict->keys()->popup_notification({time: 4000})
   1901 	  }
   1902 	WorkingNewCommand
   1903 <
   1904 Rationale: The "}" cannot be after a command because it would require parsing
   1905 the commands to find it.  For consistency with that, no command can follow the
   1906 "{".  Consequently, this means using "() => {  command  }" does not work and,
   1907 similarly, a line break (with optional leading spaces/tabs) is always required
   1908 before the "}" ending the command block too.
   1909 							*E1026*
   1910 Omitting the closing "}" of a code block gives E1026 ("Missing }"):
   1911 >vim9
   1912 	vim9script
   1913 	command C1026 {
   1914 <
   1915 							*vim9-curly*
   1916 To avoid the "{" of a dictionary being recognized as a statement block, wrap
   1917 the dictionary in parentheses:
   1918 >vim9
   1919 	vim9script
   1920 	var AgeDict: func = (arg: number): dict<number> => ({'age': arg})
   1921 	echo 42->AgeDict()
   1922 <
   1923 Similarly, wrap a dictionary in parentheses to avoid confusion with the start
   1924 of a command block.  For example, if a dictionary's opening curly bracket is
   1925 followed by a newline, wrap the dictionary in parentheses to avoid it being
   1926 interpreted as a command block:
   1927 >vim9
   1928 	vim9script
   1929 	command -nargs=+ PopDict {
   1930 	  var [key, val] = split(<q-args>)
   1931 	  ({
   1932 	    [key]: val})
   1933 	    ->string()->popup_notification({time: 5000})
   1934 	}
   1935 	PopDict one tahi
   1936 <
   1937 	Note: The dictionary's "}" cannot be on a separate line, even when
   1938 	within parentheses.  Also, the dictionary's key must be in square
   1939 	brackets to be evaluated as an expression - see |vim9-literal-dict|.
   1940 
   1941 
   1942 Automatic line continuation ~
   1943 							*vim9-line-continuation*
   1944 In many cases it is obvious that an expression continues on the next line.
   1945 In such cases, there is no need in Vim9 script to prefix the line with a
   1946 backslash, which is required in legacy Vim script (see |line-continuation|)
   1947 when a list, dictionary, tuple, or function call spans multiple lines.  The
   1948 following example illustrates all four:
   1949 >vim9
   1950 	vim9script
   1951 	var mylist: list<number> = [
   1952 	  1,
   1953 	  2,
   1954 	]
   1955 	var mydict: dict<number> = {
   1956 	  1: 1,
   1957 	  2: 2,
   1958 	}
   1959 	var mytuple: tuple<number, number> = (
   1960 	  1,
   1961 	  2,
   1962 	)
   1963 	var MyDef: func = (...l: list<any>): list<any> => l
   1964 	echo MyDef(mylist,
   1965 	  mydict,
   1966 	  mytuple)  # [[1, 2], {'1': 1, '2': 2}, (1, 2)]
   1967 <
   1968 For binary and ternary operators in expressions not within in a list,
   1969 dictionary, or tuple, a line break is possible either before or after the
   1970 operator.  For example:
   1971 >vim9
   1972 	vim9script
   1973 	var text: string = 'V'
   1974 	  .. 'i'
   1975 	  .. 'm'
   1976 	var version: number = 9 *
   1977 	  100
   1978 	  + 2
   1979 	var latest: string = v:version == 902
   1980 	  ? 'current' :
   1981 	  'out-of-date'
   1982 	echo (text, version, latest)  # ('Vim', 902, 'current')
   1983 <
   1984 For a method call using "->", a line break is allowed before it.  Likewise,
   1985 for a member using a dot.  Both are illustrated in this interactive example,
   1986 which prompts for a min:sec pace and returns the total seconds and minutes and
   1987 seconds for a 5km run/walk:
   1988 >vim9
   1989 	vim9script
   1990 	def Run5(ms: string): dict<any>
   1991 	  const M: number = ms
   1992 	    ->split('[:.]')[0]
   1993 	    ->str2nr()
   1994 	  const S: number = ms
   1995 	    ->split('[:.]')[1]
   1996 	    ->str2nr()
   1997 	  var secs: number = (M * 5 * 60) + S * 5
   1998 	  var m_s: string = (secs / 60) .. ':' .. printf('%02d', (secs % 60))
   1999 	  return {seconds: secs, minutes_seconds: m_s}
   2000 	enddef
   2001 	var result: dict<any> = input('Pace of min:sec / km: ')
   2002 	  ->Run5()
   2003 	echo ' is a 5km completed in (seconds, mins:secs):'
   2004 	echo (result
   2005 	  .seconds,
   2006 	  result
   2007 	  .minutes_seconds)
   2008 <
   2009 For commands that have an argument that is a list of commands, a | character
   2010 (see |:bar|) at the start of the line indicates line continuation:
   2011 >vim9
   2012 	vim9script
   2013 	command! ShowFileLine if !empty(bufname())
   2014 	  | echo $'File: {bufname()}'
   2015 	  | echo $'Line: {line(".")}'
   2016 	  | endif
   2017 	ShowFileLine
   2018 <
   2019 	Note: Consequently, a heredoc's first line usually cannot start with
   2020 	a bar:
   2021 >vim9
   2022 	vim9script
   2023 	# E488: Trailing characters:  | this doesn't work
   2024 	var lines =<< trim END
   2025 	  | this doesn't work
   2026 	END
   2027 <
   2028 	Either use an empty line at the start or do not use heredoc.
   2029 	Alternatively, ensure the "C" flag is temporarily in 'cpoptions':
   2030 >vim9
   2031 	vim9script
   2032 	const CPO: string = &cpoptions
   2033 	execute CPO->match('C') == -1 ? 'set cpoptions+=C' : ''
   2034 	var lines =<< trim END
   2035 	  | this works
   2036 	END
   2037 	echo lines[0]
   2038 	&cpoptions = $'{CPO}'
   2039 <
   2040 	If the heredoc is inside a function 'cpoptions' must be set before
   2041 	`:def` and restored after the `:enddef`.
   2042 
   2043 							*E1097*
   2044 A continued, incomplete line will give E1097:
   2045 >vim9
   2046 	vim9script
   2047 	def F1097(): void
   2048 	  var x =
   2049 	enddef
   2050 	defcompile	# E1097: Line incomplete
   2051 <
   2052 In places where line continuation with a backslash is still needed, such as
   2053 splitting up a long Ex command, comments can start with '#\ ' (like '"\ ' in
   2054 legacy Vim script):
   2055 >vim9
   2056 	vim9script
   2057 	syntax region IncSearch
   2058 	      \ oneline
   2059 	     #\ Sourcing this script applies the IncSearch highlight group
   2060 	     #\ to the text "Ex command" in this buffer.
   2061 	      \ start='Ex '
   2062 	      \ end='command'
   2063 <
   2064 This is also needed when line continuation is used without a backslash and a
   2065 line starts with a bar.  For example:
   2066 >vim9
   2067 	vim9script
   2068 	command! BufferWords echo $'Buffer name: {bufname()}'
   2069 	      #\ Word count of the buffer
   2070 	      | echo $'Word count: {wordcount().words}'
   2071 	BufferWords
   2072 <							*E1050*
   2073 To make it possible for an operator at the start of a line to be recognized, a
   2074 colon must come before a range.  This example will add "start" and "print"
   2075 (Note this involves shadowing the `:print` command):
   2076 >vim9
   2077 	vim9script
   2078 	var print: number = 1
   2079 	# The following two lines are the same as declaring on one line
   2080 	# var start: number = 1 + print
   2081 	var start: number = 1
   2082 	+ print
   2083 	echo start
   2084 <
   2085 Whereas, this will assign "start" and print the second line of the script:
   2086 >vim9
   2087 	vim9script
   2088 	var start: number = 1
   2089 	:+ print
   2090 <
   2091 And omitting a colon in this script gives E1050 because, unlike the initial
   2092 example, "print" is not a variable:
   2093 >vim9
   2094 	vim9script
   2095 	var start: number
   2096 	+ print
   2097 	# E1050: Colon required before a range: + print
   2098 <
   2099 After the range, an Ex command must follow.  Without the colon you can call a
   2100 function without `:call`, but after a range you do need it:
   2101 >vim9
   2102 	vim9script
   2103 	const PRINT_W_DIVIDERS: func = (): void => {
   2104 	  echohl Statement
   2105 	  :print
   2106 	  echo "_"->repeat(70)
   2107 	  echohl None
   2108 	}
   2109 	# With no range, call the function without `call`; when sourced, this
   2110 	# will print only the line with 'vim9script' preceded by a divider
   2111 	PRINT_W_DIVIDERS()
   2112 	# With the range, :call is required; when sourced, this prints lines
   2113 	# from 'const...' to the closing '}', separated by dividers
   2114 	:+,+6call PRINT_W_DIVIDERS()
   2115 <
   2116 However, the colon is not required for the |+cmd| argument.  For example:
   2117 >vim9
   2118 	vim9script
   2119 	# Opens a new split of this help buffer and applies IncSearch
   2120 	# highlight group to instances of 'MATCHME'.
   2121 	split +/MATCHME
   2122 	match IncSearch _MATCHME_
   2123 <
   2124 It is also possible to split a function's arguments over multiple lines.
   2125 For example:
   2126 >vim9
   2127 	vim9script
   2128 	def SubBlankHyphen(
   2129 	    text: string,
   2130 	    separator: string = ' '
   2131 	): string
   2132 	  return text->substitute('[[:blank:]]', separator, 'g')
   2133 	enddef
   2134 	echo 'A multiple lines	of arguments	example'->SubBlankHyphen()
   2135 <
   2136 Since a continuation line cannot be easily recognized, parsing of commands is
   2137 stricter.  In legacy Vim script, an error could result in unintended
   2138 interpretation of continuation lines.  For example, consider the following,
   2139 working script:
   2140 >vim9
   2141 	vim9script
   2142 	def Msg(..._): void
   2143 	  popup_notification("Job finished successfully!", {time: 1500})
   2144 	enddef
   2145 	var myjob = job_start([&shell, &shellcmdflag, 'date'], {
   2146 	  exit_cb: Msg})
   2147 <
   2148 However, if there is an error in the command, like in the script below, Vim9
   2149 script will give errors.
   2150 >vim9
   2151 	vim9script
   2152 	var myjob = job_start([&shell, INVALID_LIST_ITEM_HERE, 'date'], {
   2153 	  exit_cb: Msg})
   2154 	# Gives E121, E116 and the script stops executing
   2155 <
   2156 The equivalent legacy Vim script, below, fails on the `:let` command.  However,
   2157 then it continues and interprets "exit" as the `:exit` command with argument
   2158 "_cb: Msg})", causing Vim to save changes to a file literally with that name
   2159 and exits: >
   2160 >
   2161 	" *** DO NOT SOURCE this legacy Vim script ***
   2162 	" If sourced, this will write the file '_cb: Msg})' and exit!
   2163 	"
   2164 	let myjob = job_start([&shell, INVALID_ITEM_HERE, 'date'], {
   2165 	  exit_cb: Msg})
   2166 <
   2167 							*E1144*
   2168 To prevent unintended consequences, like the one above, Vim9 script
   2169 requires white space between most command names and their arguments.
   2170 (Note: Delimited commands, like `:global` and `:substitute`, are exceptions.)
   2171 For example:
   2172 >vim9
   2173 	vim9script
   2174 	exit_abc
   2175 	# E1144: Command "exit" is not followed by white space: exit_abc
   2176 <
   2177 However, the argument of a command that is a command itself won't be
   2178 recognized consistently.  For example, after "windo echo {expr}" a line break
   2179 inside the expression will only apply to the current window, not to subsequent
   2180 windows:
   2181 >vim9
   2182 	vim9script
   2183 	windo echo 'hi'
   2184 	  ->toupper()		# 'HI' (current window) and 'hi' (for others)
   2185 <
   2186 So, in instances like this, the "\" continuation character must still be used:
   2187 >vim9
   2188 	vim9script
   2189 	windo echo 'hi'
   2190 	      \ ->toupper()	# 'HI' (for every window)
   2191 <
   2192 	Note: This could have serious consequences if, for example, the
   2193 	command was "windo execute ':global/something/'" and the continuation
   2194 	line was ".. d".  The lines with "something" would be deleted only in
   2195 	the current window and the other windows would have only `:print`
   2196 	(i.e., default ":p") performed on their "something" lines.
   2197 
   2198 Other line continuation considerations:
   2199 
   2200 - `:enddef` cannot be used at the start of a continuation line.  It ends the
   2201   current `:def` function.  See |E1057|.
   2202 
   2203 - No line break is allowed in the LHS of an assignment.  Specifically, when
   2204   unpacking a list (|:let-unpack|), this is okay:
   2205 >vim9
   2206 	vim9script
   2207 	const UNPACK: func = (a: string, b: string): list<string> => [a, b]
   2208 	var [v1, v2] =
   2209 	  UNPACK('all', 'good')
   2210 	echo $'{v1} {v2}'
   2211 <
   2212   whereas this would not work - it would give |E475|: >
   2213 
   2214 	var [v1,
   2215 	  v2] = UNPACK('all', 'good')
   2216 <
   2217 - No line break is allowed in between arguments of an `:echo`, `:execute` and
   2218   similar commands.  This is okay:
   2219 >vim9
   2220 	vim9script
   2221 	echo [1,
   2222 	  2] [3,
   2223 	  4]
   2224 <
   2225   whereas this does not work (i.e., "[3, 4]" is not echoed):
   2226 >vim9
   2227 	vim9script
   2228 	echo [1, 2]
   2229 	  [3, 4]
   2230 <
   2231 - In some cases it is difficult for Vim to parse a command, especially when
   2232   commands are used as an argument to another command, such as `:windo`,
   2233   `:command` or `:autocmd`.  In those cases the line continuation with a
   2234   backslash must be used.  For example:
   2235 >
   2236 	command! Foo call Bar('x', {
   2237 	      \ 'key': 'value',
   2238 	      \ })
   2239 	autocmd BufWritePre * call Bar('x', {
   2240 	      \ 'key': 'value',
   2241 	      \ })
   2242 <
   2243   See also the "windo echo" example and note, above.
   2244 
   2245 
   2246 White space ~
   2247 							*vim9-white-space*
   2248 Vim9 script enforces proper use of white space.  There must be white space
   2249 before and after the "=" of variable assignment, for example:
   2250 >vim9
   2251 	vim9script
   2252 	var num = 234
   2253 <
   2254 White space is required:
   2255 							*E1004*
   2256 - Before and after the "=" in variable declaration:
   2257 >vim9
   2258 	vim9script
   2259 	var num=234	# E1004: White space required before and after '=' at…
   2260 	# Similarly, these would also give E1004:
   2261 	var num= 234
   2262 	var num =234
   2263 <
   2264 - Around most operators.  So, the first example here works whereas the second
   2265   gives E1004:
   2266 >vim9
   2267 	vim9cmd echo 'Yes' .. '!'	# Yes!
   2268 	vim9cmd echo 'F'..'ail'		# E1004: White space required before …
   2269 <
   2270 - In a sublist (list slice) around the ":", except at the start and end:
   2271 >vim9
   2272 	vim9script
   2273 	var mylist: list<number> = [7, 8, 9]
   2274 	echo mylist[:]     # [7, 8, 9]
   2275 	echo mylist[1 : 2] # [8, 9]
   2276 	echo mylist[: 1]   # [7, 8]
   2277 	echo mylist[2 :]   # [9]
   2278 	echo mylist[1:2]   # E1004: White space required before and after ":"…
   2279 <
   2280 							*E1069*
   2281 - After a variable name and its ":" (preceding a type declaration):
   2282 >vim9
   2283 	vim9script
   2284 	var okay_list: list<any> = ['Is', 'good']
   2285 	var fail_list:list<any> = ['Is', 'a', 'fail']	# E1069: White space …
   2286 <
   2287 - Before the '#' starting a comment.  If it isn't present, errors such as
   2288   |E121| or |E488| are given:
   2289 >vim9
   2290 	vim9cmd echo 'No'# E121: Undefined variable: #
   2291 	vim9cmd var f: number = 99# E488: Trailing characters: …
   2292 <
   2293 White space is not allowed:
   2294 							*E1068*
   2295 - Before the comma separating dictionary key-value pairs or list items (though
   2296   it is allowed with tuples).  Examples:
   2297 >vim9
   2298 	vim9cmd echo (1 , 2)        # (1, 2)  [Note: Vim normalizes the tuple]
   2299 	vim9cmd echo {1: 1 , 2: 2}  # E1068: No white space allowed before ','
   2300 	vim9cmd echo [1 , 2]        # E1068: No white space allowed before ','
   2301 <
   2302 - Before the comma separating function arguments:
   2303 >vim9
   2304 	vim9script
   2305 	def F1068(arg: string , arg2: bool): void
   2306 	  # E1068: No white space allowed before ',': , arg2: bool): void
   2307 	enddef
   2308 <
   2309 - Before either the "<" or "(" in the declaration of a generic function:
   2310 >vim9
   2311 	vim9script
   2312 	def F1068<T> (): T  # E1068: No white space allowed before '(': (): T
   2313 	enddef
   2314 	F1068()
   2315 <							*E1074*
   2316 - After the '.' of an imported item.  In this example, a temporary Vim9 script
   2317   is written, then imported.  The script's exported "okay" variable is echoed
   2318   successfully, but the space after the '.' of the second "Imp" item gives
   2319   E1074:
   2320 >vim9
   2321 	vim9script
   2322 	var tmp: string = $'{tempname()}.vim'->substitute('\\', '/', 'g')
   2323 	var temp_lines: list<string> = ['vim9script',
   2324 	  'export var okay: bool = true', 'export var err: bool']
   2325 	temp_lines->writefile(tmp)
   2326 	import tmp as Imp
   2327 	echo Imp.okay	# true
   2328 	echo Imp. err	# E1074: No white space allowed after dot
   2329 <
   2330 - Between a function name and the "(", though it is allowed before any
   2331   argument and after the last argument:
   2332 >vim9
   2333 	vim9script
   2334 	def MyN(...arg: list<number>): void
   2335 	  echo arg
   2336 	enddef
   2337 	MyN(1)			# [1]
   2338 	MyN(  2)		# [2]
   2339 	MyN(3  )		# [3]
   2340 	MyN(   4,    5,    6 )	# [4, 5, 6]
   2341 	MyN  (7, 8, 9)		# E492: Not an editor command
   2342 <
   2343 	Note: The following are also not allowed, and give |E492|: >
   2344 	MyN
   2345 	  \ (7, 8, 9)
   2346 	MyN
   2347 	  (7, 8, 9)
   2348 <							*E1202*
   2349 - After the '.' when accessing object properties, methods, or enum members.
   2350   An enum method example:
   2351 >vim9
   2352 	vim9script
   2353 	enum Metal
   2354 	  Au((79, 'Gold')),
   2355 	  Hg((80, 'Mercury'))
   2356 	  var data: tuple<number, string>
   2357 	  def Get_name(): string
   2358 	    return this.data[1]
   2359 	  enddef
   2360 	endenum
   2361 	echo Metal.Au.Get_name()   # Gold
   2362 	echo Metal.Hg. Get_name()  # E1202: No white space allowed after '.':…
   2363 <
   2364 							*E1205*
   2365 - In a `:set` command between the option name and a following "&", "!",
   2366   "<", "=", "+=", "-=" or "^=".  For example:
   2367 >vim9
   2368 	vim9script
   2369 	# This is okay
   2370 	set tabstop=8
   2371 	echo &tabstop
   2372 	# This is E1205: No white space allowed between option and: =8
   2373 	set tabstop =8
   2374 <
   2375 - In a :set command between the option name and a following ':', which gives
   2376   |E518|.  For example:
   2377 >vim9
   2378 	vim9script
   2379 	# This is okay
   2380 	set tabstop:8
   2381 	echo &tabstop
   2382 	# This is E518: Unknown option :8
   2383 	set tabstop :8
   2384 <
   2385 
   2386 No curly braces expansion ~
   2387 					*vim9-no-curly-braces-expansion*
   2388 Dynamic variable name construction using curly braces (|curly-braces-names|)
   2389 does not work in Vim9 script scopes.  This example shows two curly braces
   2390 names expanding and working to form script level variable names in a legacy
   2391 Vim script `:function` but failing in a `:def` function:
   2392 >vim9
   2393 	vim9script
   2394 	var [O, O3] = ['oxygen', 'ozone']
   2395 	function Al(arg, n = null_string) abort
   2396 	  return s:{a:arg}{a:n}
   2397 	endfunction
   2398 	def Al9(arg: string, n: any = null_string): string
   2399 	  return {arg}{n}
   2400 	enddef
   2401 	echo Al('O', 3)   # ozone
   2402 	echo Al9('O', 3)  # E720: Missing colon in Dictionary: }{n}
   2403 <
   2404 Similarly, |curly-braces-function-names| are only possible in legacy Vim
   2405 script scopes:
   2406 >vim9
   2407 	vim9script
   2408 	var low_line: string = '_'
   2409 	function F_curly()
   2410 	  echo 'A curly-braces-function-name: okay in legacy Vim script scope'
   2411 	endfunction
   2412 	legacy call s:F{s:low_line}curly()
   2413 	F{low_line}curly()	# E1144: Command "F" is not followed by white…
   2414 <
   2415 
   2416 Command modifiers may not always be ignored and give an error ~
   2417 
   2418 In some scenarios, using a command modifier for a command that does not use it
   2419 may give an error.  However, some modifiers do not give an error (just like
   2420 how they do not error in legacy Vim script).  For example, in this script the
   2421 meaningless |:vertical|, |:keepmarks|, and |:hide| modifiers are ignored:
   2422 >vim9
   2423 	vim9script
   2424 	vertical if 1 == 1
   2425 	  keepmarks echo 'Starting...'
   2426 	  try
   2427 	    echo ERROR
   2428 	  catch
   2429 	    hide echo 'Caught!'
   2430 	  endtry
   2431 	endif
   2432 <							*E1176*
   2433 However, if a modifier is applied to certain control flow commands, E1176
   2434 is given.  An example is prepending |:silent| to |:endif|:
   2435 >vim9
   2436 	vim9script
   2437 	if 1
   2438 	  echo "Hi!"
   2439 	silent endif
   2440 	# E1176: Misplaced command modifier
   2441 <
   2442 	Note: When lines 2 to 4 only of this script are sourced, you can see
   2443 	it does not give E1176 (because then the script is executed in a
   2444 	legacy Vim script context).
   2445 
   2446 Similarly, adding modifiers to any of |:try|, |:endtry|, |:for|, |:endfor|,
   2447 |:while|, |:endwhile|, |:catch|, or |:finally| may result in an E1176 error,
   2448 though it depends on the redundant modifier used.  For example, adding the
   2449 |:silent| modifier to |:for| is ignored whereas adding |:keepmarks| to
   2450 |:endfor| is an error.  (Note the behavior of `:silent` is intentional.  It works
   2451 like that so that error messages are suppressed when Vim does not support
   2452 the |+eval| feature.)
   2453 							*E1082*
   2454 Also, using a command modifier without a following command gives E1082:
   2455 >vim9
   2456 	vim9script
   2457 	silent
   2458 	# E1082: Command modifier without command
   2459 <
   2460 
   2461 Dictionary literals ~
   2462 							*vim9-literal-dict*
   2463 
   2464 Traditionally Vim has supported dictionary literals with a {} syntax: >
   2465 	let dict = {'key': value}
   2466 <
   2467 Later it became clear that using a simple text key is very common, thus
   2468 literal dictionaries were introduced in a backwards compatible way: >
   2469 	let dict = #{key: value}
   2470 <
   2471 However, this #{} syntax is unlike any existing language.  As it turns out,
   2472 using a literal key is much more common than using an expression, and
   2473 considering that JavaScript uses this syntax, using the {} form for dictionary
   2474 literals is considered a much more useful syntax.  In Vim9 script the {} form
   2475 uses literal keys: >
   2476 	var dict = {key: value}
   2477 <
   2478 For example:
   2479 >vim9
   2480 	vim9script
   2481 	var dict = {key: 9}
   2482 	echo dict	# {'key': 9}
   2483 <
   2484 	Note: Vim normalizes the key, adding the ' characters.  Dictionary
   2485 	keys are always strings.
   2486 
   2487 Literal keys work using alphanumeric characters, underscore, and dash.  If you
   2488 want to use a character other than those, or even use an expression, you may:
   2489 - Use a single or double quoted string, or
   2490 - Use `extend()` and the literal key syntax, or
   2491 - For an expression, enclose the key in [] (like in a JavaScript computed
   2492   property).
   2493 All three are illustrated in this example:
   2494 >vim9
   2495 	vim9script
   2496 	var dict: dict<bool>
   2497 	dict["key\twith\ttabs"] = true		# double quoted key
   2498 	dict->extend({[40.9 + 1.1]: true})	# evaluated expression key
   2499 	dict['¡non–ASCII! w/ spaces'] = true	# single quoted key
   2500 	for k in dict->keys()
   2501 	  echo [k, dict[k]]
   2502 	endfor
   2503 <
   2504 The key type can be string, number, bool, or float, though all keys are stored
   2505 as strings.  Trying to use other types will give an error.  For example:
   2506 >vim9
   2507 	vim9script
   2508 	var dict: dict<bool>
   2509 	dict[9] = true		# number key
   2510 	dict[true] = true	# bool key
   2511 	dict[9.2] = true	# float key
   2512 	echo dict		# {'true': true, '9.2': true, '9': true}
   2513 	dict[(9, 2)] = false	# E1522: Using a Tuple as a String
   2514 <
   2515 Without using [], the value is literal so retains any leading zeros.  An
   2516 expression given with [] is evaluated and then converted to a string.
   2517 Expression evaluation means any leading zeros are omitted.  For example:
   2518 >vim9
   2519 	vim9script
   2520 	var dict = {09: '09 is literal "09"', [09]: '[09] becomes "9"'}
   2521 	echo dict['09']		# '09 is literal "09"'
   2522 	echo dict['9']		# '[09] becomes "9"'
   2523 <							*E1139*
   2524 If the key within [] is invalid, errors such as E1139 may be given, for
   2525 example:
   2526 >vim9
   2527 	vim9script
   2528 	var E1139 = {[0😢9]: 2}	# E1139: Missing matching bracket after dict …
   2529 <
   2530 							*E1014*
   2531 An invalid key gives E1014:
   2532 >vim9
   2533 	vim9script
   2534 	# This tries to use an unquoted control code character, U+0007 (ALERT)
   2535 	var E1014: dict<string> = {: 'E1014'}	# E1014: Invalid key: ^G
   2536 <
   2537 A float key must appear inside [], either in a dictionary literal or in a
   2538 subscript assignment.  The '.' of a float outside of either context is an
   2539 invalid Vim9 script dictionary literal key:
   2540 >vim9
   2541 	vim9script
   2542 	var dict: dict<string> = {[.09]: 'ok'}
   2543 	dict[0.10] = 'ok'
   2544 	echo dict	   # {'0.09': 'ok', '0.1': 'ok'}
   2545 	try
   2546 	  dict->extend({0.11: 'fail!'})
   2547 	catch
   2548 	  echo v:exception # E720: Missing colon in Dictionary: .11: 'fail!'
   2549 	endtry
   2550 <							*E1127*
   2551 If the name after a '.' is omitted, E1127 is given:
   2552 >vim9
   2553 	vim9script
   2554 	def F1127(): void
   2555 	  var d = {x: 0}
   2556 	  echo d.
   2557 	enddef
   2558 	F1127()  # E1127: Missing name after dot
   2559 <
   2560 
   2561 No :xit, :t, :k, :Print, :append, :change, :insert, or :open ~
   2562 
   2563 Some commands are too easily confused with local variable names, though they
   2564 have alternative commands that do the same thing:
   2565 
   2566 	Not allowed	Instead use ~
   2567 	`:k`		|:mark|
   2568 	`:Print`	|:print|
   2569 	`:t`		|:copy|
   2570 	`:xit`		|:exit|
   2571 
   2572 	Note: Shortened forms like `:x` also are not allowed.
   2573 
   2574 							*E1100*
   2575 For example, using "mark x" in the following script would work, whereas using
   2576 "k x" gives E1100:
   2577 >vim9
   2578 	vim9script
   2579 	:+2
   2580 	k x
   2581 	# E1100: Command not supported in Vim9 script (missing :var?): k x
   2582 <
   2583 Some commands are not available at all in Vim9 script.  These will give E1100
   2584 if they are used, including their shortened forms, like `:a`, `:o`, and `:ch`:
   2585 
   2586 	`:append`
   2587 	`:change`
   2588 	`:insert`
   2589 	`:open`
   2590 
   2591 See also |vim9-invalid-Ex-commands|.
   2592 
   2593 
   2594 Comparators ~
   2595 							*vim9-comparators*
   2596 The 'ignorecase' option is not used for string comparators.  Consequently,
   2597 "=~" and "=~#" work identically (i.e., comparisons are case sensitive):
   2598 >vim9
   2599 	vim9script
   2600 	var ic: bool = &ignorecase
   2601 	set ignorecase
   2602 	# Both of these echo 'false' because 'ignorecase' isn't used
   2603 	echo 'a' =~# 'A'
   2604 	echo 'a' =~ 'A'
   2605 	# Case sensitive '=~#' echoes 0.  Case insensitive '=~' echoes 1
   2606 	legacy echo 'a' =~# 'A'
   2607 	legacy echo 'a' =~ 'A'
   2608 	# Revert 'ignorecase' to its setting before running this script
   2609 	&ignorecase = ic
   2610 <
   2611 The expression "is" (|expr-is|), when used on strings, returns false (except
   2612 where the strings being compared are either explicitly null or uninitialized).
   2613 Similarly, the expression "isnot" (|expr-isnot|) returns true.  This is
   2614 because, whereas in a legacy Vim script scope strings' content is compared,
   2615 in a |Vim9| script scope identity is compared.  Consequently, because strings
   2616 are copied when used, two strings are not the same, though this might change
   2617 someday if strings are not copied but reference counted.  For example:
   2618 >vim9
   2619 	vim9script
   2620 	var str: string = ''
   2621 	echo str is str			# false
   2622 	legacy echo s:str is s:str |	# 1
   2623 	var x: string
   2624 	var y: string = null_string
   2625 	echo x is y			# true
   2626 <
   2627 For boolean, number, and float types, in legacy Vim script "is" and "isnot"
   2628 work like string comparison.  In Vim9 script, except when comparing a number
   2629 with a float, "is" will give either |E1037| or |E1072|.  For example:
   2630 >vim
   2631 	vim9cmd var [boo: bool, num: number, flo: float] = [true, 9, 9.2]
   2632 	legacy echo s:boo is v:true	| " 1
   2633 	legacy echo s:num is 9		| " 1
   2634 	legacy echo s:flo is 9.2	| " 1
   2635 	legacy echo s:boo is 9		| " 0
   2636 	legacy echo s:boo is 9.2	| " 0
   2637 	legacy echo s:num is 9.2	| " 0
   2638 	vim9cmd echo boo is true  # E1037: Cannot use "is" with bool
   2639 	vim9cmd echo num is 9     # E1037: Cannot use "is" with number
   2640 	vim9cmd echo flo is 9.2   # E1037: Cannot use "is" with float
   2641 	vim9cmd echo boo is 9     # E1072: Cannot compare bool with number
   2642 	vim9cmd echo boo is 9.2   # E1072: Cannot compare bool with float
   2643 	vim9cmd echo num is 9.2   # false
   2644 <
   2645 Similarly, "is" and "isnot" may not be used to compare job and channel types.
   2646 This example shows job comparison working with "is" in a legacy Vim script
   2647 scope but giving |E1072| in a Vim9 script scope:
   2648 >vim9
   2649 	vim9script
   2650 	var job1: job
   2651 	var job2: job = job1
   2652 	legacy echo s:job1 is s:job2  | # 1
   2653 	echo job1 is job2		# E1072: Cannot compare job with job
   2654 <
   2655 Comparing container types list, dict, tuple, and blob using "is" and "isnot"
   2656 behaves the same in Vim9 script as it does in legacy Vim script.  The
   2657 comparison checks instances, not content.  Because they behave similarly,
   2658 only a Vim9 script list example is provided in this example, with legacy Vim
   2659 script scope comparisons to show the same behavior:
   2660 >vim9
   2661 	vim9script
   2662 	var l1: list<any>
   2663 	var l2: list<any> = l1
   2664 	echo l1 is l2			# true (same instance)
   2665 	legacy echo s:l1 is s:l2 |	# 1
   2666 	echo l1 is []			# false (different instance)
   2667 	legacy echo s:l1 is [] |	# 0
   2668 	echo l1 is null_list		# false (different instance)
   2669 <
   2670 Comparing a `Funcref` variable is almost the same as comparing container
   2671 variables, though an uninitialized `Funcref` variable compared to Vim9
   2672 script's `null_function` behaves differently:
   2673 >vim9
   2674 	vim9script
   2675 	var F1: func
   2676 	var F2: func = F1
   2677 	echo F1 is F2			# true (same uninitialized instance)
   2678 	echo F1 is null_function	# true
   2679 <
   2680 In Vim9 script, comparing class objects behaves similarly:
   2681 >vim9
   2682 	vim9script
   2683 	class C
   2684 	endclass
   2685 	# Uninitialized class objects
   2686 	var O1: C
   2687 	var O2: C
   2688 	echo O1 is O2		# true (same uninitialized class object)
   2689 	echo O1 is null_object	# true
   2690 	# Initialized class objects
   2691 	var O4: C = C.new()
   2692 	var O5: C = O4
   2693 	var O6: C = C.new()
   2694 	echo O4 is O5		# true (same initialized class object)
   2695 	echo O5 is O6		# false (different class objects)
   2696 <
   2697 	Note: Classes themselves cannot be compared:
   2698 >vim9
   2699 	vim9script
   2700 	class C
   2701 	endclass
   2702 	echo C is null_class	# E1401: Class "C" cannot be used as a value
   2703 <
   2704 Comparison of enum objects differs from class objects.  Each enumvalue
   2705 is a singleton, so variables assigned the same enumvalue always reference
   2706 the identical instance.  Even when a mutable instance variable of an enum
   2707 value is modified, the change affects all references to that enumvalue:
   2708 >vim9
   2709 	vim9script
   2710 	enum Switch
   2711 	  On(['active', true]),
   2712 	  Off(['inactive', false])
   2713 	  final state: list<any>
   2714 	endenum
   2715 	var on1: Switch = Switch.On
   2716 	var on2: Switch = Switch.On
   2717 	on2.state[0] = 'engaged'
   2718 	# The change affects on1 and on2 because they're the same enumvalue
   2719 	echo on1 is on2				# true
   2720 	# Uninitialized enumvalue (and there is no null_enumvalue):
   2721 	var uninitialized: Switch
   2722 	echo uninitialized is null_object	# true
   2723 <
   2724 In summary, in relation to the "is" and "isnot" comparison operators:
   2725 
   2726 - Vim9 script introduces stricter rules than legacy Vim script and:
   2727 	- Behaves differently for strings,
   2728 	- Behaves the same for lists, dictionaries, tuples, and blobs,
   2729 	- Does not allow comparison of booleans, numbers, floats, jobs, and
   2730 	  channels (except for comparing a number with a float), and
   2731 	- Behaves the same for function references (though Vim9 script's
   2732 	  `null_function` behaves differently).
   2733 
   2734 - Entirely exclusive to Vim9 script:
   2735 	- Comparing class objects is similar to comparing function references,
   2736 	  and
   2737 	- For enum objects, "is" and "isnot" always compare the same instance
   2738 	  of a given enumvalue.
   2739 
   2740 
   2741 Abort after error ~
   2742 
   2743 In legacy Vim script, when an error is encountered, Vim continues to execute
   2744 the lines following the error.  This can lead to a long sequence of errors
   2745 and need to type CTRL-C to stop it.  For example, this script produces two
   2746 |E121| errors:
   2747 >vim
   2748 	" legacy Vim script
   2749 	let x = does_not_exist
   2750 	let y = does_not_exist_too
   2751 <
   2752 However, in Vim9 script, execution of commands stops at the first error:
   2753 >vim9
   2754 	vim9script
   2755 	var x = does_not_exist  # E121: Undefined variable: does_not_exist
   2756 	# Execution stops and the following line is not executed
   2757 	var y = does_not_exist_too
   2758 <
   2759 
   2760 For loop ~
   2761 
   2762 The loop variable must not be declared yet:
   2763 >vim9
   2764 	vim9script
   2765 	var it: list<number>
   2766 	for it in [1, 2, 3]	# E1041: Redefining script item: "it"
   2767 <
   2768 But it is possible to use a prefixed variable, e.g., a buffer local variable:
   2769 >vim9
   2770 	vim9script
   2771 	b:i = []
   2772 	for b:i in [1, 2, 3]
   2773 	  echo b:i
   2774 	endfor
   2775 <							*E1254*
   2776 A loop variable in a `:def` function cannot be a s: variable:
   2777 >vim9
   2778 	vim9script
   2779 	def F()
   2780 	  for s:n in range(9) # E1254: Cannot use script variable in for loop
   2781 	  endfor
   2782 	enddef
   2783 	defcompile
   2784 <
   2785 Legacy Vim script has some tricks to make a for loop over a list handle
   2786 deleting items at the current or previous item.  In Vim9 script, the same
   2787 trick applies in a non-compiled scope.  However, in a compiled Vim9 script
   2788 scope, when an item is deleted the following item in the list is skipped
   2789 ("iterator invalidation"), producing the same result as what you would see in
   2790 Python and Ruby.  The following script demonstrates the differing behaviors in
   2791 non-compiled and compiled Vim9 script scopes:
   2792 >vim9
   2793 	vim9script
   2794 	echo 'Removing items from a list in a Vim9 script non-compiled scope:'
   2795 	# This echoes 10, then 20, 30, 40, and []
   2796 	var list_one: list<number> = [10, 20, 30, 40]
   2797 	for n in list_one
   2798 	  echo n
   2799 	  list_one->remove(index(list_one, n))
   2800 	endfor
   2801 	echo list_one
   2802 	echo 'Removing items from a list in a Vim9 script compiled scope:'
   2803 	# This echoes 10, then 30, and the list [20, 40]
   2804 	# This happens because when 10 is removed, 20 moves to index 0, but
   2805 	# the iterator moves to index 1, which is now 30!
   2806 	var list_two: list<number> = [10, 20, 30, 40]
   2807 	var Remove_items: func = (): void => {
   2808 	  for n in list_two
   2809 	    echo n
   2810 	    list_two->remove(index(list_two, n))
   2811 	  endfor
   2812 	  echo list_two
   2813 	}
   2814 	Remove_items()
   2815 <
   2816 What this example shows is usually it is better not to change a list that is
   2817 iterated over.  Making a copy first is often safer.
   2818 
   2819 When looping over a list of lists, the nested lists can be changed.  The loop
   2820 variable is "final" - that is, it cannot be changed but its value can be
   2821 changed.  For example:
   2822 >vim9
   2823 	vim9script
   2824 	var lst: list<list<number>> = [[1, 2], [3, 4], [5, 6]]
   2825 	for subl in lst
   2826 	  subl[0] = 9
   2827 	endfor
   2828 	echo lst  # [[9, 2], [9, 4], [9, 6]]
   2829 	for subl in lst
   2830 	  subl = [9, subl[1]] # E46: Cannot change read-only variable "subl"
   2831 	endfor
   2832 <							*E1306*
   2833 The depth of |:for| and |:while| loops added together, cannot exceed 10.
   2834 
   2835 
   2836 Conditions and expressions ~
   2837 
   2838 Vim9 script has stricter type checking than legacy Vim script in boolean
   2839 contexts.  Most operators require either a boolean, or 0/1, or a |Special| type.
   2840 The falsy (|??|) and logical NOT (|expr-!|) operators use truthiness rules.
   2841 
   2842 – Strict Boolean Expressions ~
   2843 							*vim9-boolean*
   2844 In Vim9 script, the conditionals |:if|, |ternary|, |:while|, `||` (|expr-barbar|),
   2845 and `&&` (|expr-&&|), require strict boolean types.  This is different to
   2846 legacy Vim script, which treats any non-zero number as 1 and implicitly infers
   2847 a string or |Special| as a number equivalent.  To illustrate, in legacy Vim
   2848 script, all these conditional expressions work:
   2849 >vim
   2850 	" legacy Vim script
   2851 	" These evaluate to 1:
   2852 	echo 1 ? 1 : 0
   2853 	echo 0 || 1
   2854 	echo 1 || v:false
   2855 	echo 1 && v:true
   2856 	echo v:null || 1
   2857 	echo 99 ? 1 : 0
   2858 	echo "99" ? 1 : 0
   2859 	" These evaluate to 0:
   2860 	echo 0 || v:none
   2861 	echo 0 && 1
   2862 	echo "text" ? 1 : 0
   2863 <
   2864 In Vim9 script, conditional expressions (excluding `??` and `!`) have stricter
   2865 |type-checking|, which means:
   2866 - For numbers, only 0 (falsy) or 1 (truthy) are permitted, otherwise |E1023|
   2867   is given, and
   2868 - Strings are not permitted (|E1135|).
   2869 >vim
   2870 	vim9cmd echo 1 ? 1 : 0		# 1
   2871 	vim9cmd echo 0 || 1		# true
   2872 	vim9cmd echo 1 || false		# true
   2873 	vim9cmd echo 1 && true		# true
   2874 	vim9cmd echo null || 1		# true
   2875 	vim9cmd echo 0 || v:none	# false
   2876 	vim9cmd echo 0 && v:true	# false
   2877 	vim9cmd echo 9 ? 1 : 0		# E1023: Using a Number as a Bool: 9
   2878 	vim9cmd echo "9" ? 1 : 0	# E1135: Using a String as a Bool: "9"
   2879 	vim9cmd echo "x" ? 1 : 0	# E1135: Using a String as a Bool: "x"
   2880 <
   2881 – Falsiness Operator ~
   2882 							*vim9-falsy*
   2883 For most types there is no error using `??` (the |falsy-operator|).
   2884 Values are either falsy or truthy, with falsy evaluated as follows:
   2885 
   2886 	Type		Falsy when~
   2887 	Number		zero
   2888 	String		empty
   2889 	Funcref		null
   2890 	List		empty
   2891 	Dictionary	empty
   2892 	Float		zero
   2893 	Boolean		`false` (also |Special| `v:false`)
   2894 	None		always (`v:null` and `v:none`)
   2895 	Job		null
   2896 	Channel		null
   2897 	Blob		empty
   2898 	Class		not applicable (see |E1405|)
   2899 	Object		null
   2900 	Typealias	not applicable (see |E1403|)
   2901 	Enum		not applicable (see |E1421|)
   2902 	EnumValue	null
   2903 	Tuple		empty
   2904 	void		always
   2905 
   2906 To illustrate, a script showing falsiness of all except error-giving types:
   2907 >vim9
   2908 	vim9script
   2909 	echo "Number: \t0\t\t"			0 ?? 'is falsy'
   2910 	echo "String: \t''\t\t"			'' ?? 'is falsy'
   2911 	echo "Funcref:\tnull_function\t"	null_function ?? 'is falsy'
   2912 	echo "List:   \t[]\t\t"			[] ?? 'is falsy'
   2913 	echo "Dictionary:\t{}\t\t"		{} ?? 'is falsy'
   2914 	echo "Float:  \t0.0\t\t"		0.0 ?? 'is falsy'
   2915 	echo "Boolean:\tfalse\t\t"		false ?? 'is falsy'
   2916 	echo "        \tv:false\t\t"		v:false ?? 'is falsy'
   2917 	echo "None:   \tv:none\t\t"		v:none ?? 'is falsy'
   2918 	echo "        \tv:null\t\t"		v:null ?? 'is falsy'
   2919 	echo "Job:    \tnull_job\t"		null_job ?? 'is falsy'
   2920 	echo "Channel:\tnull_channel\t"		null_channel ?? 'is falsy'
   2921 	echo "Blob:   \t0z\t\t"			0z ?? 'is falsy'
   2922 	echo "Object: \tnull_object\t"		null_object ?? 'is falsy'
   2923 	enum Enum
   2924 	endenum
   2925 	var null_enumval: Enum  # NB: There is no inherent "null_enumvalue"
   2926 	echo "EnumValue:\t'null_enumval'\t"	null_enumval ?? 'is falsy'
   2927 	echo "Tuple:  \t()\t\t"			() ?? 'is falsy'
   2928 	echo "void:   \t\t\t"			test_void() ?? 'is falsy'
   2929 <
   2930 Note: Vim9 script's falsiness is much the same as Python's (e.g., "if []:" in
   2931 Python is falsy, the same as "if []" in Vim9 script.  JavaScript is similar
   2932 too, though it differs in its unusual truthy evaluation of an empty
   2933 object/array.
   2934 
   2935 – Type Conversions and Exceptions ~
   2936 							*vim9-!*
   2937 When using the logical NOT operation, "!" (|expr-!|), for inverting, there is
   2938 no error (except with a class - |E1405|, enum - |E1421|, or typealias -
   2939 |E1403|) and the result is always a boolean.  In this example, the falsy
   2940 values are inverted and all evaluations return "true":
   2941 >vim9
   2942 	vim9script
   2943 	echo [!0, !'', !null_function, ![], !{}, !0.0, !false,
   2944 	  !v:false, !v:none, !v:null, !null_job, !null_channel, !0z,
   2945 	  !null_object, !(), !test_void()]
   2946 <							*vim9-!!*
   2947 Similarly, when using "!!" to turn a value into a boolean all the evaluations
   2948 return "false", as this example shows:
   2949 >vim9
   2950 	vim9script
   2951 	echo [!!0, !!'', !!null_function, !![], !!{}, !!0.0, !!false,
   2952 	  !!v:false, !!v:none, !!v:null, !!null_job, !!null_channel, !!0z,
   2953 	  !!null_object, !!(), !!test_void()]
   2954 <
   2955 Note: This is a rare instance where Vim9 script is more permissive than legacy
   2956 Vim script.  As the following example demonstrates, legacy Vim script gives
   2957 errors when using "!" or "!!" with many types (including Funcref, List,
   2958 Dictionary, Blob, Job, and Tuple):
   2959 >vim
   2960 	" legacy Vim script: !! erroring examples
   2961 	let F = {x -> x}
   2962 	let j = job_start([&shell, &shellcmdflag, 'date'], {})
   2963 	echo !!F  |	" E703: Using a Funcref as a Number
   2964 	echo !![] |	" E745: Using a List as a Number
   2965 	echo !!{} |	" E728: Using a Dictionary as a Number
   2966 	echo !!0z |	" E974: Using a Blob as a Number
   2967 	echo !!j  |	" E910: Using a Job as a Number
   2968 	echo !!() |	" E1520: Using a Tuple as a Number
   2969 <
   2970 When using ".." for string concatenation, number, float, bool and |Special|
   2971 types are always converted to strings:
   2972 >vim9
   2973 	vim9script
   2974 	var mystr = 8 .. ', ' .. 9.2 .. ', ' .. true .. ' and ' .. v:none
   2975 	echo [mystr, mystr->typename()]
   2976 <
   2977 	Notes: 1. Both `true` (and `v:true`, not shown) are stringified to
   2978 	"true" whereas legacy Vim script stringifies `v:true` to "v:true".
   2979 	2. In Vim9 script '..' string concatenation handles floats
   2980 	consistently.  Legacy Vim script doesn't, with the decimal point
   2981 	being interpreted as a concatenation "." after the first "." or "..".
   2982 	In the following legacy Vim script, 9.2 loses its decimal point:
   2983 >vim
   2984 	let s:my8str = 8 .. ', ' .. 9.2 .. ', ' .. v:true .. ' and ' .. v:none
   2985 	echo s:my8str | " 8, 92, v:true and v:none
   2986 <
   2987 This illustrates that primitives (|v:t_number|, |v:t_float|, and |v:t_bool|),
   2988 plus |Special| types may be compared directly with "==".  For all other types,
   2989 |string()| must be used.  For example:
   2990 >vim9
   2991 	vim9script
   2992 	echo 'This is a list: ' .. [1, 2, 3]->string()
   2993 	# Whereas doing this gives E730: Using a List as a String:
   2994 	echo 'This does not work! ' .. [1, 2, 3]
   2995 <
   2996 Similarly, |string()| should be used for "==" comparisons, otherwise |E1072|
   2997 is given.  For example:
   2998 >vim9
   2999 	vim9script
   3000 	var l: list<any> = [9, '9.2']
   3001 	echo string(l) == "[9, '9.2']"	# true
   3002 	echo l == "[9, '9.2']"	# E1072: Cannot compare List with String
   3003 <
   3004 WARNING: Short-circuit evaluation may hide errors in boolean expressions when
   3005 an OR expression can be determined to be `true` without evaluating all
   3006 operands.  Evaluation stops early, meaning invalid code may never execute,
   3007 masking errors that would otherwise occur at runtime, including Vim9 script
   3008 type-related errors.  For example, a class itself cannot be used in a
   3009 comparison, but here it does not give an error in the first ternary expression
   3010 because "t" has already been evaluated to `true`:
   3011 >vim9
   3012 	vim9script
   3013 	var t: bool = true
   3014 	echo t || null_class ? true : false  # true
   3015 	echo null_class || t ? true : false  # E1405: Class "" cannot be used…
   3016 <
   3017 
   3018 Predefined values ~
   3019 				*false* *true* *null* *null_blob* *null_channel*
   3020 				*null_class* *null_dict* *null_function* *null_job*
   3021 				*null_list* *null_object* *null_partial* *null_string*
   3022 Vim9 script has predefined values representing true, false, and null states.
   3023 The following table lists those predefined values, along with their
   3024 |type()|, |typename()|, and |string()| representations:
   3025 
   3026  Predefined value  type()	  typename()		string() ~
   3027  null_string	   |v:t_string|	  string		''
   3028  null_function	   |v:t_func|	  func(...): unknown	function()
   3029  null_partial	   |v:t_func|	  func(...): unknown	function('')
   3030  null_list	   |v:t_list|	  list<any>		[]
   3031  null_dict	   |v:t_dict|	  dict<any>		{}
   3032  true		   |v:t_bool|	  bool			true
   3033  false		   |v:t_bool|	  bool			false
   3034  null		   |v:t_none|	  special		null
   3035  null_job	   |v:t_job|	  job			no process
   3036  null_channel	   |v:t_channel|    channel		channel fail
   3037  null_blob	   |v:t_blob|	  blob			0z
   3038  null_class	   |v:t_class|	  class<Unknown>	class [unknown]
   3039  null_object	   |v:t_object|	  object<any>		object of [unknown]
   3040  null_tuple	   |v:t_tuple|	  tuple<any>		()
   3041 
   3042 The predefined value `true` is the same as `v:true`, `false` is the same as
   3043 `v:false`, and `null` is the same as `v:null`.
   3044 
   3045 A "null_<type>" value is treated the same as an empty value only in some
   3046 cases.  See |null-details|.
   3047 
   3048 The following types do not have predefined "null_<type>" values:
   3049 - Number (instead use 0, though it is not `null`)
   3050 - Float (instead use 0.0, though, like the number 0, it also is not `null`)
   3051 - Typealias (which cannot be used as a value; it gives |E1403|)
   3052 - Enum (which cannot be used as a value; it gives |E1421|)
   3053 - EnumValue (however, it can be a `null_object` - see the "Switch" example in
   3054   |vim9-comparators|)
   3055 
   3056 The "null_<type>" values can be useful for clearing script-local variables
   3057 because they cannot be deleted with `:unlet`.  For example:
   3058 >vim9
   3059 	vim9script
   3060 	var myvar: string = "not null_string"
   3061 	try
   3062 	  unlet myvar
   3063 	catch
   3064 	  echo v:exception  # E1081: Cannot unlet myvar
   3065 	finally
   3066 	  myvar = null_string
   3067 	  echo $"'myvar' is {myvar->string()}"
   3068 	endtry
   3069 <
   3070 The values can also be useful as the default value for an argument:
   3071 >vim9
   3072 	vim9script
   3073 	def CheckMyList(l: list<number> = null_list): string
   3074 	  if l == null
   3075 	    return 'No list was passed'
   3076 	  elseif l->empty()
   3077 	    return 'An empty list was passed'
   3078 	  else
   3079 	    return $"List {l->string()} was passed"
   3080 	  endif
   3081 	enddef
   3082 	echo CheckMyList()
   3083 	echo CheckMyList([])
   3084 	echo CheckMyList([8, 9])
   3085 <
   3086 	Note: This examples shows comparing the list "l" against `null`, not
   3087 	`null_list`.  This is useful because it enables distinguishing the
   3088 	default value, null_list, from an empty list [].  See |null-compare|
   3089 	and |null-anomalies| for more information testing against null.
   3090 
   3091 It is possible to compare `null` with any value - it does not give a type
   3092 error.  However, comparing `null` with a number, float or bool always results
   3093 in `false`.  This is different than number and float in legacy Vim script
   3094 where comparing `v:null` with 0 or 0.0 returns 1.  For example:
   3095 >vim9
   3096 	vim9script
   3097 	echo [0 == null, 0.0 == null]		   # [false, false]
   3098 	legacy echo [0 == v:null, 0.0 == v:null] | # [1, 1]
   3099 <
   3100 							*vim9-false-true*
   3101 When converting a boolean to a string, `false` and `true` are used.  In Vim9
   3102 scripts, `v:false` is equal to `false` and `v:true` is equal to `true`.
   3103 >vim9
   3104 	vim9script
   3105 	echo $'{v:none} has no "none" equivalent, but'
   3106 	echo $'"v:true" is stringified to "{v:true}" in a string, and'
   3107 	echo 'Q: "v:false" and "false" can be used interchangeably?'
   3108 	echo $'A: {v:false == false}'
   3109 <
   3110 Note: There is no "none" for `v:none` because it has no equivalent in other
   3111 languages.
   3112 
   3113 							*vim9-string-index*
   3114 Indexing a string with [idx] or taking a slice with [idx : idx] uses character
   3115 indexes instead of byte indexes.  Combining/composing characters are included.
   3116 Example:
   3117 >vim9
   3118 	vim9script
   3119 	echo 'très'[2]		# è (U+00E8)
   3120 	legacy echo 'très'[2] | # <c3> (Illegal byte 0xc3)
   3121 <
   3122 A negative index is counting from the end, "[-1]" is the last character.
   3123 >vim9
   3124 	vim9script
   3125 	echo 'fenêtre'[-4 : -1]		 # être
   3126 	legacy echo 'fenêtre'[-5 : -1] | # être (-5 because ê is two bytes)
   3127 <
   3128 Using the builtin function, |slice()|, can be a good choice because it uses
   3129 character indexes in both legacy Vim script scopes and Vim9 script scopes:
   3130 >vim9
   3131 	vim9script
   3132 	echo 'fenêtre'->slice(-4)	   # être
   3133 	legacy echo 'fenêtre'->slice(-4) | # être
   3134 <
   3135 Use |strcharpart()| to count combining characters separately.  The following
   3136 example uses "a" (U+0061) and a combining macron (U+0304):
   3137 >vim9
   3138 	vim9script
   3139 	echo 'Ngā mihi'->strcharpart(2, 1)  # a (excluding combining macron)
   3140 	echo 'Ngā mihi'[2]		    # ā (including combining macron)
   3141 <
   3142 If the index is out of range, an empty string is the result.
   3143 >vim9
   3144 	vim9script
   3145 	echo ['In range'[0 : 1]]	# ['In']
   3146 	echo ['Out of range'[19 : ]]	# ['']
   3147 <							*E1148*
   3148 Attempting to assign to or modify a string using an index gives an error.
   3149 For example:
   3150 >vim9
   3151 	vim9script
   3152 	def F1148(): void
   3153 	  b:s = 'Fails'
   3154 	  b:s[4] = '!'	# E1148: Cannot index a string
   3155 	enddef
   3156 	F1148()
   3157 <
   3158 	Note: Other errors may be given depending on the scope and whether the
   3159 	variable is prefixed.  For example, if the variable in this example
   3160 	was declared with `:var` instead of being a buffer variable, it would
   3161 	give |E1141| and, if the scope was script-local rather than a `:def`,
   3162 	it would give |E689|.
   3163 
   3164 In legacy Vim script, if either "++var" (|:++|) or "--var" (|:--|) are used in
   3165 a character index they are ignored.  In Vim9 script, they are invalid:
   3166 >vim9
   3167 	vim9script
   3168 	var int: number = 1
   3169 	var str: string = 'hear'
   3170 	legacy echo s:str[++s:int : ] | # ear
   3171 	echo str[++int : ]		# E15: Invalid expression: "++int : ]
   3172 <
   3173 Numbers starting with zero are not considered to be octal, only numbers
   3174 starting with "0o" are octal: "0o744".  (See |scriptversion-4|.)  For example:
   3175 >vim9
   3176 	vim9script
   3177 	echo 017	  # 17 (inferred decimal)
   3178 	legacy echo 017 | # 15 (inferred octal)
   3179 	echo 0o17	  # 15 (explicit octal)
   3180 <
   3181 What to watch out for ~
   3182 							*vim9-gotchas*
   3183 Vim9 script was designed to be closer to contemporary programming languages,
   3184 but at the same time tries to support legacy Vim commands.  Some compromises
   3185 had to be made.  Here is a summary of what might be unexpected.
   3186 
   3187 Ex command ranges often need to be prefixed with a colon:
   3188 
   3189 - A line beginning with "%" in legacy Vim script means "all lines" (|:%|)
   3190   whereas in Vim9 script it may mean modulo (|expr-%|) or give |E1050|.
   3191   For example:
   3192 >vim
   3193 	" legacy Vim script
   3194 	let g = 97
   3195 	echo 1000
   3196 	  % g / 9.7
   3197 	" 1000 (then prints all lines containing '9.7' to messages)
   3198 <
   3199   whereas:
   3200 >vim9
   3201 	vim9script
   3202 	var g = 97
   3203 	echo 1000
   3204 	  % g / 9.7
   3205 	# 3.092784 (which is 1000 % 97 / 9.7)
   3206 	echo 1000
   3207 	:%g/9.7
   3208 	# 1000 (then prints all lines containing '9.7' to messages)
   3209 	% g / 9.7
   3210 	# E1050: Colon required before a range: % g / 9.7
   3211 <
   3212 - An initial apostrophe in legacy Vim script means go to mark (|'|).  In Vim9
   3213   script it's either the start of a quoted string or it gives |E115|:
   3214 >vim
   3215 	" legacy Vim script
   3216 	:normal! mt
   3217 	" Sets mark t at the line with the comment " legacy Vim script
   3218 	't
   3219 	" Jumps to mark t (which is at this line after sourcing this script)
   3220 <
   3221   whereas:
   3222 >vim9
   3223 	vim9script
   3224 	:normal! mt
   3225 	# Sets mark t on the line with the vim9script command
   3226 	't'->popup_notification({time: 4000})  # Vim9 script method chain
   3227 	:'t
   3228 	# Jumps to mark t (which is at this line after sourcing this script)
   3229 	# 't by itself would be E115: Missing single quote
   3230 <
   3231 - In legacy Vim script, "->" shifts the prior line, which is prior to a range
   3232   if it is a sourced script, right by 'shiftwidth' spaces.  In Vim9 script, it
   3233   is a continuation line of a chained method:
   3234 >vim9
   3235 	vim9script
   3236 	const mine: string = 'MINE'
   3237 	  ->toupper()
   3238 	echo mine	# MINE
   3239 	# In a modifiable buffer, using :-> on a line by itself would shift
   3240 	# the line before vim9script to the right by 'shiftwidth' spaces when
   3241 	# this script is sourced.
   3242 <
   3243 Some Ex commands can be confused with assignments in Vim9 script:
   3244 >vim
   3245 	" legacy Vim script
   3246 	let let = 8
   3247 	echo let | " 8
   3248 	:g:let = 8
   3249 	" Prints lines matching 'let = 8' to messages
   3250 <whereas: >vim9
   3251 	vim9script
   3252 	g:let = 9
   3253 	echo g:let  # 9
   3254 	:g:let = 9  # E1241: Separator not supported: :let = 9
   3255 <
   3256 To avoid confusion between a `:global` or `:substitute` command and an
   3257 expression or assignment, a few separators cannot be used when these commands
   3258 are abbreviated to a single character: '-', '.' and ':'.  Examples using `:g`:
   3259 >vim9
   3260 	vim9cmd g-pattern-cmd	# E1241: Separator not supported: -pattern-cm…
   3261 	vim9cmd g:pattern:cmd	# E1069: White space required after ':': :cmd…
   3262 	vim9cmd g.pattern.cmd	# E121: Undefined variable: g
   3263 <
   3264 Also, there cannot be a space between the command and the separator, unlike in
   3265 legacy Vim script.  For example:
   3266 >vim
   3267 	g /[-:.]pattern/p | " This prints the three vim9cmd lines above
   3268 <
   3269 whereas in Vim9 script:
   3270 >vim9
   3271 	vim9cmd g /[-:.]pattern/p  # E1242: No whitespace allowed before sepa…
   3272 <
   3273 Functions defined with `:def` compile the whole function, so any syntax or
   3274 type errors will be detected during compilation, regardless of execution path.
   3275 Legacy functions have no static type checking so type-related issues (if any)
   3276 can only manifest for code that actually executes.  For example, the following
   3277 legacy Vim script `:function` returns "yes" (except in the very unlikely
   3278 scenario that you source this in z/OS UNIX):
   3279 >vim9
   3280 	vim9script
   3281 	func Maybe()
   3282 	  if !has('ebcdic')
   3283 	    return 'yes'
   3284 	  endif
   3285 	  return [] + 'yes'
   3286 	endfunc
   3287 	echo Maybe()  # yes
   3288 <
   3289 The equivalent Vim9 script gives |E1051|:
   3290 >vim9
   3291 	vim9script
   3292 	def Maybe(): any
   3293 	  if !has('ebcdic')
   3294 	    return 'yes'
   3295 	  endif
   3296 	  return [] + 'yes'  # E1051: Wrong argument type for +
   3297 	enddef
   3298 	echo Maybe()
   3299 <
   3300 For a workaround, put the unsupported code inside a conditional with a
   3301 constant expression that evaluates to false.  The compiler then skips
   3302 compiling the unsupported code.  For example:
   3303 >vim9
   3304 	vim9script
   3305 	def Maybe(): any
   3306 	  if has('ebcdic')
   3307 	    return [] + 'yes'
   3308 	  endif
   3309 	  return 'yes'
   3310 	enddef
   3311 	echo Maybe()	# yes
   3312 <
   3313 Another option is to split it into two functions:
   3314 >vim9
   3315 	vim9script
   3316 	if has('ebcdic')
   3317 	  # This is not compiled at all unless on an EBCDIC system
   3318 	  def MaybeInner(): any
   3319 	    return [] + 'yes'
   3320 	  enddef
   3321 	endif
   3322 	func Maybe()
   3323 	  if has('ebcdic')
   3324 	    return MaybeInner()
   3325 	  else
   3326 	    return 'yes'
   3327 	  endif
   3328 	endfunc
   3329 	echo Maybe()	# yes
   3330 <
   3331 Yet another option, though this time using a different scenario, is using
   3332 `exists_compiled()`.  Here the builtin function |luaeval()| will only be used
   3333 when it's available:
   3334 >vim9
   3335 	vim9script
   3336 	def Version(): string
   3337 	  if !exists_compiled('*luaeval')
   3338 	    return $"Version using v:version: {v:version}"
   3339 	  else
   3340 	    return $"Version via Lua: {luaeval('900 + 2')}"
   3341 	  endif
   3342 	enddef
   3343 	echo Version()
   3344 <
   3345 Unreachable code after `:return` gives an |E1095| error in a `:def` or Vim9
   3346 lambda function, whereas it is ignored in a legacy function:
   3347 >vim9
   3348 	vim9script
   3349 	function Legacy()
   3350 	  return v:true
   3351 	  let X = "Although this is unreachable, it's ignored."
   3352 	endfunction
   3353 	echo Legacy()		# true
   3354 	var Vim9: func = (): bool => {
   3355 	  return true
   3356 	  const X = false	# E1095: Unreachable code after :return
   3357 	}
   3358 <							*vim9-user-command*
   3359 Another side effect of compiling a function is that the presence of a user
   3360 command is checked at compile time.  If the user command is defined later an
   3361 error will result.  This works:
   3362 >vim9
   3363 	vim9script
   3364 	command -nargs=1 MyCommand echomsg <q-args>
   3365 	def Works()
   3366 	  MyCommand 'this works'
   3367 	enddef
   3368 	Works()
   3369 <
   3370 This gives |E476| for "MyCommandFails" not being defined at compile time:
   3371 >vim9
   3372 	vim9script
   3373 	def Fails()
   3374 	  command -nargs=1 MyCommandFails echomsg <q-args>
   3375 	  MyCommandFails 'this fails'
   3376 	enddef
   3377 	Fails()
   3378 <
   3379 A workaround is to invoke the command indirectly with `:execute`, like this:
   3380 >vim9
   3381 	vim9script
   3382 	def Works_Using_Execute()
   3383 	  command -nargs=1 MyCommandUsingExecute echomsg <q-args>
   3384 	  execute "MyCommandUsingExecute 'this works'"
   3385 	enddef
   3386 	Works_Using_Execute()
   3387 <
   3388 For unrecognized commands in a conditional statement, there is no bailing out.
   3389 So, if the condition evaluates to false, an invalid command will give |E171|
   3390 and, if the condition evaluates to true, an invalid command will give |E476|.
   3391 Examples:
   3392 >vim9
   3393 	vim9script
   3394 	def F171()
   3395 	  if has('ebcdic') | Nah | endif
   3396 	enddef
   3397 	F171()	# E171: Missing :endif
   3398 < >vim9
   3399 	vim9script
   3400 	def F476()
   3401 	  if !has('ebcdic') | Nah | endif
   3402 	enddef
   3403 	F476()	# E476: Invalid command: Nah | endif
   3404 <
   3405 
   3406 Other differences ~
   3407 
   3408 - Patterns use 'magic', unless explicitly overruled.  That is, if the global
   3409   option 'nomagic' is set, it is ignored.
   3410 
   3411 - If the option value 'edcompatible' is set, it is ignored.
   3412 
   3413 - If the option value 'gdefault' is set, it is ignored.
   3414 
   3415 							*:++* *:--*
   3416 - The ++ and -- commands have been added.  They add and subtract one
   3417   respectively.  They work with number and float types.  For example:
   3418 >vim9
   3419 	vim9script
   3420 	var flo: float = 41.0
   3421 	++flo
   3422 	echo flo	# 42.0
   3423 <
   3424 - Using ++var or --var in an expression is not supported yet.  |E15| is given
   3425   if either is used.  For example:
   3426 >vim9
   3427 	vim9script
   3428 	var num: number = 43
   3429 	# The following line gives E15: Invalid expression: "--num"
   3430 	echo --num
   3431 <
   3432 
   3433 ==============================================================================
   3434 
   3435 3. New style functions					*fast-functions*
   3436 
   3437 							*:def*
   3438 :def[!] {name}([arguments])[: {return-type}]
   3439 			Define a new function by the name {name}.  The body of
   3440 			the function follows in the next lines, until the
   3441 			matching `:enddef`.
   3442 							*E1073*
   3443 			{name} cannot be reused at the script-local level:
   3444 >vim9
   3445 			  vim9script
   3446 			  def F_1073()
   3447 			  enddef
   3448 			  def F_1073()	# E1073: Name already defined: <SNR...
   3449 			  enddef
   3450 <							*E1011*
   3451 			{name} must be less than 100 bytes long.
   3452 
   3453 							*E1077*
   3454 			{arguments} is a sequence of zero or more argument
   3455 			declarations.  There are three forms:
   3456 				{name}: {type}
   3457 				{name} = {value}
   3458 				{name}: {type} = {value}
   3459 			The first form is a mandatory argument.  So, the
   3460 			declaration must provide a type.  Example:
   3461 >vim9
   3462 			  vim9script
   3463 			  def F_1077(x): void
   3464 			    # E1077: Missing argument type for x
   3465 			  enddef
   3466 <
   3467 			For the second form, because the declaration does not
   3468 			specify it, Vim infers the type.  For both second and
   3469 			third forms, a default {value} applies when the
   3470 			caller omits it.  Examples:
   3471 >vim9
   3472 			  vim9script
   3473 			  def SecondForm(arg = "Hi"): void
   3474 			    echo $'2. arg is a "{arg->typename()}" type ' ..
   3475 				 $'and the default value of arg is "{arg}"'
   3476 			  enddef
   3477 			  SecondForm()
   3478 			  def ThirdForm(arg2: number = 9): void
   3479 			    echo $'3. default value of arg2 is {arg2}'
   3480 			  enddef
   3481 			  ThirdForm()
   3482 <							*E1123*
   3483 			Arguments in a builtin function called in a `:def`
   3484 			function must have commas between arguments:
   3485 >vim9
   3486 			  vim9script
   3487 			  def F_1123(a: number, b: number): void
   3488 			    echo max(a b)  # E1123: Missing comma before ar...
   3489 			  enddef
   3490 			  F_1123(1, 2)
   3491 <							*E1003* *E1027* *E1096*
   3492 			The type of value used with `:return` must match
   3493 			{return-type}.  When {return-type} is omitted or is
   3494 			"void" the function is not allowed to return
   3495 			anything.  Examples:
   3496 >vim9
   3497 			  vim9script
   3498 			  def F_1003(): bool
   3499 			    return  # E1003: Missing return value
   3500 			  enddef
   3501 			  F_1003()
   3502 < >vim9
   3503 			  vim9script
   3504 			  def F_1027(): bool
   3505 			    echo false  # E1027: Missing return statement
   3506 			  enddef
   3507 			  F_1027()
   3508 < >vim9
   3509 			  vim9script
   3510 			  def F_1096(): void
   3511 			    return false  # E1096: Returning a value in a f...
   3512 			  enddef
   3513 			  F_1096()
   3514 <							*E1056* *E1059*
   3515 			When ": {return-type}" is specified, {return-type}
   3516 			cannot be omitted (leaving a hanging colon).  The ": "
   3517 			also cannot be preceded by white space.  Examples:
   3518 >vim
   3519 			  def F_1056():
   3520 			  # E1056: Expected a type:
   3521 			  enddef
   3522 			  def F_1059() : bool
   3523 			  # E1059: No white space allowed before colon: ... 
   3524 			  enddef
   3525 <
   3526 			The function will be compiled into instructions when
   3527 			called or when either `:defcompile` or `:disassemble` is
   3528 			used.  (For an example, see |:disassemble|.)  Syntax
   3529 			and type errors will be produced at that time.
   3530 
   3531 							*E1058*
   3532 			It is possible to nest `:def` inside another `:def` or
   3533 			`:function` only up to 49 levels deep.  At 50 or more
   3534 			levels, it is a |E1058| error.
   3535 
   3536 							*E1117*
   3537 			[!] is allowed only in legacy Vim script because it
   3538 			permits function redefinition (as with `:function`!).
   3539 			In Vim9 script, ! is not allowed because script-local
   3540 			functions cannot be deleted or redefined, though they
   3541 			can be removed by reloading the script.  Also, nested
   3542 			functions cannot use ! for redefinition.  Examples:
   3543 >vim
   3544 			  " Legacy Vim script :def! example
   3545 			  def! LegacyFunc()
   3546 			    echo "def! is allowed in a legacy Vim script"
   3547 			  enddef
   3548 			  call LegacyFunc()
   3549 < >vim9
   3550 			  vim9script
   3551 			  def F1117()
   3552 			    def! InnerFunc()
   3553 			      # E1117: Cannot use ! with nested :def
   3554 			    enddef
   3555 			  enddef
   3556 			  F1117()
   3557 < >vim9
   3558 			  vim9script
   3559 			  def! F_477(): void  # E477: No ! allowed
   3560 			  enddef
   3561 < >vim9
   3562 			  vim9script
   3563 			  def F_1084(): void
   3564 			  enddef
   3565 			  delfunction! F_1084
   3566 			  # E1084: Cannot delete Vim9 script function F_1084
   3567 <
   3568 			Note: The generic error *E1028* ("Compiling :def
   3569 			function failed") indicates an undeterminable error
   3570 			during compilation.  If reproducible, it may be
   3571 			reported at https://github.com/vim/vim/issues as
   3572 			it could represent a gap in Vim's error reporting.
   3573 
   3574 							*:enddef*
   3575 							*E1057* *E1152* *E1173*
   3576 :enddef			End of a function defined with `:def`.  It should be on
   3577 			a line by itself.  Examples:
   3578 >vim9
   3579 			  vim9script
   3580 			  def MyFunc()
   3581 			  echo 'Do Something' | enddef
   3582 			  # E1057: Missing :enddef
   3583 < >vim9
   3584 			  vim9script
   3585 			  def F_1173()
   3586 			  enddef echo 'X'
   3587 			  # E1173: Text found after enddef: echo 'X'
   3588 < >vim9
   3589 			  vim9script
   3590 			  def F_1152()
   3591 			    function X()
   3592 			    enddef  # E1152: Mismatched enddef
   3593 			  enddef
   3594 <
   3595 You may also find this wiki useful.  It was written by an early adopter of
   3596 Vim9 script: https://github.com/lacygoill/wiki/blob/master/vim/vim9.md
   3597 
   3598 							*vim9-s:var*
   3599 When referencing a script-local variable, the context determines whether using
   3600 the "s:" prefix is either mandatory, optional, or gives |E1268|.  The context
   3601 factors are whether the script version is Vim9 script or legacy Vim script and
   3602 whether the reference is at the script-local level, within a `:def` function,
   3603 or within a `:function`.  The three rules are:
   3604 
   3605  1. In a `:function`, "s:" is always mandatory.  This is regardless of the
   3606     script type or the function's parent context (such as nested within
   3607     another function).  Similarly, "s:" is also mandatory in the script-local
   3608     scope of a legacy Vim script.
   3609  2. In a Vim9 script, "s:" always gives |E1268| when used in a `:def` function,
   3610     regardless of the function's parent context.  Similarly, it gives E1268 in
   3611     the script-local scope of a Vim9 script.
   3612  3. In a legacy Vim script, "s:" is optional in a `:def` function, regardless
   3613     of the function's parent context.
   3614 
   3615 The following three scripts demonstrate these rules:
   3616 >vim
   3617 	" 1. In a :function, "s:" is always mandatory.  It is also mandatory
   3618 	" in a legacy Vim script's script-local scope
   3619 	let s:MyVar = v:true
   3620 	echo s:MyVar		| " v:true
   3621 	" echo MyVar		  (Would give E121: Undefined variable: MyVar)
   3622 	vim9cmd echo MyVar	  # true
   3623 	function! MyFunc()
   3624 	  echo s:MyVar		| " v:true
   3625 	  " echo MyVar		  (Would give E121: Undefined variable: MyVar)
   3626 	  vim9cmd echo MyVar	  # true
   3627 	endfunction
   3628 	call MyFunc()
   3629 < >vim9
   3630 	vim9script
   3631 	# 2. In a Vim9 script, "s:" gives E1268 when used in any :def function
   3632 	# and in the script-local scope
   3633 	var MyVar: bool = true
   3634 	echo MyVar		  # true
   3635 	# echo s:MyVar		  (Would give E1268: Cannot use s: in Vim9...)
   3636 	legacy echo s:MyVar	| # v:true
   3637 	def MyFunc()
   3638 	  echo MyVar		# true
   3639 	  # echo s:MyVar	  (Would give E1268: Cannot use s: in Vim9...)
   3640 	  legacy echo s:MyVar	| # v:true
   3641 	enddef
   3642 	MyFunc()
   3643 < >vim
   3644 	" 3. In a legacy Vim script, "s:" is optional in a :def function
   3645 	let s:MyVar = v:true
   3646 	function! Outer()
   3647 	  def! MyFunc()
   3648 	    echo MyVar		# true
   3649 	    echo s:MyVar	# true
   3650 	  enddef
   3651 	  call MyFunc()
   3652 	endfunction
   3653 	call Outer()
   3654 <
   3655 Using |exists()|, which is evaluated at runtime, cannot be used conditionally
   3656 to skip undeclared variables, though |exists_compiled()|, which is evaluated at
   3657 compile time, may be used.  For example:
   3658 >vim9
   3659 	vim9script
   3660 	def MyDef()
   3661 	  if exists_compiled('MyVar')	# evaluated at compile time
   3662 	    echo $"MyVar = {MyVar}"	# MyVar = 1
   3663 	  endif
   3664 	  if exists_compiled('MyVar2')	# evaluated at compile time
   3665 	    echo $"MyVar2 = {MyVar2}"	# not reached
   3666 	  else
   3667 	    echo "MyVar2 does not exist at compile time"
   3668 	  endif
   3669 	  if exists('MyVar')		# evaluated at runtime
   3670 	    echo $"MyVar = {MyVar}"	# MyVar = 1
   3671 	  endif
   3672 	  if exists('MyVar2')		# evaluated at runtime
   3673 	    # The following would give E1001: Variable not found: MyVar2
   3674 	    # echo MyVar2
   3675 	  else
   3676 	    echo "MyVar2 does not exist at runtime"
   3677 	  endif
   3678 	enddef
   3679 	var MyVar: number = 1	# Declared before MyDef() is compiled
   3680 	MyDef()
   3681 	var MyVar2: number = 2	# Declared after MyDef() is compiled
   3682 <
   3683 							*E1269*
   3684 Script-local variables in a Vim9 script must be declared at the script
   3685 level.  They cannot be created in a `:def` function and may not be declared
   3686 in a legacy function with the "s:" prefix.  For example:
   3687 >vim9
   3688 	vim9script
   3689 	function F_1269()
   3690 	  let s:i_wish = v:true
   3691 	endfunction
   3692 	F_1269()
   3693 	# E1269: Cannot create a Vim9 script variable in a function: s:i_wish
   3694 <
   3695 							*:defc* *:defcompile*
   3696 :defc[ompile]		Compile functions and classes (|class-compile|)
   3697 			defined in the current script that were not compiled
   3698 			yet.  This will report any errors found during
   3699 			compilation.
   3700 
   3701 			Example: When the three lines (up to and including
   3702 			`enddef`) are sourced, there is no error because the
   3703 			Vim9 `:def` function is not compiled.  However, if all
   3704 			four lines are sourced, compilation fails:
   3705 >vim9
   3706 			  vim9script
   3707 			  def F_1027(): string
   3708 			  enddef
   3709 			  defcompile F_1027  # E1027: Missing return statement
   3710 <
   3711 :defc[ompile] MyClass	Compile all methods in a class.  (See |:disassemble|
   3712 			for an example.)
   3713 
   3714 :defc[ompile] {func}
   3715 :defc[ompile] debug {func}
   3716 :defc[ompile] profile {func}
   3717 			Compile function {func}, if needed.  Use "debug" and
   3718 			"profile" to specify the compilation mode.
   3719 			This will report any errors found during compilation.
   3720 			{func} can also be "ClassName.functionName" to
   3721 			compile a function or method in a class.
   3722 			{func} can also be "ClassName" to compile all
   3723 			functions and methods in a class.
   3724 
   3725 							*:disa* *:disassemble*
   3726 :disa[ssemble] {func}	Show the instructions generated for {func}.
   3727 			This is for debugging and testing.
   3728 			If {func} is not found, error *E1061* occurs.
   3729 			{func} can also be "ClassName.functionName" to
   3730 			disassemble a function in a class.
   3731 			The following example demonstrates using `:defcompile`
   3732 			with a |class| and `:disassemble` with a
   3733 			"ClassName.functionName" (positioning the cursor on
   3734 			the last line of the visually sourced script):
   3735 >vim9
   3736 			  vim9script
   3737 			  class Line
   3738 			    var lnum: number
   3739 			    def new(this.lnum)
   3740 			    enddef
   3741 			    def SetLnum()
   3742 			      cursor(this.lnum, 52)
   3743 			    enddef
   3744 			  endclass
   3745 			  defcompile Line
   3746 			  disassemble Line.SetLnum
   3747 			  var vlast: Line = Line.new(line("'>"))
   3748 			  vlast.SetLnum()	# Cursor is positioned here->_
   3749 <
   3750 :disa[ssemble] profile {func}
   3751 			Like `:disassemble` but with the instructions used for
   3752 			profiling.
   3753 
   3754 :disa[ssemble] debug {func}
   3755 			Like `:disassemble` but with the instructions used for
   3756 			debugging.
   3757 
   3758 	Note: For command line completion of {func}, script-local functions
   3759 	are shown with their <SNR>.  Depending on options, including
   3760 	|wildmenumode()|, completion may work with "s:", "<S", or the function
   3761 	name directly.  (For example, in Vim started with |-u| NONE,
   3762 	":disa s:" and |c_CTRL-E| lists script-local function names.)
   3763 
   3764 
   3765 Limitations ~
   3766 
   3767 Variables local to `:def` functions are not visible to string evaluation.
   3768 The following example shows that the script-local constant "SCRIPT_LOCAL" is
   3769 visible whereas the function-local constant "DEF_LOCAL" is not:
   3770 >vim9
   3771 	vim9script
   3772 	const SCRIPT_LOCAL = ['A', 'script-local', 'list']
   3773 	def MapList(scope: string): list<string>
   3774 	  const DEF_LOCAL: list<string> = ['A', 'def-local', 'list']
   3775 	  if scope == 'script-local'
   3776 	    return [1]->map('SCRIPT_LOCAL[v:val]')
   3777 	  else
   3778 	    return [1]->map('DEF_LOCAL[v:val]')
   3779 	  endif
   3780 	enddef
   3781 	echo 'script-local'->MapList()	# ['script-local']
   3782 	echo 'def-local'->MapList()	# E121: Undefined variable: DEF_LOCAL
   3783 <
   3784 The map argument is a string expression, which is evaluated without the
   3785 function scope.  Instead, in Vim9 script, use a lambda:
   3786 >vim9
   3787 	vim9script
   3788 	def MapList(): list<string>
   3789 	  const DEF_LOCAL: list<string> = ['A', 'def-local', 'list']
   3790 	  return [1]->map((_, v): string => DEF_LOCAL[v])
   3791 	enddef
   3792 	echo MapList()			# ['def-local']
   3793 <
   3794 For commands that are not compiled, such as `:edit`, |backtick-expansion| can
   3795 be used and it can use the local scope.  Example:
   3796 >vim9
   3797 	vim9script
   3798 	def EditNewBlah()
   3799 	  var fname: string = 'blah.txt'
   3800 	  split
   3801 	  edit `=fname`
   3802 	enddef
   3803 	EditNewBlah()  # A new split is created as buffer 'blah.txt'
   3804 <
   3805 							*vim9-closure*
   3806 Closures defined in a loop can either share a variable or each have their own
   3807 copy, depending on where the variable is declared.  With a variable declared
   3808 outside the loop, all closures reference the same shared variable.
   3809 The following example demonstrates the consequences, with the "outloop"
   3810 variable existing only once:
   3811 >vim9
   3812 	vim9script
   3813 	var flist: list<func>
   3814 	def ClosureEg(n: number): void
   3815 	  var outloop: number = 0  # outloop is declared outside the loop!
   3816 	  for i in range(n)
   3817 	    outloop = i
   3818 	    flist[i] = (): number => outloop  # Closures ref the same var
   3819 	  endfor
   3820 	  echo range(n)->map((i, _): number => flist[i]())
   3821 	enddef
   3822 	ClosureEg(4)	# [3, 3, 3, 3]
   3823 <
   3824 All closures put in the list refer to the same instance, which, in the end,
   3825 is 3.
   3826 
   3827 However, when the variable is declared inside the loop, each closure gets its
   3828 own copy, as shown in this example:
   3829 >vim9
   3830 	vim9script
   3831 	var flist: list<func>
   3832 	def ClosureEg(n: number): void
   3833 	  for i in range(n)
   3834 	    var inloop: number = i  # inloop is declared inside the loop
   3835 	    flist[i] = (): number => inloop  # Closures ref each inloop
   3836 	  endfor
   3837 	  echo range(n)->map((i, _): number => flist[i]())
   3838 	enddef
   3839 	ClosureEg(4)	# [0, 1, 2, 3]
   3840 <
   3841 Another way to have a separate context for each closure is to call a
   3842 function to define it:
   3843 >vim9
   3844 	vim9script
   3845 	def GetClosure(i: number): func
   3846 	  var infunc: number = i
   3847 	  return (): number => infunc
   3848 	enddef
   3849 	var flist: list<func>
   3850 	def ClosureEg(n: number): void
   3851 	  for i in range(n)
   3852 	    flist[i] = GetClosure(i)
   3853 	  endfor
   3854 	  echo range(n)->map((i, _): number => flist[i]())
   3855 	enddef
   3856 	ClosureEg(4)	# [0, 1, 2, 3]
   3857 <							*E1271*
   3858 A closure must be compiled in the context that it is defined in, so that
   3859 variables in that context can be found.  This mostly happens correctly,
   3860 except when a function is marked for debugging with `:breakadd` after it was
   3861 compiled.  Make sure to define the breakpoint before compiling the outer
   3862 function.
   3863 							*E1248*
   3864 In some situations, such as when a Vim9 closure which captures local variables
   3865 is converted to a string and then executed, an error occurs.  This happens
   3866 because the string execution context cannot access the local variables from
   3867 the original context where the closure was defined.  For example:
   3868 >vim9
   3869 	vim9script
   3870 	def F_1248(): void
   3871 	  var n: number
   3872 	  var F: func = () => {
   3873 	    n += 1
   3874 	  }
   3875 	  try
   3876 	    execute printf("call %s()", F)
   3877 	  catch
   3878 	    echo v:exception
   3879 	  endtry
   3880 	enddef
   3881 	F_1248()  # Vim(call):E1248: Closure called from invalid context
   3882 <
   3883 In Vim9 script, a loop variable is invalid after the loop is closed.
   3884 For example, this timer will echo 0 to 2 on separate lines.  However, if
   3885 the variable "n" is used after the `:endfor`, that is an |E121| error:
   3886 >vim9
   3887 	vim9script
   3888 	for n in range(3)
   3889 	  var nr: number = n
   3890 	  timer_start(1000 * n, (_) => {
   3891 	    echowindow nr
   3892 	  })
   3893 	endfor
   3894 	try
   3895 	  echowindow n
   3896 	catch
   3897 	  echo v:exception
   3898 	endtry
   3899 <
   3900 	Note: Using `:echowindow` is useful in a timer because messages go
   3901 	into a popup and will not interfere with what the user is doing when
   3902 	it triggers.
   3903 
   3904 
   3905 Converting a :function to a :def~
   3906 					*convert_legacy_function_to_vim9*
   3907 					*convert_:function_to_:def*
   3908 There are many changes that need to be made to convert a `:function` to
   3909 a `:def` function.  The following are some of them:
   3910 
   3911 - Change `let` used to declare variables to one of `var`, `const`, or `final`,
   3912   and remove the "s:" from each |script-variable|.
   3913 - Change `func` or `function` to `def`.
   3914 - Change `endfunc` or `endfunction` to `enddef`.
   3915 - Add the applicable type (or "any") to each function argument.
   3916 - Remove "a:" from each |function-argument|.
   3917 - Remove inapplicable options such as |:func-range|, |:func-abort|,
   3918   |:func-dict|, and |:func-closure|.
   3919 - If the function returns something, add the return type.  (Ideally, add
   3920   "void" if it does not return anything.)
   3921 - Remove line continuation backslashes from places they are not required.
   3922 - Remove `let` for assigning values to global (|g:|), buffer (|b:|),
   3923   window (|w:|), tab (|t:|), and local (|l:|) variables.
   3924 - Rewrite |lambda| expressions in Vim9 script syntax (see |vim9-lambda|).
   3925 - Change comments to start with # (preceded by white space) instead of ".
   3926 - Insert white space in expressions where required (see |vim9-white-space|).
   3927 - Change "." used for string concatenation to " .. ".  (Alternatively, use
   3928   an |interpolated-string|.)
   3929 
   3930 The following legacy Vim script and Vim9 script examples demonstrate all
   3931 those differences.  First, legacy Vim script:
   3932 >vim
   3933 	let s:lnum=0
   3934 	function Leg8(arg) abort
   3935 	  let l:pre=['Result',
   3936 	    \': ']
   3937 	  let b:arg=a:arg
   3938 	  let s:lnum+=2
   3939 	  let b:arg*=4
   3940 	  let l:result={pre->join(pre,'')}(l:pre)
   3941 	  return l:result.(b:arg+s:lnum)"no space before comment
   3942 	endfunction
   3943 	call Leg8(10)->popup_notification(#{time: 3000})" Pops up 'Result: 42'
   3944 <
   3945 The equivalent in Vim9 script:
   3946 >vim9
   3947 	vim9script
   3948 	var lnum: number
   3949 	def Vim9(arg: number): string
   3950 	  final pre = ['Result',
   3951 	    ': ']
   3952 	  b:arg = arg
   3953 	  lnum += 2
   3954 	  b:arg *= 4
   3955 	  const RESULT: string = ((lpre) => join(lpre, ''))(pre)
   3956 	  return RESULT .. (b:arg + lnum)  # space required before # comment
   3957 	enddef
   3958 	Vim9(10)->popup_notification({time: 3000})  # Pops up 'Result: 42'
   3959 <
   3960 	Note: This example also demonstrates (outside the `:def` function):
   3961 	- Removing "#" from the legacy |#{}| - see |vim9-literal-dict|, and
   3962 	- Omitting `:call` (allowed, though unnecessary in Vim9 script)
   3963 
   3964 
   3965 Calling a :def function in an expr option ~
   3966 							*expr-option-function*
   3967 The value of a few options, such as 'foldexpr', is an expression that is
   3968 evaluated to get a value.  The evaluation can have quite a bit of overhead.
   3969 One way to minimize the overhead, and also to keep the option value simple,
   3970 is to define a compiled function and set the option to call it without
   3971 arguments.  For example:
   3972 >vim9
   3973 	vim9script
   3974 	def MyFoldFunc(): string
   3975 	  # This matches start of line (^), followed by a digit, a full stop
   3976 	  # a space or tab, an uppercase character, with an empty next line
   3977 	  return getline(v:lnum) =~ '^[[:digit:]]\.[[:blank:]][[:upper:]]'
   3978 	    && getline(v:lnum + 1)->empty() ? '>1' : '1'
   3979 	enddef
   3980 	set foldexpr=MyFoldFunc()
   3981 	set foldmethod=expr
   3982 	normal! zM
   3983 <
   3984 Warning: This script creates and applies folds at the "Heading 1" level of
   3985 this vim9.txt help buffer.  (You can use |zR|, in Normal mode, to open all the
   3986 folds after sourcing the script.)
   3987 
   3988 
   3989 ==============================================================================
   3990 
   3991 4. Types						*vim9-types*
   3992 
   3993 The following types, each shown with its corresponding internal |v:t_TYPE|
   3994 variable, are supported:
   3995 
   3996 	number				|v:t_number|
   3997 	string				|v:t_string|
   3998 	func				|v:t_func|
   3999 	func: {type}			|v:t_func|
   4000 	func({type}, ...)		|v:t_func|
   4001 	func({type}, ...): {type}	|v:t_func|
   4002 	list<{type}>			|v:t_list|
   4003 	dict<{type}>			|v:t_dict|
   4004 	float				|v:t_float|
   4005 	bool				|v:t_bool|
   4006 	none				|v:t_none|
   4007 	job				|v:t_job|
   4008 	channel				|v:t_channel|
   4009 	blob				|v:t_blob|
   4010 	class				|v:t_class|
   4011 	object				|v:t_object|
   4012 	typealias			|v:t_typealias|
   4013 	enum				|v:t_enum|
   4014 	enumvalue			|v:t_enumvalue|
   4015 	tuple<{type}>			|v:t_tuple|
   4016 	tuple<{type}, {type}, ...>	|v:t_tuple|
   4017 	tuple<...list<{type}>>		|v:t_tuple|
   4018 	tuple<{type}, ...list<{type}>>	|v:t_tuple|
   4019 	void
   4020 
   4021 							*E1031* *E1186*
   4022 These types can be used in declarations, though no simple value can have the
   4023 "void" type.  Trying to use a void as a value results in an error.
   4024 Examples:
   4025 >vim9
   4026 	vim9script
   4027 	def NoReturnValue(): void
   4028 	enddef
   4029 	try
   4030 	  const X: any = NoReturnValue()
   4031 	catch
   4032 	  echo v:exception  # E1031: Cannot use void value
   4033 	  try
   4034 	    echo NoReturnValue()
   4035 	  catch
   4036 	    echo v:exception  # E1186: Expression does not result in a valu...
   4037 	  endtry
   4038 	endtry
   4039 <						*E1008* *E1009* *E1010* *E1012*
   4040 Ill-formed declarations and mismatching types result in errors.  The following
   4041 are examples of errors E1008, E1009, E1010, and E1012:
   4042 >vim9
   4043 	vim9cmd var l_1008: list
   4044 	vim9cmd var l_1009: list<number
   4045 	vim9cmd var l_1010: list<invalidtype>
   4046 	vim9cmd var l_1012: list<number> = ['42']
   4047 <
   4048 There is no array type.  Instead, use either a list or a tuple.  Those types
   4049 may also be literals (constants).  In the following example, [5, 6] is a list
   4050 literal and (7, ) a tuple literal.  The echoed list is a list literal too:
   4051 >vim9
   4052 	vim9script
   4053 	var l: list<number> = [1, 2]
   4054 	var t: tuple<...list<number>> = (3, 4)
   4055 	echo [l, t, [5, 6], (7, )]
   4056 <
   4057 							*tuple-type*
   4058 A tuple type may be declared in the following ways:
   4059 tuple<number>			a tuple with a single item of type |Number|
   4060 tuple<number, string>		a tuple with two items of type |Number| and
   4061 				|String|
   4062 tuple<number, float, bool>	a tuple with three items of type |Number|,
   4063 				|Float| and |Boolean|
   4064 tuple<...list<number>>		a variadic tuple with zero or more items of
   4065 				type |Number|
   4066 tuple<number, ...list<string>>	a tuple with an item of type |Number| followed
   4067 				by zero or more items of type |String|
   4068 
   4069 Examples:
   4070 >vim9
   4071 	vim9script
   4072 	var t1: tuple<number> = (20,)
   4073 	var t2: tuple<number, string> = (30, 'vim')
   4074 	var t3: tuple<number, float, bool> = (40, 1.1, true)
   4075 	var t4: tuple<...list<string>> = ('a', 'b', 'c')
   4076 	var t5: tuple<number, ...list<string>> = (3, 'a', 'b', 'c', 'd')
   4077 <
   4078 							*variadic-tuple* *E1539*
   4079 A variadic tuple has zero or more items of the same type.  The type of a
   4080 variadic tuple must end with a list type otherwise E1539 is given.  Examples:
   4081 >vim9
   4082 	vim9script
   4083 	var t6: tuple<...list<number>> = (1, 2, 3)
   4084 	var t7: tuple<...list<string>> = ('a', 'b', 'c')
   4085 	var t8: tuple<...list<bool>> = ()
   4086 	var tE: tuple<...any> = () # E1539: Variadic tuple must end with li...
   4087 <
   4088 						*vim9-func-declaration*
   4089 						*vim9-partial-declaration*
   4090 						*vim9-func-type*
   4091 A function (or partial) may be declared in many ways, including:
   4092 >
   4093 	func
   4094 	func: void
   4095 	func: {type}
   4096 	func()[: void]
   4097 	func(): {type}
   4098 	func({type})[: void]
   4099 	func({type}): {type}
   4100 	func(?{type})[: void]
   4101 	func(?{type}): {type}
   4102 	func(...list<{type}>)[: void]
   4103 	func(...list<{type}>): {type}
   4104 	func({type}, ...list<{type}>)[: void]
   4105 	func({type}, ...list<{type}>): {type}
   4106 <
   4107 If the return type is "void", the function does not return a value.  All the
   4108 ways listed above are explained and demonstrated in the following examples,
   4109 all of which echo '9'.
   4110 
   4111 func
   4112 		- any kind of function reference
   4113 		- any type of return value or no return value
   4114 >vim9
   4115 		vim9script
   4116 		const I = (n) => n + 1
   4117 		const F: func = I->function()
   4118 		echo F(8)
   4119 <
   4120 func: void
   4121 		- any number and type of arguments
   4122 		- does not return a value
   4123 >vim9
   4124 		vim9script
   4125 		def I(n: number): void
   4126 		  echo n + 1
   4127 		enddef
   4128 		const F: func: void = I->function()
   4129 		F(8)
   4130 <
   4131 func: {type}
   4132 		- any number and type of arguments
   4133 		- returns a typed value
   4134 >vim9
   4135 		vim9script
   4136 		const I = (n): number => n + 1
   4137 		const F: func: number = I->function()
   4138 		echo F(8)
   4139 <
   4140 func()[: void]
   4141 		- no arguments
   4142 		- does not return a value
   4143 >vim9
   4144 		vim9script
   4145 		var n: number = 8
   4146 		def I(): void
   4147 		  echo n + 1
   4148 		enddef
   4149 		const F: func(): void = I->function()
   4150 		F()
   4151 <
   4152 func(): {type}
   4153 		- no arguments
   4154 		- returns a typed value
   4155 >vim9
   4156 		vim9script
   4157 		var n: number = 8
   4158 		def I(): number
   4159 		  return n + 1
   4160 		enddef
   4161 		const F: func(): number = I->function()
   4162 		echo F()
   4163 <
   4164 func({type})[: void]
   4165 		- typed argument
   4166 		- does not return a value
   4167 >vim9
   4168 		vim9script
   4169 		def I(n: number): void
   4170 		  echo n + 1
   4171 		enddef
   4172 		const F: func(number): void = I->function()
   4173 		F(8)
   4174 <
   4175 func({type}): {type}
   4176 		- typed argument
   4177 		- returns a typed value
   4178 >vim9
   4179 		vim9script
   4180 		const I = (n: number): number => n + 1
   4181 		const F: func(number): number = I->function()
   4182 		echo F(8)
   4183 <
   4184 func(?{type})[: void]
   4185 		- optional typed argument
   4186 		- does not return a value
   4187 >vim9
   4188 		vim9script
   4189 		def I(n: number = 8): void
   4190 		  echo n + 1
   4191 		enddef
   4192 		const F: func(?number): void = I->function()
   4193 		F()
   4194 <
   4195 func(?{type}): {type}
   4196 		- optional typed argument
   4197 		- returns a typed value
   4198 >vim9
   4199 		vim9script
   4200 		def I(n: number = 8): number
   4201 		  return n + 1
   4202 		enddef
   4203 		const F: func(?number): number = I->function()
   4204 		echo F()
   4205 <
   4206 func(...list<{type}>)[: void]
   4207 		- typed list for variable number of arguments
   4208 		- does not return a value
   4209 >vim9
   4210 		vim9script
   4211 		def L(...l: list<number>): void
   4212 		  echo l->reduce((x, y) => x + y)
   4213 		enddef
   4214 		const F: func(...list<number>): void = L->function()
   4215 		F(8, 0, 0, 1)
   4216 <
   4217 func(...list<{type}>): {type}
   4218 		- typed list for variable number of arguments
   4219 		- returns a typed value
   4220 >vim9
   4221 		vim9script
   4222 		def L(...l: list<number>): number
   4223 		  return l->reduce((x, y) => x + y)
   4224 		enddef
   4225 		const F: func(...list<number>): number = L->function()
   4226 		echo F(8, 0, 0, 1)
   4227 <
   4228 func({type}, ...list<{type}>)[: void]
   4229 		- typed mandatory argument
   4230 		- typed list for variable number of arguments
   4231 		- does not return a value
   4232 >vim9
   4233 		vim9script
   4234 		def D(a: float, ...l: list<number>): void
   4235 		  echo (a + l->reduce((x, y) => x + y))->float2nr()
   4236 		enddef
   4237 		const F: func(float, ...list<number>): void = D->function()
   4238 		F(8.0, 0, 0, 1)
   4239 <
   4240 func({type}, ...list<{type}>): {type}
   4241 		- typed mandatory argument
   4242 		- typed list for variable number of arguments
   4243 		- returns a typed value
   4244 >vim9
   4245 		vim9script
   4246 		def D(a: float, ...l: list<number>): number
   4247 		  return (a + l->reduce((x, y) => x + y))->float2nr()
   4248 		enddef
   4249 		const F: func(float, ...list<number>): number = D->function()
   4250 		echo F(8.0, 0, 0, 1)
   4251 <
   4252 The reference can also be a |Partial|, in which case it stores extra arguments
   4253 and/or a dictionary, which are not visible to the caller.  Since they are
   4254 called in the same way, the declaration is the same.  This interactive example
   4255 prompts for a circle's radius and returns its area using a partial:
   4256 >vim9
   4257 	vim9script
   4258 	def CircleArea(pi: float, radius: float): float
   4259 	  return pi * radius->pow(2)
   4260 	enddef
   4261 	const AREA: func(float): float = CircleArea->function([3.14])
   4262 	const RADIUS: float = "Enter a radius value: "->input()->str2float()
   4263 	echo $"\nThe area of a circle with a radius of {RADIUS} is " ..
   4264 	  $"{AREA(RADIUS)} (π to two d.p.)"
   4265 <
   4266 							*E1005*
   4267 No more than 19 argument types may be used in a Funcref (one less than what is
   4268 allowed in a function, including a `:def` or lambda - see |E740|).  Twenty or
   4269 more argument types gives E1005, as this example shows:
   4270 >vim9
   4271 	vim9script
   4272 	var X: func
   4273 	X = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) => 0
   4274 	var F: func(any, any, any, any, any, any, any, any, any, any, any,
   4275 	  \ any, any, any, any, any, any, any, any, any): any = X->function()
   4276 	# E1005: Too many argument types
   4277 <
   4278 							*E1007*
   4279 A mandatory argument may not come after an optional argument in a Funcref:
   4280 >vim9
   4281 	vim9script
   4282 	def I(n: number, f: float): void
   4283 	  echo n + f
   4284 	enddef
   4285 	const F: func(?number, float) = I->function()
   4286 	# E1007: Mandatory argument after optional argument
   4287 <
   4288 							*vim9-typealias-type*
   4289 Custom types (|typealias|) can be defined with `:type`.  They must start with
   4290 a capital letter (which avoids name clashes with either current or future
   4291 builtin types) similar to user functions.  This example creates a list of
   4292 perfect squares, reporting on |type()| (14, a typealias) and the |typename()|:
   4293 >vim9
   4294 	vim9script
   4295 	type Ln = list<number>
   4296 	final perfect_squares: Ln = [1, 4, 9, 16, 25]
   4297 	echo "Typename (Ln): " ..
   4298 	  $"type() is {Ln->type()} and typename() is {Ln->typename()}"
   4299 <
   4300 							*E1105*
   4301 A typealias itself cannot be converted to a string:
   4302 >vim9
   4303 	vim9script
   4304 	type Ln = list<number>
   4305 	const FAILS: func = (): string => {
   4306 	  echo $"{Ln}"  # E1105: Cannot convert typealias to string
   4307 	}
   4308 <				    *vim9-class-type*  *vim9-interface-type*
   4309 				    *vim9-object-type*
   4310 A |class|, |object|, and |interface| may all be used as types.  The following
   4311 interactive example prompts for a float value and returns the area of two
   4312 different shapes.  It also reports on the |type()| and |typename()| of the
   4313 classes, objects, and interface:
   4314 >vim9
   4315 	vim9script
   4316 	interface Shape
   4317 	  def InfoArea(): tuple<string, float>
   4318 	endinterface
   4319 	class Circle implements Shape
   4320 	  var radius: float
   4321 	  def InfoArea(): tuple<string, float>
   4322 	    return ('Circle (π × r²)', 3.141593 * this.radius->pow(2))
   4323 	  enddef
   4324 	endclass
   4325 	class Square implements Shape
   4326 	  var side: float
   4327 	  def InfoArea(): tuple<string, float>
   4328 	    return ('Square (s²)', this.side->pow(2))
   4329 	  enddef
   4330 	endclass
   4331 	const INPUT: float = "Enter a float value: "->input()->str2float()
   4332 	echo "\nAreas of shapes:"
   4333 	var myCircle: object<Circle> = Circle.new(INPUT)
   4334 	var mySquare: object<Square> = Square.new(INPUT)
   4335 	final shapes: list<Shape> = [myCircle, mySquare]
   4336 	for shape in shapes
   4337 	  const [N: string, A: float] = shape.InfoArea()
   4338 	  echo $"\t- {N} has area of {A}"
   4339 	endfor
   4340 	echo "\n\t\ttype()\ttypename()\n\t\t------\t----------"
   4341 	echo $"Circle\t\t{Circle->type()}\t{Circle->typename()}"
   4342 	echo $"Square\t\t{Square->type()}\t{Square->typename()}"
   4343 	echo $"Shape\t\t{Shape->type()}\t{Shape->typename()}"
   4344 	echo $"MyCircle\t{myCircle->type()}\t{myCircle->typename()}"
   4345 	echo $"MySquare\t{mySquare->type()}\t{mySquare->typename()}"
   4346 	echo $"shapes\t\t{shapes->type()}\t{shapes->typename()}"
   4347 <
   4348 					*vim9-enum-type*  *vim9-enumvalue-type*
   4349 An |enum| may be used as a type (|v:t_enum|).  Variables holding enum values
   4350 have the enumvalue type (|v:t_enumvalue|) at runtime.  The following
   4351 interactive example prompts for a character and returns information about
   4352 either a square or a rhombus.  It also reports on the |type()| and the
   4353 |typename()| of the enum and enumvalue:
   4354 >vim9
   4355 	vim9script
   4356 	enum Quad
   4357 	  Square('four', 'only'),
   4358 	  Rhombus('opposite', 'no')
   4359 	  var eq: string
   4360 	  var ra: string
   4361 	  def string(): string
   4362 	    return $"\nA {this.name} has " ..
   4363 	      $"{this.eq} equal sides and {this.ra} right angles\n\n"
   4364 	  enddef
   4365 	endenum
   4366 	echo "Rhombus (r) or Square (s)?"
   4367 	var myQuad: Quad = getcharstr() =~ '\c^R' ? Quad.Rhombus : Quad.Square
   4368 	echo myQuad.string() .. "\ttype()\ttypename()"
   4369 	echo $"Quad  \t{Quad->type()}  \t{Quad->typename()}"
   4370 	echo $"myQuad\t{myQuad->type()}\t{myQuad->typename()}"
   4371 <
   4372 	Notes: This uses builtin method "string()" - see |object-string()|.
   4373 	The typename() of Quad and myQuad are the same ("enum<Quad>") whereas
   4374 	the type() is distinguished (myQuad returns 16, which is an EnumValue,
   4375 	whereas Quad returns 15, which is an Enum).
   4376 
   4377 Variable types and type casting	~
   4378 							*variable-types*
   4379 Variables declared in Vim9 script or in a `:def` function have a type, either
   4380 specified explicitly or inferred from the initialization.
   4381 
   4382 Global, buffer, window and tab page variables do not have a specific type.
   4383 Consequently, their values may change at any time, possibly changing the type.
   4384 Therefore, in compiled code, the "any" type is assumed.
   4385 
   4386 This can be a problem when stricter typing is desired, for example, when
   4387 declaring a list: >
   4388 	var l: list<number> = [1, b:two]
   4389 Since Vim doesn't know the type of "b:two", the expression becomes list<any>.
   4390 A runtime check verifies the list matches the declared type before assignment.
   4391 
   4392 							*type-casting*
   4393 To get more specific type checking, use type casting.  This checks the
   4394 variable's type before building the list, rather than checking whether
   4395 list items match the declared type.  For example: >
   4396 	var l: list<number> = [1, <number>b:two]
   4397 <
   4398 So, here the type cast checks whether "b:two" is a number and gives an error
   4399 if it isn't.
   4400 
   4401 The difference is demonstrated in the following example.  With funcref
   4402 variable "NTC", Vim infers the expression type "[1, b:two]" as list<any>, then
   4403 verifies whether it can be assigned to the list<number> return type.  With
   4404 funcref variable "TC", the type cast means Vim first checks whether "b:two" is
   4405 a <number> type:
   4406 >vim9
   4407 	vim9script
   4408 	b:two = '2'
   4409 	const NTC: func = (): list<number> => {
   4410 	  return [1, b:two]
   4411 	}
   4412 	disassemble NTC  # 3 CHECKTYPE list<number> stack [-1]
   4413 	try
   4414 	  NTC()
   4415 	catch
   4416 	  echo v:exception .. "\n\n"  # E1012: Type mismatch; Expected list...
   4417 	endtry
   4418 	const TC: func = (): list<number> => {
   4419 	  return [1, <number>b:two]
   4420 	}
   4421 	disassemble TC  # 2 CHECKTYPE number stack [-1]
   4422 	try
   4423 	  TC()
   4424 	catch
   4425 	  echo v:exception  # E1012: Type mismatch; Expected number but got...
   4426 	endtry
   4427 <
   4428 	Note: Notice how the error messages differ, showing when type checking
   4429 	occurs.
   4430 
   4431 							*E1104*
   4432 The syntax of a type cast is "<{type}>".  An error occurs if either the
   4433 opening "<" (|E121|) or closing ">" (E1104) is omitted.  Also, white space
   4434 is not allowed either after the "<" (|E15|) or before the ">" (|E1068|), which
   4435 avoids ambiguity with smaller-than and greater-than operators.
   4436 
   4437 Although a type casting forces explicit type checking, it neither changes the
   4438 value of, nor the type of, a variable.  If you need to alter the type, use a
   4439 function such as |string()| to convert to a string, or |str2nr()| to convert a
   4440 string to a number.
   4441 
   4442 If type casting is applied to a chained expression, it must be compatible with
   4443 the final result.  Examples:
   4444 >vim9
   4445 	vim9script
   4446 	# These type casts work
   4447 	echo <list<any>>[3, 2, 1]->extend(['Go!'])
   4448 	echo <string>[3, 2, 1]->extend(['Go!'])->string()
   4449 	echo <tuple<...list<number>>>[3, 2, 1]->list2tuple()
   4450 	# This type cast fails
   4451 	echo <number>[3, 2, 1]->extend(['Go!'])->string()
   4452 <
   4453 							*E1272*
   4454 If a type is used in a context where types are not expected you can get
   4455 E1272.  For example: >
   4456 	:vim9cmd echo islocked('x: string')
   4457 <  Note: To see the error, this command must be executed from Vim's command
   4458   line, not sourced.
   4459 
   4460 							*E1363* *E1395*
   4461 If a type is incomplete, such as when an object's class is unknown, E1363
   4462 or E1395 are given.  Examples:
   4463 >vim9
   4464 	vim9script
   4465 	var E1363 = null_class.member	# E1363: Incomplete type
   4466 < >vim9
   4467 	vim9script
   4468 	def F1395(): void
   4469 	  echo null_class.member
   4470 	enddef
   4471 	F1395()  # E1395: Using a null class
   4472 <
   4473 Another null object-related error is |E1360|:
   4474 >vim9
   4475 	vim9script
   4476 	var obj = null_object
   4477 	var E1360 = obj.MyMethod()	# E1360: Using a null object
   4478 <
   4479 
   4480 Type inference ~
   4481 							*type-inference*
   4482 Declaring types explicitly provides many benefits, including targeted type
   4483 checking and clearer error messages.  Nonetheless, Vim often can infer types
   4484 automatically when they are omitted.  For example, each of these variables'
   4485 types are inferred, with the |type()| and |typename()| echoed showing those
   4486 inferred types:
   4487 >vim9
   4488 	vim9script
   4489 	echo "\t type()\t typename()"
   4490 	var b = true   | echo $"{b} \t {b->type()} \t {b->typename()}"
   4491 	var f = 4.2    | echo $"{f} \t {f->type()} \t {f->typename()}"
   4492 	var l = [1, 2] | echo $"{l} \t {l->type()} \t {l->typename()}"
   4493 	var n = 42     | echo $"{n} \t {n->type()} \t {n->typename()}"
   4494 	var s = 'yes'  | echo $"{s} \t {s->type()} \t {s->typename()}"
   4495 	var t = (42, ) | echo $"{t} \t {t->type()} \t {t->typename()}"
   4496 <
   4497 The type of a list, tuple, or dictionary is inferred from the common type of
   4498 its values.  When the values are all the same type, that type is used.
   4499 If there is a mix of types, the "any" type is used.  In the following example,
   4500 the echoed |typename()| for each literal demonstrates these points:
   4501 >vim9
   4502 	vim9script
   4503 	echo [1, 2]->typename()				# list<number>
   4504 	echo [1, 'x']->typename()			# list<any>
   4505 	echo {ints: [1, 2], bools: [false]}->typename()	# dict<list<any>>
   4506 	echo (true, false)->typename()			# tuple<bool, bool>
   4507 <
   4508 The common type of function references, when they do not all have the same
   4509 number of arguments, is indicated with "(...)", meaning the number of
   4510 arguments is unequal.  This script demonstrates a "list<func(...): void>":
   4511 >vim9
   4512 	vim9script
   4513 	def Foo(x: bool): void
   4514 	enddef
   4515 	def Bar(x: bool, y: bool): void
   4516 	enddef
   4517 	var funclist = [Foo, Bar]
   4518 	echo funclist->typename()
   4519 <
   4520 Script-local variables in a Vim9 script are type checked.  The type is
   4521 also checked for variables declared in a legacy function.  For example:
   4522 >vim9
   4523 	vim9script
   4524 	var my_local = (1, 2)
   4525 	function Legacy()
   4526 	  let b:legacy = [1, 2]
   4527 	endfunction
   4528 	Legacy()
   4529 	echo $"{my_local} is type {my_local->type()} ({my_local->typename()})"
   4530 	echo $"{b:legacy} is type {b:legacy->type()} ({b:legacy->typename()})"
   4531 <
   4532 							*E1013*
   4533 When a type is declared for a List, Tuple, or Dictionary, the type is attached
   4534 to it.  Similarly, if a type is not declared, the type Vim infers is attached.
   4535 In either case, if an expression attempts to change the type, E1013 results.
   4536 This example has its type inferred and demonstrates E1013:
   4537 >vim9
   4538 	vim9script
   4539 	var lb = [true, true]	# Two bools, so Vim infers list<bool> type
   4540 	echo lb->typename()	# list<bool>
   4541 	lb->extend([0])		# E1013 Argument 2: type mismatch, ...
   4542 <
   4543 If you want a permissive list, either explicitly use <any> or declare an
   4544 empty list initially (or both, i.e., `list<any> = []`).  Examples:
   4545 >vim9
   4546 	vim9script
   4547 	final la: list<any> = []
   4548 	echo la->extend(['two', 1])
   4549 	final le = []
   4550 	echo le->extend(la)
   4551 <
   4552 Similarly for a permissive dictionary:
   4553 >vim9
   4554 	vim9script
   4555 	final da: dict<any> = {}
   4556 	echo da->extend({2: 2, 1: 'One'})
   4557 	final de = {}
   4558 	echo de->extend(da)->string()
   4559 <
   4560 And, although tuples themselves are immutable, permissive tuple concatenation
   4561 can be achieved with either "any" or an empty tuple:
   4562 >vim9
   4563 	vim9script
   4564 	var t_any: tuple<...list<any>> = (3, '2')
   4565 	t_any = t_any + (true, )
   4566 	echo t_any
   4567 	var t_dec_empty = ()
   4568 	t_dec_empty = t_dec_empty + (3, '2', true)
   4569 	echo t_dec_empty
   4570 <
   4571 If a list literal or dictionary literal is not bound to a variable, its type
   4572 may change, as this example shows:
   4573 >vim9
   4574 	vim9script
   4575 	echo [3, 2, 1]->typename()			# list<number>
   4576 	echo [3, 2, 1]->extend(['Zero'])->typename()	# list<any>
   4577 	echo {1: ['One']}->typename()			# dict<list<string>>
   4578 	echo {1: ['One']}->extend({2: [2]})->typename()	# dict<list<any>>
   4579 <
   4580 
   4581 Stricter type checking ~
   4582 							*type-checking*
   4583 In legacy Vim script, where a number was expected, a string would be
   4584 automatically converted to a number.  This was convenient for an actual number
   4585 such as "123", but leads to unexpected problems (and no error message) if the
   4586 string doesn't start with a number.  Quite often this leads to hard-to-find
   4587 bugs.  For example, in legacy Vim script this echoes "1":
   4588 >vim
   4589 	echo 123 == '123'
   4590 <
   4591 However, if an unintended space is included, "0" is echoed:
   4592 >vim
   4593 	echo 123 == ' 123'
   4594 <
   4595 							*E1206*
   4596 In Vim9 script this has been made stricter.  In most places it works just as
   4597 before if the value used matches the expected type.  For example, in both
   4598 legacy Vim script and Vim9 script trying to use anything other than a
   4599 dictionary when it is required:
   4600 >vim
   4601 	echo [8, 9]->keys()
   4602 	vim9cmd echo [8, 9]->keys()	# E1206: Dictionary required
   4603 <
   4604 							*E1023* *E1024* *E1029*
   4605 							*E1030* *E1174* *E1175*
   4606 							*E1210* *E1212*
   4607 However, sometimes there will be an error in Vim9 script, which breaks
   4608 backwards compatibility.  The following examples illustrate various places
   4609 this happens.  The legacy Vim script behavior, which does not fail, is shown
   4610 first.  It is followed by the error that occurs if the same command is used
   4611 in Vim9 script.
   4612 
   4613 - Using a number (except 0 or 1) where a bool is expected:
   4614 >vim
   4615 	echo v:version ? v:true : v:false
   4616 	vim9cmd echo v:version ? true : false	# E1023: Using a Number as ...
   4617 <
   4618 - Using a number where a string is expected:
   4619 >vim
   4620 	echo filter([1, 2], 0)
   4621 	vim9cmd echo filter([1, 2], 0)	# E1024: Using a Number as a String
   4622 <
   4623 - Assigning a number to an environment variable, a register or a String
   4624   v: variable:
   4625 >vim
   4626 	let $FOO = 123
   4627 	vim9cmd $FOO = 123	# E1012: Type mismatch; expected string but ...
   4628 <
   4629 - Not using a number where a number is expected:
   4630 >vim
   4631 	" In this example, legacy Vim script treats v:false as 0
   4632 	function Not1029()
   4633 	    let b:l = [42] | unlet b:l[v:false]
   4634 	endfunction
   4635 	call Not1029() | echo b:l
   4636 < >vim9
   4637 	vim9script
   4638 	def E1029(): void
   4639 	    b:l = [42] | unlet b:l[false]
   4640 	enddef
   4641 	E1029()  # E1029: Expected number but got bool
   4642 <
   4643 - Using a string as a number:
   4644 >vim
   4645 	let b:l = [42] | unlet b:l['#'] | echo b:l
   4646 	vim9cmd b:l = [42] | vim9cmd unlet b:l['#']  # E1030: Using a string
   4647 <
   4648 - Not using a string where an argument requires a string:
   4649 >vim9
   4650 	echo substitute('Hallo', 'a', 'e', v:true)
   4651 	vim9cmd echo substitute('Hallo', 'a', 'e', true)  # E1174: String ...
   4652 <
   4653 - Using an empty string in an argument that requires a non-empty string:
   4654 >vim9
   4655 	echo exepath('')
   4656 	vim9cmd echo exepath('')  # E1175: Non-empty string required for ar...
   4657 <
   4658 - Not using a number when it is required:
   4659 >vim
   4660 	echo gettabinfo('a')
   4661 	vim9cmd echo gettabinfo('a')  # E1210: Number required for argument 1
   4662 <
   4663 - Not using a bool when it is required:
   4664 >vim
   4665 	echo char2nr('¡', 2)
   4666 	vim9cmd echo char2nr('¡', 2)  # E1212: Bool required for argument 2
   4667 <
   4668 - Not using a number when a number is required (|E521|):
   4669 >vim
   4670 	let &laststatus='2'
   4671 	vim9cmd &laststatus = '2'
   4672 <
   4673 - Not using a string when a string is required (|E928|):
   4674 >vim
   4675 	let &langmenu = 42
   4676 	vim9cmd &langmenu = 42  # E928: String required
   4677 <
   4678 - Comparing a |Special| with "is" often fails (|E1037|, |E1072|):
   4679 >vim
   4680 	" 1 is echoed because these are both true in legacy Vim script
   4681 	echo v:null is v:null && v:none is v:none
   4682 	" Similarly, 0 is echoed for these (false in legacy Vim script)
   4683 	echo v:none is v:null || v:none is 8 || v:true is v:none
   4684 	" All these are errors in Vim9 script
   4685 	vim9cmd echo v:null is v:null	# E1037: Cannot use 'is' with special
   4686 	vim9cmd echo v:none is v:none	# E1037: Cannot use 'is' with special
   4687 	vim9cmd echo v:none is v:null	# E1037: Cannot use 'is' with special
   4688 	vim9cmd echo v:none is 8	# E1072: Cannot compare special wit...
   4689 	vim9cmd echo v:true is v:none	# E1072: Cannot compare bool with s...
   4690 <
   4691 	Note: Although the last two Vim9 script examples above error with
   4692 	`v:none`, they return `false` with `v:null` (which is the same as
   4693 	`null` - see |v:null|):
   4694 >vim9
   4695 	vim9script
   4696 	echo v:null is 8	# false
   4697 	echo true is v:null	# false
   4698 <
   4699 - Using a string where a bool is required (|E1135|):
   4700 >vim
   4701 	echo '42' ? v:true : v:false
   4702 	vim9cmd echo '42' ? true : false  # E1135: Using a String as a Bool
   4703 <
   4704 - Using a bool as a number (|E1138|):
   4705 >vim
   4706 	let &laststatus=v:true
   4707 	vim9cmd &laststatus = true
   4708 <
   4709 One consequence is that the item type of a list or dict given to |map()| must
   4710 not change when its type is either declared or inferred.  For example, this
   4711 list's type is changed successfully in legacy Vim script:
   4712 >vim
   4713 	" legacy Vim script changing list [0, 1] to ['item 0', 'item 1']
   4714 	let s:mylist = [0, 1]
   4715 	call map(s:mylist, {i -> $"item {i}"})
   4716 	echo s:mylist
   4717 <
   4718 whereas in Vim9 script it gives |E1012|:
   4719 >vim9
   4720 	vim9script
   4721 	var mylist = [0, 1]		   # Vim infers mylist is list<number>
   4722 	map(mylist, (i, _) => $"item {i}") # E1012: Type mismatch; expected...
   4723 <
   4724 The error occurs because `map()` tries to modify the list elements to strings,
   4725 which conflicts with the declared type.
   4726 
   4727 Use |mapnew()| instead.  It creates a new list, and Vim infers its type when it
   4728 is not specified.  Inferred and declared types are shown in this example:
   4729 >vim9
   4730 	vim9script
   4731 	var mylist = [0, 1]
   4732 	var infer = mylist->mapnew((i, _) => $"item {i}")
   4733 	echo [infer, infer->typename()]
   4734 	var declare: list<string> = mylist->mapnew((i, _) => $"item {i}")
   4735 	echo [declare, declare->typename()]
   4736 <
   4737 The key concept here is, variables with declared or inferred types cannot
   4738 have the types of the elements within their containers change.  However, type
   4739 "changes" are allowed for either:
   4740 - a container literal (not bound to a variable), or
   4741 - a container where |copy()| or |deepcopy()| is used in method chaining.
   4742 Both are demonstrated in this example:
   4743 >vim9
   4744 	vim9script
   4745 	# list literal
   4746 	echo [1, 2]->map((_, v) => $"#{v}")
   4747 	echo [1, 2]->map((_, v) => $"#{v}")->typename()
   4748 	# deepcopy() in a method chain
   4749 	var mylist = [1, 2]
   4750 	echo mylist->deepcopy()->map((_, v) => $"#{v}")
   4751 	echo mylist->deepcopy()->map((_, v) => $"#{v}")->typename()
   4752 	echo mylist
   4753 <
   4754 The reasoning behind this is, when a type is either declared or inferred
   4755 and the list is passed around and changed, the declaration/inference must
   4756 always hold so that you can rely on the type to match the declared/inferred
   4757 type.  For either a list literal or a fully copied list, that type safety is
   4758 not needed because the original list is unchanged (as "echo mylist" shows,
   4759 above).
   4760 
   4761 If the item type was not declared or determined to be "<any>", it will not
   4762 change, even if all items later become the same type.  However, when
   4763 `mapnew()` is used, inference means that the new list will reflect the type(s)
   4764 present.  For example:
   4765 >vim9
   4766 	vim9script
   4767 	# list<any>
   4768 	var mylist = [1, '2']			# mixed types, i.e., list<any>
   4769 	echo (mylist, mylist->typename())	# ([1, '2'], 'list<any>')
   4770 	mylist->map((_, v) => $"item {v}")	# all items are now strings
   4771 	echo (mylist, mylist->typename())	# both strings, but list<any>
   4772 	# mapnew()
   4773 	var newlist = mylist->mapnew((_, v) => v)
   4774 	echo (newlist, newlist->typename())	# newlist is a list<string>
   4775 <
   4776 Using |extend()| and |extendnew()| is similar, i.e., a list literal may use
   4777 the former, so, this is okay:
   4778 >vim9
   4779 	vim9cmd echo [1, 2]->extend(['3'])	# [1, 2, '3']
   4780 <
   4781 whereas, this is not:
   4782 >vim9
   4783 	vim9script
   4784 	var mylist: list<number> = [1, 2]
   4785 	echo mylist->extend(['3'])	# E1013: Argument 2: type mismatch
   4786 <
   4787 Using |extendnew()| is needed for extending an existing typed list, except
   4788 where the extension matches the list's type (or it is "any").  For example,
   4789 first extending with an element of the same type, then extending with a
   4790 different type:
   4791 >vim9
   4792 	vim9script
   4793 	var mylist: list<number> = [1, 2]
   4794 	mylist->extend([3])
   4795 	echo mylist->extendnew(['4'])	# [1, 2, 3, '4']
   4796 <
   4797 							*E1158*
   4798 Using |flatten()| is not allowed in Vim9 script, because it is intended
   4799 always to change the type.  This even applies to a list literal
   4800 (unlike |map()| and |extend()|).  Instead, use |flattennew()|:
   4801 >vim9
   4802 	vim9cmd [1, [2, 3]]->flatten()		# E1158: Cannot use flatten
   4803 	vim9cmd echo [1, [2, 3]]->flattennew()	# [1, 2, 3]
   4804 <
   4805 Assigning to a funcref with specified arguments (see |vim9-func-declaration|)
   4806 involves strict type checking of the arguments.  For example, this works:
   4807 >vim9
   4808 	vim9script
   4809 	var F_name_age: func(string, number): string
   4810 	F_name_age = (n: string, a: number): string => $"Name: {n}, Age: {a}"
   4811 	echo F_name_age('Bob', 42)
   4812 <
   4813 whereas this fails with error |E1012| (type mismatch):
   4814 >vim9
   4815 	vim9script
   4816 	var F_name_age: func(string, number): string
   4817 	F_name_age = (n: string, a: string): string => $"Name: {n}, Age: {a}"
   4818 <
   4819 If there is a variable number of arguments they must have the same type, as in
   4820 this example:
   4821 >vim9
   4822 	vim9script
   4823 	var Fproduct: func(...list<number>): number
   4824 	Fproduct = (...v: list<number>): number => reduce(v, (a, b) => a * b)
   4825 	echo Fproduct(3, 2, 4)	# 24
   4826 <
   4827 And <any> may be used to accommodate mixed types:
   4828 >vim9
   4829 	vim9script
   4830 	var FlatSort: func(...list<any>): any
   4831 	FlatSort = (...v: list<any>) => flattennew(v)->sort('n')
   4832 	echo FlatSort(true, [[[5, 3], 2], 4])	# [true, 2, 3, 4, 5]
   4833 <
   4834 	Note: Using <any> in a lambda does not avoid type checking of the
   4835 	funcref.  It remains constrained by the declared funcref's type and,
   4836 	as these examples show, a runtime or compiling error occurs when the
   4837 	types mismatch:
   4838 >vim9
   4839 	vim9script
   4840 	var FuncSN: func(string): number
   4841 	FuncSN = (v: any): number => v->str2nr()
   4842 	echo FuncSN('162')->nr2char()	# ¢
   4843 	echo FuncSN(162)->nr2char()	# E1013 (a runtime error)
   4844 < >vim9
   4845 	vim9script
   4846 	var FuncSN: func(string): number
   4847 	FuncSN = (v: any): number => v->str2nr()
   4848 	def FuncSNfail(): void
   4849 	  echo FuncSN('162')->nr2char()	# No echo because ...
   4850 	  echo FuncSN(162)->nr2char()	# E1013 (now, a compiling error)
   4851 	enddef
   4852 	FuncSNfail()
   4853 <
   4854 When the funcref has no arguments specified, there is no type checking.  This
   4855 example shows FlexArgs has a string argument the first time and a list the
   4856 following time:
   4857 >vim9
   4858 	vim9script
   4859 	var FlexArgs: func: string
   4860 	FlexArgs = (s: string): string => $"It's countdown time {s}..."
   4861 	echo FlexArgs("everyone")
   4862 	FlexArgs = (...values: list<string>): string => join(values, ', ')
   4863 	echo FlexArgs('3', '2', '1', 'GO!')
   4864 <
   4865 					*E1211* *E1217* *E1218* *E1219* *E1220*
   4866 					*E1221* *E1222* *E1223* *E1224* *E1225*
   4867 					*E1226* *E1228* *E1235* *E1238* *E1251*
   4868 					*E1253* *E1256* *E1297* *E1298* *E1301*
   4869 					*E1528* *E1529* *E1530* *E1531* *E1534*
   4870 Types are checked for most builtin functions to make it easier to spot
   4871 mistakes.  The following one-line |:vim9| commands, calling builtin functions,
   4872 demonstrate many of those type-checking errors:
   4873 >vim9
   4874 	vim9 9->list2blob()		  # E1211: List required for argume...
   4875 	vim9 9->ch_close()		  # E1217: Channel or Job required ...
   4876 	vim9 9->job_info()		  # E1218: Job required for argumen...
   4877 	vim9 [9]->cos()			  # E1219: Float or Number required...
   4878 	vim9 {}->remove([])		  # E1220: String or Number require...
   4879 	vim9 null_channel->ch_evalraw(9)  # E1221: String or Blob required ...
   4880 	vim9 9->col()			  # E1222: String or List required ...
   4881 	vim9 9->complete_add()		  # E1223: String or Dictionary req...
   4882 	vim9 setbufline(9, 9, {})	  # E1224: String, Number or List r...
   4883 	vim9 9->count(9)		  # E1225: String, List, Tuple or D...
   4884 	vim9 9->add(9)			  # E1226: List or Blob required fo...
   4885 	vim9 9->remove(9)		  # E1228: List, Dictionary, or Blo...
   4886 	vim9 getcharstr('9')		  # E1235: Bool or number required ...
   4887 	vim9 9->blob2list()		  # E1238: Blob required for argume...
   4888 	vim9 9->filter(9)		  # E1251: List, Tuple, Dictionary,...
   4889 	vim9 9->reverse()		  # E1253: String, List, Tuple or B...
   4890 	vim9 9->call(9)			  # E1256: String or Function requi...
   4891 	vim9 null_dict->winrestview()	  # E1297: Non-NULL Dictionary requ...
   4892 	vim9 {}->prop_add_list(null_list) # E1298: Non-NULL List required f...
   4893 	vim9 {}->repeat(9)		  # E1301: String, Number, List, Tu...
   4894 	vim9 9->index(9)		  # E1528: List or Tuple or Blob re...
   4895 	vim9 9->join()			  # E1529: List or Tuple required f...
   4896 	vim9 9->max()			  # E1530: List or Tuple or Diction...
   4897 	vim9 9->get(9)			  # E1531: Argument of get() must b...
   4898 	vim9 9->tuple2list()		  # E1534: Tuple required for argum...
   4899 <
   4900 Reserved for future use:			*E1227* *E1250* *E1252*
   4901 	E1227: List or Dictionary required for argument %d
   4902 	E1250: Argument of %s must be a List, String, Dictionary or Blob
   4903 	E1252: String, List or Blob required for argument %d
   4904 
   4905 
   4906 Categories of variables, defaults and null handling ~
   4907 					*variable-categories* *null-variables*
   4908 There are three categories of variables:
   4909 	primitive	number, float, boolean
   4910 	container	string, blob, list, tuple, dict
   4911 	specialized	function, job, channel, user-defined-object
   4912 
   4913 When declaring a variable without an initializer, an explicit type must be
   4914 provided.  Each category has different default initialization semantics.
   4915 
   4916 Primitives default to type-specific values.  All primitives are empty but do
   4917 not equal `null`:
   4918 >vim9
   4919 	vim9script
   4920 	var n: number | echo [n, n->empty(), n == null]  # [0, 1, false]
   4921 	var f: float  | echo [f, f->empty(), f == null]  # [0.0, 1, false]
   4922 	var b: bool   | echo [b, b->empty(), b == null]  # [false, 1, false]
   4923 <
   4924 Containers default to an empty container.  Only an empty string equals `null`:
   4925 >vim9
   4926 	vim9script
   4927 	var s: string       | echo [s, s->empty(), s == null] # ['', 1, true]
   4928 	var z: blob         | echo [z, z->empty(), z == null] # [0z, 1, false]
   4929 	var l: list<string> | echo [l, l->empty(), l == null] # [[], 1, false]
   4930 	var t: tuple<any>   | echo [t, t->empty(), t == null] # [(), 1, false]
   4931 	var d: dict<number> | echo [d, d->empty(), d == null] # [{}, 1, false]
   4932 <
   4933 Specialized types default to equaling `null`:
   4934 >vim9
   4935 	vim9script
   4936 	var F: func    | echo [F, F == null]  # [function(''), true]
   4937 	var j: job     | echo [j, j == null]  # ['no process', true]
   4938 	var c: channel | echo [c, c == null]  # ['channel fail', true]
   4939 	class Class
   4940 	endclass
   4941 	var o: Class   | echo [o, o == null]  # [object of [unknown], true]
   4942 	enum Enum
   4943 	endenum
   4944 	var e: Enum    | echo [e, e == null]  # [object of [unknown], true]
   4945 <
   4946 	Notes: (1) See |empty()| for explanations of empty job, empty channel,
   4947 	and empty object types.  (2) The `class`, `enum`, and `typealias`
   4948 	types cannot be used as values, so cannot be compared to `null` (see
   4949 	|E1405|, |E1421|, and |E1403| respectively).
   4950 
   4951 Vim does not have a familiar null value.  Instead, it has various null_<type>
   4952 predefined values including |null_string|, |null_list|, and |null_job|.
   4953 Primitives do not have a null_<type>.  Typical use cases for null_<type> are:
   4954 - to clear a variable and release its resources,
   4955 - as a default for a parameter in a function definition (for an example,
   4956   see |null_blob|), or
   4957 - assigned to a container or specialized variable to set it to null
   4958   for later comparison (for an example, see |null-compare|).
   4959 
   4960 For a specialized variable, like `job`, null_<type> is used to clear the
   4961 resources.  For example:
   4962 >vim9
   4963 	vim9script
   4964 	var mydate: list<string>
   4965 	def Date(channel: channel, msg: string): void
   4966 	  mydate->add(msg)
   4967 	enddef
   4968 	var myjob = job_start([&shell, &shellcmdflag, 'date'], {out_cb: Date})
   4969 	echo [myjob, myjob->job_status()]
   4970 	sleep 2
   4971 	echo $"The date and time is {mydate->join('')}"
   4972 	echo [myjob, myjob->job_status()]
   4973 	myjob = null_job  # Clear the variable; release the job's resources.
   4974 	echo myjob
   4975 <
   4976 For a container variable, resources may also be cleared by assigning an
   4977 empty container to the variable.  For example:
   4978 >vim9
   4979 	vim9script
   4980 	var perfect: list<number> = [1, 4]
   4981 	perfect->extend([9, 16, 25])
   4982 	perfect = []
   4983 	echo perfect
   4984 <
   4985 Using an empty container, rather than null_<type>, to clear a container
   4986 variable may avoid null complications - see |null-anomalies|.
   4987 
   4988 The initialization semantics of container variables and specialized variables
   4989 differ.  For containers:
   4990 - An uninitialized container defaults to empty but does not equal `null`
   4991   (except for an uninitialized string).
   4992 - A container initialized to [], (), {}, "", or 0z is empty but does not equal
   4993   `null`.
   4994 - A container initialized as null_<type> defaults to empty and it also equals
   4995   `null`.
   4996 
   4997 In the following example, the uninitialized list ("lu") and [] initialized
   4998 list ("li") are equivalent and indistinguishable whereas "ln" is a null
   4999 container, which is similar to, but not equivalent to, an empty container
   5000 (see |null-anomalies|).
   5001 >vim9
   5002 	vim9script
   5003 	# uninitialized: empty container, not null
   5004 	var lu: list<any>
   5005 	echo ['lu', $"empty={lu->empty()}", $"null={lu == null}"]
   5006 	# initialized: empty container, not null
   5007 	var li: list<any> = []
   5008 	echo ['li', $"empty={li->empty()}", $"null={li == null}"]
   5009 	# initialized: empty container, null
   5010 	var ln: list<any> = null_list
   5011 	echo ['ln', $"empty={ln->empty()}", $"null={ln == null}"]
   5012 <
   5013 Specialized variables default to equaling null.  These job initializations
   5014 are equivalent and indistinguishable:
   5015 >vim9
   5016 	vim9script
   5017 	var j1: job
   5018 	var j2: job = null_job
   5019 	var j3 = null_job
   5020 	echo (j1 == j2) == (j2 == j3)  # true (equivalent, indistinguishable)
   5021 <
   5022 When a list, tuple, or dict is declared, if the item type is not specified
   5023 it cannot be inferred.  Consequently, the item type defaults to "any":
   5024 >vim9
   5025 	vim9script
   5026 	var [t1, t2] = [(), null_tuple]
   5027 	echo $'t1 is {t1->typename()} and t2 is {t2->typename()} too'
   5028 <
   5029 Tuples and functions (or partials) may be declared in various ways.
   5030 See |tuple-type|, |variadic-tuple|, and |vim9-func-declaration|.
   5031 
   5032 							*null-compare*
   5033 For familiar null compare semantics, where an empty container is not equal to
   5034 a null container, do not use null_<type> in a comparison.  That is because,
   5035 in Vim9 script, although null_<type> == `null`, comparing an:
   5036 - empty container to `null` is `false`, but
   5037 - empty container to null_<type> is `true`.
   5038 
   5039 So, compare against `null`, not null_<type>.  For example:
   5040 >vim9
   5041 	vim9script
   5042 	var bonds: dict<list<string>> = {g: ['007', '008'], o: ['007', '009']}
   5043 	def Search(query: string): list<string>
   5044 	  return query == "\r" ? null_list : bonds->get(query, [])
   5045 	enddef
   5046 	echo "Goldfinger (g) or Octopussy (o)?: "
   5047 	const C: string = getcharstr()
   5048 	var result: list<string> = C->Search()
   5049 	if result == null  # <<< DO NOT USE null_list HERE!
   5050 	  echo "Error: Nothing was entered"
   5051 	else
   5052 	  echo result->empty() ? $"No matches for '{C}'" : $"{result}"
   5053 	endif
   5054 <
   5055 	Note: Using "result == null_list" instead of "result == null" would
   5056 	fail to distinguish the error (nothing entered) and the valid
   5057 	(nothing matched) result because [] == null_list whereas [] != null.
   5058 
   5059 Conceptually, think of the null_<type> construct as a hybrid/bridge between
   5060 the general `null` and typed `empty` containers, having properties of both.
   5061 In the following section there are details about comparison results.
   5062 
   5063 						*null-details* *null-anomalies*
   5064 This section describes issues about using null and null_<type>; included below
   5065 are the enumerated results of null comparisons.  In some cases, if familiar
   5066 with vim9 null semantics, the programmer may choose to use null_<type> in
   5067 comparisons and/or other situations.
   5068 
   5069 Elsewhere in the documentation it says, "often a null value is handled the
   5070 same as an empty value, but not always".  For example, you cannot add to a
   5071 null container:
   5072 >vim9
   5073 	vim9script
   5074 	var le: list<any> = []
   5075 	le->add('Okay')		# le is now ['Okay']
   5076 	var ln = null_list
   5077 	ln->add("E1130")	# E1130: Cannot add to null list
   5078 <
   5079 As explained in |null-compare|, there is a non-transitive relationship among
   5080 `null`, null_<type> containers, and `empty`.  To recap, for example:
   5081 >vim9
   5082 	vim9cmd echo (null_dict == {}, null_dict == null, {} != null)
   5083 <
   5084 The exception is an uninitialized string.  It is equal to `null` (and is the
   5085 same instance as `null_string`).  The "is" operator (|expr-is|) may be used to
   5086 determine whether a string is uninitialized:
   5087 >vim9
   5088 	vim9script
   5089 	var s: string
   5090 	echo s == null_string	# true
   5091 	echo s is null_string	# true (the same instance)
   5092 	echo s == null		# true (unexpected, perhaps)
   5093 	echo s is null		# false (not the same instance)
   5094 <
   5095 However, don't do the same for the other containers because, when evaluated
   5096 against their applicable null_<type> with "is", they return `false`:
   5097 >vim9
   5098 	vim9script
   5099 	var d: dict<any>
   5100 	echo d == null_dict	# true
   5101 	echo d is null_dict	# false (not the same instance)
   5102 	echo d == null		# false (as expected)
   5103 	echo d is null		# false (not the same instance)
   5104 <
   5105 The key distinction here is an uninitialized string is implemented as
   5106 `null_string`, while an uninitialized list, dict, tuple, or blob is
   5107 implemented as an empty container ([], {}, (), and 0z respectively).
   5108 So, those uninitialized types are equal to, but not the same instance as,
   5109 their null_<type> counterparts, as this example shows:
   5110 >vim9
   5111 	vim9script
   5112 	var t: tuple<any>
   5113 	echo t == null_tuple	# true
   5114 	echo t is null_tuple	# false
   5115 <
   5116 However, a variable initialized to the null_<type> is equal not only to the
   5117 null_<type>, it is also equal to null.  For example:
   5118 >vim9
   5119 	vim9script
   5120 	var t: tuple<any> = null_tuple
   5121 	echo t == null_tuple	# true
   5122 	echo t is null_tuple	# true
   5123 	echo t == null		# true
   5124 <
   5125 An uninitialized container variable is not equal to null, except for an
   5126 uninitialized string, which is explained in an example, above.  So, these
   5127 all echo `true`:
   5128 >vim9
   5129 	vim9script
   5130 	var b: blob	  | echo b != null
   5131 	var d: dict<any>  | echo d != null
   5132 	var l: list<any>  | echo l != null
   5133 	var t: tuple<any> | echo t != null
   5134 	var s: string	  | echo s == null
   5135 <
   5136 An uninitialized specialized variable is equal to null.  So, these all
   5137 echo `true`:
   5138 >vim9
   5139 	vim9script
   5140 	var c: channel	| echo c == null
   5141 	var F: func	| echo F == null
   5142 	var j: job	| echo j == null
   5143 	class Class
   5144 	endclass
   5145 	var nc: Class	| echo nc == null
   5146 	enum Enum
   5147 	endenum
   5148 	var ne: Enum	| echo ne == null
   5149 <
   5150 	Note: the specialized variables, like job, default to null and no
   5151 	specialized variable has a corresponding empty value.
   5152 
   5153 A container variable initialized to empty equals null_<type>, so these are all
   5154 `true`:
   5155 >vim9
   5156 	vim9script
   5157 	var s: string = ""	| echo s == null_string
   5158 	var b: blob = 0z	| echo b == null_blob
   5159 	var l: list<any> = []	| echo l == null_list
   5160 	var t: tuple<any> = ()	| echo t == null_tuple
   5161 	var d: dict<any> = {}	| echo d == null_dict
   5162 <
   5163 However, a container variable initialized to empty does not equal null, so
   5164 these are all `true`:
   5165 >vim9
   5166 	vim9script
   5167 	var s: string = ""	| echo s != null
   5168 	var b: blob = 0z	| echo b != null
   5169 	var l: list<any> = []	| echo l != null
   5170 	var t: tuple<any> = ()	| echo t != null
   5171 	var d: dict<any> = {}	| echo d != null
   5172 <
   5173 
   5174 ==============================================================================
   5175 
   5176 5. Generic functions					*generic-functions*
   5177 
   5178 A generic function allows using the same function with different type
   5179 arguments, while retaining type checking for arguments and the return value.
   5180 This provides type safety and code reusability.
   5181 
   5182 
   5183 Declaration~
   5184 						*generic-function-declaration*
   5185 						*E1553* *E1554*
   5186 The type variables for a generic function are declared as its type parameters
   5187 within angle brackets ("<" and ">"), directly after the function name.
   5188 Multiple type parameters are separated by commas:
   5189 >
   5190 	def[!] {funcname}<{type} [, {types}]>([arguments])[: {return-type}]
   5191 	  {function body}
   5192 	enddef
   5193 <						*generic-function-example*
   5194 These type parameters may then be used, like any other type, within the
   5195 function signature and its body.  The following example combines two lists
   5196 into a list of tuples:
   5197 >vim9
   5198 	vim9script
   5199 	def Zip<T, U>(first: list<T>, second: list<U>): list<tuple<T, U>>
   5200 	  const LEN: number = ([first->len(), second->len()])->min()
   5201 	  final result: list<tuple<T, U>> = []
   5202 	  for i in range(LEN)
   5203 	    result->add((first[i], second[i]))
   5204 	  endfor
   5205 	  return result
   5206 	enddef
   5207 	var n: list<number> = [61, 62, 63]
   5208 	var s: list<string> = ['a', 'b', 'c']
   5209 	echo $"Zip example #1: {Zip<number, string>(n, s)}"
   5210 	echo $"Zip example #2: {Zip<string, number>(s, n)}"
   5211 <
   5212 						*type-variable-naming* *E1552*
   5213 						*type-parameter-naming*
   5214 As in the preceding example, the convention is to use a single capital letter
   5215 for a name (e.g., T, U, A, etc.).  Although they may comprise more than one
   5216 letter, names must start with a capital letter.  In this example, "Ok" is
   5217 valid whereas "n" is not:
   5218 >vim9
   5219 	vim9script
   5220 	def MyFail<Ok, n>(): void
   5221 	enddef
   5222 	# E1552: Type variable name must start with an uppercase letter: n>...
   5223 <
   5224 							*E1558* *E1560*
   5225 A function must be declared and used either as a generic function or as a
   5226 regular function, but not both.  The following Vim9 scripts demonstrate these
   5227 errors:
   5228 >vim9
   5229 	vim9script
   5230 	My1558<number>()
   5231 	# E1558: Unknown generic function: My1558
   5232 < >vim9
   5233 	vim9script
   5234 	def My1560(): void
   5235 	enddef
   5236 	My1560<string>()
   5237 	# E1560: Not a generic function: My1560
   5238 <
   5239 							*E1561*
   5240 Type parameter names must not clash with other identifiers:
   5241 >vim9
   5242 	vim9script
   5243 	def My1561<D, E, D>(): D
   5244 	enddef
   5245 	# E1561: Duplicate type variable name: D
   5246 
   5247 	vim9script
   5248 	enum E
   5249 	  Yes, No
   5250 	endenum
   5251 	def My1041<E>(): E
   5252 	enddef
   5253 	# E1041: Redefining script item: "E"
   5254 <
   5255 
   5256 Calling a generic function~
   5257 							*generic-function-call*
   5258 To call a generic function, specify the concrete types in "<" and ">"
   5259 between the function name and the argument list:
   5260 >
   5261 	MyFunc<number, string, list<number>>()
   5262 <
   5263 	Note: There are several working examples in this section, which may be
   5264 	sourced, including |generic-function-example|.
   5265 
   5266 						*E1555* *E1556* *E1557* *E1559*
   5267 The number of passed type arguments to the function must match the number
   5268 of its declared type parameters.  An empty type list is not allowed.
   5269 Examples:
   5270 >vim9
   5271 	vim9script
   5272 	def My1555<>(): void
   5273 	enddef	# E1555: Empty type list specified for generic function '<S...
   5274 < >vim9
   5275 	vim9script
   5276 	def My1556<T>(): void
   5277 	enddef
   5278 	My1556<bool, bool>()  # E1556: Too many types specified for generic...
   5279 < >vim9
   5280 	vim9script
   5281 	def My1557<T, U>(): void
   5282 	enddef
   5283 	My1557<bool>()	# E1557: Not enough types specified for generic fun...
   5284 < >vim9
   5285 	vim9script
   5286 	def My1559<T>(): T
   5287 	enddef
   5288 	My1559()  # E1559: Type arguments missing for generic function '<SN...
   5289 <
   5290 Any Vim9 type (|vim9-types|) can be used as a concrete type in a generic
   5291 function.
   5292 
   5293 Spaces are not allowed:
   5294 - Between the function name and "<" (|E1068|)
   5295 - Between ">" and the opening "(" (|E1068|), or
   5296 - Within the "<" and ">", except where required after the comma separating
   5297   the types (|E1202|).
   5298 
   5299 A generic function can be exported and imported like a regular function.
   5300 See |:export| and |:import|.
   5301 
   5302 A generic function can be defined inside another regular or generic function.
   5303 An example:
   5304 >vim9
   5305 	vim9script
   5306 	def Outer(): void
   5307 	  # Returns either the first item of a list or a default value
   5308 	  def FirstOrDefault<T, U>(lst: list<T>, default: U): any
   5309 	    return lst->len() > 0 ? lst[0] : default
   5310 	  enddef
   5311 	  echo FirstOrDefault<string, bool>(['B', 'C'], false)	# B
   5312 	  echo FirstOrDefault<number, number>([], 42)		# 42
   5313 	enddef
   5314 	Outer()
   5315 <
   5316 
   5317 Using a type variable as a type argument ~
   5318 
   5319 A type variable may also be passed as a type argument.  For example:
   5320 >vim9
   5321 	vim9script
   5322 	# T is declared as a type parameter
   5323 	# It is used for the 'value' parameter and the return type
   5324 	def Id<T>(value: T): T
   5325 	  return value
   5326 	enddef
   5327 	# U is declared as a type parameter
   5328 	# It is used for the 'value' parameter and the return type
   5329 	def CallId<U>(value: U): U
   5330 	  # U is a type variable passed/used as a type argument
   5331 	  return Id<U>(value)
   5332 	enddef
   5333 	echo CallId<string>('I am') .. ' ' .. CallId<number>(42)
   5334 <
   5335 This is useful for complex data structures like dictionaries of lists or,
   5336 as in the following example, lists of dictionaries:
   5337 >vim9
   5338 	vim9script
   5339 	def Flatten<T>(x: list<list<T>>): list<T>
   5340 	  final result: list<T> = []
   5341 	  for inner in x
   5342 	    result->extend(inner)
   5343 	  endfor
   5344 	  return result
   5345 	enddef
   5346 	const ENGLISH: list<dict<string>> = [{1: 'one'}, {2: 'two'}]
   5347 	const MANDARIN: list<dict<string>> = [{1: '壹'}, {2: '贰'}]
   5348 	const ARABIC_N: list<dict<number>> = [{1: 1}, {2: 2}]
   5349 	echo Flatten<dict<string>>([ENGLISH, MANDARIN])
   5350 	echo Flatten<dict<any>>([ENGLISH, ARABIC_N])
   5351 <
   5352 In "Flatten<T>", "T" is a declared type parameter.  Everywhere else in
   5353 the function, "T" is a type variable referencing that type parameter.
   5354 
   5355 
   5356 Generic class method~
   5357 
   5358 A Vim9 class method can be a generic function:
   5359 >vim9
   5360 	vim9script
   5361 	class Config
   5362 	  var settings: dict<any>
   5363 	  def Get<T>(key: string): T
   5364 	    return this.settings[key]
   5365 	  enddef
   5366 	endclass
   5367 	var c: Config = Config.new({timeout: 30, debug: true})
   5368 	echo c.Get<number>('timeout')
   5369 	echo c.Get<bool>('debug')
   5370 <
   5371 							*E1432* *E1433* *E1434*
   5372 A generic class method in a base class can be overridden by a generic method
   5373 in a child class.  The number of type variables must match between both
   5374 methods.  A concrete class method cannot be overridden by a generic method,
   5375 and vice versa.
   5376 
   5377 
   5378 Generic function reference~
   5379 
   5380 A function reference (|Funcref|) can be a generic function.  This allows for
   5381 creating factories of functions that operate on specific types:
   5382 >vim9
   5383 	vim9script
   5384 	# Match a specified character in a string or the decimal value of the
   5385 	# character in a list.  Note: '*' is decimal 42 (U+002A)
   5386 	var c: string = "*"
   5387 	var char_dec: tuple<string, string> = (c, c->char2nr()->string())
   5388 	def Matcher<T>(pattern: string): func(T): bool
   5389 	  return (value: T): bool => match(value, pattern) >= 0
   5390 	enddef
   5391 	var StringMatch = Matcher<string>(char_dec[0])
   5392 	echo "*+"->StringMatch()	# true (has *)
   5393 	echo ",-"->StringMatch()	# false
   5394 	var ListMatch = Matcher<list<number>>(char_dec[1])
   5395 	echo [42, 43]->ListMatch()	# true (has 42)
   5396 	echo [44, 45]->ListMatch()	# false
   5397 <
   5398 
   5399 Compiling and Disassembling Generic functions~
   5400 
   5401 The |:defcompile| command can be used to compile a generic function with a
   5402 specific list of concrete types:
   5403 >
   5404 	defcompile MyFunc<number, list<number>, dict<string>>
   5405 <
   5406 The |:disassemble| command can be used to list the instructions generated for
   5407 a generic function:
   5408 >
   5409 	disassemble MyFunc<string, dict<string>>
   5410 	disassemble MyFunc<number, list<blob>>
   5411 <
   5412 
   5413 Limitations and Future Work~
   5414 
   5415 Currently, Vim does not support:
   5416 - Type inference for type variables: All types must be explicitly specified
   5417   when calling a generic function.
   5418 - Type constraints: It's not possible to restrict a type variable to a
   5419   specific class or interface (e.g., `T extends SomeInterface`).
   5420 - Default type arguments: Providing a default type for a type parameter
   5421   when not explicitly specified.
   5422 
   5423 ==============================================================================
   5424 
   5425 6. Namespace, Import and Export				*vim9script*
   5426 						*vim9-export* *vim9-import*
   5427 A Vim9 script can be written to be imported.  This means that some items are
   5428 intentionally exported, made available to other scripts.  When the exporting
   5429 script is imported in another script, these exported items can then be used in
   5430 that script.  All the other items remain script-local in the exporting script
   5431 and cannot be accessed by the importing script.
   5432 
   5433 This mechanism exists for writing a script that can be sourced (imported) by
   5434 other scripts, while making sure these other scripts only have access to what
   5435 you want them to.  This also avoids using the global namespace, which has a
   5436 risk of name collisions.  For example when you have two plugins with similar
   5437 functionality.
   5438 
   5439 You can cheat by using the global namespace explicitly.  That should be done
   5440 only for things that really are global.
   5441 
   5442 
   5443 Namespace ~
   5444 							*vim9-namespace*
   5445 To recognize a file that can be imported, the `vim9script` command must appear
   5446 as the first command in the file (though see |vim9-mix| for an exception).
   5447 It tells Vim to interpret the script in its own namespace, instead of the
   5448 global namespace.  Consider this script:
   5449 >vim9
   5450 	vim9script
   5451 	var myvar = 'yes'
   5452 <
   5453 The variable "myvar" will only exist in this script's scope.  That is
   5454 different from legacy Vim script where "let myvar" would make "myvar"
   5455 available to other scripts and functions (as `g:myvar`).
   5456 							*E1101*
   5457 The variables at the file level are very much like the script-local "s:"
   5458 variables in legacy Vim script, but the "s:" is omitted.  And they cannot be
   5459 deleted.
   5460 							*E1304*
   5461 In Vim9 script the global (`g:`), buffer (`b:`), window (`w:`), and tab (`t:`)
   5462 namespaces can be used like in legacy Vim script.  In Vim9 script, namespace
   5463 prefixed variables:
   5464 - are not declared
   5465 - have no specific type, and
   5466 - can be deleted.
   5467 If a namespace prefixed variable is declared, |E1016| is given.  And, if a
   5468 type is specified, E1304 is given:
   5469 >vim9
   5470 	vim9cmd var b:fails: bool	# E1016: Cannot declare a buffer va...
   5471 	vim9cmd b:fails: bool = false	# E1304: Cannot use type with this ...
   5472 <
   5473 A side effect of `:vim9script` is that the 'cpoptions' option is set to the
   5474 Vim default value, like with:
   5475 >
   5476 	:set cpo&vim
   5477 <
   5478 One of the effects is that |line-continuation| is always enabled.
   5479 The original value of 'cpoptions' is restored at the end of the script, while
   5480 flags added or removed in the script are also added to or removed from the
   5481 original value to get the same effect.  The order of flags may change.
   5482 In the |vimrc| file sourced on startup this does not happen.
   5483 
   5484 							*vim9-mix*
   5485 There is one way to use both legacy and Vim9 syntax in one script file:
   5486 >vim9
   5487 	" _legacy Vim script_ comments are placed here
   5488 	if !has('vim9script')
   5489 	  " _legacy Vim script_ comments and commands are placed here
   5490 	  finish
   5491 	endif
   5492 	vim9script
   5493 	# _Vim9 script_ commands/commands from here onwards
   5494 	echowindow $"has('vim9script') == {has('vim9script')}"
   5495 <
   5496 This allows for writing a script that takes advantage of the Vim9 script
   5497 syntax if possible, and prevents the `vim9script` command from giving an
   5498 error if used in a version of Vim without Vim9 script.
   5499 
   5500 Note that Vim9 syntax changed before Vim 9 so that scripts using the current
   5501 syntax (such as "import from" instead of "import") might give errors.
   5502 To prevent these, a safer check may be |v:version| >= 900 instead (because
   5503 "has('vim9script')" will return `v:true` back to Vim 8.2 with patch 3965).
   5504 Sometimes it is prudent to cut off even later.  Vim9 script's feature set
   5505 continues to grow so, for example, if tuples are used (introduced in Vim 9.1
   5506 patch 1232), a better condition is:
   5507 >vim9
   5508 	if !has('patch-9.1.1232')
   5509 	  echowindow $"Fail: Vim does not have patch 9.1.1232"
   5510 	  finish
   5511 	endif
   5512 	vim9script
   5513 	echowindow $"Pass: version {v:versionlong}.  Continuing ..."
   5514 <
   5515 Whichever vim-mix condition is used, it only works in one of two ways:
   5516   1. The "if" statement evaluates to false, the commands up to `endif` are
   5517      skipped and `vim9script` is then the first command actually executed.
   5518   2. The "if" statement evaluates to true, the commands up to `endif` are
   5519      executed and `finish` bails out before reaching `vim9script`.
   5520 
   5521 
   5522 Export ~
   5523 							*:export*
   5524 Exporting an item can be written as: >
   5525 	export var myvar ...
   5526 	export const MYCONST ...
   5527 	export final myvar ...
   5528 	export def MyDef() ...
   5529 	export function MyFunc() ...
   5530 	export class MyClass ...
   5531 	export abstract class MyAbstractClass ...
   5532 	export interface MyInterface ...
   5533 	export enum MyEnum ...
   5534 	export type MyType ...
   5535 <							*E1043*
   5536 As this suggests, variables, constants, functions, classes (including abstract
   5537 classes), interfaces, enums, and types can be exported.  Trying to export
   5538 something else gives E1043:
   5539 >vim9
   5540 	vim9cmd export echo 0  # E1043: Invalid command after :export
   5541 <
   5542 							*E1042*
   5543 `:export` can only be used in a Vim9 script scope.  So, for example, although
   5544 exporting a `:function` is okay, trying to export an item within such a
   5545 function gives E1042:
   5546 >vim9
   5547 	vim9script
   5548 	export function F1042()
   5549 	  export var b: bool
   5550 	endfunction
   5551 	F1042()	# E1042: Export can only be used in vim9script
   5552 <
   5553 							*E1044*
   5554 An invalid argument can give E1044:
   5555 >vim9
   5556 	vim9script
   5557 	export def /a1044(): void
   5558 	enddef	# E1044: Export with invalid argument: ...
   5559 <
   5560 
   5561 Import ~
   5562 							*:import*
   5563 The exported items can be imported in another script.  The import syntax has
   5564 two forms.  The simpler form is: >
   5565 	import {filename}
   5566 <
   5567 Where {filename} is an expression that must evaluate to a string.  In this
   5568 form the filename should end in ".vim" and the portion before ".vim" will
   5569 become the script-local name of the namespace.  For example: >
   5570 	import "myscript.vim"
   5571 <
   5572 This makes each exported item in "myscript.vim" available as "myscript.item".
   5573 
   5574 							*E1094*
   5575 Importing is only allowed in the script-local scope.  Trying to do so
   5576 elsewhere gives E1094; for example, from a `:function` or `:def` scope:
   5577 >vim9
   5578 	vim9script
   5579 	def F1094(): void
   5580 	  import 'nah.vim'  # E1094: Import can only be used in a script
   5581 	enddef
   5582 	F1094()
   5583 <
   5584 							*E1053* *E1071*
   5585 Errors are given when either the {filename} is not found or it is invalid:
   5586 >vim9
   5587 	vim9cmd import 'e1053.vim'  # E1053: Could not import "e1053.vim"
   5588 	vim9cmd import false  # E1071: Invalid string for :import: false
   5589 <
   5590 							*:import-as*
   5591 When the name of the file is long, ambiguous (such as with filenames that are
   5592 the same but in different directories), or if you just want to use a distinct
   5593 structure for the name, this form can be used: >
   5594 	import {longfilename} as {name}
   5595 <
   5596 In this longer form, {name} becomes a specific script-local name for the
   5597 imported namespace.  Therefore {name} must consist of letters, digits, or '_',
   5598 and cannot start with a digit, like |internal-variables|.  The {longfilename}
   5599 expression must evaluate to an existing filename.
   5600 
   5601 The following script demonstrates using `:import-as`.  It:
   5602 - Creates a constant, "TMP", for the {longfilename} of a temporary Vim9 script
   5603   file to import
   5604 - Writes a two-line Vim9 script to TMP
   5605 - Imports the Vim9 script file "as" the {name}, "that", and
   5606 - Echoes the result, showing the imported Vim9 script file's {longfilename}
   5607   and, on a separate line, the content of "that.myvar" (where "myvar" is an
   5608   exported variable in the imported script).
   5609 >vim9
   5610 	vim9script
   5611 	const TMP: string = tempname()
   5612 	['vim9script', 'export var myvar: string = "YES!"']->writefile(TMP)
   5613 	import TMP as that
   5614 	echo $"Exported var 'myvar' in 'that' ({TMP}):\n" .. that.myvar
   5615 <
   5616 This example shows you can use "that.myvar", etc.  You are free to choose the
   5617 name "that", or something that will be recognized as referring to the imported
   5618 script.  It is best to avoid command names, command modifiers, and builtin
   5619 function names, because {name} will shadow any of those.  It also is better to
   5620 begin the name with a lowercase letter because that avoids potential shadowing
   5621 of global user commands and functions.  The {name} cannot be used for anything
   5622 else in the script, such as a function or variable name (see |E1213|), and it
   5623 cannot be assigned something else (see |E1258|).
   5624 
   5625 In case the "." in the name is undesired, a local reference can be made for a
   5626 function: >
   5627 	var LongDef = that.LongDefName
   5628 
   5629 This also works for constants: >
   5630 	const MAXLEN = that.MAXIMUM_LENGTH_OF_NAME
   5631 
   5632 This does not work for variables, since the value would be copied once and
   5633 when changing the variable the copy will change, not the original variable.
   5634 You need to use the full name (i.e., including the '.').
   5635 
   5636 Imported items are intended to exist at the script level and only be imported
   5637 once.  Also, `:import` can not be used in a `:function` or `:def` - see |E1094|.
   5638 
   5639 The script name after `:import` can be:
   5640 - A relative path, starting "." or "..".  This finds a file relative to the
   5641   location of the script file itself.  This is useful to split up a large
   5642   plugin into several files.
   5643 - An absolute path, starting with "/" on Unix or "D:/" on MS-Windows.  This
   5644   will rarely be used.
   5645 - A path not being relative or absolute.  This will be found in the
   5646   "import" subdirectories of 'runtimepath' entries.  The name will usually be
   5647   longer and unique, to avoid loading the wrong file.
   5648   Note that "after/import" is not used.
   5649 
   5650 Once a Vim9 script file has been imported, the result is cached and it will
   5651 not be read again.
   5652 
   5653 Many syntax and other errors may be given when importing.  Examples:
   5654 
   5655 							*E1047*
   5656 - Using an invalid "as" {name}:
   5657 >vim9
   5658 	vim9script
   5659 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i-cc
   5660 	# E1047: Syntax error in import: i-cc
   5661 <
   5662 							*E1048*
   5663 - Trying to use a non-existent item in an imported script:
   5664 >vim9
   5665 	vim9script
   5666 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc
   5667 	echo i_cc.absent_item  # E1048: Item not found in script: absent_item
   5668 <
   5669 							*E1049*
   5670 - Trying to use a declared, but non-exported, item in an imported script:
   5671 >vim9
   5672 	vim9script
   5673 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc
   5674 	echo i_cc.prepended  # E1049: Item not exported in script: prepended
   5675 <
   5676 							*E1060*
   5677 When using the imported name, the '.' and the item name must be contiguous.
   5678 So there can be neither white space nor a line break:
   5679 - After the '.' (see |E1074|), or
   5680 - Before the '.', for example:
   5681 >vim9
   5682 	vim9script
   5683 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc
   5684 	echo i_cc .GetPath()	# E1060: Expected dot after name: i_cc .Get...
   5685 <
   5686 							*E1088*
   5687 - Attempting to have an imported script import itself:
   5688 >vim9
   5689 	vim9script
   5690 	const TMP: string = $'{tempname()}.vim'->substitute('\\', '/', 'g')
   5691 	var lines: list<string> = ['vim9script', $'import "{TMP}" as e1088']
   5692 	lines->writefile(TMP)
   5693 	import TMP  # E1088: Script cannot import itself
   5694 <
   5695 							*E1236*
   5696 - Trying to use the script itself:
   5697 >vim9
   5698 	vim9script
   5699 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as cc
   5700 	cc()  # E1236: Cannot use cc itself, it is imported
   5701 <
   5702 							*E1257*
   5703 - Not using "as {name}" when the imported filename does not end in ".vim":
   5704 >vim9
   5705 	vim9script
   5706 	const TMP: string = tempname()
   5707 	['vim9script']->writefile(TMP)
   5708 	import TMP  # E1257: Imported script must use "as" or end in .vim: ...
   5709 <
   5710 							*E1258*
   5711 - Omitting the '.' after an imported name:
   5712 >vim9
   5713 	vim9script
   5714 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc
   5715 	def F1258(): void
   5716 	  i_cc =
   5717 	enddef
   5718 	defcompile  # E1258: No '.' after imported name: i_cc =
   5719 <
   5720 							*E1259*
   5721 - Omitting the name after an imported name:
   5722 >vim9
   5723 	vim9script
   5724 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc
   5725 	def F1259(): void
   5726 	  i_cc.8 = 0
   5727 	enddef
   5728 	defcompile  # E1259: Missing name after imported name: i_cc.8 = 0
   5729 <
   5730 							*E1260*
   5731 - Attempting to `:unlet` an imported item:
   5732 >vim9
   5733 	vim9script
   5734 	const TMP: string = tempname()
   5735 	['vim9script', 'export var b: bool']->writefile(TMP)
   5736 	import TMP as e_unlet
   5737 	unlet e_unlet.b  # E1260: Cannot unlet an imported item: b
   5738 <
   5739 							*E1261*
   5740 - Attempting to import the filename ".vim" without using "as".  This script
   5741   writes the temporary file '.vim' to the operating system's applicable
   5742   temporary directory, then attempts to import it:
   5743 >vim9
   5744 	vim9script
   5745 	const TMPDIR: string = tempname()
   5746 	  ->substitute('\\', '/', 'g')		# Ensure Windows \ chars are /
   5747 	  ->substitute('/[^/]\+$', '/', '')	# Remove the filename
   5748 	['vim9script']->writefile($'{TMPDIR}.vim')
   5749 	echo $"Temporary import file name is: {TMPDIR}.vim"
   5750 	import $'{TMPDIR}.vim'	# E1261: Cannot import .vim without using "as"
   5751 <
   5752 							*E1262*
   5753 - Trying to import the same script multiple times (including using different
   5754   "as" names):
   5755 >vim9
   5756 	vim9script
   5757 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc1
   5758 	import $'{$VIMRUNTIME}/autoload/ccomplete.vim' as i_cc2
   5759 	# E1262: Cannot import the same script twice: .../ccomplete.vim
   5760 <
   5761 							*import-map*
   5762 When you've imported a function from one script into a Vim9 script you can
   5763 refer to the imported function in a mapping by prefixing it with |<SID>|: >
   5764 	noremap <silent> ,a :call <SID>name.Function()<CR>
   5765 
   5766 When the mapping is defined "<SID>name." will be replaced with <SNR> and the
   5767 script ID of the imported script.
   5768 
   5769 An even simpler solution is using |<ScriptCmd>|: >
   5770 	noremap ,a <ScriptCmd>name.Function()<CR>
   5771 
   5772 Note that this does not work for variables, only for functions.
   5773 This self-contained example demonstrates using <ScriptCmd>, creating and
   5774 writing a temporary script, which is then imported and the function
   5775 "exported.MyDef()" mapped to <leader>a:
   5776 >vim9
   5777 	vim9script
   5778 	const TMP: string = tempname()
   5779 	['vim9script',
   5780 	'export def MyDef(): void',
   5781 	'  popup_notification("exported.MyDef() was called", {time: 4000})',
   5782 	'enddef']->writefile(TMP)
   5783 	import TMP as exported
   5784 	nnoremap <leader>a <ScriptCmd>exported.MyDef()<CR>
   5785 	# Now, pressing <leader>a calls exported.MyDef(), generating a popup
   5786 <
   5787 					*import-legacy* *legacy-import* *:imp*
   5788 `:import`, including the shortened form `:imp`, can also be used in legacy Vim
   5789 script.  The imported namespace still becomes script-local, even when the
   5790 "s:" prefix is not given.  For example: >
   5791 	import "myfile.vim"
   5792 	call s:myfile.MyFunc()
   5793 
   5794 When using the "as name" form, the namespace cannot be resolved on its own
   5795 (see also |E1060|).  This example demonstrates using `:imp` with `as` successfully,
   5796 then the error:
   5797 >vim
   5798 	let s:tmp = $'{tempname()}.vim'->substitute('\\', '/', 'g')
   5799 	call writefile(['vim9script',
   5800 		\ 'export function L()',
   5801 		\ '  return "Vim9 script exporting a :function"',
   5802 		\ 'endfunction'], s:tmp)
   5803 	imp s:tmp as iLegacy
   5804 	echo s:iLegacy.L()	|" echoes 'Vim9 script exporting a :function'
   5805 	echo s:iLegacy		|" E1060: Expected dot after name: s:iLegacy
   5806 <
   5807 This also affects the use of |<SID>| in the legacy mapping context.  Since
   5808 |<SID>| is only a valid prefix for a function and NOT for a namespace, you
   5809 cannot use it to scope a function in a script-local namespace.  Instead of
   5810 prefixing the function with |<SID>| you should use |<ScriptCmd>|.
   5811 For example:
   5812 >
   5813 	noremap ,a <ScriptCmd>:call s:that.OtherFunc()<CR>
   5814 <
   5815 							*:import-cycle*
   5816 The `import` commands are executed when encountered.  If script A imports
   5817 script B, and B (directly or indirectly) imports A, this will be skipped over.
   5818 At this point items in A after "import B" will not have been processed and
   5819 defined yet.  Therefore cyclic imports can exist and not result in an error
   5820 directly, but may result in an error for items in A after "import B" not being
   5821 defined.  This does not apply to autoload imports, see the next section.
   5822 
   5823 
   5824 Importing an autoload script ~
   5825 						*vim9-autoload* *import-autoload*
   5826 For optimal startup speed, loading scripts should be postponed until they are
   5827 actually needed.  Using the autoload mechanism is recommended:
   5828 							*E1264*
   5829      1. In the plugin, define user commands, functions and/or mappings
   5830 	referring to items imported from an autoload script.
   5831 >
   5832 	import autoload 'for/search.vim'
   5833 	command -nargs=1 SearchForStuff search.Stuff(<f-args>)
   5834 <
   5835 	This goes in .../plugin/anyname.vim.  "anyname.vim" can be freely
   5836 	chosen.  The "SearchForStuff" command is now available to the user.
   5837 
   5838 	The "autoload" argument to `:import` means that the script is not
   5839 	loaded until one of the items is actually used.  The script will be
   5840 	found under the "autoload" directory in 'runtimepath' instead of the
   5841 	"import" directory.  Alternatively, either a relative or absolute
   5842 	name can be used - see below.
   5843 
   5844      2. In the autoload script put the bulk of the code.
   5845 >
   5846 	vim9script
   5847 	export def Stuff(arg: string): void
   5848 	  ...
   5849 <
   5850 	This goes in .../autoload/for/search.vim.
   5851 
   5852 	Putting the "search.vim" script under the "/autoload/for/" directory
   5853 	has the effect that "for#search#" will be prefixed to every exported
   5854 	item.  The prefix is obtained from the file name, just as you would
   5855 	add it manually in a legacy autoload script.  Thus the exported
   5856 	function can be found with "for#search#Stuff", but you would normally
   5857 	use `import autoload` and not use the prefix (which has the side effect
   5858 	of loading the autoload script when compiling a function that
   5859 	encounters this name).
   5860 
   5861 	You can split up the functionality and import other scripts from the
   5862 	autoload script as you like.  This way you can share code between
   5863 	plugins.
   5864 
   5865 Searching for the autoload script in all entries in 'runtimepath' can be a bit
   5866 slow.  If the plugin knows where the script is located, quite often a relative
   5867 path can be used.  This avoids the search and should be quite a bit faster.
   5868 Another advantage is that the script name does not need to be unique.  Also,
   5869 an absolute path is possible.  Examples: >
   5870 	import autoload '../lib/implement.vim'
   5871 	import autoload MyScriptsDir .. '/lib/implement.vim'
   5872 
   5873 For defining a mapping that uses the imported autoload script the special key
   5874 |<ScriptCmd>| is useful.  It allows for a command in a mapping to use the
   5875 script context of where the mapping was defined.
   5876 
   5877 When compiling a `:def` function and a function in an autoload script is
   5878 encountered, the script is not loaded until the `:def` function is called.
   5879 This also means you get any errors only at runtime, since the argument and
   5880 return types are not known yet.  If you would use the name with '#' characters
   5881 then the autoload script IS loaded.
   5882 
   5883 Be careful to not refer to an item in an autoload script that does trigger
   5884 loading it unintentionally.  For example, when setting an option that takes a
   5885 function name, make sure to use a string, not a function reference: >
   5886 	import autoload 'qftf.vim'
   5887 	&quickfixtextfunc = 'qftf.Func'  # autoload script NOT loaded
   5888 	&quickfixtextfunc = qftf.Func    # autoload script IS loaded
   5889 On the other hand, it can be useful to load the script early, at a time when
   5890 any errors should be given.
   5891 
   5892 For testing the |test_override()| function can be used to have the
   5893 `import autoload` load the script right away, so that the items and types can
   5894 be checked without waiting for them to be actually used: >
   5895 	test_override('autoload', 1)
   5896 Reset it later with: >
   5897 	test_override('autoload', 0)
   5898 Or: >
   5899 	test_override('ALL', 0)
   5900 
   5901 
   5902 ==============================================================================
   5903 
   5904 7. Classes and interfaces				*vim9-classes*
   5905 
   5906 In legacy Vim script, a Dictionary could be used as a kind-of object by adding
   5907 members that are functions.  However, this is quite inefficient and requires
   5908 the writer to do the work of making sure all the objects have the right
   5909 members.  See |Dictionary-function|.
   5910 
   5911 In |Vim9| script you can have classes, objects, interfaces, and enums like
   5912 in most popular object-oriented programming languages.  Since this is a lot
   5913 of functionality, it is located in a separate help file, |vim9class.txt|,
   5914 though there are several sourceable examples within this help file too (at
   5915 |vim9-class-type|, |vim9-enum-type|, and elsewhere).
   5916 
   5917 
   5918 ==============================================================================
   5919 
   5920 8. Rationale						*vim9-rationale*
   5921 
   5922 The :def command ~
   5923 
   5924 Plugin writers have asked for much faster Vim script.  Investigations have
   5925 shown that keeping the existing semantics of function calls make this close to
   5926 impossible, because of the overhead involved with calling a function, setting
   5927 up the local function scope and executing lines.  There are many details that
   5928 need to be handled, such as error messages and exceptions.  The need to create
   5929 a dictionary for a: and l: scopes, the a:000 list and several others add too
   5930 much overhead that cannot be avoided.
   5931 
   5932 Therefore the `:def` method to define a new-style function had to be added,
   5933 which allows for a function with different semantics.  Most things still work
   5934 as before, but some parts do not.  A new way to define a function was
   5935 considered the best way to separate the legacy style code from Vim9 style
   5936 code.
   5937 
   5938 Using "def" to define a function comes from Python.  Other languages use
   5939 "function" which clashes with legacy Vim script.
   5940 
   5941 
   5942 Type checking ~
   5943 
   5944 When compiling lines of Vim commands into instructions as much as possible
   5945 should be done at compile time.  Postponing it to runtime makes the execution
   5946 slower and means mistakes are found only later.  For example, when
   5947 encountering the "+" character and compiling this into a generic add
   5948 instruction, at runtime the instruction would have to inspect the type of the
   5949 arguments and decide what kind of addition to do.  And when the type is
   5950 dictionary, give an error.  If the types are known to be numbers then an "add
   5951 number" instruction can be used, which is faster.  The error can be given at
   5952 compile time, no error handling is needed at runtime, since adding two numbers
   5953 almost never fails.
   5954 
   5955 Note: As a tangential point, the exception is integer overflow, where the
   5956 result exceeds the maximum integer value.  For example, adding to a 64-bit
   5957 signed integer where the result is greater than 2^63:
   5958 >vim9
   5959 	vim9script
   5960 	echo 9223372036854775807 + 1     # -9223372036854775808
   5961 	echo 2->pow(63)->float2nr() + 1  # -9223372036854775808
   5962 <
   5963 The syntax for types, using <type> for compound types, is similar to Java.
   5964 It is easy to understand and widely used.  The type names are what were used
   5965 in Vim before, with some additions such as "void" and "bool".
   5966 
   5967 
   5968 Removing clutter and weirdness ~
   5969 
   5970 Once decided that `:def` functions have different syntax than legacy
   5971 functions, we are free to add improvements to make the code more familiar for
   5972 users who know popular programming languages.  In other words: remove weird
   5973 things that only Vim does.
   5974 
   5975 We can also remove clutter, mainly things that were done to make Vim script
   5976 backwards compatible with the good old Vi commands.
   5977 
   5978 Examples:
   5979 - Drop `:call` for calling a function and `:eval` for evaluating an
   5980   expression.
   5981 - Drop using a leading backslash for line continuation, automatically figure
   5982   out where an expression ends.
   5983 
   5984 However, this does require that some things need to change:
   5985 - Comments start with # instead of ", to avoid confusing them with strings.
   5986   This is good anyway, it is also used by several popular languages.
   5987 - Ex command ranges need to be prefixed with a colon, to avoid confusion with
   5988   expressions (single quote can be a string or a mark, "/" can be divide or a
   5989   search command, etc.).
   5990 
   5991 Goal is to limit the differences.  A good criteria is that when the old syntax
   5992 is accidentally used you are very likely to get an error message.
   5993 
   5994 
   5995 Syntax and semantics from popular languages ~
   5996 
   5997 Script writers have complained that the Vim script syntax is unexpectedly
   5998 different from what they are used to.  To reduce this complaint popular
   5999 languages are used as an example.  At the same time, we do not want to abandon
   6000 the well-known parts of legacy Vim script.
   6001 
   6002 For many things TypeScript is followed.  It's a recent language that is
   6003 gaining popularity and has similarities with Vim script.  It also has a
   6004 mix of static typing (a variable always has a known value type) and dynamic
   6005 typing (a variable can have different types, this changes at runtime).  Since
   6006 legacy Vim script is dynamically typed and a lot of existing functionality
   6007 (esp. builtin functions) depends on that, while static typing allows for much
   6008 faster execution, we need to have this mix in Vim9 script.
   6009 
   6010 There is no intention to completely match TypeScript syntax and semantics.  We
   6011 just want to take those parts that we can use for Vim and we expect Vim users
   6012 will be happy with.  TypeScript is a complex language with its own history,
   6013 advantages and disadvantages.  To get an idea of the disadvantages read the
   6014 book: "JavaScript: The Good Parts".  Or find the article "TypeScript: the good
   6015 parts" and read the "Things to avoid" section.
   6016 
   6017 People familiar with other languages (Java, Python, etc.) will also find
   6018 things in TypeScript that they do not like or do not understand.  We'll try to
   6019 avoid those things.
   6020 
   6021 Specific items from TypeScript we avoid:
   6022 - Overloading "+", using it both for addition and string concatenation.  This
   6023   goes against legacy Vim script and often leads to mistakes.  For that reason
   6024   we will keep using ".." for string concatenation.  Lua also uses ".." this
   6025   way.  And it allows for conversion to string for more values.
   6026 - TypeScript can use an expression like '99 || "yes"' in a condition, but
   6027   cannot assign the value to a boolean.  That is inconsistent and can be
   6028   annoying.  Vim recognizes an expression with && or || and allows using the
   6029   result as a bool.  The |falsy-operator| was added for the mechanism to use a
   6030   default value - see |vim9-falsy|.
   6031 - TypeScript considers an empty string as Falsy, but an empty list or dict as
   6032   Truthy.  That is inconsistent.  In Vim an empty list and dict are also
   6033   Falsy.
   6034 - TypeScript has various "Readonly" types, which have limited usefulness,
   6035   since a type cast can remove the immutable nature.  Vim locks the value,
   6036   which is more flexible, but is only checked at runtime.
   6037 - TypeScript has a complicated "import" statement that does not match how the
   6038   Vim import mechanism works.  A much simpler mechanism is used instead, which
   6039   matches that the imported script is only sourced once.
   6040 
   6041 
   6042 Declarations ~
   6043 
   6044 Legacy Vim script uses `:let` for every assignment, while in Vim9 declarations
   6045 are used.  That is different, thus it's good to use a different command:
   6046 `:var`.  This is used in many languages.  The semantics might be slightly
   6047 different, but it's easily recognized as a declaration.
   6048 
   6049 Using `:const`  for constants is common, but the semantics varies.  Some
   6050 languages only make the variable immutable, others also make the value
   6051 immutable.  Since "final" is well known from Java for only making the variable
   6052 immutable we decided to use that.  And then `:const` can be used for making
   6053 both immutable.  This was also used in legacy Vim script and the meaning is
   6054 almost the same.
   6055 
   6056 What we end up with is very similar to Dart: >
   6057 	:var name	# mutable variable and value
   6058 	:final name	# immutable variable, mutable value
   6059 	:const name	# immutable variable and value
   6060 
   6061 Since legacy and Vim9 script will be mixed and global variables will be
   6062 shared, optional type checking is desirable.  Also, type inference will avoid
   6063 the need for specifying the type in many cases.  The TypeScript syntax fits
   6064 best for adding types to declarations:
   6065 >vim9
   6066 	vim9script
   6067 	var name: string		# string type is specified
   6068 	name = 'John'
   6069 	const GREETING = 'Hello'	# string type is inferred
   6070 	echo $'{GREETING} {name}'
   6071 <
   6072 This is how we put types in a declaration:
   6073 >vim9
   6074 	vim9script
   6075 	var vlist: list<number>
   6076 	final flist: list<string> = ['Vim']
   6077 	def Func(arg1: string, arg2: number): string
   6078 	    return $'{arg1}{arg2}'
   6079 	enddef
   6080 	vlist[0] = 9
   6081 	echo Func(flist[0], vlist[0])	# Vim9
   6082 <
   6083 These alternatives were considered:
   6084 
   6085   1. Put the type before the name, like Dart:
   6086 >
   6087 	var list<string> mylist
   6088 	final list<string> mylist = ['foo']
   6089 	def Func(number arg1, string arg2) bool
   6090 <
   6091   2. Put the type after the variable name, but do not use a colon, like Go:
   6092 >
   6093 	var mylist list<string>
   6094 	final mylist list<string> = ['foo']
   6095 	def Func(arg1 number, arg2 string) bool
   6096 <
   6097 The first is more familiar for anyone used to C or Java.  The second one
   6098 doesn't really have an advantage over the first, so let's discard the second.
   6099 
   6100 Since we use type inference the type can be left out when it can be inferred
   6101 from the value.  This means that after `var` we don't know if a type or a name
   6102 follows.  That makes parsing harder, not only for Vim but also for humans.
   6103 Also, it will not be allowed to use a variable name that could be a type name,
   6104 using `var string string` is too confusing.
   6105 
   6106 The chosen syntax, using a colon to separate the name from the type, adds
   6107 punctuation, but it actually makes it easier to recognize the parts of a
   6108 declaration.
   6109 
   6110 
   6111 Expressions ~
   6112 
   6113 Expression evaluation was already close to what other languages are doing.
   6114 Some details are unexpected and can be improved.  For example a boolean
   6115 condition would accept a string, convert it to a number and check if the
   6116 number is non-zero.  This is unexpected and often leads to mistakes, since
   6117 text not starting with a number would be converted to zero, which is
   6118 considered false.  Thus using a string for a condition would often not give an
   6119 error and be considered false.  That is confusing.
   6120 
   6121 In Vim9 type checking is stricter to avoid mistakes.  Where a condition is
   6122 used, e.g. with the `:if` command and the `||` operator, only boolean-like
   6123 values are accepted:
   6124 	true:  `true`, `v:true`, `1`, `0 < 9`
   6125 	false: `false`, `v:false`, `0`, `0 > 9`
   6126 Note that the number zero is false and the number one is true.  This is more
   6127 permissive than most other languages.  It was done because many builtin
   6128 functions return these values, and changing that causes more problems than it
   6129 solves.  After using this for a while it turned out to work well.
   6130 
   6131 If you have any type of value and want to use it as a boolean, use the `!!`
   6132 operator (see also |vim9-!!|):
   6133 >vim9
   6134 	vim9script
   6135 	# The following are all true:
   6136 	echo [!!'text', !![1], !!{'x': 1}, !!1, !!1.1]
   6137 	# And these are all false:
   6138 	echo [!!'', !![], !!{}, !!0, !!0.0]
   6139 <
   6140 From a language like JavaScript we have this handy construct: >
   6141 	GetName() || 'unknown'
   6142 However, this conflicts with only allowing a boolean for a condition.
   6143 Therefore the "??" operator was added: >
   6144 	GetName() ?? 'unknown'
   6145 Here you can explicitly express your intention to use the value as-is and not
   6146 result in a boolean.  This is called the |falsy-operator| - see |vim9-falsy|.
   6147 
   6148 
   6149 Import and Export ~
   6150 
   6151 A problem of legacy Vim script is that by default all functions and variables
   6152 are global.  It is possible to make them script-local, but then they are not
   6153 available in other scripts.  This defies the concept of a package that only
   6154 exports selected items and keeps the rest local.
   6155 
   6156 In Vim9 script a mechanism very similar to the JavaScript import and export
   6157 mechanism is supported.  It is a variant to the existing `:source` command
   6158 that works like one would expect:
   6159 - Instead of making everything global by default, everything is script-local,
   6160   some of these are exported.
   6161 - When importing a script the symbols that are imported are explicitly listed,
   6162   avoiding name conflicts and failures if functionality is added later.
   6163 - The mechanism allows for writing a big, long script with a very clear API:
   6164   the exported functions, variables and classes.
   6165 - By using relative paths loading can be much faster for an import inside of a
   6166   package, no need to search many directories.
   6167 - Once an import has been used, its items are cached and loading it again is
   6168   not needed.
   6169 - The Vim-specific use of "s:" to make things script-local can be dropped.
   6170 
   6171 When sourcing a Vim9 script (from either a Vim9 script or legacy Vim script),
   6172 only the items defined globally can be used, not the exported items.
   6173 Alternatives considered:
   6174 - All the exported items become available as script-local items.  This makes
   6175   it uncontrollable what items get defined and likely soon leads to trouble.
   6176 - Use the exported items and make them global.  Disadvantage is that it's then
   6177   not possible to avoid name clashes in the global namespace.
   6178 - Completely disallow sourcing a Vim9 script, require using `:import`.  That
   6179   makes it difficult to use scripts for testing, or sourcing them from the
   6180   command line to try them out.
   6181 Note that you CAN also use `:import` in legacy Vim script, see above.
   6182 
   6183 
   6184 Compiling functions early ~
   6185 
   6186 Functions are compiled when called or when `:defcompile` is used.  Why not
   6187 compile them early, so that syntax and type errors are reported early?
   6188 
   6189 The functions can't be compiled right away when encountered, because there may
   6190 be forward references to functions defined later.  Consider defining functions
   6191 A, B and C, where A calls B, B calls C, and C calls A again.  It's impossible
   6192 to reorder the functions to avoid forward references.
   6193 
   6194 An alternative would be to first scan through the file to locate items and
   6195 figure out their type, so that forward references are found, and only then
   6196 execute the script and compile the functions.  This means the script has to be
   6197 parsed twice, which is slower, and some conditions at the script level, such
   6198 as checking if a feature is supported, are hard to use.  An attempt was made
   6199 to see if it works, but it turned out to be impossible to make work well.
   6200 
   6201 It would be possible to compile all the functions at the end of the script.
   6202 The drawback is that if a function never gets called, the overhead of
   6203 compiling it counts anyway.  Since startup speed is very important, in most
   6204 cases it's better to do it later and accept that syntax and type errors are
   6205 only reported then.  In case these errors should be found early, e.g. when
   6206 testing, a `:defcompile` command at the end of the script will help out.
   6207 
   6208 
   6209 Why not use an existing embedded language? ~
   6210 
   6211 Vim supports interfaces to Perl, Python, Lua, Tcl and a few others.  But
   6212 these interfaces have never become widely used, for various reasons.  When
   6213 Vim9 was designed a decision was made to make these interfaces lower priority
   6214 and concentrate on Vim script.
   6215 
   6216 Still, plugin writers may find other languages more familiar, want to use
   6217 existing libraries or see a performance benefit.  We encourage plugin authors
   6218 to write code in any language and run it as an external process, using jobs
   6219 and channels.  We can try to make this easier somehow.
   6220 
   6221 Using an external tool also has disadvantages.  An alternative is to convert
   6222 the tool into Vim script.  For that to be possible without too much
   6223 translation, and keeping the code fast at the same time, the constructs of the
   6224 tool need to be supported.  Since Vim9 script now includes support for
   6225 classes, objects, interfaces, and enums, that is increasingly feasible.
   6226 
   6227 
   6228 
   6229  vim:tw=78:ts=8:noet:ft=help:norl: