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