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