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