1" Tests for various functions.
2
3source shared.vim
4source check.vim
5source term_util.vim
6source screendump.vim
7source vim9.vim
8
9" Must be done first, since the alternate buffer must be unset.
10func Test_00_bufexists()
11  call assert_equal(0, bufexists('does_not_exist'))
12  call assert_equal(1, bufexists(bufnr('%')))
13  call assert_equal(0, bufexists(0))
14  new Xfoo
15  let bn = bufnr('%')
16  call assert_equal(1, bufexists(bn))
17  call assert_equal(1, bufexists('Xfoo'))
18  call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
19  call assert_equal(1, bufexists(0))
20  bw
21  call assert_equal(0, bufexists(bn))
22  call assert_equal(0, bufexists('Xfoo'))
23endfunc
24
25func Test_has()
26  call assert_equal(1, has('eval'))
27  call assert_equal(1, has('eval', 1))
28
29  if has('unix')
30    call assert_equal(1, or(has('ttyin'), 1))
31    call assert_equal(0, and(has('ttyout'), 0))
32    call assert_equal(1, has('multi_byte_encoding'))
33  endif
34  call assert_equal(1, has('vcon', 1))
35  call assert_equal(1, has('mouse_gpm_enabled', 1))
36
37  call assert_equal(0, has('nonexistent'))
38  call assert_equal(0, has('nonexistent', 1))
39
40  " Will we ever have patch 9999?
41  let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999'
42  call assert_equal(0, has(ver))
43endfunc
44
45func Test_empty()
46  call assert_equal(1, empty(''))
47  call assert_equal(0, empty('a'))
48
49  call assert_equal(1, empty(0))
50  call assert_equal(1, empty(-0))
51  call assert_equal(0, empty(1))
52  call assert_equal(0, empty(-1))
53
54  if has('float')
55    call assert_equal(1, empty(0.0))
56    call assert_equal(1, empty(-0.0))
57    call assert_equal(0, empty(1.0))
58    call assert_equal(0, empty(-1.0))
59    call assert_equal(0, empty(1.0/0.0))
60    call assert_equal(0, empty(0.0/0.0))
61  endif
62
63  call assert_equal(1, empty([]))
64  call assert_equal(0, empty(['a']))
65
66  call assert_equal(1, empty({}))
67  call assert_equal(0, empty({'a':1}))
68
69  call assert_equal(1, empty(v:null))
70  call assert_equal(1, empty(v:none))
71  call assert_equal(1, empty(v:false))
72  call assert_equal(0, empty(v:true))
73
74  if has('channel')
75    call assert_equal(1, empty(test_null_channel()))
76  endif
77  if has('job')
78    call assert_equal(1, empty(test_null_job()))
79  endif
80
81  call assert_equal(0, empty(function('Test_empty')))
82  call assert_equal(0, empty(function('Test_empty', [0])))
83
84  call assert_fails("call empty(test_void())", 'E685:')
85  call assert_fails("call empty(test_unknown())", 'E685:')
86endfunc
87
88func Test_test_void()
89  call assert_fails('echo 1 == test_void()', 'E685:')
90  if has('float')
91    call assert_fails('echo 1.0 == test_void()', 'E685:')
92  endif
93  call assert_fails('let x = json_encode(test_void())', 'E685:')
94  call assert_fails('let x = copy(test_void())', 'E685:')
95  call assert_fails('let x = copy([test_void()])', 'E685:')
96endfunc
97
98func Test_len()
99  call assert_equal(1, len(0))
100  call assert_equal(2, len(12))
101
102  call assert_equal(0, len(''))
103  call assert_equal(2, len('ab'))
104
105  call assert_equal(0, len([]))
106  call assert_equal(0, len(test_null_list()))
107  call assert_equal(2, len([2, 1]))
108
109  call assert_equal(0, len({}))
110  call assert_equal(0, len(test_null_dict()))
111  call assert_equal(2, len({'a': 1, 'b': 2}))
112
113  call assert_fails('call len(v:none)', 'E701:')
114  call assert_fails('call len({-> 0})', 'E701:')
115endfunc
116
117func Test_max()
118  call assert_equal(0, max([]))
119  call assert_equal(2, max([2]))
120  call assert_equal(2, max([1, 2]))
121  call assert_equal(2, max([1, 2, v:null]))
122
123  call assert_equal(0, max({}))
124  call assert_equal(2, max({'a':1, 'b':2}))
125
126  call assert_fails('call max(1)', 'E712:')
127  call assert_fails('call max(v:none)', 'E712:')
128
129  " check we only get one error
130  call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:'])
131  call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:'])
132endfunc
133
134func Test_min()
135  call assert_equal(0, min([]))
136  call assert_equal(2, min([2]))
137  call assert_equal(1, min([1, 2]))
138  call assert_equal(0, min([1, 2, v:null]))
139
140  call assert_equal(0, min({}))
141  call assert_equal(1, min({'a':1, 'b':2}))
142
143  call assert_fails('call min(1)', 'E712:')
144  call assert_fails('call min(v:none)', 'E712:')
145  call assert_fails('call min([1, {}])', 'E728:')
146
147  " check we only get one error
148  call assert_fails('call min([[1], #{}])', ['E745:', 'E745:'])
149  call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:'])
150endfunc
151
152func Test_strwidth()
153  for aw in ['single', 'double']
154    exe 'set ambiwidth=' . aw
155    call assert_equal(0, strwidth(''))
156    call assert_equal(1, strwidth("\t"))
157    call assert_equal(3, strwidth('Vim'))
158    call assert_equal(4, strwidth(1234))
159    call assert_equal(5, strwidth(-1234))
160
161    call assert_equal(2, strwidth('��'))
162    call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
163    call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
164
165    call assert_fails('call strwidth({->0})', 'E729:')
166    call assert_fails('call strwidth([])', 'E730:')
167    call assert_fails('call strwidth({})', 'E731:')
168    if has('float')
169      call assert_fails('call strwidth(1.2)', 'E806:')
170    endif
171  endfor
172
173  set ambiwidth&
174endfunc
175
176func Test_str2nr()
177  call assert_equal(0, str2nr(''))
178  call assert_equal(1, str2nr('1'))
179  call assert_equal(1, str2nr(' 1 '))
180
181  call assert_equal(1, str2nr('+1'))
182  call assert_equal(1, str2nr('+ 1'))
183  call assert_equal(1, str2nr(' + 1 '))
184
185  call assert_equal(-1, str2nr('-1'))
186  call assert_equal(-1, str2nr('- 1'))
187  call assert_equal(-1, str2nr(' - 1 '))
188
189  call assert_equal(123456789, str2nr('123456789'))
190  call assert_equal(-123456789, str2nr('-123456789'))
191
192  call assert_equal(5, str2nr('101', 2))
193  call assert_equal(5, '0b101'->str2nr(2))
194  call assert_equal(5, str2nr('0B101', 2))
195  call assert_equal(-5, str2nr('-101', 2))
196  call assert_equal(-5, str2nr('-0b101', 2))
197  call assert_equal(-5, str2nr('-0B101', 2))
198
199  call assert_equal(65, str2nr('101', 8))
200  call assert_equal(65, str2nr('0101', 8))
201  call assert_equal(-65, str2nr('-101', 8))
202  call assert_equal(-65, str2nr('-0101', 8))
203  call assert_equal(65, str2nr('0o101', 8))
204  call assert_equal(65, str2nr('0O0101', 8))
205  call assert_equal(-65, str2nr('-0O101', 8))
206  call assert_equal(-65, str2nr('-0o0101', 8))
207
208  call assert_equal(11259375, str2nr('abcdef', 16))
209  call assert_equal(11259375, str2nr('ABCDEF', 16))
210  call assert_equal(-11259375, str2nr('-ABCDEF', 16))
211  call assert_equal(11259375, str2nr('0xabcdef', 16))
212  call assert_equal(11259375, str2nr('0Xabcdef', 16))
213  call assert_equal(11259375, str2nr('0XABCDEF', 16))
214  call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
215
216  call assert_equal(1, str2nr("1'000'000", 10, 0))
217  call assert_equal(256, str2nr("1'0000'0000", 2, 1))
218  call assert_equal(262144, str2nr("1'000'000", 8, 1))
219  call assert_equal(1000000, str2nr("1'000'000", 10, 1))
220  call assert_equal(1000, str2nr("1'000''000", 10, 1))
221  call assert_equal(65536, str2nr("1'00'00", 16, 1))
222
223  call assert_equal(0, str2nr('0x10'))
224  call assert_equal(0, str2nr('0b10'))
225  call assert_equal(0, str2nr('0o10'))
226  call assert_equal(1, str2nr('12', 2))
227  call assert_equal(1, str2nr('18', 8))
228  call assert_equal(1, str2nr('1g', 16))
229
230  call assert_equal(0, str2nr(v:null))
231  call assert_equal(0, str2nr(v:none))
232
233  call assert_fails('call str2nr([])', 'E730:')
234  call assert_fails('call str2nr({->2})', 'E729:')
235  if has('float')
236    call assert_fails('call str2nr(1.2)', 'E806:')
237  endif
238  call assert_fails('call str2nr(10, [])', 'E745:')
239endfunc
240
241func Test_strftime()
242  CheckFunction strftime
243
244  " Format of strftime() depends on system. We assume
245  " that basic formats tested here are available and
246  " identical on all systems which support strftime().
247  "
248  " The 2nd parameter of strftime() is a local time, so the output day
249  " of strftime() can be 17 or 18, depending on timezone.
250  call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
251  "
252  call assert_match('^\d\d\d\d-\(0\d\|1[012]\)-\([012]\d\|3[01]\) \([01]\d\|2[0-3]\):[0-5]\d:\([0-5]\d\|60\)$', '%Y-%m-%d %H:%M:%S'->strftime())
253
254  call assert_fails('call strftime([])', 'E730:')
255  call assert_fails('call strftime("%Y", [])', 'E745:')
256
257  " Check that the time changes after we change the timezone
258  " Save previous timezone value, if any
259  if exists('$TZ')
260    let tz = $TZ
261  endif
262
263  " Force EST and then UTC, save the current hour (24-hour clock) for each
264  let $TZ = 'EST' | let est = strftime('%H')
265  let $TZ = 'UTC' | let utc = strftime('%H')
266
267  " Those hours should be two bytes long, and should not be the same; if they
268  " are, a tzset(3) call may have failed somewhere
269  call assert_equal(strlen(est), 2)
270  call assert_equal(strlen(utc), 2)
271  " TODO: this fails on MS-Windows
272  if has('unix')
273    call assert_notequal(est, utc)
274  endif
275
276  " If we cached a timezone value, put it back, otherwise clear it
277  if exists('tz')
278    let $TZ = tz
279  else
280    unlet $TZ
281  endif
282endfunc
283
284func Test_strptime()
285  CheckFunction strptime
286
287  if exists('$TZ')
288    let tz = $TZ
289  endif
290  let $TZ = 'UTC'
291
292  call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
293
294  " Force DST and check that it's considered
295  let $TZ = 'WINTER0SUMMER,J1,J365'
296  call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
297
298  call assert_fails('call strptime()', 'E119:')
299  call assert_fails('call strptime("xxx")', 'E119:')
300  call assert_equal(0, strptime("%Y", ''))
301  call assert_equal(0, strptime("%Y", "xxx"))
302
303  if exists('tz')
304    let $TZ = tz
305  else
306    unlet $TZ
307  endif
308endfunc
309
310func Test_resolve_unix()
311  CheckUnix
312
313  " Xlink1 -> Xlink2
314  " Xlink2 -> Xlink3
315  silent !ln -s -f Xlink2 Xlink1
316  silent !ln -s -f Xlink3 Xlink2
317  call assert_equal('Xlink3', resolve('Xlink1'))
318  call assert_equal('./Xlink3', resolve('./Xlink1'))
319  call assert_equal('Xlink3/', resolve('Xlink2/'))
320  " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
321  "call assert_equal('Xlink3/', resolve('Xlink1/'))
322  "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
323  "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
324  call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
325
326  " Test resolve() with a symlink cycle.
327  " Xlink1 -> Xlink2
328  " Xlink2 -> Xlink3
329  " Xlink3 -> Xlink1
330  silent !ln -s -f Xlink1 Xlink3
331  call assert_fails('call resolve("Xlink1")',   'E655:')
332  call assert_fails('call resolve("./Xlink1")', 'E655:')
333  call assert_fails('call resolve("Xlink2")',   'E655:')
334  call assert_fails('call resolve("Xlink3")',   'E655:')
335  call delete('Xlink1')
336  call delete('Xlink2')
337  call delete('Xlink3')
338
339  silent !ln -s -f Xdir//Xfile Xlink
340  call assert_equal('Xdir/Xfile', resolve('Xlink'))
341  call delete('Xlink')
342
343  silent !ln -s -f Xlink2/ Xlink1
344  call assert_equal('Xlink2', 'Xlink1'->resolve())
345  call assert_equal('Xlink2/', resolve('Xlink1/'))
346  call delete('Xlink1')
347
348  silent !ln -s -f ./Xlink2 Xlink1
349  call assert_equal('Xlink2', resolve('Xlink1'))
350  call assert_equal('./Xlink2', resolve('./Xlink1'))
351  call delete('Xlink1')
352
353  call assert_equal('/', resolve('/'))
354endfunc
355
356func s:normalize_fname(fname)
357  let ret = substitute(a:fname, '\', '/', 'g')
358  let ret = substitute(ret, '//', '/', 'g')
359  return ret->tolower()
360endfunc
361
362func Test_resolve_win32()
363  CheckMSWindows
364
365  " test for shortcut file
366  if executable('cscript')
367    new Xfile
368    wq
369    let lines =<< trim END
370	Set fs = CreateObject("Scripting.FileSystemObject")
371	Set ws = WScript.CreateObject("WScript.Shell")
372	Set shortcut = ws.CreateShortcut("Xlink.lnk")
373	shortcut.TargetPath = fs.BuildPath(ws.CurrentDirectory, "Xfile")
374	shortcut.Save
375    END
376    call writefile(lines, 'link.vbs')
377    silent !cscript link.vbs
378    call delete('link.vbs')
379    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink.lnk')))
380    call delete('Xfile')
381
382    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink.lnk')))
383    call delete('Xlink.lnk')
384  else
385    echomsg 'skipped test for shortcut file'
386  endif
387
388  " remove files
389  call delete('Xlink')
390  call delete('Xdir', 'd')
391  call delete('Xfile')
392
393  " test for symbolic link to a file
394  new Xfile
395  wq
396  call assert_equal('Xfile', resolve('Xfile'))
397  silent !mklink Xlink Xfile
398  if !v:shell_error
399    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink')))
400    call delete('Xlink')
401  else
402    echomsg 'skipped test for symbolic link to a file'
403  endif
404  call delete('Xfile')
405
406  " test for junction to a directory
407  call mkdir('Xdir')
408  silent !mklink /J Xlink Xdir
409  if !v:shell_error
410    call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
411
412    call delete('Xdir', 'd')
413
414    " test for junction already removed
415    call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
416    call delete('Xlink')
417  else
418    echomsg 'skipped test for junction to a directory'
419    call delete('Xdir', 'd')
420  endif
421
422  " test for symbolic link to a directory
423  call mkdir('Xdir')
424  silent !mklink /D Xlink Xdir
425  if !v:shell_error
426    call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
427
428    call delete('Xdir', 'd')
429
430    " test for symbolic link already removed
431    call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
432    call delete('Xlink')
433  else
434    echomsg 'skipped test for symbolic link to a directory'
435    call delete('Xdir', 'd')
436  endif
437
438  " test for buffer name
439  new Xfile
440  wq
441  silent !mklink Xlink Xfile
442  if !v:shell_error
443    edit Xlink
444    call assert_equal('Xlink', bufname('%'))
445    call delete('Xlink')
446    bw!
447  else
448    echomsg 'skipped test for buffer name'
449  endif
450  call delete('Xfile')
451
452  " test for reparse point
453  call mkdir('Xdir')
454  call assert_equal('Xdir', resolve('Xdir'))
455  silent !mklink /D Xdirlink Xdir
456  if !v:shell_error
457    w Xdir/text.txt
458    call assert_equal('Xdir/text.txt', resolve('Xdir/text.txt'))
459    call assert_equal(s:normalize_fname(getcwd() . '\Xdir\text.txt'), s:normalize_fname(resolve('Xdirlink\text.txt')))
460    call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve('Xdirlink')))
461    call delete('Xdirlink')
462  else
463    echomsg 'skipped test for reparse point'
464  endif
465
466  call delete('Xdir', 'rf')
467endfunc
468
469func Test_simplify()
470  call assert_equal('',            simplify(''))
471  call assert_equal('/',           simplify('/'))
472  call assert_equal('/',           simplify('/.'))
473  call assert_equal('/',           simplify('/..'))
474  call assert_equal('/...',        simplify('/...'))
475  call assert_equal('//path',      simplify('//path'))
476  if has('unix')
477    call assert_equal('/path',       simplify('///path'))
478    call assert_equal('/path',       simplify('////path'))
479  endif
480
481  call assert_equal('./dir/file',  './dir/file'->simplify())
482  call assert_equal('./dir/file',  simplify('.///dir//file'))
483  call assert_equal('./dir/file',  simplify('./dir/./file'))
484  call assert_equal('./file',      simplify('./dir/../file'))
485  call assert_equal('../dir/file', simplify('dir/../../dir/file'))
486  call assert_equal('./file',      simplify('dir/.././file'))
487  call assert_equal('../dir',      simplify('./../dir'))
488  call assert_equal('..',          simplify('../testdir/..'))
489  call mkdir('Xdir')
490  call assert_equal('.',           simplify('Xdir/../.'))
491  call delete('Xdir', 'd')
492
493  call assert_fails('call simplify({->0})', 'E729:')
494  call assert_fails('call simplify([])', 'E730:')
495  call assert_fails('call simplify({})', 'E731:')
496  if has('float')
497    call assert_fails('call simplify(1.2)', 'E806:')
498  endif
499endfunc
500
501func Test_pathshorten()
502  call assert_equal('', pathshorten(''))
503  call assert_equal('foo', pathshorten('foo'))
504  call assert_equal('/foo', '/foo'->pathshorten())
505  call assert_equal('f/', pathshorten('foo/'))
506  call assert_equal('f/bar', pathshorten('foo/bar'))
507  call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten())
508  call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
509  call assert_equal('.f/bar', pathshorten('.foo/bar'))
510  call assert_equal('~f/bar', pathshorten('~foo/bar'))
511  call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
512  call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
513  call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
514  call assert_fails('call pathshorten([])', 'E730:')
515
516  " test pathshorten with optional variable to set preferred size of shortening
517  call assert_equal('', pathshorten('', 2))
518  call assert_equal('foo', pathshorten('foo', 2))
519  call assert_equal('/foo', pathshorten('/foo', 2))
520  call assert_equal('fo/', pathshorten('foo/', 2))
521  call assert_equal('fo/bar', pathshorten('foo/bar', 2))
522  call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2))
523  call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2))
524  call assert_equal('.fo/bar', pathshorten('.foo/bar', 2))
525  call assert_equal('~fo/bar', pathshorten('~foo/bar', 2))
526  call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2))
527  call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2))
528  call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2))
529  call assert_fails('call pathshorten([],2)', 'E730:')
530  call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3))
531  call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3))
532  call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0))
533endfunc
534
535func Test_strpart()
536  call assert_equal('de', strpart('abcdefg', 3, 2))
537  call assert_equal('ab', strpart('abcdefg', -2, 4))
538  call assert_equal('abcdefg', 'abcdefg'->strpart(-2))
539  call assert_equal('fg', strpart('abcdefg', 5, 4))
540  call assert_equal('defg', strpart('abcdefg', 3))
541  call assert_equal('', strpart('abcdefg', 10))
542  call assert_fails("let s=strpart('abcdef', [])", 'E745:')
543
544  call assert_equal('lép', strpart('éléphant', 2, 4))
545  call assert_equal('léphant', strpart('éléphant', 2))
546
547  call assert_equal('é', strpart('éléphant', 0, 1, 1))
548  call assert_equal('ép', strpart('éléphant', 3, 2, v:true))
549  call assert_equal('ó', strpart('cómposed', 1, 1, 1))
550endfunc
551
552func Test_tolower()
553  call assert_equal("", tolower(""))
554
555  " Test with all printable ASCII characters.
556  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
557          \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
558
559  " Test with a few uppercase diacritics.
560  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
561  call assert_equal("bḃḇ", tolower("BḂḆ"))
562  call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
563  call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
564  call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
565  call assert_equal("fḟ ", tolower("FḞ "))
566  call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
567  call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
568  call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
569  call assert_equal("jĵ", tolower("JĴ"))
570  call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
571  call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
572  call assert_equal("mḿṁ", tolower("MḾṀ"))
573  call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
574  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
575  call assert_equal("pṕṗ", tolower("PṔṖ"))
576  call assert_equal("q", tolower("Q"))
577  call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
578  call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
579  call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
580  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
581  call assert_equal("vṽ", tolower("VṼ"))
582  call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
583  call assert_equal("xẋẍ", tolower("XẊẌ"))
584  call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
585  call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
586
587  " Test with a few lowercase diacritics, which should remain unchanged.
588  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
589  call assert_equal("bḃḇ", tolower("bḃḇ"))
590  call assert_equal("cçćĉċč", tolower("cçćĉċč"))
591  call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
592  call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
593  call assert_equal("fḟ", tolower("fḟ"))
594  call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
595  call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
596  call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
597  call assert_equal("jĵǰ", tolower("jĵǰ"))
598  call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
599  call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
600  call assert_equal("mḿṁ ", tolower("mḿṁ "))
601  call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
602  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
603  call assert_equal("pṕṗ", tolower("pṕṗ"))
604  call assert_equal("q", tolower("q"))
605  call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
606  call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
607  call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
608  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
609  call assert_equal("vṽ", tolower("vṽ"))
610  call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
611  call assert_equal("ẋẍ", tolower("ẋẍ"))
612  call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
613  call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
614
615  " According to https://twitter.com/jifa/status/625776454479970304
616  " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
617  " in length (2 to 3 bytes) when lowercased. So let's test them.
618  call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
619
620  " This call to tolower with invalid utf8 sequence used to cause access to
621  " invalid memory.
622  call tolower("\xC0\x80\xC0")
623  call tolower("123\xC0\x80\xC0")
624
625  " Test in latin1 encoding
626  let save_enc = &encoding
627  set encoding=latin1
628  call assert_equal("abc", tolower("ABC"))
629  let &encoding = save_enc
630endfunc
631
632func Test_toupper()
633  call assert_equal("", toupper(""))
634
635  " Test with all printable ASCII characters.
636  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
637          \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
638
639  " Test with a few lowercase diacritics.
640  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper())
641  call assert_equal("BḂḆ", toupper("bḃḇ"))
642  call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
643  call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
644  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
645  call assert_equal("FḞ", toupper("fḟ"))
646  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
647  call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
648  call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
649  call assert_equal("JĴǰ", toupper("jĵǰ"))
650  call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
651  call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
652  call assert_equal("MḾṀ ", toupper("mḿṁ "))
653  call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
654  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
655  call assert_equal("PṔṖ", toupper("pṕṗ"))
656  call assert_equal("Q", toupper("q"))
657  call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
658  call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
659  call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
660  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
661  call assert_equal("VṼ", toupper("vṽ"))
662  call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
663  call assert_equal("ẊẌ", toupper("ẋẍ"))
664  call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
665  call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
666
667  " Test that uppercase diacritics, which should remain unchanged.
668  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
669  call assert_equal("BḂḆ", toupper("BḂḆ"))
670  call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
671  call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
672  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
673  call assert_equal("FḞ ", toupper("FḞ "))
674  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
675  call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
676  call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
677  call assert_equal("JĴ", toupper("JĴ"))
678  call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
679  call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
680  call assert_equal("MḾṀ", toupper("MḾṀ"))
681  call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
682  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
683  call assert_equal("PṔṖ", toupper("PṔṖ"))
684  call assert_equal("Q", toupper("Q"))
685  call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
686  call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
687  call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
688  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
689  call assert_equal("VṼ", toupper("VṼ"))
690  call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
691  call assert_equal("XẊẌ", toupper("XẊẌ"))
692  call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
693  call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
694
695  call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
696
697  " This call to toupper with invalid utf8 sequence used to cause access to
698  " invalid memory.
699  call toupper("\xC0\x80\xC0")
700  call toupper("123\xC0\x80\xC0")
701
702  " Test in latin1 encoding
703  let save_enc = &encoding
704  set encoding=latin1
705  call assert_equal("ABC", toupper("abc"))
706  let &encoding = save_enc
707endfunc
708
709func Test_tr()
710  call assert_equal('foo', tr('bar', 'bar', 'foo'))
711  call assert_equal('zxy', 'cab'->tr('abc', 'xyz'))
712  call assert_fails("let s=tr([], 'abc', 'def')", 'E730:')
713  call assert_fails("let s=tr('abc', [], 'def')", 'E730:')
714  call assert_fails("let s=tr('abc', 'abc', [])", 'E730:')
715  call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
716  set encoding=latin1
717  call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
718  call assert_equal('hEllO', tr('hello', 'eo', 'EO'))
719  call assert_equal('hello', tr('hello', 'xy', 'ab'))
720  call assert_fails('call tr("abc", "123", "₁₂")', 'E475:')
721  set encoding=utf8
722endfunc
723
724" Tests for the mode() function
725let current_modes = ''
726func Save_mode()
727  let g:current_modes = mode(0) . '-' . mode(1)
728  return ''
729endfunc
730
731" Test for the mode() function
732func Test_mode()
733  new
734  call append(0, ["Blue Ball Black", "Brown Band Bowl", ""])
735
736  " Only complete from the current buffer.
737  set complete=.
738
739  inoremap <F2> <C-R>=Save_mode()<CR>
740
741  normal! 3G
742  exe "normal i\<F2>\<Esc>"
743  call assert_equal('i-i', g:current_modes)
744  " i_CTRL-P: Multiple matches
745  exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
746  call assert_equal('i-ic', g:current_modes)
747  " i_CTRL-P: Single match
748  exe "normal iBro\<C-P>\<F2>\<Esc>u"
749  call assert_equal('i-ic', g:current_modes)
750  " i_CTRL-X
751  exe "normal iBa\<C-X>\<F2>\<Esc>u"
752  call assert_equal('i-ix', g:current_modes)
753  " i_CTRL-X CTRL-P: Multiple matches
754  exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
755  call assert_equal('i-ic', g:current_modes)
756  " i_CTRL-X CTRL-P: Single match
757  exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u"
758  call assert_equal('i-ic', g:current_modes)
759  " i_CTRL-X CTRL-P + CTRL-P: Single match
760  exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
761  call assert_equal('i-ic', g:current_modes)
762  " i_CTRL-X CTRL-L: Multiple matches
763  exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
764  call assert_equal('i-ic', g:current_modes)
765  " i_CTRL-X CTRL-L: Single match
766  exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
767  call assert_equal('i-ic', g:current_modes)
768  " i_CTRL-P: No match
769  exe "normal iCom\<C-P>\<F2>\<Esc>u"
770  call assert_equal('i-ic', g:current_modes)
771  " i_CTRL-X CTRL-P: No match
772  exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u"
773  call assert_equal('i-ic', g:current_modes)
774  " i_CTRL-X CTRL-L: No match
775  exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
776  call assert_equal('i-ic', g:current_modes)
777
778  " R_CTRL-P: Multiple matches
779  exe "normal RBa\<C-P>\<F2>\<Esc>u"
780  call assert_equal('R-Rc', g:current_modes)
781  " R_CTRL-P: Single match
782  exe "normal RBro\<C-P>\<F2>\<Esc>u"
783  call assert_equal('R-Rc', g:current_modes)
784  " R_CTRL-X
785  exe "normal RBa\<C-X>\<F2>\<Esc>u"
786  call assert_equal('R-Rx', g:current_modes)
787  " R_CTRL-X CTRL-P: Multiple matches
788  exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
789  call assert_equal('R-Rc', g:current_modes)
790  " R_CTRL-X CTRL-P: Single match
791  exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u"
792  call assert_equal('R-Rc', g:current_modes)
793  " R_CTRL-X CTRL-P + CTRL-P: Single match
794  exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
795  call assert_equal('R-Rc', g:current_modes)
796  " R_CTRL-X CTRL-L: Multiple matches
797  exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
798  call assert_equal('R-Rc', g:current_modes)
799  " R_CTRL-X CTRL-L: Single match
800  exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
801  call assert_equal('R-Rc', g:current_modes)
802  " R_CTRL-P: No match
803  exe "normal RCom\<C-P>\<F2>\<Esc>u"
804  call assert_equal('R-Rc', g:current_modes)
805  " R_CTRL-X CTRL-P: No match
806  exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u"
807  call assert_equal('R-Rc', g:current_modes)
808  " R_CTRL-X CTRL-L: No match
809  exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
810  call assert_equal('R-Rc', g:current_modes)
811
812  call assert_equal('n', 0->mode())
813  call assert_equal('n', 1->mode())
814
815  " i_CTRL-O
816  exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
817  call assert_equal("n-niI", g:current_modes)
818
819  " R_CTRL-O
820  exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
821  call assert_equal("n-niR", g:current_modes)
822
823  " gR_CTRL-O
824  exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
825  call assert_equal("n-niV", g:current_modes)
826
827  " How to test operator-pending mode?
828
829  call feedkeys("v", 'xt')
830  call assert_equal('v', mode())
831  call assert_equal('v', mode(1))
832  call feedkeys("\<Esc>V", 'xt')
833  call assert_equal('V', mode())
834  call assert_equal('V', mode(1))
835  call feedkeys("\<Esc>\<C-V>", 'xt')
836  call assert_equal("\<C-V>", mode())
837  call assert_equal("\<C-V>", mode(1))
838  call feedkeys("\<Esc>", 'xt')
839
840  call feedkeys("gh", 'xt')
841  call assert_equal('s', mode())
842  call assert_equal('s', mode(1))
843  call feedkeys("\<Esc>gH", 'xt')
844  call assert_equal('S', mode())
845  call assert_equal('S', mode(1))
846  call feedkeys("\<Esc>g\<C-H>", 'xt')
847  call assert_equal("\<C-S>", mode())
848  call assert_equal("\<C-S>", mode(1))
849  call feedkeys("\<Esc>", 'xt')
850
851  call feedkeys(":echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
852  call assert_equal('c-c', g:current_modes)
853  call feedkeys("gQecho \<C-R>=Save_mode()\<CR>\<CR>vi\<CR>", 'xt')
854  call assert_equal('c-cv', g:current_modes)
855  call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt')
856  call assert_equal('c-ce', g:current_modes)
857  " How to test Ex mode?
858
859  bwipe!
860  iunmap <F2>
861  set complete&
862endfunc
863
864" Test for append()
865func Test_append()
866  enew!
867  split
868  call append(0, ["foo"])
869  call append(1, [])
870  call append(1, test_null_list())
871  call assert_equal(['foo', ''], getline(1, '$'))
872  split
873  only
874  undo
875  undo
876
877  " Using $ instead of '$' must give an error
878  call assert_fails("call append($, 'foobar')", 'E116:')
879endfunc
880
881" Test for setline()
882func Test_setline()
883  new
884  call setline(0, ["foo"])
885  call setline(0, [])
886  call setline(0, test_null_list())
887  call setline(1, ["bar"])
888  call setline(1, [])
889  call setline(1, test_null_list())
890  call setline(2, [])
891  call setline(2, test_null_list())
892  call setline(3, [])
893  call setline(3, test_null_list())
894  call setline(2, ["baz"])
895  call assert_equal(['bar', 'baz'], getline(1, '$'))
896  close!
897endfunc
898
899func Test_getbufvar()
900  let bnr = bufnr('%')
901  let b:var_num = '1234'
902  let def_num = '5678'
903  call assert_equal('1234', getbufvar(bnr, 'var_num'))
904  call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
905
906  let bd = getbufvar(bnr, '')
907  call assert_equal('1234', bd['var_num'])
908  call assert_true(exists("bd['changedtick']"))
909  call assert_equal(2, len(bd))
910
911  let bd2 = getbufvar(bnr, '', def_num)
912  call assert_equal(bd, bd2)
913
914  unlet b:var_num
915  call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
916  call assert_equal('', getbufvar(bnr, 'var_num'))
917
918  let bd = getbufvar(bnr, '')
919  call assert_equal(1, len(bd))
920  let bd = getbufvar(bnr, '',def_num)
921  call assert_equal(1, len(bd))
922
923  call assert_equal('', getbufvar(9999, ''))
924  call assert_equal(def_num, getbufvar(9999, '', def_num))
925  unlet def_num
926
927  call assert_equal(0, getbufvar(bnr, '&autoindent'))
928  call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
929
930  " Set and get a buffer-local variable
931  call setbufvar(bnr, 'bufvar_test', ['one', 'two'])
932  call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test'))
933
934  " Open new window with forced option values
935  set fileformats=unix,dos
936  new ++ff=dos ++bin ++enc=iso-8859-2
937  call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
938  call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
939  call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
940  close
941
942  " Get the b: dict.
943  let b:testvar = 'one'
944  new
945  let b:testvar = 'two'
946  let thebuf = bufnr()
947  wincmd w
948  call assert_equal('two', getbufvar(thebuf, 'testvar'))
949  call assert_equal('two', getbufvar(thebuf, '').testvar)
950  bwipe!
951
952  set fileformats&
953endfunc
954
955func Test_last_buffer_nr()
956  call assert_equal(bufnr('$'), last_buffer_nr())
957endfunc
958
959func Test_stridx()
960  call assert_equal(-1, stridx('', 'l'))
961  call assert_equal(0,  stridx('', ''))
962  call assert_equal(0,  'hello'->stridx(''))
963  call assert_equal(-1, stridx('hello', 'L'))
964  call assert_equal(2,  stridx('hello', 'l', -1))
965  call assert_equal(2,  stridx('hello', 'l', 0))
966  call assert_equal(2,  'hello'->stridx('l', 1))
967  call assert_equal(3,  stridx('hello', 'l', 3))
968  call assert_equal(-1, stridx('hello', 'l', 4))
969  call assert_equal(-1, stridx('hello', 'l', 10))
970  call assert_equal(2,  stridx('hello', 'll'))
971  call assert_equal(-1, stridx('hello', 'hello world'))
972  call assert_fails("let n=stridx('hello', [])", 'E730:')
973  call assert_fails("let n=stridx([], 'l')", 'E730:')
974endfunc
975
976func Test_strridx()
977  call assert_equal(-1, strridx('', 'l'))
978  call assert_equal(0,  strridx('', ''))
979  call assert_equal(5,  strridx('hello', ''))
980  call assert_equal(-1, strridx('hello', 'L'))
981  call assert_equal(3,  'hello'->strridx('l'))
982  call assert_equal(3,  strridx('hello', 'l', 10))
983  call assert_equal(3,  strridx('hello', 'l', 3))
984  call assert_equal(2,  strridx('hello', 'l', 2))
985  call assert_equal(-1, strridx('hello', 'l', 1))
986  call assert_equal(-1, strridx('hello', 'l', 0))
987  call assert_equal(-1, strridx('hello', 'l', -1))
988  call assert_equal(2,  strridx('hello', 'll'))
989  call assert_equal(-1, strridx('hello', 'hello world'))
990  call assert_fails("let n=strridx('hello', [])", 'E730:')
991  call assert_fails("let n=strridx([], 'l')", 'E730:')
992endfunc
993
994func Test_match_func()
995  call assert_equal(4,  match('testing', 'ing'))
996  call assert_equal(4,  'testing'->match('ing', 2))
997  call assert_equal(-1, match('testing', 'ing', 5))
998  call assert_equal(-1, match('testing', 'ing', 8))
999  call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
1000  call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
1001  call assert_fails("let x=match('vim', [])", 'E730:')
1002  call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1))
1003  call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5))
1004  call assert_equal(4,  match('testing', 'ing', -1))
1005  call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:')
1006  call assert_equal(-1, match(test_null_list(), 2))
1007  call assert_equal(-1, match('abc', '\\%('))
1008endfunc
1009
1010func Test_matchend()
1011  call assert_equal(7,  matchend('testing', 'ing'))
1012  call assert_equal(7,  'testing'->matchend('ing', 2))
1013  call assert_equal(-1, matchend('testing', 'ing', 5))
1014  call assert_equal(-1, matchend('testing', 'ing', 8))
1015  call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
1016  call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
1017endfunc
1018
1019func Test_matchlist()
1020  call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
1021  call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''],  'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
1022  call assert_equal([],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
1023endfunc
1024
1025func Test_matchstr()
1026  call assert_equal('ing',  matchstr('testing', 'ing'))
1027  call assert_equal('ing',  'testing'->matchstr('ing', 2))
1028  call assert_equal('', matchstr('testing', 'ing', 5))
1029  call assert_equal('', matchstr('testing', 'ing', 8))
1030  call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
1031  call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
1032endfunc
1033
1034func Test_matchstrpos()
1035  call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
1036  call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2))
1037  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
1038  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
1039  call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
1040  call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
1041  call assert_equal(['', -1, -1], matchstrpos(test_null_list(), '\a'))
1042endfunc
1043
1044func Test_nextnonblank_prevnonblank()
1045  new
1046insert
1047This
1048
1049
1050is
1051
1052a
1053Test
1054.
1055  call assert_equal(0, nextnonblank(-1))
1056  call assert_equal(0, nextnonblank(0))
1057  call assert_equal(1, nextnonblank(1))
1058  call assert_equal(4, 2->nextnonblank())
1059  call assert_equal(4, nextnonblank(3))
1060  call assert_equal(4, nextnonblank(4))
1061  call assert_equal(6, nextnonblank(5))
1062  call assert_equal(6, nextnonblank(6))
1063  call assert_equal(7, nextnonblank(7))
1064  call assert_equal(0, 8->nextnonblank())
1065
1066  call assert_equal(0, prevnonblank(-1))
1067  call assert_equal(0, prevnonblank(0))
1068  call assert_equal(1, 1->prevnonblank())
1069  call assert_equal(1, prevnonblank(2))
1070  call assert_equal(1, prevnonblank(3))
1071  call assert_equal(4, prevnonblank(4))
1072  call assert_equal(4, 5->prevnonblank())
1073  call assert_equal(6, prevnonblank(6))
1074  call assert_equal(7, prevnonblank(7))
1075  call assert_equal(0, prevnonblank(8))
1076  bw!
1077endfunc
1078
1079func Test_byte2line_line2byte()
1080  new
1081  set endofline
1082  call setline(1, ['a', 'bc', 'd'])
1083
1084  set fileformat=unix
1085  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1086  \                 map(range(-1, 8), 'byte2line(v:val)'))
1087  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1088  \                 map(range(-1, 5), 'line2byte(v:val)'))
1089
1090  set fileformat=mac
1091  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1092  \                 map(range(-1, 8), 'v:val->byte2line()'))
1093  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1094  \                 map(range(-1, 5), 'v:val->line2byte()'))
1095
1096  set fileformat=dos
1097  call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
1098  \                 map(range(-1, 11), 'byte2line(v:val)'))
1099  call assert_equal([-1, -1, 1, 4, 8, 11, -1],
1100  \                 map(range(-1, 5), 'line2byte(v:val)'))
1101
1102  bw!
1103  set noendofline nofixendofline
1104  normal a-
1105  for ff in ["unix", "mac", "dos"]
1106    let &fileformat = ff
1107    call assert_equal(1, line2byte(1))
1108    call assert_equal(2, line2byte(2))  " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
1109  endfor
1110
1111  set endofline& fixendofline& fileformat&
1112  bw!
1113endfunc
1114
1115" Test for byteidx() and byteidxcomp() functions
1116func Test_byteidx()
1117  let a = '.é.' " one char of two bytes
1118  call assert_equal(0, byteidx(a, 0))
1119  call assert_equal(0, byteidxcomp(a, 0))
1120  call assert_equal(1, byteidx(a, 1))
1121  call assert_equal(1, byteidxcomp(a, 1))
1122  call assert_equal(3, byteidx(a, 2))
1123  call assert_equal(3, byteidxcomp(a, 2))
1124  call assert_equal(4, byteidx(a, 3))
1125  call assert_equal(4, byteidxcomp(a, 3))
1126  call assert_equal(-1, byteidx(a, 4))
1127  call assert_equal(-1, byteidxcomp(a, 4))
1128
1129  let b = '.é.' " normal e with composing char
1130  call assert_equal(0, b->byteidx(0))
1131  call assert_equal(1, b->byteidx(1))
1132  call assert_equal(4, b->byteidx(2))
1133  call assert_equal(5, b->byteidx(3))
1134  call assert_equal(-1, b->byteidx(4))
1135  call assert_fails("call byteidx([], 0)", 'E730:')
1136
1137  call assert_equal(0, b->byteidxcomp(0))
1138  call assert_equal(1, b->byteidxcomp(1))
1139  call assert_equal(2, b->byteidxcomp(2))
1140  call assert_equal(4, b->byteidxcomp(3))
1141  call assert_equal(5, b->byteidxcomp(4))
1142  call assert_equal(-1, b->byteidxcomp(5))
1143  call assert_fails("call byteidxcomp([], 0)", 'E730:')
1144endfunc
1145
1146" Test for charidx()
1147func Test_charidx()
1148  let a = 'xáb́y'
1149  call assert_equal(0, charidx(a, 0))
1150  call assert_equal(1, charidx(a, 3))
1151  call assert_equal(2, charidx(a, 4))
1152  call assert_equal(3, charidx(a, 7))
1153  call assert_equal(-1, charidx(a, 8))
1154  call assert_equal(-1, charidx(a, -1))
1155  call assert_equal(-1, charidx('', 0))
1156  call assert_equal(-1, charidx(test_null_string(), 0))
1157
1158  " count composing characters
1159  call assert_equal(0, charidx(a, 0, 1))
1160  call assert_equal(2, charidx(a, 2, 1))
1161  call assert_equal(3, charidx(a, 4, 1))
1162  call assert_equal(5, charidx(a, 7, 1))
1163  call assert_equal(-1, charidx(a, 8, 1))
1164  call assert_equal(-1, charidx('', 0, 1))
1165
1166  call assert_fails('let x = charidx([], 1)', 'E474:')
1167  call assert_fails('let x = charidx("abc", [])', 'E474:')
1168  call assert_fails('let x = charidx("abc", 1, [])', 'E474:')
1169  call assert_fails('let x = charidx("abc", 1, -1)', 'E1023:')
1170  call assert_fails('let x = charidx("abc", 1, 2)', 'E1023:')
1171endfunc
1172
1173func Test_count()
1174  let l = ['a', 'a', 'A', 'b']
1175  call assert_equal(2, count(l, 'a'))
1176  call assert_equal(1, count(l, 'A'))
1177  call assert_equal(1, count(l, 'b'))
1178  call assert_equal(0, count(l, 'B'))
1179
1180  call assert_equal(2, count(l, 'a', 0))
1181  call assert_equal(1, count(l, 'A', 0))
1182  call assert_equal(1, count(l, 'b', 0))
1183  call assert_equal(0, count(l, 'B', 0))
1184
1185  call assert_equal(3, count(l, 'a', 1))
1186  call assert_equal(3, count(l, 'A', 1))
1187  call assert_equal(1, count(l, 'b', 1))
1188  call assert_equal(1, count(l, 'B', 1))
1189  call assert_equal(0, count(l, 'c', 1))
1190
1191  call assert_equal(1, count(l, 'a', 0, 1))
1192  call assert_equal(2, count(l, 'a', 1, 1))
1193  call assert_fails('call count(l, "a", 0, 10)', 'E684:')
1194  call assert_fails('call count(l, "a", [])', 'E745:')
1195
1196  let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
1197  call assert_equal(2, count(d, 'a'))
1198  call assert_equal(1, count(d, 'A'))
1199  call assert_equal(1, count(d, 'b'))
1200  call assert_equal(0, count(d, 'B'))
1201
1202  call assert_equal(2, count(d, 'a', 0))
1203  call assert_equal(1, count(d, 'A', 0))
1204  call assert_equal(1, count(d, 'b', 0))
1205  call assert_equal(0, count(d, 'B', 0))
1206
1207  call assert_equal(3, count(d, 'a', 1))
1208  call assert_equal(3, count(d, 'A', 1))
1209  call assert_equal(1, count(d, 'b', 1))
1210  call assert_equal(1, count(d, 'B', 1))
1211  call assert_equal(0, count(d, 'c', 1))
1212
1213  call assert_fails('call count(d, "a", 0, 1)', 'E474:')
1214
1215  call assert_equal(0, count("foo", "bar"))
1216  call assert_equal(1, count("foo", "oo"))
1217  call assert_equal(2, count("foo", "o"))
1218  call assert_equal(0, count("foo", "O"))
1219  call assert_equal(2, count("foo", "O", 1))
1220  call assert_equal(2, count("fooooo", "oo"))
1221  call assert_equal(0, count("foo", ""))
1222
1223  call assert_fails('call count(0, 0)', 'E712:')
1224endfunc
1225
1226func Test_changenr()
1227  new Xchangenr
1228  call assert_equal(0, changenr())
1229  norm ifoo
1230  call assert_equal(1, changenr())
1231  set undolevels=10
1232  norm Sbar
1233  call assert_equal(2, changenr())
1234  undo
1235  call assert_equal(1, changenr())
1236  redo
1237  call assert_equal(2, changenr())
1238  bw!
1239  set undolevels&
1240endfunc
1241
1242func Test_filewritable()
1243  new Xfilewritable
1244  write!
1245  call assert_equal(1, filewritable('Xfilewritable'))
1246
1247  call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
1248  call assert_equal(0, filewritable('Xfilewritable'))
1249
1250  call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
1251  call assert_equal(1, 'Xfilewritable'->filewritable())
1252
1253  call assert_equal(0, filewritable('doesnotexist'))
1254
1255  call mkdir('Xdir')
1256  call assert_equal(2, filewritable('Xdir'))
1257  call delete('Xdir', 'd')
1258
1259  call delete('Xfilewritable')
1260  bw!
1261endfunc
1262
1263func Test_Executable()
1264  if has('win32')
1265    call assert_equal(1, executable('notepad'))
1266    call assert_equal(1, 'notepad.exe'->executable())
1267    call assert_equal(0, executable('notepad.exe.exe'))
1268    call assert_equal(0, executable('shell32.dll'))
1269    call assert_equal(0, executable('win.ini'))
1270
1271    " get "notepad" path and remove the leading drive and sep. (ex. 'C:\')
1272    let notepadcmd = exepath('notepad.exe')
1273    let driveroot = notepadcmd[:2]
1274    let notepadcmd = notepadcmd[3:]
1275    new
1276    " check that the relative path works in /
1277    execute 'lcd' driveroot
1278    call assert_equal(1, executable(notepadcmd))
1279    call assert_equal(driveroot .. notepadcmd, notepadcmd->exepath())
1280    bwipe
1281
1282    " create "notepad.bat"
1283    call mkdir('Xdir')
1284    let notepadbat = fnamemodify('Xdir/notepad.bat', ':p')
1285    call writefile([], notepadbat)
1286    new
1287    " check that the path and the pathext order is valid
1288    lcd Xdir
1289    let [pathext, $PATHEXT] = [$PATHEXT, '.com;.exe;.bat;.cmd']
1290    call assert_equal(notepadbat, exepath('notepad'))
1291    let $PATHEXT = pathext
1292    bwipe
1293    eval 'Xdir'->delete('rf')
1294  elseif has('unix')
1295    call assert_equal(1, 'cat'->executable())
1296    call assert_equal(0, executable('nodogshere'))
1297
1298    " get "cat" path and remove the leading /
1299    let catcmd = exepath('cat')[1:]
1300    new
1301    " check that the relative path works in /
1302    lcd /
1303    call assert_equal(1, executable(catcmd))
1304    let result = catcmd->exepath()
1305    " when using chroot looking for sbin/cat can return bin/cat, that is OK
1306    if catcmd =~ '\<sbin\>' && result =~ '\<bin\>'
1307      call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result)
1308    else
1309      call assert_equal('/' .. catcmd, result)
1310    endif
1311    bwipe
1312  else
1313    throw 'Skipped: does not work on this platform'
1314  endif
1315endfunc
1316
1317func Test_executable_longname()
1318  CheckMSWindows
1319
1320  " Create a temporary .bat file with 205 characters in the name.
1321  " Maximum length of a filename (including the path) on MS-Windows is 259
1322  " characters.
1323  " See https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
1324  let len = 259 - getcwd()->len() - 6
1325  if len > 200
1326    let len = 200
1327  endif
1328
1329  let fname = 'X' . repeat('あ', len) . '.bat'
1330  call writefile([], fname)
1331  call assert_equal(1, executable(fname))
1332  call delete(fname)
1333endfunc
1334
1335func Test_hostname()
1336  let hostname_vim = hostname()
1337  if has('unix')
1338    let hostname_system = systemlist('uname -n')[0]
1339    call assert_equal(hostname_vim, hostname_system)
1340  endif
1341endfunc
1342
1343func Test_getpid()
1344  " getpid() always returns the same value within a vim instance.
1345  call assert_equal(getpid(), getpid())
1346  if has('unix')
1347    call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
1348  endif
1349endfunc
1350
1351func Test_hlexists()
1352  call assert_equal(0, hlexists('does_not_exist'))
1353  call assert_equal(0, 'Number'->hlexists())
1354  call assert_equal(0, highlight_exists('does_not_exist'))
1355  call assert_equal(0, highlight_exists('Number'))
1356  syntax on
1357  call assert_equal(0, hlexists('does_not_exist'))
1358  call assert_equal(1, hlexists('Number'))
1359  call assert_equal(0, highlight_exists('does_not_exist'))
1360  call assert_equal(1, highlight_exists('Number'))
1361  syntax off
1362endfunc
1363
1364" Test for the col() function
1365func Test_col()
1366  new
1367  call setline(1, 'abcdef')
1368  norm gg4|mx6|mY2|
1369  call assert_equal(2, col('.'))
1370  call assert_equal(7, col('$'))
1371  call assert_equal(2, col('v'))
1372  call assert_equal(4, col("'x"))
1373  call assert_equal(6, col("'Y"))
1374  call assert_equal(2, [1, 2]->col())
1375  call assert_equal(7, col([1, '$']))
1376
1377  call assert_equal(0, col(''))
1378  call assert_equal(0, col('x'))
1379  call assert_equal(0, col([2, '$']))
1380  call assert_equal(0, col([1, 100]))
1381  call assert_equal(0, col([1]))
1382  call assert_equal(0, col(test_null_list()))
1383  call assert_fails('let c = col({})', 'E731:')
1384
1385  " test for getting the visual start column
1386  func T()
1387    let g:Vcol = col('v')
1388    return ''
1389  endfunc
1390  let g:Vcol = 0
1391  xmap <expr> <F2> T()
1392  exe "normal gg3|ve\<F2>"
1393  call assert_equal(3, g:Vcol)
1394  xunmap <F2>
1395  delfunc T
1396
1397  " Test for the visual line start and end marks '< and '>
1398  call setline(1, ['one', 'one two', 'one two three'])
1399  "normal! ggVG
1400  call feedkeys("ggVG\<Esc>", 'xt')
1401  call assert_equal(1, col("'<"))
1402  call assert_equal(14, col("'>"))
1403  " Delete the last line of the visually selected region
1404  $d
1405  call assert_notequal(14, col("'>"))
1406
1407  " Test with 'virtualedit'
1408  set virtualedit=all
1409  call cursor(1, 10)
1410  call assert_equal(4, col('.'))
1411  set virtualedit&
1412
1413  bw!
1414endfunc
1415
1416" Test for input()
1417func Test_input_func()
1418  " Test for prompt with multiple lines
1419  redir => v
1420  call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt')
1421  redir END
1422  call assert_equal("B", c)
1423  call assert_equal(['A', 'B', 'C'], split(v, "\n"))
1424
1425  " Test for default value
1426  call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt')
1427  call assert_equal('red', c)
1428
1429  " Test for completion at the input prompt
1430  func! Tcomplete(arglead, cmdline, pos)
1431    return "item1\nitem2\nitem3"
1432  endfunc
1433  call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>"
1434        \ .. "\<C-A>\<CR>", 'xt')
1435  delfunc Tcomplete
1436  call assert_equal('item1 item2 item3', c)
1437
1438  " Test for using special characters as default input
1439  call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt')
1440  call assert_equal('y', c)
1441
1442  " Test for using <CR> as default input
1443  call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt')
1444  call assert_equal(' x', c)
1445
1446  call assert_fails("call input('F:', '', 'invalid')", 'E180:')
1447  call assert_fails("call input('F:', '', [])", 'E730:')
1448endfunc
1449
1450" Test for the inputdialog() function
1451func Test_inputdialog()
1452  set timeout timeoutlen=10
1453  if has('gui_running')
1454    call assert_fails('let v=inputdialog([], "xx")', 'E730:')
1455    call assert_fails('let v=inputdialog("Q", [])', 'E730:')
1456  else
1457    call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt')
1458    call assert_equal('xx', v)
1459    call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt')
1460    call assert_equal('yy', v)
1461  endif
1462  set timeout& timeoutlen&
1463endfunc
1464
1465" Test for inputlist()
1466func Test_inputlist()
1467  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
1468  call assert_equal(1, c)
1469  call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx')
1470  call assert_equal(2, c)
1471  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
1472  call assert_equal(3, c)
1473
1474  " CR to cancel
1475  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx')
1476  call assert_equal(0, c)
1477
1478  " Esc to cancel
1479  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx')
1480  call assert_equal(0, c)
1481
1482  " q to cancel
1483  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx')
1484  call assert_equal(0, c)
1485
1486  " Cancel after inputting a number
1487  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx')
1488  call assert_equal(0, c)
1489
1490  " Use backspace to delete characters in the prompt
1491  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx')
1492  call assert_equal(2, c)
1493
1494  " Use mouse to make a selection
1495  call test_setmouse(&lines - 3, 2)
1496  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
1497  call assert_equal(1, c)
1498  " Mouse click outside of the list
1499  call test_setmouse(&lines - 6, 2)
1500  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
1501  call assert_equal(-2, c)
1502
1503  call assert_fails('call inputlist("")', 'E686:')
1504  call assert_fails('call inputlist(test_null_list())', 'E686:')
1505endfunc
1506
1507func Test_balloon_show()
1508  CheckFeature balloon_eval
1509
1510  " This won't do anything but must not crash either.
1511  call balloon_show('hi!')
1512  if !has('gui_running')
1513    call balloon_show(range(3))
1514    call balloon_show([])
1515  endif
1516endfunc
1517
1518func Test_setbufvar_options()
1519  " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
1520  " window layout.
1521  call assert_equal(1, winnr('$'))
1522  split dummy_preview
1523  resize 2
1524  set winfixheight winfixwidth
1525  let prev_id = win_getid()
1526
1527  wincmd j
1528  let wh = winheight(0)
1529  let dummy_buf = bufnr('dummy_buf1', v:true)
1530  call setbufvar(dummy_buf, '&buftype', 'nofile')
1531  execute 'belowright vertical split #' . dummy_buf
1532  call assert_equal(wh, winheight(0))
1533  let dum1_id = win_getid()
1534
1535  wincmd h
1536  let wh = winheight(0)
1537  let dummy_buf = bufnr('dummy_buf2', v:true)
1538  eval 'nofile'->setbufvar(dummy_buf, '&buftype')
1539  execute 'belowright vertical split #' . dummy_buf
1540  call assert_equal(wh, winheight(0))
1541
1542  bwipe!
1543  call win_gotoid(prev_id)
1544  bwipe!
1545  call win_gotoid(dum1_id)
1546  bwipe!
1547endfunc
1548
1549func Test_redo_in_nested_functions()
1550  nnoremap g. :set opfunc=Operator<CR>g@
1551  function Operator( type, ... )
1552     let @x = 'XXX'
1553     execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
1554  endfunction
1555
1556  function! Apply()
1557      5,6normal! .
1558  endfunction
1559
1560  new
1561  call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
1562  1normal g.i"
1563  call assert_equal('some "XXX" text', getline(1))
1564  3,4normal .
1565  call assert_equal('some "XXX" text', getline(3))
1566  call assert_equal('more "XXX" text', getline(4))
1567  call Apply()
1568  call assert_equal('some "XXX" text', getline(5))
1569  call assert_equal('more "XXX" text', getline(6))
1570  bwipe!
1571
1572  nunmap g.
1573  delfunc Operator
1574  delfunc Apply
1575endfunc
1576
1577func Test_shellescape()
1578  let save_shell = &shell
1579  set shell=bash
1580  call assert_equal("'text'", shellescape('text'))
1581  call assert_equal("'te\"xt'", 'te"xt'->shellescape())
1582  call assert_equal("'te'\\''xt'", shellescape("te'xt"))
1583
1584  call assert_equal("'te%xt'", shellescape("te%xt"))
1585  call assert_equal("'te\\%xt'", shellescape("te%xt", 1))
1586  call assert_equal("'te#xt'", shellescape("te#xt"))
1587  call assert_equal("'te\\#xt'", shellescape("te#xt", 1))
1588  call assert_equal("'te!xt'", shellescape("te!xt"))
1589  call assert_equal("'te\\!xt'", shellescape("te!xt", 1))
1590
1591  call assert_equal("'te\nxt'", shellescape("te\nxt"))
1592  call assert_equal("'te\\\nxt'", shellescape("te\nxt", 1))
1593  set shell=tcsh
1594  call assert_equal("'te\\!xt'", shellescape("te!xt"))
1595  call assert_equal("'te\\\\!xt'", shellescape("te!xt", 1))
1596  call assert_equal("'te\\\nxt'", shellescape("te\nxt"))
1597  call assert_equal("'te\\\\\nxt'", shellescape("te\nxt", 1))
1598
1599  let &shell = save_shell
1600endfunc
1601
1602func Test_trim()
1603  call assert_equal("Testing", trim("  \t\r\r\x0BTesting  \t\n\r\n\t\x0B\x0B"))
1604  call assert_equal("Testing", "  \t  \r\r\n\n\x0BTesting  \t\n\r\n\t\x0B\x0B"->trim())
1605  call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
1606  call assert_equal("wRE    \tSERVEzyww", trim("wRE    \tSERVEzyww"))
1607  call assert_equal("abcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail"))
1608  call assert_equal("\tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", " "))
1609  call assert_equal(" \tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", "abx"))
1610  call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
1611  call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
1612  call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r   你好您R E SER V E早好你你    \t  \x0B", ))
1613  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    你好您R E SER V E早好你你    \t  \x0B", " 你好"))
1614  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", " 你好tes"))
1615  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", "   你你你好好好tttsses"))
1616  call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
1617  call assert_equal("", trim("", ""))
1618  call assert_equal("a", trim("a", ""))
1619  call assert_equal("", trim("", "a"))
1620
1621  call assert_equal("vim", trim("  vim  ", " ", 0))
1622  call assert_equal("vim  ", trim("  vim  ", " ", 1))
1623  call assert_equal("  vim", trim("  vim  ", " ", 2))
1624  call assert_fails('eval trim("  vim  ", " ", [])', 'E745:')
1625  call assert_fails('eval trim("  vim  ", " ", -1)', 'E475:')
1626  call assert_fails('eval trim("  vim  ", " ", 3)', 'E475:')
1627
1628  let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '')
1629  call assert_equal("x", trim(chars . "x" . chars))
1630
1631  call assert_fails('let c=trim([])', 'E730:')
1632endfunc
1633
1634" Test for reg_recording() and reg_executing()
1635func Test_reg_executing_and_recording()
1636  let s:reg_stat = ''
1637  func s:save_reg_stat()
1638    let s:reg_stat = reg_recording() . ':' . reg_executing()
1639    return ''
1640  endfunc
1641
1642  new
1643  call s:save_reg_stat()
1644  call assert_equal(':', s:reg_stat)
1645  call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
1646  call assert_equal('a:', s:reg_stat)
1647  call feedkeys("@a", 'xt')
1648  call assert_equal(':a', s:reg_stat)
1649  call feedkeys("qb@aq", 'xt')
1650  call assert_equal('b:a', s:reg_stat)
1651  call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
1652  call assert_equal('":', s:reg_stat)
1653
1654  " :normal command saves and restores reg_executing
1655  let s:reg_stat = ''
1656  let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
1657  func TestFunc() abort
1658    normal! ia
1659  endfunc
1660  call feedkeys("@q", 'xt')
1661  call assert_equal(':q', s:reg_stat)
1662  delfunc TestFunc
1663
1664  " getchar() command saves and restores reg_executing
1665  map W :call TestFunc()<CR>
1666  let @q = "W"
1667  let g:typed = ''
1668  let g:regs = []
1669  func TestFunc() abort
1670    let g:regs += [reg_executing()]
1671    let g:typed = getchar(0)
1672    let g:regs += [reg_executing()]
1673  endfunc
1674  call feedkeys("@qy", 'xt')
1675  call assert_equal(char2nr("y"), g:typed)
1676  call assert_equal(['q', 'q'], g:regs)
1677  delfunc TestFunc
1678  unmap W
1679  unlet g:typed
1680  unlet g:regs
1681
1682  " input() command saves and restores reg_executing
1683  map W :call TestFunc()<CR>
1684  let @q = "W"
1685  let g:typed = ''
1686  let g:regs = []
1687  func TestFunc() abort
1688    let g:regs += [reg_executing()]
1689    let g:typed = '?'->input()
1690    let g:regs += [reg_executing()]
1691  endfunc
1692  call feedkeys("@qy\<CR>", 'xt')
1693  call assert_equal("y", g:typed)
1694  call assert_equal(['q', 'q'], g:regs)
1695  delfunc TestFunc
1696  unmap W
1697  unlet g:typed
1698  unlet g:regs
1699
1700  bwipe!
1701  delfunc s:save_reg_stat
1702  unlet s:reg_stat
1703endfunc
1704
1705func Test_inputsecret()
1706  map W :call TestFunc()<CR>
1707  let @q = "W"
1708  let g:typed1 = ''
1709  let g:typed2 = ''
1710  let g:regs = []
1711  func TestFunc() abort
1712    let g:typed1 = '?'->inputsecret()
1713    let g:typed2 = inputsecret('password: ')
1714  endfunc
1715  call feedkeys("@qsomething\<CR>else\<CR>", 'xt')
1716  call assert_equal("something", g:typed1)
1717  call assert_equal("else", g:typed2)
1718  delfunc TestFunc
1719  unmap W
1720  unlet g:typed1
1721  unlet g:typed2
1722endfunc
1723
1724func Test_getchar()
1725  call feedkeys('a', '')
1726  call assert_equal(char2nr('a'), getchar())
1727
1728  call setline(1, 'xxxx')
1729  call test_setmouse(1, 3)
1730  let v:mouse_win = 9
1731  let v:mouse_winid = 9
1732  let v:mouse_lnum = 9
1733  let v:mouse_col = 9
1734  call feedkeys("\<S-LeftMouse>", '')
1735  call assert_equal("\<S-LeftMouse>", getchar())
1736  call assert_equal(1, v:mouse_win)
1737  call assert_equal(win_getid(1), v:mouse_winid)
1738  call assert_equal(1, v:mouse_lnum)
1739  call assert_equal(3, v:mouse_col)
1740  enew!
1741endfunc
1742
1743func Test_libcall_libcallnr()
1744  CheckFeature libcall
1745
1746  if has('win32')
1747    let libc = 'msvcrt.dll'
1748  elseif has('mac')
1749    let libc = 'libSystem.B.dylib'
1750  elseif executable('ldd')
1751    let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
1752  endif
1753  if get(l:, 'libc', '') ==# ''
1754    " On Unix, libc.so can be in various places.
1755    if has('linux')
1756      " There is not documented but regarding the 1st argument of glibc's
1757      " dlopen an empty string and nullptr are equivalent, so using an empty
1758      " string for the 1st argument of libcall allows to call functions.
1759      let libc = ''
1760    elseif has('sun')
1761      " Set the path to libc.so according to the architecture.
1762      let test_bits = system('file ' . GetVimProg())
1763      let test_arch = system('uname -p')
1764      if test_bits =~ '64-bit' && test_arch =~ 'sparc'
1765        let libc = '/usr/lib/sparcv9/libc.so'
1766      elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
1767        let libc = '/usr/lib/amd64/libc.so'
1768      else
1769        let libc = '/usr/lib/libc.so'
1770      endif
1771    else
1772      " Unfortunately skip this test until a good way is found.
1773      return
1774    endif
1775  endif
1776
1777  if has('win32')
1778    call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
1779  else
1780    call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
1781  endif
1782
1783  " If function returns NULL, libcall() should return an empty string.
1784  call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
1785
1786  " Test libcallnr() with string and integer argument.
1787  call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
1788  call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
1789
1790  call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
1791  call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
1792
1793  call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
1794  call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
1795endfunc
1796
1797sandbox function Fsandbox()
1798  normal ix
1799endfunc
1800
1801func Test_func_sandbox()
1802  sandbox let F = {-> 'hello'}
1803  call assert_equal('hello', F())
1804
1805  sandbox let F = {-> "normal ix\<Esc>"->execute()}
1806  call assert_fails('call F()', 'E48:')
1807  unlet F
1808
1809  call assert_fails('call Fsandbox()', 'E48:')
1810  delfunc Fsandbox
1811
1812  " From a sandbox try to set a predefined variable (which cannot be modified
1813  " from a sandbox)
1814  call assert_fails('sandbox let v:lnum = 10', 'E794:')
1815endfunc
1816
1817func EditAnotherFile()
1818  let word = expand('<cword>')
1819  edit Xfuncrange2
1820endfunc
1821
1822func Test_func_range_with_edit()
1823  " Define a function that edits another buffer, then call it with a range that
1824  " is invalid in that buffer.
1825  call writefile(['just one line'], 'Xfuncrange2')
1826  new
1827  eval 10->range()->setline(1)
1828  write Xfuncrange1
1829  call assert_fails('5,8call EditAnotherFile()', 'E16:')
1830
1831  call delete('Xfuncrange1')
1832  call delete('Xfuncrange2')
1833  bwipe!
1834endfunc
1835
1836func Test_func_exists_on_reload()
1837  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists')
1838  call assert_equal(0, exists('*ExistingFunction'))
1839  source Xfuncexists
1840  call assert_equal(1, '*ExistingFunction'->exists())
1841  " Redefining a function when reloading a script is OK.
1842  source Xfuncexists
1843  call assert_equal(1, exists('*ExistingFunction'))
1844
1845  " But redefining in another script is not OK.
1846  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2')
1847  call assert_fails('source Xfuncexists2', 'E122:')
1848
1849  " Defining a new function from the cmdline should fail if the function is
1850  " already defined
1851  call assert_fails('call feedkeys(":func ExistingFunction()\<CR>", "xt")', 'E122:')
1852
1853  delfunc ExistingFunction
1854  call assert_equal(0, exists('*ExistingFunction'))
1855  call writefile([
1856	\ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
1857	\ 'func ExistingFunction()', 'echo "no"', 'endfunc',
1858	\ ], 'Xfuncexists')
1859  call assert_fails('source Xfuncexists', 'E122:')
1860  call assert_equal(1, exists('*ExistingFunction'))
1861
1862  call delete('Xfuncexists2')
1863  call delete('Xfuncexists')
1864  delfunc ExistingFunction
1865endfunc
1866
1867" Test confirm({msg} [, {choices} [, {default} [, {type}]]])
1868func Test_confirm()
1869  CheckUnix
1870  CheckNotGui
1871
1872  call feedkeys('o', 'L')
1873  let a = confirm('Press O to proceed')
1874  call assert_equal(1, a)
1875
1876  call feedkeys('y', 'L')
1877  let a = 'Are you sure?'->confirm("&Yes\n&No")
1878  call assert_equal(1, a)
1879
1880  call feedkeys('n', 'L')
1881  let a = confirm('Are you sure?', "&Yes\n&No")
1882  call assert_equal(2, a)
1883
1884  " confirm() should return 0 when pressing CTRL-C.
1885  call feedkeys("\<C-C>", 'L')
1886  let a = confirm('Are you sure?', "&Yes\n&No")
1887  call assert_equal(0, a)
1888
1889  " <Esc> requires another character to avoid it being seen as the start of an
1890  " escape sequence.  Zero should be harmless.
1891  eval "\<Esc>0"->feedkeys('L')
1892  let a = confirm('Are you sure?', "&Yes\n&No")
1893  call assert_equal(0, a)
1894
1895  " Default choice is returned when pressing <CR>.
1896  call feedkeys("\<CR>", 'L')
1897  let a = confirm('Are you sure?', "&Yes\n&No")
1898  call assert_equal(1, a)
1899
1900  call feedkeys("\<CR>", 'L')
1901  let a = confirm('Are you sure?', "&Yes\n&No", 2)
1902  call assert_equal(2, a)
1903
1904  call feedkeys("\<CR>", 'L')
1905  let a = confirm('Are you sure?', "&Yes\n&No", 0)
1906  call assert_equal(0, a)
1907
1908  " Test with the {type} 4th argument
1909  for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
1910    call feedkeys('y', 'L')
1911    let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
1912    call assert_equal(1, a)
1913  endfor
1914
1915  call assert_fails('call confirm([])', 'E730:')
1916  call assert_fails('call confirm("Are you sure?", [])', 'E730:')
1917  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
1918  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
1919endfunc
1920
1921func Test_platform_name()
1922  " The system matches at most only one name.
1923  let names = ['amiga', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
1924  call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
1925
1926  " Is Unix?
1927  call assert_equal(has('bsd'), has('bsd') && has('unix'))
1928  call assert_equal(has('hpux'), has('hpux') && has('unix'))
1929  call assert_equal(has('linux'), has('linux') && has('unix'))
1930  call assert_equal(has('mac'), has('mac') && has('unix'))
1931  call assert_equal(has('qnx'), has('qnx') && has('unix'))
1932  call assert_equal(has('sun'), has('sun') && has('unix'))
1933  call assert_equal(has('win32'), has('win32') && !has('unix'))
1934  call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
1935
1936  if has('unix') && executable('uname')
1937    let uname = system('uname')
1938    " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
1939    call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
1940    call assert_equal(uname =~? 'HP-UX', has('hpux'))
1941    call assert_equal(uname =~? 'Linux', has('linux'))
1942    call assert_equal(uname =~? 'Darwin', has('mac'))
1943    call assert_equal(uname =~? 'QNX', has('qnx'))
1944    call assert_equal(uname =~? 'SunOS', has('sun'))
1945    call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
1946  endif
1947endfunc
1948
1949func Test_readdir()
1950  call mkdir('Xdir')
1951  call writefile([], 'Xdir/foo.txt')
1952  call writefile([], 'Xdir/bar.txt')
1953  call mkdir('Xdir/dir')
1954
1955  " All results
1956  let files = readdir('Xdir')
1957  call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
1958
1959  " Only results containing "f"
1960  let files = 'Xdir'->readdir({ x -> stridx(x, 'f') != -1 })
1961  call assert_equal(['foo.txt'], sort(files))
1962
1963  " Only .txt files
1964  let files = readdir('Xdir', { x -> x =~ '.txt$' })
1965  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
1966
1967  " Only .txt files with string
1968  let files = readdir('Xdir', 'v:val =~ ".txt$"')
1969  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
1970
1971  " Limit to 1 result.
1972  let l = []
1973  let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1})
1974  call assert_equal(1, len(files))
1975
1976  " Nested readdir() must not crash
1977  let files = readdir('Xdir', 'readdir("Xdir", "1") != []')
1978  call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
1979
1980  eval 'Xdir'->delete('rf')
1981endfunc
1982
1983func Test_readdirex()
1984  call mkdir('Xdir')
1985  call writefile(['foo'], 'Xdir/foo.txt')
1986  call writefile(['barbar'], 'Xdir/bar.txt')
1987  call mkdir('Xdir/dir')
1988
1989  " All results
1990  let files = readdirex('Xdir')->map({-> v:val.name})
1991  call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
1992  let sizes = readdirex('Xdir')->map({-> v:val.size})
1993  call assert_equal([0, 4, 7], sort(sizes))
1994
1995  " Only results containing "f"
1996  let files = 'Xdir'->readdirex({ e -> stridx(e.name, 'f') != -1 })
1997			  \ ->map({-> v:val.name})
1998  call assert_equal(['foo.txt'], sort(files))
1999
2000  " Only .txt files
2001  let files = readdirex('Xdir', { e -> e.name =~ '.txt$' })
2002			  \ ->map({-> v:val.name})
2003  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2004
2005  " Only .txt files with string
2006  let files = readdirex('Xdir', 'v:val.name =~ ".txt$"')
2007			  \ ->map({-> v:val.name})
2008  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2009
2010  " Limit to 1 result.
2011  let l = []
2012  let files = readdirex('Xdir', {e -> len(add(l, e.name)) == 2 ? -1 : 1})
2013			  \ ->map({-> v:val.name})
2014  call assert_equal(1, len(files))
2015
2016  " Nested readdirex() must not crash
2017  let files = readdirex('Xdir', 'readdirex("Xdir", "1") != []')
2018			  \ ->map({-> v:val.name})
2019  call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
2020
2021  " report broken link correctly
2022  if has("unix")
2023    call writefile([], 'Xdir/abc.txt')
2024    call system("ln -s Xdir/abc.txt Xdir/link")
2025    call delete('Xdir/abc.txt')
2026    let files = readdirex('Xdir', 'readdirex("Xdir", "1") != []')
2027			  \ ->map({-> v:val.name .. '_' .. v:val.type})
2028    call sort(files)->assert_equal(
2029        \ ['bar.txt_file', 'dir_dir', 'foo.txt_file', 'link_link'])
2030  endif
2031  eval 'Xdir'->delete('rf')
2032
2033  call assert_fails('call readdirex("doesnotexist")', 'E484:')
2034endfunc
2035
2036func Test_readdirex_sort()
2037  CheckUnix
2038  " Skip tests on Mac OS X and Cygwin (does not allow several files with different casing)
2039  if has("osxdarwin") || has("osx") || has("macunix") || has("win32unix")
2040    throw 'Skipped: Test_readdirex_sort on systems that do not allow this using the default filesystem'
2041  endif
2042  let _collate = v:collate
2043  call mkdir('Xdir2')
2044  call writefile(['1'], 'Xdir2/README.txt')
2045  call writefile(['2'], 'Xdir2/Readme.txt')
2046  call writefile(['3'], 'Xdir2/readme.txt')
2047
2048  " 1) default
2049  let files = readdirex('Xdir2')->map({-> v:val.name})
2050  let default = copy(files)
2051  call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort using default')
2052
2053  " 2) no sorting
2054  let files = readdirex('Xdir2', 1, #{sort: 'none'})->map({-> v:val.name})
2055  let unsorted = copy(files)
2056  call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], sort(files), 'unsorted')
2057  call assert_fails("call readdirex('Xdir2', 1, #{slort: 'none'})", 'E857: Dictionary key "sort" required')
2058
2059  " 3) sort by case (same as default)
2060  let files = readdirex('Xdir2', 1, #{sort: 'case'})->map({-> v:val.name})
2061  call assert_equal(default, files, 'sort by case')
2062
2063  " 4) sort by ignoring case
2064  let files = readdirex('Xdir2', 1, #{sort: 'icase'})->map({-> v:val.name})
2065  call assert_equal(unsorted->sort('i'), files, 'sort by icase')
2066
2067  " 5) Default Collation
2068  let collate = v:collate
2069  lang collate C
2070  let files = readdirex('Xdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
2071  call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort by C collation')
2072
2073  " 6) Collation de_DE
2074  " Switch locale, this may not work on the CI system, if the locale isn't
2075  " available
2076  try
2077    lang collate de_DE
2078    let files = readdirex('Xdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
2079    call assert_equal(['readme.txt', 'Readme.txt', 'README.txt'], files, 'sort by de_DE collation')
2080  catch
2081    throw 'Skipped: de_DE collation is not available'
2082
2083  finally
2084    exe 'lang collate' collate
2085    eval 'Xdir2'->delete('rf')
2086  endtry
2087endfunc
2088
2089func Test_readdir_sort()
2090  " some more cases for testing sorting for readdirex
2091  let dir = 'Xdir3'
2092  call mkdir(dir)
2093  call writefile(['1'], dir .. '/README.txt')
2094  call writefile(['2'], dir .. '/Readm.txt')
2095  call writefile(['3'], dir .. '/read.txt')
2096  call writefile(['4'], dir .. '/Z.txt')
2097  call writefile(['5'], dir .. '/a.txt')
2098  call writefile(['6'], dir .. '/b.txt')
2099
2100  " 1) default
2101  let files = readdir(dir)
2102  let default = copy(files)
2103  call assert_equal(default->sort(), files, 'sort using default')
2104
2105  " 2) sort by case (same as default)
2106  let files = readdir(dir, '1', #{sort: 'case'})
2107  call assert_equal(default, files, 'sort using default')
2108
2109  " 3) sort by ignoring case
2110  let files = readdir(dir, '1', #{sort: 'icase'})
2111  call assert_equal(default->sort('i'), files, 'sort by ignoring case')
2112
2113  " 4) collation
2114  let collate = v:collate
2115  lang collate C
2116  let files = readdir(dir, 1, #{sort: 'collate'})
2117  call assert_equal(default->sort(), files, 'sort by C collation')
2118  exe "lang collate" collate
2119
2120  " 5) Errors
2121  call assert_fails('call readdir(dir, 1, 1)', 'E715:')
2122  call assert_fails('call readdir(dir, 1, #{sorta: 1})')
2123  call assert_fails('call readdirex(dir, 1, #{sorta: 1})')
2124
2125  " 6) ignore other values in dict
2126  let files = readdir(dir, '1', #{sort: 'c'})
2127  call assert_equal(default, files, 'sort using default2')
2128
2129  " Cleanup
2130  exe "lang collate" collate
2131
2132  eval dir->delete('rf')
2133endfunc
2134
2135func Test_delete_rf()
2136  call mkdir('Xdir')
2137  call writefile([], 'Xdir/foo.txt')
2138  call writefile([], 'Xdir/bar.txt')
2139  call mkdir('Xdir/[a-1]')  " issue #696
2140  call writefile([], 'Xdir/[a-1]/foo.txt')
2141  call writefile([], 'Xdir/[a-1]/bar.txt')
2142  call assert_true(filereadable('Xdir/foo.txt'))
2143  call assert_true('Xdir/[a-1]/foo.txt'->filereadable())
2144
2145  call assert_equal(0, delete('Xdir', 'rf'))
2146  call assert_false(filereadable('Xdir/foo.txt'))
2147  call assert_false(filereadable('Xdir/[a-1]/foo.txt'))
2148endfunc
2149
2150func Test_call()
2151  call assert_equal(3, call('len', [123]))
2152  call assert_equal(3, 'len'->call([123]))
2153  call assert_fails("call call('len', 123)", 'E714:')
2154  call assert_equal(0, call('', []))
2155  call assert_equal(0, call('len', test_null_list()))
2156
2157  function Mylen() dict
2158     return len(self.data)
2159  endfunction
2160  let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
2161  eval mydict.len->call([], mydict)->assert_equal(4)
2162  call assert_fails("call call('Mylen', [], 0)", 'E715:')
2163  call assert_fails('call foo', 'E107:')
2164
2165  " This once caused a crash.
2166  call call(test_null_function(), [])
2167  call call(test_null_partial(), [])
2168endfunc
2169
2170func Test_char2nr()
2171  call assert_equal(12354, char2nr('あ', 1))
2172  call assert_equal(120, 'x'->char2nr())
2173  set encoding=latin1
2174  call assert_equal(120, 'x'->char2nr())
2175  set encoding=utf-8
2176endfunc
2177
2178func Test_charclass()
2179  call assert_equal(0, charclass(' '))
2180  call assert_equal(1, charclass('.'))
2181  call assert_equal(2, charclass('x'))
2182  call assert_equal(3, charclass("\u203c"))
2183endfunc
2184
2185func Test_eventhandler()
2186  call assert_equal(0, eventhandler())
2187endfunc
2188
2189func Test_bufadd_bufload()
2190  call assert_equal(0, bufexists('someName'))
2191  let buf = bufadd('someName')
2192  call assert_notequal(0, buf)
2193  call assert_equal(1, bufexists('someName'))
2194  call assert_equal(0, getbufvar(buf, '&buflisted'))
2195  call assert_equal(0, bufloaded(buf))
2196  call bufload(buf)
2197  call assert_equal(1, bufloaded(buf))
2198  call assert_equal([''], getbufline(buf, 1, '$'))
2199
2200  let curbuf = bufnr('')
2201  eval ['some', 'text']->writefile('XotherName')
2202  let buf = 'XotherName'->bufadd()
2203  call assert_notequal(0, buf)
2204  eval 'XotherName'->bufexists()->assert_equal(1)
2205  call assert_equal(0, getbufvar(buf, '&buflisted'))
2206  call assert_equal(0, bufloaded(buf))
2207  eval buf->bufload()
2208  call assert_equal(1, bufloaded(buf))
2209  call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
2210  call assert_equal(curbuf, bufnr(''))
2211
2212  let buf1 = bufadd('')
2213  let buf2 = bufadd('')
2214  call assert_notequal(0, buf1)
2215  call assert_notequal(0, buf2)
2216  call assert_notequal(buf1, buf2)
2217  call assert_equal(1, bufexists(buf1))
2218  call assert_equal(1, bufexists(buf2))
2219  call assert_equal(0, bufloaded(buf1))
2220  exe 'bwipe ' .. buf1
2221  call assert_equal(0, bufexists(buf1))
2222  call assert_equal(1, bufexists(buf2))
2223  exe 'bwipe ' .. buf2
2224  call assert_equal(0, bufexists(buf2))
2225
2226  bwipe someName
2227  bwipe XotherName
2228  call assert_equal(0, bufexists('someName'))
2229  call delete('XotherName')
2230endfunc
2231
2232func Test_state()
2233  CheckRunVimInTerminal
2234
2235  let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
2236
2237  let lines =<< trim END
2238	call setline(1, ['one', 'two', 'three'])
2239	map ;; gg
2240	set complete=.
2241	func RunTimer()
2242	  call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
2243	endfunc
2244	au Filetype foobar let g:state = state()|let g:mode = mode()
2245  END
2246  call writefile(lines, 'XState')
2247  let buf = RunVimInTerminal('-S XState', #{rows: 6})
2248
2249  " Using a ":" command Vim is busy, thus "S" is returned
2250  call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
2251  call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
2252  call term_sendkeys(buf, ":\<CR>")
2253
2254  " Using a timer callback
2255  call term_sendkeys(buf, ":call RunTimer()\<CR>")
2256  call TermWait(buf, 25)
2257  call term_sendkeys(buf, getstate)
2258  call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
2259
2260  " Halfway a mapping
2261  call term_sendkeys(buf, ":call RunTimer()\<CR>;")
2262  call TermWait(buf, 25)
2263  call term_sendkeys(buf, ";")
2264  call term_sendkeys(buf, getstate)
2265  call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
2266
2267  " Insert mode completion (bit slower on Mac)
2268  call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
2269  call TermWait(buf, 25)
2270  call term_sendkeys(buf, "\<Esc>")
2271  call term_sendkeys(buf, getstate)
2272  call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
2273
2274  " Autocommand executing
2275  call term_sendkeys(buf, ":set filetype=foobar\<CR>")
2276  call TermWait(buf, 25)
2277  call term_sendkeys(buf, getstate)
2278  call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
2279
2280  " Todo: "w" - waiting for ch_evalexpr()
2281
2282  " messages scrolled
2283  call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
2284  call TermWait(buf, 25)
2285  call term_sendkeys(buf, "\<CR>")
2286  call term_sendkeys(buf, getstate)
2287  call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
2288
2289  call StopVimInTerminal(buf)
2290  call delete('XState')
2291endfunc
2292
2293func Test_range()
2294  " destructuring
2295  let [x, y] = range(2)
2296  call assert_equal([0, 1], [x, y])
2297
2298  " index
2299  call assert_equal(4, range(1, 10)[3])
2300
2301  " add()
2302  call assert_equal([0, 1, 2, 3], add(range(3), 3))
2303  call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
2304  call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
2305
2306  " append()
2307  new
2308  call append('.', range(5))
2309  call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
2310  bwipe!
2311
2312  " appendbufline()
2313  new
2314  call appendbufline(bufnr(''), '.', range(5))
2315  call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
2316  bwipe!
2317
2318  " call()
2319  func TwoArgs(a, b)
2320    return [a:a, a:b]
2321  endfunc
2322  call assert_equal([0, 1], call('TwoArgs', range(2)))
2323
2324  " col()
2325  new
2326  call setline(1, ['foo', 'bar'])
2327  call assert_equal(2, col(range(1, 2)))
2328  bwipe!
2329
2330  " complete()
2331  execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
2332  " complete_info()
2333  execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
2334
2335  " copy()
2336  call assert_equal([1, 2, 3], copy(range(1, 3)))
2337
2338  " count()
2339  call assert_equal(0, count(range(0), 3))
2340  call assert_equal(0, count(range(2), 3))
2341  call assert_equal(1, count(range(5), 3))
2342
2343  " cursor()
2344  new
2345  call setline(1, ['aaa', 'bbb', 'ccc'])
2346  call cursor(range(1, 2))
2347  call assert_equal([2, 1], [col('.'), line('.')])
2348  bwipe!
2349
2350  " deepcopy()
2351  call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
2352
2353  " empty()
2354  call assert_true(empty(range(0)))
2355  call assert_false(empty(range(2)))
2356
2357  " execute()
2358  new
2359  call setline(1, ['aaa', 'bbb', 'ccc'])
2360  call execute(range(3))
2361  call assert_equal(2, line('.'))
2362  bwipe!
2363
2364  " extend()
2365  call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
2366  call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
2367  call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
2368
2369  " filter()
2370  call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
2371  call assert_equal([1, 5, 7, 11, 13], filter(filter(range(15), 'v:val % 2'), 'v:val % 3'))
2372
2373  " funcref()
2374  call assert_equal([0, 1], funcref('TwoArgs', range(2))())
2375
2376  " function()
2377  call assert_equal([0, 1], function('TwoArgs', range(2))())
2378
2379  " garbagecollect()
2380  let thelist = [1, range(2), 3]
2381  let otherlist = range(3)
2382  call test_garbagecollect_now()
2383
2384  " get()
2385  call assert_equal(4, get(range(1, 10), 3))
2386  call assert_equal(-1, get(range(1, 10), 42, -1))
2387
2388  " index()
2389  call assert_equal(1, index(range(1, 5), 2))
2390  call assert_fails("echo index([1, 2], 1, [])", 'E745:')
2391
2392  " inputlist()
2393  call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x')
2394  call assert_equal(1, result)
2395  call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x')
2396  call assert_equal(1, result)
2397
2398  " insert()
2399  call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
2400  call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
2401  call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
2402  call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
2403  call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
2404  call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
2405
2406  " join()
2407  call assert_equal('0 1 2 3 4', join(range(5)))
2408
2409  " json_encode()
2410  call assert_equal('[0,1,2,3]', json_encode(range(4)))
2411
2412  " len()
2413  call assert_equal(0, len(range(0)))
2414  call assert_equal(2, len(range(2)))
2415  call assert_equal(5, len(range(0, 12, 3)))
2416  call assert_equal(4, len(range(3, 0, -1)))
2417
2418  " list2str()
2419  call assert_equal('ABC', list2str(range(65, 67)))
2420  call assert_fails('let s = list2str(5)', 'E474:')
2421
2422  " lock()
2423  let thelist = range(5)
2424  lockvar thelist
2425
2426  " map()
2427  call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
2428  call assert_equal([3, 5, 7, 9, 11], map(map(range(5), 'v:val * 2'), 'v:val + 3'))
2429  call assert_equal([2, 6], map(filter(range(5), 'v:val % 2'), 'v:val * 2'))
2430  call assert_equal([2, 4, 8], filter(map(range(5), 'v:val * 2'), 'v:val % 3'))
2431
2432  " match()
2433  call assert_equal(3, match(range(5), 3))
2434
2435  " matchaddpos()
2436  highlight MyGreenGroup ctermbg=green guibg=green
2437  call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
2438
2439  " matchend()
2440  call assert_equal(4, matchend(range(5), '4'))
2441  call assert_equal(3, matchend(range(1, 5), '4'))
2442  call assert_equal(-1, matchend(range(1, 5), '42'))
2443
2444  " matchstrpos()
2445  call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
2446  call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
2447  call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
2448
2449  " max() reverse()
2450  call assert_equal(0, max(range(0)))
2451  call assert_equal(0, max(range(10, 9)))
2452  call assert_equal(9, max(range(10)))
2453  call assert_equal(18, max(range(0, 20, 3)))
2454  call assert_equal(20, max(range(20, 0, -3)))
2455  call assert_equal(99999, max(range(100000)))
2456  call assert_equal(99999, max(range(99999, 0, -1)))
2457  call assert_equal(99999, max(reverse(range(100000))))
2458  call assert_equal(99999, max(reverse(range(99999, 0, -1))))
2459
2460  " min() reverse()
2461  call assert_equal(0, min(range(0)))
2462  call assert_equal(0, min(range(10, 9)))
2463  call assert_equal(5, min(range(5, 10)))
2464  call assert_equal(5, min(range(5, 10, 3)))
2465  call assert_equal(2, min(range(20, 0, -3)))
2466  call assert_equal(0, min(range(100000)))
2467  call assert_equal(0, min(range(99999, 0, -1)))
2468  call assert_equal(0, min(reverse(range(100000))))
2469  call assert_equal(0, min(reverse(range(99999, 0, -1))))
2470
2471  " remove()
2472  call assert_equal(1, remove(range(1, 10), 0))
2473  call assert_equal(2, remove(range(1, 10), 1))
2474  call assert_equal(9, remove(range(1, 10), 8))
2475  call assert_equal(10, remove(range(1, 10), 9))
2476  call assert_equal(10, remove(range(1, 10), -1))
2477  call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
2478
2479  " repeat()
2480  call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
2481  call assert_equal([0, 1, 2], repeat(range(3), 1))
2482  call assert_equal([], repeat(range(3), 0))
2483  call assert_equal([], repeat(range(5, 4), 2))
2484  call assert_equal([], repeat(range(5, 4), 0))
2485
2486  " reverse()
2487  call assert_equal([2, 1, 0], reverse(range(3)))
2488  call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
2489  call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
2490  call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
2491  call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
2492  call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
2493  call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
2494  call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
2495  call assert_equal([], reverse(range(0)))
2496
2497  " TODO: setpos()
2498  " new
2499  " call setline(1, repeat([''], bufnr('')))
2500  " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
2501  " call setpos('x', range(bufnr(''), bufnr('') + 3))
2502  " bwipe!
2503
2504  " setreg()
2505  call setreg('a', range(3))
2506  call assert_equal("0\n1\n2\n", getreg('a'))
2507
2508  " settagstack()
2509  call settagstack(1, #{items : range(4)})
2510
2511  " sign_define()
2512  call assert_fails("call sign_define(range(5))", "E715:")
2513  call assert_fails("call sign_placelist(range(5))", "E715:")
2514
2515  " sign_undefine()
2516  call assert_fails("call sign_undefine(range(5))", "E908:")
2517
2518  " sign_unplacelist()
2519  call assert_fails("call sign_unplacelist(range(5))", "E715:")
2520
2521  " sort()
2522  call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
2523
2524  " string()
2525  call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
2526
2527  " taglist() with 'tagfunc'
2528  func TagFunc(pattern, flags, info)
2529    return range(10)
2530  endfunc
2531  set tagfunc=TagFunc
2532  call assert_fails("call taglist('asdf')", 'E987:')
2533  set tagfunc=
2534
2535  " term_start()
2536  if has('terminal') && has('termguicolors')
2537    call assert_fails('call term_start(range(3, 4))', 'E474:')
2538    let g:terminal_ansi_colors = range(16)
2539    if has('win32')
2540      let cmd = "cmd /c dir"
2541    else
2542      let cmd = "ls"
2543    endif
2544    call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"})', 'E475:')
2545    unlet g:terminal_ansi_colors
2546  endif
2547
2548  " type()
2549  call assert_equal(v:t_list, type(range(5)))
2550
2551  " uniq()
2552  call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
2553
2554  " errors
2555  call assert_fails('let x=range(2, 8, 0)', 'E726:')
2556  call assert_fails('let x=range(3, 1)', 'E727:')
2557  call assert_fails('let x=range(1, 3, -2)', 'E727:')
2558  call assert_fails('let x=range([])', 'E745:')
2559  call assert_fails('let x=range(1, [])', 'E745:')
2560  call assert_fails('let x=range(1, 4, [])', 'E745:')
2561endfunc
2562
2563func Test_echoraw()
2564  CheckScreendump
2565
2566  " Normally used for escape codes, but let's test with a CR.
2567  let lines =<< trim END
2568    call echoraw("hello\<CR>x")
2569  END
2570  call writefile(lines, 'XTest_echoraw')
2571  let buf = RunVimInTerminal('-S XTest_echoraw', {'rows': 5, 'cols': 40})
2572  call VerifyScreenDump(buf, 'Test_functions_echoraw', {})
2573
2574  " clean up
2575  call StopVimInTerminal(buf)
2576  call delete('XTest_echoraw')
2577endfunc
2578
2579" Test for echo highlighting
2580func Test_echohl()
2581  echohl Search
2582  echo 'Vim'
2583  call assert_equal('Vim', Screenline(&lines))
2584  " TODO: How to check the highlight group used by echohl?
2585  " ScreenAttrs() returns all zeros.
2586  echohl None
2587endfunc
2588
2589" Test for the eval() function
2590func Test_eval()
2591  call assert_fails("call eval('5 a')", 'E488:')
2592endfunc
2593
2594" Test for the nr2char() function
2595func Test_nr2char()
2596  set encoding=latin1
2597  call assert_equal('@', nr2char(64))
2598  set encoding=utf8
2599  call assert_equal('a', nr2char(97, 1))
2600  call assert_equal('a', nr2char(97, 0))
2601
2602  call assert_equal("\x80\xfc\b\xf4\x80\xfeX\x80\xfeX\x80\xfeX", eval('"\<M-' .. nr2char(0x100000) .. '>"'))
2603  call assert_equal("\x80\xfc\b\xfd\x80\xfeX\x80\xfeX\x80\xfeX\x80\xfeX\x80\xfeX", eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
2604endfunc
2605
2606" Test for screenattr(), screenchar() and screenchars() functions
2607func Test_screen_functions()
2608  call assert_equal(-1, screenattr(-1, -1))
2609  call assert_equal(-1, screenchar(-1, -1))
2610  call assert_equal([], screenchars(-1, -1))
2611endfunc
2612
2613" Test for getcurpos() and setpos()
2614func Test_getcurpos_setpos()
2615  new
2616  call setline(1, ['012345678', '012345678'])
2617  normal gg6l
2618  let sp = getcurpos()
2619  normal 0
2620  call setpos('.', sp)
2621  normal jyl
2622  call assert_equal('6', @")
2623  call assert_equal(-1, setpos('.', test_null_list()))
2624  call assert_equal(-1, setpos('.', {}))
2625
2626  let winid = win_getid()
2627  normal G$
2628  let pos = getcurpos()
2629  wincmd w
2630  call assert_equal(pos, getcurpos(winid))
2631
2632  wincmd w
2633  close!
2634
2635  call assert_equal(getcurpos(), getcurpos(0))
2636  call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
2637  call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
2638endfunc
2639
2640" Test for glob()
2641func Test_glob()
2642  call assert_equal('', glob(test_null_string()))
2643  call assert_equal('', globpath(test_null_string(), test_null_string()))
2644  call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
2645
2646  call writefile([], 'Xglob1')
2647  call writefile([], 'XGLOB2')
2648  set wildignorecase
2649  " Sort output of glob() otherwise we end up with different
2650  " ordering depending on whether file system is case-sensitive.
2651  call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
2652  set wildignorecase&
2653
2654  call delete('Xglob1')
2655  call delete('XGLOB2')
2656
2657  call assert_fails("call glob('*', 0, {})", 'E728:')
2658endfunc
2659
2660" Test for browse()
2661func Test_browse()
2662  CheckFeature browse
2663  call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
2664endfunc
2665
2666" Test for browsedir()
2667func Test_browsedir()
2668  CheckFeature browse
2669  call assert_fails('call browsedir("open", [])', 'E730:')
2670endfunc
2671
2672func HasDefault(msg = 'msg')
2673  return a:msg
2674endfunc
2675
2676func Test_default_arg_value()
2677  call assert_equal('msg', HasDefault())
2678endfunc
2679
2680" Test for gettext()
2681func Test_gettext()
2682  call assert_fails('call gettext(1)', 'E475:')
2683endfunc
2684
2685func Test_builtin_check()
2686  call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
2687  call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
2688  call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
2689  call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
2690  let lines =<< trim END
2691    vim9script
2692    var s:trim = (x) => " " .. x
2693  END
2694  call CheckScriptFailure(lines, 'E704:')
2695
2696  call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
2697  let g:bar = 123
2698  call extend(g:, #{bar: { -> "foo" }}, "keep")
2699  call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
2700endfunc
2701
2702
2703" vim: shiftwidth=2 sts=2 expandtab
2704