robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
139.8 KiB4049 linesraw
1" Tests for various functions.
2
3source shared.vim
4source check.vim
5source term_util.vim
6source screendump.vim
7source vim9.vim
8
9" Must be done first, since the alternate buffer must be unset.
10func Test_00_bufexists()
11  call assert_equal(0, bufexists('does_not_exist'))
12  call assert_equal(1, bufexists(bufnr('%')))
13  call assert_equal(0, bufexists(0))
14  new Xfoo
15  let bn = bufnr('%')
16  call assert_equal(1, bufexists(bn))
17  call assert_equal(1, bufexists('Xfoo'))
18  call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
19  call assert_equal(1, bufexists(0))
20  bw
21  call assert_equal(0, bufexists(bn))
22  call assert_equal(0, bufexists('Xfoo'))
23endfunc
24
25func Test_has()
26  throw 'Skipped: Nvim has removed some features'
27  call assert_equal(1, has('eval'))
28  call assert_equal(1, has('eval', 1))
29
30  if has('unix')
31    call assert_equal(1, or(has('ttyin'), 1))
32    call assert_equal(0, and(has('ttyout'), 0))
33    call assert_equal(1, has('multi_byte_encoding'))
34    call assert_equal(0, has(':tearoff'))
35  endif
36  call assert_equal(1, has('vcon', 1))
37  call assert_equal(1, has('mouse_gpm_enabled', 1))
38
39  call assert_equal(has('gui_win32') && has('menu'), has(':tearoff'))
40
41  call assert_equal(0, has('nonexistent'))
42  call assert_equal(0, has('nonexistent', 1))
43
44  " Will we ever have patch 9999?
45  let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999'
46  call assert_equal(0, has(ver))
47
48  " There actually isn't a patch 9.0.0, but this is more consistent.
49  call assert_equal(1, has('patch-9.0.0'))
50endfunc
51
52func Test_empty()
53  call assert_equal(1, empty(''))
54  call assert_equal(0, empty('a'))
55
56  call assert_equal(1, empty(0))
57  call assert_equal(1, empty(-0))
58  call assert_equal(0, empty(1))
59  call assert_equal(0, empty(-1))
60
61  if has('float')
62    call assert_equal(1, empty(0.0))
63    call assert_equal(1, empty(-0.0))
64    call assert_equal(0, empty(1.0))
65    call assert_equal(0, empty(-1.0))
66    call assert_equal(0, empty(1.0/0.0))
67    call assert_equal(0, empty(0.0/0.0))
68  endif
69
70  call assert_equal(1, empty([]))
71  call assert_equal(0, empty(['a']))
72
73  call assert_equal(1, empty({}))
74  call assert_equal(0, empty({'a':1}))
75
76  call assert_equal(1, empty(v:null))
77  " call assert_equal(1, empty(v:none))
78  call assert_equal(1, empty(v:false))
79  call assert_equal(0, empty(v:true))
80
81  if has('channel')
82    call assert_equal(1, empty(test_null_channel()))
83  endif
84  if has('job')
85    call assert_equal(1, empty(test_null_job()))
86  endif
87
88  call assert_equal(0, empty(function('Test_empty')))
89  call assert_equal(0, empty(function('Test_empty', [0])))
90endfunc
91
92func Test_err_teapot()
93  throw 'Skipped: Nvim does not have err_teapot()'
94  call assert_fails('call err_teapot()', "E418: I'm a teapot")
95  call assert_fails('call err_teapot(0)', "E418: I'm a teapot")
96  call assert_fails('call err_teapot(v:false)', "E418: I'm a teapot")
97
98  call assert_fails('call err_teapot("1")', "E503: Coffee is currently not available")
99  call assert_fails('call err_teapot(v:true)', "E503: Coffee is currently not available")
100  let expr = 1
101  call assert_fails('call err_teapot(expr)', "E503: Coffee is currently not available")
102endfunc
103
104func Test_islocked()
105  call assert_fails('call islocked(99)', 'E475:')
106  call assert_fails('call islocked("s: x")', 'E488:')
107endfunc
108
109func Test_len()
110  call assert_equal(1, len(0))
111  call assert_equal(2, len(12))
112
113  call assert_equal(0, len(''))
114  call assert_equal(2, len('ab'))
115
116  call assert_equal(0, len([]))
117  call assert_equal(0, len(v:_null_list))
118  call assert_equal(2, len([2, 1]))
119
120  call assert_equal(0, len({}))
121  call assert_equal(0, len(v:_null_dict))
122  call assert_equal(2, len({'a': 1, 'b': 2}))
123
124  " call assert_fails('call len(v:none)', 'E701:')
125  call assert_fails('call len({-> 0})', 'E701:')
126endfunc
127
128func Test_max()
129  call assert_equal(0, max([]))
130  call assert_equal(2, max([2]))
131  call assert_equal(2, max([1, 2]))
132  call assert_equal(2, max([1, 2, v:null]))
133
134  call assert_equal(0, max({}))
135  call assert_equal(2, max({'a':1, 'b':2}))
136
137  call assert_fails('call max(1)', 'E712:')
138  " call assert_fails('call max(v:none)', 'E712:')
139
140  " check we only get one error
141  call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:'])
142  call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:'])
143endfunc
144
145func Test_min()
146  call assert_equal(0, min([]))
147  call assert_equal(2, min([2]))
148  call assert_equal(1, min([1, 2]))
149  call assert_equal(0, min([1, 2, v:null]))
150
151  call assert_equal(0, min({}))
152  call assert_equal(1, min({'a':1, 'b':2}))
153
154  call assert_fails('call min(1)', 'E712:')
155  " call assert_fails('call min(v:none)', 'E712:')
156  call assert_fails('call min([1, {}])', 'E728:')
157
158  " check we only get one error
159  call assert_fails('call min([[1], #{}])', ['E745:', 'E745:'])
160  call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:'])
161endfunc
162
163func Test_strwidth()
164  for aw in ['single', 'double']
165    exe 'set ambiwidth=' . aw
166    call assert_equal(0, strwidth(''))
167    call assert_equal(1, strwidth("\t"))
168    call assert_equal(3, strwidth('Vim'))
169    call assert_equal(4, strwidth(1234))
170    call assert_equal(5, strwidth(-1234))
171
172    call assert_equal(2, strwidth('😉'))
173    call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
174    call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
175
176    call assert_fails('call strwidth({->0})', 'E729:')
177    call assert_fails('call strwidth([])', 'E730:')
178    call assert_fails('call strwidth({})', 'E731:')
179  endfor
180
181  if has('float')
182    call assert_equal(3, strwidth(1.2))
183    call CheckDefExecAndScriptFailure(['echo strwidth(1.2)'], 'E806:')
184  endif
185
186  set ambiwidth&
187endfunc
188
189func Test_strtrans()
190  " The default of 'isprint' is platform-dependent: 0x7f and 0x9f are
191  " printable on Win32 and VMS.  Set it so the expectations below hold
192  " everywhere.
193  let save_isprint = &isprint
194  set isprint=@,161-255
195
196  " printable ASCII is unchanged
197  call assert_equal('', strtrans(''))
198  call assert_equal('abc', strtrans('abc'))
199
200  " control characters are displayed as ^X
201  call assert_equal('^I', strtrans("\t"))
202  call assert_equal('a^Mb^[c', strtrans("a\rb\ec"))
203  call assert_equal('^A^_^?', strtrans("\x01\x1f\x7f"))
204
205  " printable multibyte characters are unchanged, including composing
206  " characters and characters above 0xffff
207  call assert_equal('héllo 你好', strtrans('héllo 你好'))
208  let s = 'e' .. nr2char(0x301) .. 'x'
209  call assert_equal(s, strtrans(s))
210  call assert_equal(nr2char(0x1d11e), strtrans(nr2char(0x1d11e)))
211
212  " unprintable multibyte characters are displayed in <xx> hex form
213  call assert_equal('<9f>', strtrans(nr2char(0x9f)))
214  call assert_equal('<200b>', strtrans(nr2char(0x200b)))
215  call assert_equal('<feff>', strtrans(nr2char(0xfeff)))
216
217  " illegal bytes are displayed in <xx> hex form
218  call assert_equal('A<ff>B', strtrans("A\xffB"))
219
220  " a long string mixing all kinds of characters
221  call assert_equal(repeat('a^Bé<9f>', 100),
222        \ strtrans(repeat("a\x02é" .. nr2char(0x9f), 100)))
223
224  " the non-multi-byte code path
225  "set encoding=latin1
226  set isprint=@,161-255
227  call assert_equal('a^Mb^[c', strtrans("a\rb\ec"))
228  call assert_equal('^A^_^?', strtrans("\x01\x1f\x7f"))
229  " an unprintable byte above 0x7f uses the meta notation
230  "call assert_equal('| ', strtrans("\xa0"))
231  "call assert_equal("\xe9", strtrans("\xe9"))
232  "call assert_equal("x^B\xe9| y", strtrans("x\x02\xe9\xa0y"))
233  set encoding=utf-8
234
235  let &isprint = save_isprint
236endfunc
237
238func Test_str2nr()
239  call assert_equal(0, str2nr(''))
240  call assert_equal(1, str2nr('1'))
241  call assert_equal(1, str2nr(' 1 '))
242
243  call assert_equal(1, str2nr('+1'))
244  call assert_equal(1, str2nr('+ 1'))
245  call assert_equal(1, str2nr(' + 1 '))
246
247  call assert_equal(-1, str2nr('-1'))
248  call assert_equal(-1, str2nr('- 1'))
249  call assert_equal(-1, str2nr(' - 1 '))
250
251  call assert_equal(123456789, str2nr('123456789'))
252  call assert_equal(-123456789, str2nr('-123456789'))
253
254  call assert_equal(5, str2nr('101', 2))
255  call assert_equal(5, '0b101'->str2nr(2))
256  call assert_equal(5, str2nr('0B101', 2))
257  call assert_equal(-5, str2nr('-101', 2))
258  call assert_equal(-5, str2nr('-0b101', 2))
259  call assert_equal(-5, str2nr('-0B101', 2))
260
261  call assert_equal(65, str2nr('101', 8))
262  call assert_equal(65, str2nr('0101', 8))
263  call assert_equal(-65, str2nr('-101', 8))
264  call assert_equal(-65, str2nr('-0101', 8))
265  call assert_equal(65, str2nr('0o101', 8))
266  call assert_equal(65, str2nr('0O0101', 8))
267  call assert_equal(-65, str2nr('-0O101', 8))
268  call assert_equal(-65, str2nr('-0o0101', 8))
269
270  call assert_equal(11259375, str2nr('abcdef', 16))
271  call assert_equal(11259375, str2nr('ABCDEF', 16))
272  call assert_equal(-11259375, str2nr('-ABCDEF', 16))
273  call assert_equal(11259375, str2nr('0xabcdef', 16))
274  call assert_equal(11259375, str2nr('0Xabcdef', 16))
275  call assert_equal(11259375, str2nr('0XABCDEF', 16))
276  call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
277
278  call assert_equal(1, str2nr("1'000'000", 10, 0))
279  call assert_equal(256, str2nr("1'0000'0000", 2, 1))
280  call assert_equal(262144, str2nr("1'000'000", 8, 1))
281  call assert_equal(1000000, str2nr("1'000'000", 10, 1))
282  call assert_equal(1000, str2nr("1'000''000", 10, 1))
283  call assert_equal(65536, str2nr("1'00'00", 16, 1))
284
285  call assert_equal(0, str2nr('0x10'))
286  call assert_equal(0, str2nr('0b10'))
287  call assert_equal(0, str2nr('0o10'))
288  call assert_equal(1, str2nr('12', 2))
289  call assert_equal(1, str2nr('18', 8))
290  call assert_equal(1, str2nr('1g', 16))
291
292  call assert_equal(0, str2nr(v:null))
293  " call assert_equal(0, str2nr(v:none))
294
295  call assert_fails('call str2nr([])', 'E730:')
296  call assert_fails('call str2nr({->2})', 'E729:')
297  if has('float')
298    call assert_equal(1, str2nr(1.2))
299    call CheckDefExecFailure(['echo str2nr(1.2)'], 'E1013:')
300    call CheckScriptFailure(['vim9script', 'echo str2nr(1.2)'], 'E806:')
301  endif
302  call assert_fails('call str2nr(10, [])', 'E745:')
303endfunc
304
305func Test_strftime()
306  CheckFunction strftime
307
308  " Format of strftime() depends on system. We assume
309  " that basic formats tested here are available and
310  " identical on all systems which support strftime().
311  "
312  " The 2nd parameter of strftime() is a local time, so the output day
313  " of strftime() can be 17 or 18, depending on timezone.
314  call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
315  "
316  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())
317
318  call assert_fails('call strftime([])', 'E730:')
319  call assert_fails('call strftime("%Y", [])', 'E745:')
320
321  " Check that the time changes after we change the timezone
322  " Save previous timezone value, if any
323  if exists('$TZ')
324    let tz = $TZ
325  endif
326
327  " Force different time zones, save the current hour (24-hour clock) for each
328  let $TZ = 'GMT+1' | let one = strftime('%H')
329  let $TZ = 'GMT+2' | let two = strftime('%H')
330
331  " Those hours should be two bytes long, and should not be the same; if they
332  " are, a tzset(3) call may have failed somewhere
333  call assert_equal(strlen(one), 2)
334  call assert_equal(strlen(two), 2)
335  " TODO: this fails on MS-Windows
336  if has('unix')
337    call assert_notequal(one, two)
338  endif
339
340  " If we cached a timezone value, put it back, otherwise clear it
341  if exists('tz')
342    let $TZ = tz
343  else
344    unlet $TZ
345  endif
346endfunc
347
348func Test_strptime()
349  CheckFunction strptime
350  CheckNotBSD
351  CheckNotMSWindows
352
353  if exists('$TZ')
354    let tz = $TZ
355  endif
356  let $TZ = 'UTC'
357
358  call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
359
360  " Force DST and check that it's considered
361  let $TZ = 'WINTER0SUMMER,J1,J365'
362  call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
363
364  call assert_fails('call strptime()', 'E119:')
365  call assert_fails('call strptime("xxx")', 'E119:')
366  " This fails on BSD 14 and returns
367  " -2209078800 instead of 0
368  call assert_equal(0, strptime("%Y", ''))
369  call assert_equal(0, strptime("%Y", "xxx"))
370
371  if exists('tz')
372    let $TZ = tz
373  else
374    unlet $TZ
375  endif
376endfunc
377
378func Test_repeat_overflow()
379  call assert_fails("call repeat('abcdef', 715827883)", 'E1510:')
380  call assert_fails("call repeat('ab', 4294967297)", 'E1510:')
381  call assert_fails('call repeat([1, 2, 3, 4, 5, 6], 715827883)', 'E1510:')
382endfunc
383
384func Test_resolve_unix()
385  CheckUnix
386
387  " Xlink1 -> Xlink2
388  " Xlink2 -> Xlink3
389  silent !ln -s -f Xlink2 Xlink1
390  silent !ln -s -f Xlink3 Xlink2
391  call assert_equal('Xlink3', resolve('Xlink1'))
392  call assert_equal('./Xlink3', resolve('./Xlink1'))
393  call assert_equal('Xlink3/', resolve('Xlink2/'))
394  " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
395  "call assert_equal('Xlink3/', resolve('Xlink1/'))
396  "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
397  "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
398  call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
399
400  " Test resolve() with a symlink cycle.
401  " Xlink1 -> Xlink2
402  " Xlink2 -> Xlink3
403  " Xlink3 -> Xlink1
404  silent !ln -s -f Xlink1 Xlink3
405  call assert_fails('call resolve("Xlink1")',   'E655:')
406  call assert_fails('call resolve("./Xlink1")', 'E655:')
407  call assert_fails('call resolve("Xlink2")',   'E655:')
408  call assert_fails('call resolve("Xlink3")',   'E655:')
409  call delete('Xlink1')
410  call delete('Xlink2')
411  call delete('Xlink3')
412
413  silent !ln -s -f Xdir//Xfile Xlink
414  call assert_equal('Xdir/Xfile', resolve('Xlink'))
415  call delete('Xlink')
416
417  silent !ln -s -f Xlink2/ Xlink1
418  call assert_equal('Xlink2', 'Xlink1'->resolve())
419  call assert_equal('Xlink2/', resolve('Xlink1/'))
420  call delete('Xlink1')
421
422  silent !ln -s -f ./Xlink2 Xlink1
423  call assert_equal('Xlink2', resolve('Xlink1'))
424  call assert_equal('./Xlink2', resolve('./Xlink1'))
425  call delete('Xlink1')
426
427  call assert_equal('/', resolve('/'))
428endfunc
429
430func s:normalize_fname(fname)
431  let ret = substitute(a:fname, '\', '/', 'g')
432  let ret = substitute(ret, '//', '/', 'g')
433  return ret->tolower()
434endfunc
435
436func Test_simplify()
437  call assert_equal('',            simplify(''))
438  call assert_equal('/',           simplify('/'))
439  call assert_equal('/',           simplify('/.'))
440  call assert_equal('/',           simplify('/..'))
441  call assert_equal('/...',        simplify('/...'))
442  call assert_equal('//path',      simplify('//path'))
443  if has('unix')
444    call assert_equal('/path',       simplify('///path'))
445    call assert_equal('/path',       simplify('////path'))
446  endif
447
448  call assert_equal('./dir/file',  './dir/file'->simplify())
449  call assert_equal('./dir/file',  simplify('.///dir//file'))
450  call assert_equal('./dir/file',  simplify('./dir/./file'))
451  call assert_equal('./file',      simplify('./dir/../file'))
452  call assert_equal('../dir/file', simplify('dir/../../dir/file'))
453  call assert_equal('./file',      simplify('dir/.././file'))
454  call assert_equal('../dir',      simplify('./../dir'))
455  call assert_equal('..',          simplify('../testdir/..'))
456  call mkdir('Xdir')
457  call assert_equal('.',           simplify('Xdir/../.'))
458  call delete('Xdir', 'd')
459
460  call assert_fails('call simplify({->0})', 'E729:')
461  call assert_fails('call simplify([])', 'E730:')
462  call assert_fails('call simplify({})', 'E731:')
463  if has('float')
464    call assert_equal('1.2', simplify(1.2))
465    call CheckDefExecAndScriptFailure(['echo simplify(1.2)'], 'E806:')
466  endif
467endfunc
468
469func Test_pathshorten()
470  call assert_equal('', pathshorten(''))
471  call assert_equal('foo', pathshorten('foo'))
472  call assert_equal('/foo', '/foo'->pathshorten())
473  call assert_equal('f/', pathshorten('foo/'))
474  call assert_equal('f/bar', pathshorten('foo/bar'))
475  call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten())
476  call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
477  call assert_equal('.f/bar', pathshorten('.foo/bar'))
478  call assert_equal('~f/bar', pathshorten('~foo/bar'))
479  call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
480  call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
481  call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
482  call assert_fails('call pathshorten([])', 'E730:')
483
484  " test pathshorten with optional variable to set preferred size of shortening
485  call assert_equal('', pathshorten('', 2))
486  call assert_equal('foo', pathshorten('foo', 2))
487  call assert_equal('/foo', pathshorten('/foo', 2))
488  call assert_equal('fo/', pathshorten('foo/', 2))
489  call assert_equal('fo/bar', pathshorten('foo/bar', 2))
490  call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2))
491  call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2))
492  call assert_equal('.fo/bar', pathshorten('.foo/bar', 2))
493  call assert_equal('~fo/bar', pathshorten('~foo/bar', 2))
494  call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2))
495  call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2))
496  call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2))
497  call assert_fails('call pathshorten([],2)', 'E730:')
498  call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3))
499  call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3))
500  call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0))
501endfunc
502
503func Test_strpart()
504  call assert_equal('de', strpart('abcdefg', 3, 2))
505  call assert_equal('ab', strpart('abcdefg', -2, 4))
506  call assert_equal('abcdefg', 'abcdefg'->strpart(-2))
507  call assert_equal('fg', strpart('abcdefg', 5, 4))
508  call assert_equal('defg', strpart('abcdefg', 3))
509  call assert_equal('', strpart('abcdefg', 10))
510  call assert_fails("let s=strpart('abcdef', [])", 'E745:')
511
512  call assert_equal('lép', strpart('éléphant', 2, 4))
513  call assert_equal('léphant', strpart('éléphant', 2))
514
515  call assert_equal('é', strpart('éléphant', 0, 1, 1))
516  call assert_equal('ép', strpart('éléphant', 3, 2, v:true))
517  call assert_equal('ó', strpart('cómposed', 1, 1, 1))
518endfunc
519
520func Test_tolower()
521  call assert_equal("", tolower(""))
522
523  " Test with all printable ASCII characters.
524  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
525          \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
526
527  " Test with a few uppercase diacritics.
528  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
529  call assert_equal("bḃḇ", tolower("BḂḆ"))
530  call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
531  call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
532  call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
533  call assert_equal("fḟ ", tolower("FḞ "))
534  call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
535  call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
536  call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
537  call assert_equal("jĵ", tolower("JĴ"))
538  call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
539  call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
540  call assert_equal("mḿṁ", tolower("MḾṀ"))
541  call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
542  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
543  call assert_equal("pṕṗ", tolower("PṔṖ"))
544  call assert_equal("q", tolower("Q"))
545  call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
546  call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
547  call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
548  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
549  call assert_equal("vṽ", tolower("VṼ"))
550  call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
551  call assert_equal("xẋẍ", tolower("XẊẌ"))
552  call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
553  call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
554
555  " Test with a few lowercase diacritics, which should remain unchanged.
556  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
557  call assert_equal("bḃḇ", tolower("bḃḇ"))
558  call assert_equal("cçćĉċč", tolower("cçćĉċč"))
559  call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
560  call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
561  call assert_equal("fḟ", tolower("fḟ"))
562  call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
563  call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
564  call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
565  call assert_equal("jĵǰ", tolower("jĵǰ"))
566  call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
567  call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
568  call assert_equal("mḿṁ ", tolower("mḿṁ "))
569  call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
570  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
571  call assert_equal("pṕṗ", tolower("pṕṗ"))
572  call assert_equal("q", tolower("q"))
573  call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
574  call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
575  call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
576  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
577  call assert_equal("vṽ", tolower("vṽ"))
578  call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
579  call assert_equal("ẋẍ", tolower("ẋẍ"))
580  call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
581  call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
582
583  " According to https://twitter.com/jifa/status/625776454479970304
584  " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
585  " in length (2 to 3 bytes) when lowercased. So let's test them.
586  call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
587
588  " This call to tolower with invalid utf8 sequence used to cause access to
589  " invalid memory.
590  call tolower("\xC0\x80\xC0")
591  call tolower("123\xC0\x80\xC0")
592
593  " Test in latin1 encoding
594  let save_enc = &encoding
595  " set encoding=latin1
596  call assert_equal("abc", tolower("ABC"))
597  let &encoding = save_enc
598endfunc
599
600func Test_toupper()
601  call assert_equal("", toupper(""))
602
603  " Test with all printable ASCII characters.
604  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
605          \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
606
607  " Test with a few lowercase diacritics.
608  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper())
609  call assert_equal("BḂḆ", toupper("bḃḇ"))
610  call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
611  call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
612  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
613  call assert_equal("FḞ", toupper("fḟ"))
614  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
615  call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
616  call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
617  call assert_equal("JĴǰ", toupper("jĵǰ"))
618  call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
619  call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
620  call assert_equal("MḾṀ ", toupper("mḿṁ "))
621  call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
622  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
623  call assert_equal("PṔṖ", toupper("pṕṗ"))
624  call assert_equal("Q", toupper("q"))
625  call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
626  call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
627  call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
628  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
629  call assert_equal("VṼ", toupper("vṽ"))
630  call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
631  call assert_equal("ẊẌ", toupper("ẋẍ"))
632  call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
633  call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
634
635  " Test that uppercase diacritics, which should remain unchanged.
636  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
637  call assert_equal("BḂḆ", toupper("BḂḆ"))
638  call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
639  call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
640  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
641  call assert_equal("FḞ ", toupper("FḞ "))
642  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
643  call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
644  call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
645  call assert_equal("JĴ", toupper("JĴ"))
646  call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
647  call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
648  call assert_equal("MḾṀ", toupper("MḾṀ"))
649  call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
650  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
651  call assert_equal("PṔṖ", toupper("PṔṖ"))
652  call assert_equal("Q", toupper("Q"))
653  call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
654  call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
655  call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
656  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
657  call assert_equal("VṼ", toupper("VṼ"))
658  call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
659  call assert_equal("XẊẌ", toupper("XẊẌ"))
660  call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
661  call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
662
663  call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
664
665  " This call to toupper with invalid utf8 sequence used to cause access to
666  " invalid memory.
667  call toupper("\xC0\x80\xC0")
668  call toupper("123\xC0\x80\xC0")
669
670  " Test in latin1 encoding
671  let save_enc = &encoding
672  " set encoding=latin1
673  call assert_equal("ABC", toupper("abc"))
674  let &encoding = save_enc
675endfunc
676
677func Test_tr()
678  call assert_equal('foo', tr('bar', 'bar', 'foo'))
679  call assert_equal('zxy', 'cab'->tr('abc', 'xyz'))
680  call assert_fails("let s=tr([], 'abc', 'def')", 'E730:')
681  call assert_fails("let s=tr('abc', [], 'def')", 'E730:')
682  call assert_fails("let s=tr('abc', 'abc', [])", 'E730:')
683  call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
684  " set encoding=latin1
685  call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
686  call assert_equal('hEllO', tr('hello', 'eo', 'EO'))
687  call assert_equal('hello', tr('hello', 'xy', 'ab'))
688  call assert_fails('call tr("abc", "123", "₁₂")', 'E475:')
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  noremap! <F2> <C-R>=Save_mode()<CR>
708  xnoremap <F2> <Cmd>call Save_mode()<CR>
709
710  normal! 3G
711  exe "normal i\<F2>\<Esc>"
712  call assert_equal('i-i', g:current_modes)
713  " i_CTRL-P: Multiple matches
714  exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
715  call assert_equal('i-ic', g:current_modes)
716  " i_CTRL-P: Single match
717  exe "normal iBro\<C-P>\<F2>\<Esc>u"
718  call assert_equal('i-ic', g:current_modes)
719  " i_CTRL-X
720  exe "normal iBa\<C-X>\<F2>\<Esc>u"
721  call assert_equal('i-ix', g:current_modes)
722  " i_CTRL-X CTRL-P: Multiple matches
723  exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
724  call assert_equal('i-ic', g:current_modes)
725  " i_CTRL-X CTRL-P: Single match
726  exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u"
727  call assert_equal('i-ic', g:current_modes)
728  " i_CTRL-X CTRL-P + CTRL-P: Single match
729  exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
730  call assert_equal('i-ic', g:current_modes)
731  " i_CTRL-X CTRL-L: Multiple matches
732  exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
733  call assert_equal('i-ic', g:current_modes)
734  " i_CTRL-X CTRL-L: Single match
735  exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
736  call assert_equal('i-ic', g:current_modes)
737  " i_CTRL-P: No match
738  exe "normal iCom\<C-P>\<F2>\<Esc>u"
739  call assert_equal('i-ic', g:current_modes)
740  " i_CTRL-X CTRL-P: No match
741  exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u"
742  call assert_equal('i-ic', g:current_modes)
743  " i_CTRL-X CTRL-L: No match
744  exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
745  call assert_equal('i-ic', g:current_modes)
746
747  exe "normal R\<F2>\<Esc>"
748  call assert_equal('R-R', g:current_modes)
749  " R_CTRL-P: Multiple matches
750  exe "normal RBa\<C-P>\<F2>\<Esc>u"
751  call assert_equal('R-Rc', g:current_modes)
752  " R_CTRL-P: Single match
753  exe "normal RBro\<C-P>\<F2>\<Esc>u"
754  call assert_equal('R-Rc', g:current_modes)
755  " R_CTRL-X
756  exe "normal RBa\<C-X>\<F2>\<Esc>u"
757  call assert_equal('R-Rx', g:current_modes)
758  " R_CTRL-X CTRL-P: Multiple matches
759  exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
760  call assert_equal('R-Rc', g:current_modes)
761  " R_CTRL-X CTRL-P: Single match
762  exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u"
763  call assert_equal('R-Rc', g:current_modes)
764  " R_CTRL-X CTRL-P + CTRL-P: Single match
765  exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
766  call assert_equal('R-Rc', g:current_modes)
767  " R_CTRL-X CTRL-L: Multiple matches
768  exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
769  call assert_equal('R-Rc', g:current_modes)
770  " R_CTRL-X CTRL-L: Single match
771  exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
772  call assert_equal('R-Rc', g:current_modes)
773  " R_CTRL-P: No match
774  exe "normal RCom\<C-P>\<F2>\<Esc>u"
775  call assert_equal('R-Rc', g:current_modes)
776  " R_CTRL-X CTRL-P: No match
777  exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u"
778  call assert_equal('R-Rc', g:current_modes)
779  " R_CTRL-X CTRL-L: No match
780  exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
781  call assert_equal('R-Rc', g:current_modes)
782
783  exe "normal gR\<F2>\<Esc>"
784  call assert_equal('R-Rv', g:current_modes)
785  " gR_CTRL-P: Multiple matches
786  exe "normal gRBa\<C-P>\<F2>\<Esc>u"
787  call assert_equal('R-Rvc', g:current_modes)
788  " gR_CTRL-P: Single match
789  exe "normal gRBro\<C-P>\<F2>\<Esc>u"
790  call assert_equal('R-Rvc', g:current_modes)
791  " gR_CTRL-X
792  exe "normal gRBa\<C-X>\<F2>\<Esc>u"
793  call assert_equal('R-Rvx', g:current_modes)
794  " gR_CTRL-X CTRL-P: Multiple matches
795  exe "normal gRBa\<C-X>\<C-P>\<F2>\<Esc>u"
796  call assert_equal('R-Rvc', g:current_modes)
797  " gR_CTRL-X CTRL-P: Single match
798  exe "normal gRBro\<C-X>\<C-P>\<F2>\<Esc>u"
799  call assert_equal('R-Rvc', g:current_modes)
800  " gR_CTRL-X CTRL-P + CTRL-P: Single match
801  exe "normal gRBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
802  call assert_equal('R-Rvc', g:current_modes)
803  " gR_CTRL-X CTRL-L: Multiple matches
804  exe "normal gR\<C-X>\<C-L>\<F2>\<Esc>u"
805  call assert_equal('R-Rvc', g:current_modes)
806  " gR_CTRL-X CTRL-L: Single match
807  exe "normal gRBlu\<C-X>\<C-L>\<F2>\<Esc>u"
808  call assert_equal('R-Rvc', g:current_modes)
809  " gR_CTRL-P: No match
810  exe "normal gRCom\<C-P>\<F2>\<Esc>u"
811  call assert_equal('R-Rvc', g:current_modes)
812  " gR_CTRL-X CTRL-P: No match
813  exe "normal gRCom\<C-X>\<C-P>\<F2>\<Esc>u"
814  call assert_equal('R-Rvc', g:current_modes)
815  " gR_CTRL-X CTRL-L: No match
816  exe "normal gRabc\<C-X>\<C-L>\<F2>\<Esc>u"
817  call assert_equal('R-Rvc', g:current_modes)
818
819  call assert_equal('n', 0->mode())
820  call assert_equal('n', 1->mode())
821
822  " i_CTRL-O
823  exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
824  call assert_equal("n-niI", g:current_modes)
825
826  " R_CTRL-O
827  exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
828  call assert_equal("n-niR", g:current_modes)
829
830  " gR_CTRL-O
831  exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
832  call assert_equal("n-niV", g:current_modes)
833
834  " How to test operator-pending mode?
835
836  call feedkeys("v", 'xt')
837  call assert_equal('v', mode())
838  call assert_equal('v', mode(1))
839  call feedkeys("\<Esc>V", 'xt')
840  call assert_equal('V', mode())
841  call assert_equal('V', mode(1))
842  call feedkeys("\<Esc>\<C-V>", 'xt')
843  call assert_equal("\<C-V>", mode())
844  call assert_equal("\<C-V>", mode(1))
845  call feedkeys("\<Esc>", 'xt')
846
847  call feedkeys("gh", 'xt')
848  call assert_equal('s', mode())
849  call assert_equal('s', mode(1))
850  call feedkeys("\<Esc>gH", 'xt')
851  call assert_equal('S', mode())
852  call assert_equal('S', mode(1))
853  call feedkeys("\<Esc>g\<C-H>", 'xt')
854  call assert_equal("\<C-S>", mode())
855  call assert_equal("\<C-S>", mode(1))
856  call feedkeys("\<Esc>", 'xt')
857
858  " v_CTRL-O
859  exe "normal gh\<C-O>\<F2>\<Esc>"
860  call assert_equal("v-vs", g:current_modes)
861  exe "normal gH\<C-O>\<F2>\<Esc>"
862  call assert_equal("V-Vs", g:current_modes)
863  exe "normal g\<C-H>\<C-O>\<F2>\<Esc>"
864  call assert_equal("\<C-V>-\<C-V>s", g:current_modes)
865
866  call feedkeys(":\<F2>\<CR>", 'xt')
867  call assert_equal('c-c', g:current_modes)
868  call feedkeys(":\<Insert>\<F2>\<CR>", 'xt')
869  call assert_equal("c-cr", g:current_modes)
870  " Nvim: interactive Ex mode is a cmdwin wrapper: mode()=n/i ("cv" means
871  " -es); cannot run inside :normal/feedkeys('x').
872  "call feedkeys("gQ\<F2>vi\<CR>", 'xt')
873  "call assert_equal('c-cv', g:current_modes)
874  "call feedkeys("gQ\<Insert>\<F2>vi\<CR>", 'xt')
875  "call assert_equal("c-cvr", g:current_modes)
876
877  " Commandline mode in Visual mode should return "c-c", never "v-v".
878  call feedkeys("v\<Cmd>call input('')\<CR>\<F2>\<CR>\<Esc>", 'xt')
879  call assert_equal("c-c", g:current_modes)
880
881  " Executing commands in Vim Ex mode should return "cv", never "cvr",
882  " as Cmdline editing has already ended.
883  "call feedkeys("gQcall Save_mode()\<CR>vi\<CR>", 'xt')
884  "call assert_equal('c-cv', g:current_modes)
885  "call feedkeys("gQ\<Insert>call Save_mode()\<CR>vi\<CR>", 'xt')
886  "call assert_equal('c-cv', g:current_modes)
887
888  " call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt')
889  " call assert_equal('c-ce', g:current_modes)
890
891  " Test mode in operatorfunc (it used to be Operator-pending).
892  set operatorfunc=OperatorFunc
893  function OperatorFunc(_)
894    call Save_mode()
895  endfunction
896  execute "normal! g@l\<Esc>"
897  call assert_equal('n-n', g:current_modes)
898  execute "normal! i\<C-o>g@l\<Esc>"
899  call assert_equal('n-niI', g:current_modes)
900  execute "normal! R\<C-o>g@l\<Esc>"
901  call assert_equal('n-niR', g:current_modes)
902  execute "normal! gR\<C-o>g@l\<Esc>"
903  call assert_equal('n-niV', g:current_modes)
904
905
906  if has('terminal')
907    term
908    call feedkeys("\<C-W>N", 'xt')
909    call assert_equal('n', mode())
910    call assert_equal('nt', mode(1))
911    call feedkeys("aexit\<CR>", 'xt')
912  endif
913
914  bwipe!
915  unmap! <F2>
916  xunmap <F2>
917  set complete&
918  set operatorfunc&
919  delfunction OperatorFunc
920endfunc
921
922" Test for the mode() function using Screendump feature
923func Test_mode_screendump()
924  CheckScreendump
925
926  " Test statusline updates for overstrike mode
927  let buf = RunVimInTerminal('', {'rows': 12})
928  call term_sendkeys(buf, ":set laststatus=2 statusline=%!mode(1)\<CR>")
929  call term_sendkeys(buf, ":")
930  call TermWait(buf)
931  call VerifyScreenDump(buf, 'Test_mode_1', {})
932  call term_sendkeys(buf, "\<Insert>")
933  call TermWait(buf)
934  call VerifyScreenDump(buf, 'Test_mode_2', {})
935  call StopVimInTerminal(buf)
936endfunc
937
938" Test for append()
939func Test_append()
940  enew!
941  split
942  call assert_equal(0, append(1, []))
943  call assert_equal(0, append(1, v:_null_list))
944  call assert_equal(0, append(0, ["foo"]))
945  call assert_equal(0, append(1, []))
946  call assert_equal(0, append(1, v:_null_list))
947  call assert_equal(0, append(8, []))
948  call assert_equal(0, append(9, v:_null_list))
949  call assert_equal(['foo', ''], getline(1, '$'))
950  split
951  only
952  undo
953  undo
954
955  " Using $ instead of '$' must give an error
956  call assert_fails("call append($, 'foobar')", 'E116:')
957
958  call assert_fails("call append({}, '')", ['E728:', 'E728:'])
959endfunc
960
961" Test for setline()
962func Test_setline()
963  new
964  call setline(0, ["foo"])
965  call setline(0, [])
966  call setline(0, v:_null_list)
967  call setline(1, ["bar"])
968  call setline(1, [])
969  call setline(1, v:_null_list)
970  call setline(2, [])
971  call setline(2, v:_null_list)
972  call setline(3, [])
973  call setline(3, v:_null_list)
974  call setline(2, ["baz"])
975  call assert_equal(['bar', 'baz'], getline(1, '$'))
976  bw!
977endfunc
978
979func Test_getbufvar()
980  let bnr = bufnr('%')
981  let b:var_num = '1234'
982  let def_num = '5678'
983  call assert_equal('1234', getbufvar(bnr, 'var_num'))
984  call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
985
986  let bd = getbufvar(bnr, '')
987  call assert_equal('1234', bd['var_num'])
988  call assert_true(exists("bd['changedtick']"))
989  call assert_equal(2, len(bd))
990
991  let bd2 = getbufvar(bnr, '', def_num)
992  call assert_equal(bd, bd2)
993
994  unlet b:var_num
995  call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
996  call assert_equal('', getbufvar(bnr, 'var_num'))
997
998  let bd = getbufvar(bnr, '')
999  call assert_equal(1, len(bd))
1000  let bd = getbufvar(bnr, '',def_num)
1001  call assert_equal(1, len(bd))
1002
1003  call assert_equal('', getbufvar(9999, ''))
1004  call assert_equal(def_num, getbufvar(9999, '', def_num))
1005  unlet def_num
1006
1007  call assert_equal(0, getbufvar(bnr, '&autoindent'))
1008  call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
1009
1010  " Set and get a buffer-local variable
1011  call setbufvar(bnr, 'bufvar_test', ['one', 'two'])
1012  call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test'))
1013
1014  " Open new window with forced option values
1015  set fileformats=unix,dos
1016  new ++ff=dos ++bin ++enc=iso-8859-2
1017  call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
1018  call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
1019  call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
1020  close
1021
1022  " Get the b: dict.
1023  let b:testvar = 'one'
1024  new
1025  let b:testvar = 'two'
1026  let thebuf = bufnr()
1027  wincmd w
1028  call assert_equal('two', getbufvar(thebuf, 'testvar'))
1029  call assert_equal('two', getbufvar(thebuf, '').testvar)
1030  bwipe!
1031
1032  set fileformats&
1033endfunc
1034
1035func Test_last_buffer_nr()
1036  call assert_equal(bufnr('$'), last_buffer_nr())
1037endfunc
1038
1039func Test_stridx()
1040  call assert_equal(-1, stridx('', 'l'))
1041  call assert_equal(0,  stridx('', ''))
1042  call assert_equal(0,  'hello'->stridx(''))
1043  call assert_equal(-1, stridx('hello', 'L'))
1044  call assert_equal(2,  stridx('hello', 'l', -1))
1045  call assert_equal(2,  stridx('hello', 'l', 0))
1046  call assert_equal(2,  'hello'->stridx('l', 1))
1047  call assert_equal(3,  stridx('hello', 'l', 3))
1048  call assert_equal(-1, stridx('hello', 'l', 4))
1049  call assert_equal(-1, stridx('hello', 'l', 10))
1050  call assert_equal(2,  stridx('hello', 'll'))
1051  call assert_equal(-1, stridx('hello', 'hello world'))
1052  call assert_fails("let n=stridx('hello', [])", 'E730:')
1053  call assert_fails("let n=stridx([], 'l')", 'E730:')
1054endfunc
1055
1056func Test_strridx()
1057  call assert_equal(-1, strridx('', 'l'))
1058  call assert_equal(0,  strridx('', ''))
1059  call assert_equal(5,  strridx('hello', ''))
1060  call assert_equal(-1, strridx('hello', 'L'))
1061  call assert_equal(3,  'hello'->strridx('l'))
1062  call assert_equal(3,  strridx('hello', 'l', 10))
1063  call assert_equal(3,  strridx('hello', 'l', 3))
1064  call assert_equal(2,  strridx('hello', 'l', 2))
1065  call assert_equal(-1, strridx('hello', 'l', 1))
1066  call assert_equal(-1, strridx('hello', 'l', 0))
1067  call assert_equal(-1, strridx('hello', 'l', -1))
1068  call assert_equal(2,  strridx('hello', 'll'))
1069  call assert_equal(-1, strridx('hello', 'hello world'))
1070  call assert_fails("let n=strridx('hello', [])", 'E730:')
1071  call assert_fails("let n=strridx([], 'l')", 'E730:')
1072endfunc
1073
1074func Test_match_func()
1075  call assert_equal(4,  match('testing', 'ing'))
1076  call assert_equal(4,  'testing'->match('ing', 2))
1077  call assert_equal(-1, match('testing', 'ing', 5))
1078  call assert_equal(-1, match('testing', 'ing', 8))
1079  call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
1080  call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
1081  call assert_fails("let x=match('vim', [])", 'E730:')
1082  call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1))
1083  call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5))
1084  call assert_equal(4,  match('testing', 'ing', -1))
1085  call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:')
1086  call assert_equal(-1, match(v:_null_list, 2))
1087  call assert_equal(-1, match('abc', '\\%('))
1088endfunc
1089
1090func Test_matchend()
1091  call assert_equal(7,  matchend('testing', 'ing'))
1092  call assert_equal(7,  'testing'->matchend('ing', 2))
1093  call assert_equal(-1, matchend('testing', 'ing', 5))
1094  call assert_equal(-1, matchend('testing', 'ing', 8))
1095  call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
1096  call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
1097endfunc
1098
1099func Test_matchlist()
1100  call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
1101  call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''],  'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
1102  call assert_equal([],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
1103endfunc
1104
1105func Test_matchstr()
1106  call assert_equal('ing',  matchstr('testing', 'ing'))
1107  call assert_equal('ing',  'testing'->matchstr('ing', 2))
1108  call assert_equal('', matchstr('testing', 'ing', 5))
1109  call assert_equal('', matchstr('testing', 'ing', 8))
1110  call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
1111  call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
1112endfunc
1113
1114func Test_matchstrpos()
1115  call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
1116  call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2))
1117  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
1118  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
1119  call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
1120  call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
1121  call assert_equal(['', -1, -1], matchstrpos(v:_null_list, '\a'))
1122endfunc
1123
1124" Test for matchstrlist()
1125func Test_matchstrlist()
1126  let lines =<< trim END
1127    #" Basic match
1128    call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'bout'},
1129          \ {'idx': 1, 'byteidx': 1, 'text': 'bove'}],
1130          \ matchstrlist(['about', 'above'], 'bo.*'))
1131    #" no match
1132    call assert_equal([], matchstrlist(['about', 'above'], 'xy.*'))
1133    #" empty string
1134    call assert_equal([], matchstrlist([''], '.'))
1135    #" empty pattern
1136    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}], matchstrlist(['abc'], ''))
1137    #" method call
1138    call assert_equal([{'idx': 0, 'byteidx': 2, 'text': 'it'}], ['editor']->matchstrlist('ed\zsit\zeor'))
1139    #" single character matches
1140    call assert_equal([{'idx': 0, 'byteidx': 5, 'text': 'r'}],
1141          \ ['editor']->matchstrlist('r'))
1142    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'a'}], ['a']->matchstrlist('a'))
1143    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1144          \ matchstrlist(['foobar'], '\zs'))
1145    #" string with tabs
1146    call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'foo'}],
1147          \ matchstrlist(["\tfoobar"], 'foo'))
1148    #" string with multibyte characters
1149    call assert_equal([{'idx': 0, 'byteidx': 2, 'text': '😊😊'}],
1150          \ matchstrlist(["\t\t😊😊"], '\k\+'))
1151
1152    #" null string
1153    call assert_equal([], matchstrlist(v:_null_list, 'abc'))
1154    call assert_equal([], matchstrlist([v:_null_string], 'abc'))
1155    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1156          \ matchstrlist(['abc'], v:_null_string))
1157
1158    #" sub matches
1159    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}], matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)', {'submatches': v:true}))
1160
1161    #" null dict argument
1162    call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'vim'}],
1163          \ matchstrlist(['vim'], '\w\+', v:_null_dict))
1164
1165    #" Error cases
1166    call assert_fails("echo matchstrlist('abc', 'a')", 'E1211: List required for argument 1')
1167    call assert_fails("echo matchstrlist(['abc'], {})", 'E1174: String required for argument 2')
1168    call assert_fails("echo matchstrlist(['abc'], '.', [])", 'E1206: Dictionary required for argument 3')
1169    call assert_fails("echo matchstrlist(['abc'], 'a', {'submatches': []})", 'E475: Invalid value for argument submatches')
1170    call assert_fails("echo matchstrlist(['abc'], '\\@=')", 'E866: (NFA regexp) Misplaced @')
1171  END
1172  call CheckLegacyAndVim9Success(lines)
1173
1174  let lines =<< trim END
1175    vim9script
1176    # non string items
1177    matchstrlist([0z10, {'a': 'x'}], 'x')
1178  END
1179  call CheckSourceSuccess(lines)
1180
1181  let lines =<< trim END
1182    vim9script
1183    def Foo()
1184      # non string items
1185      assert_equal([], matchstrlist([0z10, {'a': 'x'}], 'x'))
1186    enddef
1187    Foo()
1188  END
1189  call CheckSourceFailure(lines, 'E1013: Argument 1: type mismatch, expected list<string> but got list<any>', 2)
1190endfunc
1191
1192" Test for matchbufline()
1193func Test_matchbufline()
1194  let lines =<< trim END
1195    #" Basic match
1196    new
1197    call setline(1, ['about', 'above', 'below'])
1198    VAR bnr = bufnr()
1199    wincmd w
1200    call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1201          \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'}],
1202          \ matchbufline(bnr, 'bo.*', 1, '$'))
1203    #" multiple matches in a line
1204    call setbufline(bnr, 1, ['about about', 'above above', 'below'])
1205    call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1206          \ {'lnum': 1, 'byteidx': 7, 'text': 'bout'},
1207          \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'},
1208          \ {'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1209          \ matchbufline(bnr, 'bo\k\+', 1, '$'))
1210    #" no match
1211    call assert_equal([], matchbufline(bnr, 'xy.*', 1, '$'))
1212    #" match on a particular line
1213    call assert_equal([{'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1214          \ matchbufline(bnr, 'bo\k\+$', 2, 2))
1215    #" match on a particular line
1216    call assert_equal([], matchbufline(bnr, 'bo.*', 3, 3))
1217    #" empty string
1218    call deletebufline(bnr, 1, '$')
1219    call assert_equal([], matchbufline(bnr, '.', 1, '$'))
1220    #" empty pattern
1221    call setbufline(bnr, 1, 'abc')
1222    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1223          \ matchbufline(bnr, '', 1, '$'))
1224    #" method call
1225    call setbufline(bnr, 1, 'editor')
1226    call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': 'it'}],
1227          \ bnr->matchbufline('ed\zsit\zeor', 1, 1))
1228    #" single character matches
1229    call assert_equal([{'lnum': 1, 'byteidx': 5, 'text': 'r'}],
1230          \ matchbufline(bnr, 'r', 1, '$'))
1231    call setbufline(bnr, 1, 'a')
1232    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'a'}],
1233          \ matchbufline(bnr, 'a', 1, '$'))
1234    #" zero-width match
1235    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1236          \ matchbufline(bnr, '\zs', 1, '$'))
1237    #" string with tabs
1238    call setbufline(bnr, 1, "\tfoobar")
1239    call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'foo'}],
1240          \ matchbufline(bnr, 'foo', 1, '$'))
1241    #" string with multibyte characters
1242    call setbufline(bnr, 1, "\t\t😊😊")
1243    call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': '😊😊'}],
1244          \ matchbufline(bnr, '\k\+', 1, '$'))
1245    #" empty buffer
1246    call deletebufline(bnr, 1, '$')
1247    call assert_equal([], matchbufline(bnr, 'abc', 1, '$'))
1248
1249    #" Non existing buffer
1250    call setbufline(bnr, 1, 'abc')
1251    call assert_fails("echo matchbufline(5000, 'abc', 1, 1)", 'E158: Invalid buffer name: 5000')
1252    #" null string
1253    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1254          \ matchbufline(bnr, v:_null_string, 1, 1))
1255    #" invalid starting line number
1256    call assert_equal([], matchbufline(bnr, 'abc', 100, 100))
1257    #" ending line number greater than the last line
1258    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'abc'}],
1259          \ matchbufline(bnr, 'abc', 1, 100))
1260    #" ending line number greater than the starting line number
1261    call setbufline(bnr, 1, ['one', 'two'])
1262    call assert_fails($"echo matchbufline({bnr}, 'abc', 2, 1)", 'E475: Invalid value for argument end_lnum')
1263
1264    #" sub matches
1265    call deletebufline(bnr, 1, '$')
1266    call setbufline(bnr, 1, 'acd')
1267    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}],
1268          \ matchbufline(bnr, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 1, '$', {'submatches': v:true}))
1269
1270    #" null dict argument
1271    call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd'}],
1272          \ matchbufline(bnr, '\w\+', '$', '$', v:_null_dict))
1273
1274    #" Error cases
1275    call assert_fails("echo matchbufline([1], 'abc', 1, 1)", 'E1220: String or Number required for argument 1')
1276    call assert_fails("echo matchbufline(1, {}, 1, 1)", 'E1174: String required for argument 2')
1277    call assert_fails("echo matchbufline(1, 'abc', {}, 1)", 'E1220: String or Number required for argument 3')
1278    call assert_fails("echo matchbufline(1, 'abc', 1, {})", 'E1220: String or Number required for argument 4')
1279    call assert_fails($"echo matchbufline({bnr}, 'abc', -1, '$')", 'E475: Invalid value for argument lnum')
1280    call assert_fails($"echo matchbufline({bnr}, 'abc', 1, -1)", 'E475: Invalid value for argument end_lnum')
1281    call assert_fails($"echo matchbufline({bnr}, '\\@=', 1, 1)", 'E866: (NFA regexp) Misplaced @')
1282    call assert_fails($"echo matchbufline({bnr}, 'abc', 1, 1, {{'submatches': []}})", 'E475: Invalid value for argument submatches')
1283    :%bdelete!
1284    call assert_fails($"echo matchbufline({bnr}, 'abc', 1, '$'))", 'E681: Buffer is not loaded')
1285  END
1286  call CheckLegacyAndVim9Success(lines)
1287
1288  call assert_fails($"echo matchbufline('', 'abc', 'abc', 1)", 'E475: Invalid value for argument lnum')
1289  call assert_fails($"echo matchbufline('', 'abc', 1, 'abc')", 'E475: Invalid value for argument end_lnum')
1290
1291  let lines =<< trim END
1292    vim9script
1293    def Foo()
1294      echo matchbufline('', 'abc', 'abc', 1)
1295    enddef
1296    Foo()
1297  END
1298  call CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1299
1300  let lines =<< trim END
1301    vim9script
1302    def Foo()
1303      echo matchbufline('', 'abc', 1, 'abc')
1304    enddef
1305    Foo()
1306  END
1307  call CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1308endfunc
1309
1310func Test_nextnonblank_prevnonblank()
1311  new
1312insert
1313This
1314
1315
1316is
1317
1318a
1319Test
1320.
1321  call assert_equal(0, nextnonblank(-1))
1322  call assert_equal(0, nextnonblank(0))
1323  call assert_equal(1, nextnonblank(1))
1324  call assert_equal(4, 2->nextnonblank())
1325  call assert_equal(4, nextnonblank(3))
1326  call assert_equal(4, nextnonblank(4))
1327  call assert_equal(6, nextnonblank(5))
1328  call assert_equal(6, nextnonblank(6))
1329  call assert_equal(7, nextnonblank(7))
1330  call assert_equal(0, 8->nextnonblank())
1331
1332  call assert_equal(0, prevnonblank(-1))
1333  call assert_equal(0, prevnonblank(0))
1334  call assert_equal(1, 1->prevnonblank())
1335  call assert_equal(1, prevnonblank(2))
1336  call assert_equal(1, prevnonblank(3))
1337  call assert_equal(4, prevnonblank(4))
1338  call assert_equal(4, 5->prevnonblank())
1339  call assert_equal(6, prevnonblank(6))
1340  call assert_equal(7, prevnonblank(7))
1341  call assert_equal(0, prevnonblank(8))
1342  bw!
1343endfunc
1344
1345func Test_byte2line_line2byte()
1346  new
1347  set endofline
1348  call setline(1, ['a', 'bc', 'd'])
1349
1350  set fileformat=unix
1351  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1352  \                 map(range(-1, 8), 'byte2line(v:val)'))
1353  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1354  \                 map(range(-1, 5), 'line2byte(v:val)'))
1355
1356  set fileformat=mac
1357  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1358  \                 map(range(-1, 8), 'v:val->byte2line()'))
1359  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1360  \                 map(range(-1, 5), 'v:val->line2byte()'))
1361
1362  set fileformat=dos
1363  call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
1364  \                 map(range(-1, 11), 'byte2line(v:val)'))
1365  call assert_equal([-1, -1, 1, 4, 8, 11, -1],
1366  \                 map(range(-1, 5), 'line2byte(v:val)'))
1367
1368  bw!
1369  set noendofline nofixendofline
1370  normal a-
1371  for ff in ["unix", "mac", "dos"]
1372    let &fileformat = ff
1373    call assert_equal(1, line2byte(1))
1374    call assert_equal(2, line2byte(2))  " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
1375  endfor
1376
1377  set endofline& fixendofline& fileformat&
1378  bw!
1379endfunc
1380
1381" Test for byteidx() using a character index
1382func Test_byteidx()
1383  let a = '.é.' " one char of two bytes
1384  call assert_equal(0, byteidx(a, 0))
1385  call assert_equal(1, byteidx(a, 1))
1386  call assert_equal(3, byteidx(a, 2))
1387  call assert_equal(4, byteidx(a, 3))
1388  call assert_equal(-1, byteidx(a, 4))
1389
1390  let b = '.é.' " normal e with composing char
1391  call assert_equal(0, b->byteidx(0))
1392  call assert_equal(1, b->byteidx(1))
1393  call assert_equal(4, b->byteidx(2))
1394  call assert_equal(5, b->byteidx(3))
1395  call assert_equal(-1, b->byteidx(4))
1396
1397  " string with multiple composing characters
1398  let str = '-ą́-ą́'
1399  call assert_equal(0, byteidx(str, 0))
1400  call assert_equal(1, byteidx(str, 1))
1401  call assert_equal(6, byteidx(str, 2))
1402  call assert_equal(7, byteidx(str, 3))
1403  call assert_equal(12, byteidx(str, 4))
1404  call assert_equal(-1, byteidx(str, 5))
1405
1406  " empty string
1407  call assert_equal(0, byteidx('', 0))
1408  call assert_equal(-1, byteidx('', 1))
1409
1410  " error cases
1411  call assert_fails("call byteidx([], 0)", 'E730:')
1412  call assert_fails("call byteidx('abc', [])", 'E745:')
1413  call assert_fails("call byteidx('abc', 0, {})", ['E728:', 'E728:'])
1414  call assert_fails("call byteidx('abc', 0, -1)", ['E1023:', 'E1023:'])
1415endfunc
1416
1417" Test for byteidxcomp() using a character index
1418func Test_byteidxcomp()
1419  let a = '.é.' " one char of two bytes
1420  call assert_equal(0, byteidxcomp(a, 0))
1421  call assert_equal(1, byteidxcomp(a, 1))
1422  call assert_equal(3, byteidxcomp(a, 2))
1423  call assert_equal(4, byteidxcomp(a, 3))
1424  call assert_equal(-1, byteidxcomp(a, 4))
1425
1426  let b = '.é.' " normal e with composing char
1427  call assert_equal(0, b->byteidxcomp(0))
1428  call assert_equal(1, b->byteidxcomp(1))
1429  call assert_equal(2, b->byteidxcomp(2))
1430  call assert_equal(4, b->byteidxcomp(3))
1431  call assert_equal(5, b->byteidxcomp(4))
1432  call assert_equal(-1, b->byteidxcomp(5))
1433
1434  " string with multiple composing characters
1435  let str = '-ą́-ą́'
1436  call assert_equal(0, byteidxcomp(str, 0))
1437  call assert_equal(1, byteidxcomp(str, 1))
1438  call assert_equal(2, byteidxcomp(str, 2))
1439  call assert_equal(4, byteidxcomp(str, 3))
1440  call assert_equal(6, byteidxcomp(str, 4))
1441  call assert_equal(7, byteidxcomp(str, 5))
1442  call assert_equal(8, byteidxcomp(str, 6))
1443  call assert_equal(10, byteidxcomp(str, 7))
1444  call assert_equal(12, byteidxcomp(str, 8))
1445  call assert_equal(-1, byteidxcomp(str, 9))
1446
1447  " empty string
1448  call assert_equal(0, byteidxcomp('', 0))
1449  call assert_equal(-1, byteidxcomp('', 1))
1450
1451  " error cases
1452  call assert_fails("call byteidxcomp([], 0)", 'E730:')
1453  call assert_fails("call byteidxcomp('abc', [])", 'E745:')
1454  call assert_fails("call byteidxcomp('abc', 0, {})", ['E728:', 'E728:'])
1455  call assert_fails("call byteidxcomp('abc', 0, -1)", ['E1023:', 'E1023:'])
1456endfunc
1457
1458" Test for byteidx() using a UTF-16 index
1459func Test_byteidx_from_utf16_index()
1460  " string with single byte characters
1461  let str = "abc"
1462  for i in range(3)
1463    call assert_equal(i, byteidx(str, i, v:true))
1464  endfor
1465  call assert_equal(3, byteidx(str, 3, v:true))
1466  call assert_equal(-1, byteidx(str, 4, v:true))
1467
1468  " string with two byte characters
1469  let str = "a©©b"
1470  call assert_equal(0, byteidx(str, 0, v:true))
1471  call assert_equal(1, byteidx(str, 1, v:true))
1472  call assert_equal(3, byteidx(str, 2, v:true))
1473  call assert_equal(5, byteidx(str, 3, v:true))
1474  call assert_equal(6, byteidx(str, 4, v:true))
1475  call assert_equal(-1, byteidx(str, 5, v:true))
1476
1477  " string with two byte characters
1478  let str = "a😊😊b"
1479  call assert_equal(0, byteidx(str, 0, v:true))
1480  call assert_equal(1, byteidx(str, 1, v:true))
1481  call assert_equal(1, byteidx(str, 2, v:true))
1482  call assert_equal(5, byteidx(str, 3, v:true))
1483  call assert_equal(5, byteidx(str, 4, v:true))
1484  call assert_equal(9, byteidx(str, 5, v:true))
1485  call assert_equal(10, byteidx(str, 6, v:true))
1486  call assert_equal(-1, byteidx(str, 7, v:true))
1487
1488  " string with composing characters
1489  let str = '-á-b́'
1490  call assert_equal(0, byteidx(str, 0, v:true))
1491  call assert_equal(1, byteidx(str, 1, v:true))
1492  call assert_equal(4, byteidx(str, 2, v:true))
1493  call assert_equal(5, byteidx(str, 3, v:true))
1494  call assert_equal(8, byteidx(str, 4, v:true))
1495  call assert_equal(-1, byteidx(str, 5, v:true))
1496
1497  " string with multiple composing characters
1498  let str = '-ą́-ą́'
1499  call assert_equal(0, byteidx(str, 0, v:true))
1500  call assert_equal(1, byteidx(str, 1, v:true))
1501  call assert_equal(6, byteidx(str, 2, v:true))
1502  call assert_equal(7, byteidx(str, 3, v:true))
1503  call assert_equal(12, byteidx(str, 4, v:true))
1504  call assert_equal(-1, byteidx(str, 5, v:true))
1505
1506  " empty string
1507  call assert_equal(0, byteidx('', 0, v:true))
1508  call assert_equal(-1, byteidx('', 1, v:true))
1509
1510  " error cases
1511  call assert_fails('call byteidx(str, 0, [])', 'E745:')
1512endfunc
1513
1514" Test for byteidxcomp() using a UTF-16 index
1515func Test_byteidxcomp_from_utf16_index()
1516  " string with single byte characters
1517  let str = "abc"
1518  for i in range(3)
1519    call assert_equal(i, byteidxcomp(str, i, v:true))
1520  endfor
1521  call assert_equal(3, byteidxcomp(str, 3, v:true))
1522  call assert_equal(-1, byteidxcomp(str, 4, v:true))
1523
1524  " string with two byte characters
1525  let str = "a©©b"
1526  call assert_equal(0, byteidxcomp(str, 0, v:true))
1527  call assert_equal(1, byteidxcomp(str, 1, v:true))
1528  call assert_equal(3, byteidxcomp(str, 2, v:true))
1529  call assert_equal(5, byteidxcomp(str, 3, v:true))
1530  call assert_equal(6, byteidxcomp(str, 4, v:true))
1531  call assert_equal(-1, byteidxcomp(str, 5, v:true))
1532
1533  " string with two byte characters
1534  let str = "a😊😊b"
1535  call assert_equal(0, byteidxcomp(str, 0, v:true))
1536  call assert_equal(1, byteidxcomp(str, 1, v:true))
1537  call assert_equal(1, byteidxcomp(str, 2, v:true))
1538  call assert_equal(5, byteidxcomp(str, 3, v:true))
1539  call assert_equal(5, byteidxcomp(str, 4, v:true))
1540  call assert_equal(9, byteidxcomp(str, 5, v:true))
1541  call assert_equal(10, byteidxcomp(str, 6, v:true))
1542  call assert_equal(-1, byteidxcomp(str, 7, v:true))
1543
1544  " string with composing characters
1545  let str = '-á-b́'
1546  call assert_equal(0, byteidxcomp(str, 0, v:true))
1547  call assert_equal(1, byteidxcomp(str, 1, v:true))
1548  call assert_equal(2, byteidxcomp(str, 2, v:true))
1549  call assert_equal(4, byteidxcomp(str, 3, v:true))
1550  call assert_equal(5, byteidxcomp(str, 4, v:true))
1551  call assert_equal(6, byteidxcomp(str, 5, v:true))
1552  call assert_equal(8, byteidxcomp(str, 6, v:true))
1553  call assert_equal(-1, byteidxcomp(str, 7, v:true))
1554  call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1555
1556  " string with multiple composing characters
1557  let str = '-ą́-ą́'
1558  call assert_equal(0, byteidxcomp(str, 0, v:true))
1559  call assert_equal(1, byteidxcomp(str, 1, v:true))
1560  call assert_equal(2, byteidxcomp(str, 2, v:true))
1561  call assert_equal(4, byteidxcomp(str, 3, v:true))
1562  call assert_equal(6, byteidxcomp(str, 4, v:true))
1563  call assert_equal(7, byteidxcomp(str, 5, v:true))
1564  call assert_equal(8, byteidxcomp(str, 6, v:true))
1565  call assert_equal(10, byteidxcomp(str, 7, v:true))
1566  call assert_equal(12, byteidxcomp(str, 8, v:true))
1567  call assert_equal(-1, byteidxcomp(str, 9, v:true))
1568
1569  " empty string
1570  call assert_equal(0, byteidxcomp('', 0, v:true))
1571  call assert_equal(-1, byteidxcomp('', 1, v:true))
1572
1573  " error cases
1574  call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1575endfunc
1576
1577" Test for charidx() using a byte index
1578func Test_charidx()
1579  let a = 'xáb́y'
1580  call assert_equal(0, charidx(a, 0))
1581  call assert_equal(1, charidx(a, 3))
1582  call assert_equal(2, charidx(a, 4))
1583  call assert_equal(3, charidx(a, 7))
1584  call assert_equal(4, charidx(a, 8))
1585  call assert_equal(-1, charidx(a, 9))
1586  call assert_equal(-1, charidx(a, -1))
1587
1588  " count composing characters
1589  call assert_equal(0, a->charidx(0, 1))
1590  call assert_equal(2, a->charidx(2, 1))
1591  call assert_equal(3, a->charidx(4, 1))
1592  call assert_equal(5, a->charidx(7, 1))
1593  call assert_equal(6, a->charidx(8, 1))
1594  call assert_equal(-1, a->charidx(9, 1))
1595
1596  " empty string
1597  call assert_equal(0, charidx('', 0))
1598  call assert_equal(-1, charidx('', 1))
1599  call assert_equal(0, charidx('', 0, 1))
1600  call assert_equal(-1, charidx('', 1, 1))
1601
1602  " error cases
1603  call assert_equal(0, charidx(v:_null_string, 0))
1604  call assert_equal(-1, charidx(v:_null_string, 1))
1605  call assert_fails('let x = charidx([], 1)', 'E1174:')
1606  call assert_fails('let x = charidx("abc", [])', 'E1210:')
1607  call assert_fails('let x = charidx("abc", 1, [])', 'E1212:')
1608  call assert_fails('let x = charidx("abc", 1, -1)', 'E1212:')
1609  call assert_fails('let x = charidx("abc", 1, 2)', 'E1212:')
1610endfunc
1611
1612" Test for charidx() using a UTF-16 index
1613func Test_charidx_from_utf16_index()
1614  " string with single byte characters
1615  let str = "abc"
1616  for i in range(4)
1617    call assert_equal(i, charidx(str, i, v:false, v:true))
1618  endfor
1619  call assert_equal(-1, charidx(str, 4, v:false, v:true))
1620
1621  " string with two byte characters
1622  let str = "a©©b"
1623  call assert_equal(0, charidx(str, 0, v:false, v:true))
1624  call assert_equal(1, charidx(str, 1, v:false, v:true))
1625  call assert_equal(2, charidx(str, 2, v:false, v:true))
1626  call assert_equal(3, charidx(str, 3, v:false, v:true))
1627  call assert_equal(4, charidx(str, 4, v:false, v:true))
1628  call assert_equal(-1, charidx(str, 5, v:false, v:true))
1629
1630  " string with four byte characters
1631  let str = "a😊😊b"
1632  call assert_equal(0, charidx(str, 0, v:false, v:true))
1633  call assert_equal(1, charidx(str, 1, v:false, v:true))
1634  call assert_equal(1, charidx(str, 2, v:false, v:true))
1635  call assert_equal(2, charidx(str, 3, v:false, v:true))
1636  call assert_equal(2, charidx(str, 4, v:false, v:true))
1637  call assert_equal(3, charidx(str, 5, v:false, v:true))
1638  call assert_equal(4, charidx(str, 6, v:false, v:true))
1639  call assert_equal(-1, charidx(str, 7, v:false, v:true))
1640
1641  " string with composing characters
1642  let str = '-á-b́'
1643  for i in str->strcharlen()->range()
1644    call assert_equal(i, charidx(str, i, v:false, v:true))
1645  endfor
1646  call assert_equal(4, charidx(str, 4, v:false, v:true))
1647  call assert_equal(-1, charidx(str, 5, v:false, v:true))
1648  for i in str->strchars()->range()
1649    call assert_equal(i, charidx(str, i, v:true, v:true))
1650  endfor
1651  call assert_equal(6, charidx(str, 6, v:true, v:true))
1652  call assert_equal(-1, charidx(str, 7, v:true, v:true))
1653
1654  " string with multiple composing characters
1655  let str = '-ą́-ą́'
1656  for i in str->strcharlen()->range()
1657    call assert_equal(i, charidx(str, i, v:false, v:true))
1658  endfor
1659  call assert_equal(4, charidx(str, 4, v:false, v:true))
1660  call assert_equal(-1, charidx(str, 5, v:false, v:true))
1661  for i in str->strchars()->range()
1662    call assert_equal(i, charidx(str, i, v:true, v:true))
1663  endfor
1664  call assert_equal(8, charidx(str, 8, v:true, v:true))
1665  call assert_equal(-1, charidx(str, 9, v:true, v:true))
1666
1667  " empty string
1668  call assert_equal(0, charidx('', 0, v:false, v:true))
1669  call assert_equal(-1, charidx('', 1, v:false, v:true))
1670  call assert_equal(0, charidx('', 0, v:true, v:true))
1671  call assert_equal(-1, charidx('', 1, v:true, v:true))
1672
1673  " error cases
1674  call assert_equal(0, charidx('', 0, v:false, v:true))
1675  call assert_equal(-1, charidx('', 1, v:false, v:true))
1676  call assert_equal(0, charidx('', 0, v:true, v:true))
1677  call assert_equal(-1, charidx('', 1, v:true, v:true))
1678  call assert_equal(0, charidx(v:_null_string, 0, v:false, v:true))
1679  call assert_equal(-1, charidx(v:_null_string, 1, v:false, v:true))
1680  call assert_fails('let x = charidx("abc", 1, v:false, [])', 'E1212:')
1681  call assert_fails('let x = charidx("abc", 1, v:true, [])', 'E1212:')
1682endfunc
1683
1684" Test for utf16idx() using a byte index
1685func Test_utf16idx_from_byteidx()
1686  " UTF-16 index of a string with single byte characters
1687  let str = "abc"
1688  for i in range(4)
1689    call assert_equal(i, utf16idx(str, i))
1690  endfor
1691  call assert_equal(-1, utf16idx(str, 4))
1692
1693  " UTF-16 index of a string with two byte characters
1694  let str = 'a©©b'
1695  call assert_equal(0, str->utf16idx(0))
1696  call assert_equal(1, str->utf16idx(1))
1697  call assert_equal(1, str->utf16idx(2))
1698  call assert_equal(2, str->utf16idx(3))
1699  call assert_equal(2, str->utf16idx(4))
1700  call assert_equal(3, str->utf16idx(5))
1701  call assert_equal(4, str->utf16idx(6))
1702  call assert_equal(-1, str->utf16idx(7))
1703
1704  " UTF-16 index of a string with four byte characters
1705  let str = 'a😊😊b'
1706  call assert_equal(0, utf16idx(str, 0))
1707  call assert_equal(1, utf16idx(str, 1))
1708  call assert_equal(1, utf16idx(str, 2))
1709  call assert_equal(1, utf16idx(str, 3))
1710  call assert_equal(1, utf16idx(str, 4))
1711  call assert_equal(3, utf16idx(str, 5))
1712  call assert_equal(3, utf16idx(str, 6))
1713  call assert_equal(3, utf16idx(str, 7))
1714  call assert_equal(3, utf16idx(str, 8))
1715  call assert_equal(5, utf16idx(str, 9))
1716  call assert_equal(6, utf16idx(str, 10))
1717  call assert_equal(-1, utf16idx(str, 11))
1718
1719  " UTF-16 index of a string with composing characters
1720  let str = '-á-b́'
1721  call assert_equal(0, utf16idx(str, 0))
1722  call assert_equal(1, utf16idx(str, 1))
1723  call assert_equal(1, utf16idx(str, 2))
1724  call assert_equal(1, utf16idx(str, 3))
1725  call assert_equal(2, utf16idx(str, 4))
1726  call assert_equal(3, utf16idx(str, 5))
1727  call assert_equal(3, utf16idx(str, 6))
1728  call assert_equal(3, utf16idx(str, 7))
1729  call assert_equal(4, utf16idx(str, 8))
1730  call assert_equal(-1, utf16idx(str, 9))
1731  call assert_equal(0, utf16idx(str, 0, v:true))
1732  call assert_equal(1, utf16idx(str, 1, v:true))
1733  call assert_equal(2, utf16idx(str, 2, v:true))
1734  call assert_equal(2, utf16idx(str, 3, v:true))
1735  call assert_equal(3, utf16idx(str, 4, v:true))
1736  call assert_equal(4, utf16idx(str, 5, v:true))
1737  call assert_equal(5, utf16idx(str, 6, v:true))
1738  call assert_equal(5, utf16idx(str, 7, v:true))
1739  call assert_equal(6, utf16idx(str, 8, v:true))
1740  call assert_equal(-1, utf16idx(str, 9, v:true))
1741
1742  " string with multiple composing characters
1743  let str = '-ą́-ą́'
1744  call assert_equal(0, utf16idx(str, 0))
1745  call assert_equal(1, utf16idx(str, 1))
1746  call assert_equal(1, utf16idx(str, 2))
1747  call assert_equal(1, utf16idx(str, 3))
1748  call assert_equal(1, utf16idx(str, 4))
1749  call assert_equal(1, utf16idx(str, 5))
1750  call assert_equal(2, utf16idx(str, 6))
1751  call assert_equal(3, utf16idx(str, 7))
1752  call assert_equal(3, utf16idx(str, 8))
1753  call assert_equal(3, utf16idx(str, 9))
1754  call assert_equal(3, utf16idx(str, 10))
1755  call assert_equal(3, utf16idx(str, 11))
1756  call assert_equal(4, utf16idx(str, 12))
1757  call assert_equal(-1, utf16idx(str, 13))
1758  call assert_equal(0, utf16idx(str, 0, v:true))
1759  call assert_equal(1, utf16idx(str, 1, v:true))
1760  call assert_equal(2, utf16idx(str, 2, v:true))
1761  call assert_equal(2, utf16idx(str, 3, v:true))
1762  call assert_equal(3, utf16idx(str, 4, v:true))
1763  call assert_equal(3, utf16idx(str, 5, v:true))
1764  call assert_equal(4, utf16idx(str, 6, v:true))
1765  call assert_equal(5, utf16idx(str, 7, v:true))
1766  call assert_equal(6, utf16idx(str, 8, v:true))
1767  call assert_equal(6, utf16idx(str, 9, v:true))
1768  call assert_equal(7, utf16idx(str, 10, v:true))
1769  call assert_equal(7, utf16idx(str, 11, v:true))
1770  call assert_equal(8, utf16idx(str, 12, v:true))
1771  call assert_equal(-1, utf16idx(str, 13, v:true))
1772
1773  " empty string
1774  call assert_equal(0, utf16idx('', 0))
1775  call assert_equal(-1, utf16idx('', 1))
1776  call assert_equal(0, utf16idx('', 0, v:true))
1777  call assert_equal(-1, utf16idx('', 1, v:true))
1778
1779  " error cases
1780  call assert_equal(0, utf16idx("", 0))
1781  call assert_equal(-1, utf16idx("", 1))
1782  call assert_equal(-1, utf16idx("abc", -1))
1783  call assert_equal(0, utf16idx(v:_null_string, 0))
1784  call assert_equal(-1, utf16idx(v:_null_string, 1))
1785  call assert_fails('let l = utf16idx([], 0)', 'E1174:')
1786  call assert_fails('let l = utf16idx("ab", [])', 'E1210:')
1787  call assert_fails('let l = utf16idx("ab", 0, [])', 'E1212:')
1788endfunc
1789
1790" Test for utf16idx() using a character index
1791func Test_utf16idx_from_charidx()
1792  let str = "abc"
1793  for i in str->strcharlen()->range()
1794    call assert_equal(i, utf16idx(str, i, v:false, v:true))
1795  endfor
1796  call assert_equal(3, utf16idx(str, 3, v:false, v:true))
1797  call assert_equal(-1, utf16idx(str, 4, v:false, v:true))
1798
1799  " UTF-16 index of a string with two byte characters
1800  let str = "a©©b"
1801  for i in str->strcharlen()->range()
1802    call assert_equal(i, utf16idx(str, i, v:false, v:true))
1803  endfor
1804  call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1805  call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
1806
1807  " UTF-16 index of a string with four byte characters
1808  let str = "a😊😊b"
1809  call assert_equal(0, utf16idx(str, 0, v:false, v:true))
1810  call assert_equal(1, utf16idx(str, 1, v:false, v:true))
1811  call assert_equal(3, utf16idx(str, 2, v:false, v:true))
1812  call assert_equal(5, utf16idx(str, 3, v:false, v:true))
1813  call assert_equal(6, utf16idx(str, 4, v:false, v:true))
1814  call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
1815
1816  " UTF-16 index of a string with composing characters
1817  let str = '-á-b́'
1818  for i in str->strcharlen()->range()
1819    call assert_equal(i, utf16idx(str, i, v:false, v:true))
1820  endfor
1821  call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1822  call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
1823  for i in str->strchars()->range()
1824    call assert_equal(i, utf16idx(str, i, v:true, v:true))
1825  endfor
1826  call assert_equal(6, utf16idx(str, 6, v:true, v:true))
1827  call assert_equal(-1, utf16idx(str, 7, v:true, v:true))
1828
1829  " string with multiple composing characters
1830  let str = '-ą́-ą́'
1831  for i in str->strcharlen()->range()
1832    call assert_equal(i, utf16idx(str, i, v:false, v:true))
1833  endfor
1834  call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1835  call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
1836  for i in str->strchars()->range()
1837    call assert_equal(i, utf16idx(str, i, v:true, v:true))
1838  endfor
1839  call assert_equal(8, utf16idx(str, 8, v:true, v:true))
1840  call assert_equal(-1, utf16idx(str, 9, v:true, v:true))
1841
1842  " empty string
1843  call assert_equal(0, utf16idx('', 0, v:false, v:true))
1844  call assert_equal(-1, utf16idx('', 1, v:false, v:true))
1845  call assert_equal(0, utf16idx('', 0, v:true, v:true))
1846  call assert_equal(-1, utf16idx('', 1, v:true, v:true))
1847
1848  " error cases
1849  call assert_equal(0, utf16idx(v:_null_string, 0, v:true, v:true))
1850  call assert_equal(-1, utf16idx(v:_null_string, 1, v:true, v:true))
1851  call assert_fails('let l = utf16idx("ab", 0, v:false, [])', 'E1212:')
1852endfunc
1853
1854" Test for strutf16len()
1855func Test_strutf16len()
1856  call assert_equal(3, strutf16len('abc'))
1857  call assert_equal(3, 'abc'->strutf16len(v:true))
1858  call assert_equal(4, strutf16len('a©©b'))
1859  call assert_equal(4, strutf16len('a©©b', v:true))
1860  call assert_equal(6, strutf16len('a😊😊b'))
1861  call assert_equal(6, strutf16len('a😊😊b', v:true))
1862  call assert_equal(4, strutf16len('-á-b́'))
1863  call assert_equal(6, strutf16len('-á-b́', v:true))
1864  call assert_equal(4, strutf16len('-ą́-ą́'))
1865  call assert_equal(8, strutf16len('-ą́-ą́', v:true))
1866  call assert_equal(0, strutf16len(''))
1867
1868  " error cases
1869  call assert_fails('let l = strutf16len([])', 'E1174:')
1870  call assert_fails('let l = strutf16len("a", [])', 'E1212:')
1871  call assert_equal(0, strutf16len(v:_null_string))
1872endfunc
1873
1874func Test_count()
1875  let l = ['a', 'a', 'A', 'b']
1876  call assert_equal(2, count(l, 'a'))
1877  call assert_equal(1, count(l, 'A'))
1878  call assert_equal(1, count(l, 'b'))
1879  call assert_equal(0, count(l, 'B'))
1880
1881  call assert_equal(2, count(l, 'a', 0))
1882  call assert_equal(1, count(l, 'A', 0))
1883  call assert_equal(1, count(l, 'b', 0))
1884  call assert_equal(0, count(l, 'B', 0))
1885
1886  call assert_equal(3, count(l, 'a', 1))
1887  call assert_equal(3, count(l, 'A', 1))
1888  call assert_equal(1, count(l, 'b', 1))
1889  call assert_equal(1, count(l, 'B', 1))
1890  call assert_equal(0, count(l, 'c', 1))
1891
1892  call assert_equal(1, count(l, 'a', 0, 1))
1893  call assert_equal(2, count(l, 'a', 1, 1))
1894  call assert_fails('call count(l, "a", 0, 10)', 'E684:')
1895  call assert_fails('call count(l, "a", [])', 'E745:')
1896
1897  let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
1898  call assert_equal(2, count(d, 'a'))
1899  call assert_equal(1, count(d, 'A'))
1900  call assert_equal(1, count(d, 'b'))
1901  call assert_equal(0, count(d, 'B'))
1902
1903  call assert_equal(2, count(d, 'a', 0))
1904  call assert_equal(1, count(d, 'A', 0))
1905  call assert_equal(1, count(d, 'b', 0))
1906  call assert_equal(0, count(d, 'B', 0))
1907
1908  call assert_equal(3, count(d, 'a', 1))
1909  call assert_equal(3, count(d, 'A', 1))
1910  call assert_equal(1, count(d, 'b', 1))
1911  call assert_equal(1, count(d, 'B', 1))
1912  call assert_equal(0, count(d, 'c', 1))
1913
1914  call assert_fails('call count(d, "a", 0, 1)', 'E474:')
1915
1916  call assert_equal(0, count("foo", "bar"))
1917  call assert_equal(1, count("foo", "oo"))
1918  call assert_equal(2, count("foo", "o"))
1919  call assert_equal(0, count("foo", "O"))
1920  call assert_equal(2, count("foo", "O", 1))
1921  call assert_equal(2, count("fooooo", "oo"))
1922  call assert_equal(0, count("foo", ""))
1923
1924  call assert_fails('call count(0, 0)', 'E706:')
1925  call assert_fails('call count("", "", {})', ['E728:', 'E728:'])
1926endfunc
1927
1928func Test_changenr()
1929  new Xchangenr
1930  call assert_equal(0, changenr())
1931  norm ifoo
1932  call assert_equal(1, changenr())
1933  set undolevels=10
1934  norm Sbar
1935  call assert_equal(2, changenr())
1936  undo
1937  call assert_equal(1, changenr())
1938  redo
1939  call assert_equal(2, changenr())
1940  bw!
1941  set undolevels&
1942endfunc
1943
1944func Test_filewritable()
1945  new Xfilewritable
1946  write!
1947  call assert_equal(1, filewritable('Xfilewritable'))
1948
1949  call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
1950  call assert_equal(0, filewritable('Xfilewritable'))
1951
1952  call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
1953  call assert_equal(1, 'Xfilewritable'->filewritable())
1954
1955  call assert_equal(0, filewritable('doesnotexist'))
1956
1957  call mkdir('Xdir')
1958  call assert_equal(2, filewritable('Xdir'))
1959  call delete('Xdir', 'd')
1960
1961  call delete('Xfilewritable')
1962  bw!
1963endfunc
1964
1965func Test_Executable()
1966  if has('win32')
1967    call assert_equal(1, executable('notepad'))
1968    call assert_equal(1, 'notepad.exe'->executable())
1969    call assert_equal(0, executable('notepad.exe.exe'))
1970    call assert_equal(0, executable('shell32.dll'))
1971    call assert_equal(0, executable('win.ini'))
1972  elseif has('unix')
1973    call assert_equal(1, 'cat'->executable())
1974    call assert_equal(0, executable('nodogshere'))
1975
1976    " get "cat" path and remove the leading /
1977    let catcmd = exepath('cat')[1:]
1978    new
1979    " check that the relative path works in /
1980    lcd /
1981    call assert_equal(1, executable(catcmd))
1982    let result = catcmd->exepath()
1983    " when using chroot looking for sbin/cat can return bin/cat, that is OK
1984    if catcmd =~ '\<sbin\>' && result =~ '\<bin\>'
1985      call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result)
1986    else
1987      " /bin/cat and /usr/bin/cat may be hard linked, we could get either
1988      let result = substitute(result, '/usr/bin/cat', '/bin/cat', '')
1989      let catcmd = substitute(catcmd, 'usr/bin/cat', 'bin/cat', '')
1990      call assert_equal('/' .. catcmd, result)
1991    endif
1992    bwipe
1993  else
1994    throw 'Skipped: does not work on this platform'
1995  endif
1996endfunc
1997
1998func Test_executable_longname()
1999  CheckMSWindows
2000
2001  " Create a temporary .bat file with 205 characters in the name.
2002  " Maximum length of a filename (including the path) on MS-Windows is 259
2003  " characters.
2004  " See https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
2005  let len = 259 - getcwd()->len() - 6
2006  if len > 200
2007    let len = 200
2008  endif
2009
2010  let fname = 'X' . repeat('あ', len) . '.bat'
2011  call writefile([], fname)
2012  call assert_equal(1, executable(fname))
2013  call delete(fname)
2014endfunc
2015
2016func Test_executable_single_character_dir()
2017  call mkdir('Xpath', 'R')
2018  call mkdir('Xpath/a')
2019  call mkdir('Xpath/b')
2020  call mkdir('Xpath/c')
2021  if has('win32')
2022    call writefile([], 'Xpath/a/Xcmd1.bat')
2023    call writefile([], 'Xpath/b/Xcmd2.bat')
2024    call writefile([], 'Xpath/c/Xcmd3.bat')
2025    let sep = ';'
2026  else
2027    call writefile([], 'Xpath/a/Xcmd1')
2028    call writefile([], 'Xpath/b/Xcmd2')
2029    call writefile([], 'Xpath/c/Xcmd3')
2030    call setfperm('Xpath/a/Xcmd1', 'rwxr-xr-x')
2031    call setfperm('Xpath/b/Xcmd2', 'rwxr-xr-x')
2032    call setfperm('Xpath/c/Xcmd3', 'rwxr-xr-x')
2033    let sep = ':'
2034  endif
2035
2036  let save_path = $PATH
2037  " a: single character name without path seperator
2038  " b: single character name with path seperator
2039  " c: single character name without path seperator at last of PATH
2040  let $PATH = [
2041        \ fnamemodify('./Xpath/a', ':p:h'),
2042        \ fnamemodify('./Xpath/b', ':p'),
2043        \ fnamemodify('./Xpath/c', ':p:h')
2044        \ ]->join(sep)
2045  call assert_true(executable('Xcmd1'))
2046  call assert_true(executable('Xcmd2'))
2047  call assert_true(executable('Xcmd3'))
2048  let $PATH = save_path
2049endfunc
2050
2051func Test_hostname()
2052  let hostname_vim = hostname()
2053  if has('unix')
2054    let hostname_system = systemlist('uname -n')[0]
2055    call assert_equal(hostname_vim, hostname_system)
2056  endif
2057endfunc
2058
2059func Test_getpid()
2060  " getpid() always returns the same value within a vim instance.
2061  call assert_equal(getpid(), getpid())
2062  if has('unix')
2063    call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
2064  endif
2065endfunc
2066
2067func Test_hlexists()
2068  call assert_equal(0, hlexists('does_not_exist'))
2069  " call assert_equal(0, 'Number'->hlexists())
2070  call assert_equal(0, highlight_exists('does_not_exist'))
2071  " call assert_equal(0, highlight_exists('Number'))
2072  syntax on
2073  call assert_equal(0, hlexists('does_not_exist'))
2074  " call assert_equal(1, hlexists('Number'))
2075  call assert_equal(0, highlight_exists('does_not_exist'))
2076  " call assert_equal(1, highlight_exists('Number'))
2077  syntax off
2078endfunc
2079
2080" Test for the col() function
2081func Test_col()
2082  new
2083  call setline(1, 'abcdef')
2084  norm gg4|mx6|mY2|
2085  call assert_equal(2, col('.'))
2086  call assert_equal(7, col('$'))
2087  call assert_equal(2, col('v'))
2088  call assert_equal(4, col("'x"))
2089  call assert_equal(6, col("'Y"))
2090  call assert_equal(2, [1, 2]->col())
2091  call assert_equal(7, col([1, '$']))
2092
2093  call assert_equal(0, col(''))
2094  call assert_equal(0, col('x'))
2095  call assert_equal(0, col([2, '$']))
2096  call assert_equal(0, col([1, 100]))
2097  call assert_equal(0, col([1]))
2098  call assert_equal(0, col(v:_null_list))
2099  call assert_fails('let c = col({})', 'E1222:')
2100  call assert_fails('let c = col(".", [])', 'E1210:')
2101
2102  " test for getting the visual start column
2103  func T()
2104    let g:Vcol = col('v')
2105    return ''
2106  endfunc
2107  let g:Vcol = 0
2108  xmap <expr> <F2> T()
2109  exe "normal gg3|ve\<F2>"
2110  call assert_equal(3, g:Vcol)
2111  xunmap <F2>
2112  delfunc T
2113
2114  " Test for the visual line start and end marks '< and '>
2115  call setline(1, ['one', 'one two', 'one two three'])
2116  "normal! ggVG
2117  call feedkeys("ggVG\<Esc>", 'xt')
2118  call assert_equal(1, col("'<"))
2119  call assert_equal(14, col("'>"))
2120  " Delete the last line of the visually selected region
2121  $d
2122  call assert_notequal(14, col("'>"))
2123
2124  " Test with 'virtualedit'
2125  set virtualedit=all
2126  call cursor(1, 10)
2127  call assert_equal(4, col('.'))
2128  set virtualedit&
2129
2130  " Test for getting the column number in another window
2131  let winid = win_getid()
2132  new
2133  call win_execute(winid, 'normal 1G$')
2134  call assert_equal(3, col('.', winid))
2135  call win_execute(winid, 'normal 2G')
2136  call assert_equal(8, col('$', winid))
2137  call assert_equal(0, col('.', 5001))
2138
2139  bw!
2140endfunc
2141
2142" Test for input()
2143func Test_input_func()
2144  " Test for prompt with multiple lines
2145  redir => v
2146  call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt')
2147  redir END
2148  call assert_equal("B", c)
2149  call assert_equal(['A', 'B', 'C'], split(v, "\n"))
2150
2151  " Test for default value
2152  call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt')
2153  call assert_equal('red', c)
2154
2155  " Test for completion at the input prompt
2156  func! Tcomplete(arglead, cmdline, pos)
2157    return "item1\nitem2\nitem3"
2158  endfunc
2159  call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>"
2160        \ .. "\<C-A>\<CR>", 'xt')
2161  delfunc Tcomplete
2162  call assert_equal('item1 item2 item3', c)
2163
2164  " Test for using special characters as default input
2165  call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt')
2166  call assert_equal('y', c)
2167
2168  " Test for using text with composing characters as default input
2169  call feedkeys(":let c = input('name? ', \"ã̳\")\<CR>\<CR>", 'xt')
2170  call assert_equal('ã̳', c)
2171
2172  " Test for using <CR> as default input
2173  call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt')
2174  call assert_equal(' x', c)
2175
2176  call assert_fails("call input('F:', '', 'invalid')", 'E180:')
2177  call assert_fails("call input('F:', '', [])", 'E730:')
2178
2179  " Test for using "command" as the completion function
2180  call feedkeys(":let c = input('Command? ', '', 'command')\<CR>"
2181        \ .. "echo bufnam\<C-A>\<CR>", 'xt')
2182  call assert_equal('echo bufname(', c)
2183
2184  " Test for using "shellcmdline" as the completion function
2185  call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2186        \ .. "vim test_functions.\<C-A>\<CR>", 'xt')
2187  call assert_equal('vim test_functions.vim', c)
2188  if executable('whoami')
2189    call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2190          \ .. "whoam\<C-A>\<CR>", 'xt')
2191    call assert_match('\<whoami\>', c)
2192  endif
2193endfunc
2194
2195" Test for the inputdialog() function
2196func Test_inputdialog()
2197  set timeout timeoutlen=10
2198  if has('gui_running')
2199    call assert_fails('let v=inputdialog([], "xx")', 'E730:')
2200    call assert_fails('let v=inputdialog("Q", [])', 'E730:')
2201  else
2202    call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt')
2203    call assert_equal('xx', v)
2204    call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt')
2205    call assert_equal('yy', v)
2206  endif
2207  set timeout& timeoutlen&
2208endfunc
2209
2210" Test for inputlist()
2211func Test_inputlist()
2212  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
2213  call assert_equal(1, c)
2214  call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx')
2215  call assert_equal(2, c)
2216  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
2217  call assert_equal(3, c)
2218
2219  " CR to cancel
2220  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx')
2221  call assert_equal(0, c)
2222
2223  " Esc to cancel
2224  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx')
2225  call assert_equal(0, c)
2226
2227  " q to cancel
2228  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx')
2229  call assert_equal(0, c)
2230
2231  " Cancel after inputting a number
2232  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx')
2233  call assert_equal(0, c)
2234
2235  " Use backspace to delete characters in the prompt
2236  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx')
2237  call assert_equal(2, c)
2238
2239  " Use mouse to make a selection
2240  call Ntest_setmouse(&lines - 3, 2)
2241  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2242  call assert_equal(1, c)
2243  " Mouse click outside of the list
2244  call Ntest_setmouse(&lines - 6, 2)
2245  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2246  call assert_equal(-2, c)
2247
2248  call assert_fails('call inputlist("")', 'E686:')
2249  " Nvim accepts null list as empty list
2250  " call assert_fails('call inputlist(v:_null_list)', 'E686:')
2251endfunc
2252
2253func Test_range_inputlist()
2254  " flush out any garbage left in the buffer
2255  while getchar(0)
2256  endwhile
2257
2258  call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x')
2259  call assert_equal(1, result)
2260  call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x')
2261  call assert_equal(1, result)
2262
2263  unlet result
2264endfunc
2265
2266func Test_balloon_show()
2267  CheckFeature balloon_eval
2268
2269  " This won't do anything but must not crash either.
2270  call balloon_show('hi!')
2271  if !has('gui_running')
2272    call balloon_show(range(3))
2273    call balloon_show([])
2274  endif
2275endfunc
2276
2277func Test_setbufvar_options()
2278  " This tests that ctx_switch() and ctx_restore() properly restore the
2279  " window layout and cursor position.
2280  call assert_equal(1, winnr('$'))
2281  split dummy_preview
2282  resize 2
2283  set winfixheight winfixwidth
2284  let prev_id = win_getid()
2285
2286  wincmd j
2287  let wh = winheight(0)
2288  let dummy_buf = bufnr('dummy_buf1', v:true)
2289  call setbufvar(dummy_buf, '&buftype', 'nofile')
2290  execute 'belowright vertical split #' . dummy_buf
2291  call assert_equal(wh, winheight(0))
2292  let dum1_id = win_getid()
2293  call setline(1, 'foo')
2294  normal! V$
2295  call assert_equal(4, col('.'))
2296  call setbufvar('dummy_preview', '&buftype', 'nofile')
2297  call assert_equal(4, col('.'))
2298
2299  wincmd h
2300  let wh = winheight(0)
2301  call setline(1, 'foo')
2302  normal! V$
2303  call assert_equal(4, col('.'))
2304  let dummy_buf = bufnr('dummy_buf2', v:true)
2305  eval 'nofile'->setbufvar(dummy_buf, '&buftype')
2306  call assert_equal(4, col('.'))
2307  execute 'belowright vertical split #' . dummy_buf
2308  call assert_equal(wh, winheight(0))
2309
2310  bwipe!
2311  call win_gotoid(prev_id)
2312  bwipe!
2313  call win_gotoid(dum1_id)
2314  bwipe!
2315endfunc
2316
2317func Test_setbufvar_keep_window_title()
2318  CheckRunVimInTerminal
2319  if !has('title') || empty(&t_ts)
2320    throw "Skipped: can't get/set title"
2321  endif
2322
2323  let lines =<< trim END
2324      set title
2325      edit Xa.txt
2326      let g:buf = bufadd('Xb.txt')
2327      inoremap <F2> <C-R>=setbufvar(g:buf, '&autoindent', 1) ?? ''<CR>
2328  END
2329  call writefile(lines, 'Xsetbufvar')
2330  let buf = RunVimInTerminal('-S Xsetbufvar', {})
2331  call WaitForAssert({-> assert_match('Xa.txt', term_gettitle(buf))}, 1000)
2332
2333  call term_sendkeys(buf, "i\<F2>")
2334  call TermWait(buf)
2335  call term_sendkeys(buf, "\<Esc>")
2336  call TermWait(buf)
2337  call assert_match('Xa.txt', term_gettitle(buf))
2338
2339  call StopVimInTerminal(buf)
2340  call delete('Xsetbufvar')
2341endfunc
2342
2343func Test_redo_in_nested_functions()
2344  nnoremap g. :set opfunc=Operator<CR>g@
2345  function Operator( type, ... )
2346     let @x = 'XXX'
2347     execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
2348  endfunction
2349
2350  function! Apply()
2351      5,6normal! .
2352  endfunction
2353
2354  new
2355  call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
2356  1normal g.i"
2357  call assert_equal('some "XXX" text', getline(1))
2358  3,4normal .
2359  call assert_equal('some "XXX" text', getline(3))
2360  call assert_equal('more "XXX" text', getline(4))
2361  call Apply()
2362  call assert_equal('some "XXX" text', getline(5))
2363  call assert_equal('more "XXX" text', getline(6))
2364  bwipe!
2365
2366  nunmap g.
2367  delfunc Operator
2368  delfunc Apply
2369endfunc
2370
2371func Test_trim()
2372  call assert_equal("Testing", trim("  \t\r\r\x0BTesting  \t\n\r\n\t\x0B\x0B"))
2373  call assert_equal("Testing", "  \t  \r\r\n\n\x0BTesting  \t\n\r\n\t\x0B\x0B"->trim())
2374  call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
2375  call assert_equal("wRE    \tSERVEzyww", trim("wRE    \tSERVEzyww"))
2376  call assert_equal("abcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail"))
2377  call assert_equal("\tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", " "))
2378  call assert_equal(" \tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", "abx"))
2379  call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
2380  call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
2381  call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r   你好您R E SER V E早好你你    \t  \x0B", ))
2382  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    你好您R E SER V E早好你你    \t  \x0B", " 你好"))
2383  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", " 你好tes"))
2384  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", "   你你你好好好tttsses"))
2385  call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
2386  call assert_equal("", trim("", ""))
2387  call assert_equal("a", trim("a", ""))
2388  call assert_equal("", trim("", "a"))
2389  call assert_equal("vim", trim("  vim  ", " ", 0))
2390  call assert_equal("vim  ", trim("  vim  ", " ", 1))
2391  call assert_equal("  vim", trim("  vim  ", " ", 2))
2392  call assert_fails('eval trim("  vim  ", " ", [])', 'E745:')
2393  call assert_fails('eval trim("  vim  ", " ", -1)', 'E475:')
2394  call assert_fails('eval trim("  vim  ", " ", 3)', 'E475:')
2395  call assert_fails('eval trim("  vim  ", 0)', 'E1174:')
2396
2397  let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '')
2398  call assert_equal("x", trim(chars . "x" . chars))
2399
2400  call assert_equal("x", trim(chars . "x" . chars, '', 0))
2401  call assert_equal("x" . chars, trim(chars . "x" . chars, '', 1))
2402  call assert_equal(chars . "x", trim(chars . "x" . chars, '', 2))
2403
2404  call assert_fails('let c=trim([])', 'E730:')
2405endfunc
2406
2407" Test for reg_recording() and reg_executing()
2408func Test_reg_executing_and_recording()
2409  let s:reg_stat = ''
2410  func s:save_reg_stat()
2411    let s:reg_stat = reg_recording() . ':' . reg_executing()
2412    return ''
2413  endfunc
2414
2415  new
2416  call s:save_reg_stat()
2417  call assert_equal(':', s:reg_stat)
2418  call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
2419  call assert_equal('a:', s:reg_stat)
2420  call feedkeys("@a", 'xt')
2421  call assert_equal(':a', s:reg_stat)
2422  call feedkeys("qb@aq", 'xt')
2423  call assert_equal('b:a', s:reg_stat)
2424  call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
2425  call assert_equal('":', s:reg_stat)
2426
2427  " :normal command saves and restores reg_executing
2428  let s:reg_stat = ''
2429  let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
2430  func TestFunc() abort
2431    normal! ia
2432  endfunc
2433  call feedkeys("@q", 'xt')
2434  call assert_equal(':q', s:reg_stat)
2435  delfunc TestFunc
2436
2437  " getchar() command saves and restores reg_executing
2438  map W :call TestFunc()<CR>
2439  let @q = "W"
2440  let g:typed = ''
2441  let g:regs = []
2442  func TestFunc() abort
2443    let g:regs += [reg_executing()]
2444    let g:typed = getchar(0)
2445    let g:regs += [reg_executing()]
2446  endfunc
2447  call feedkeys("@qy", 'xt')
2448  call assert_equal(char2nr("y"), g:typed)
2449  call assert_equal(['q', 'q'], g:regs)
2450  delfunc TestFunc
2451  unmap W
2452  unlet g:typed
2453  unlet g:regs
2454
2455  " input() command saves and restores reg_executing
2456  map W :call TestFunc()<CR>
2457  let @q = "W"
2458  let g:typed = ''
2459  let g:regs = []
2460  func TestFunc() abort
2461    let g:regs += [reg_executing()]
2462    let g:typed = '?'->input()
2463    let g:regs += [reg_executing()]
2464  endfunc
2465  call feedkeys("@qy\<CR>", 'xt')
2466  call assert_equal("y", g:typed)
2467  call assert_equal(['q', 'q'], g:regs)
2468  delfunc TestFunc
2469  unmap W
2470  unlet g:typed
2471  unlet g:regs
2472
2473  bwipe!
2474  delfunc s:save_reg_stat
2475  unlet s:reg_stat
2476endfunc
2477
2478func Test_inputsecret()
2479  map W :call TestFunc()<CR>
2480  let @q = "W"
2481  let g:typed1 = ''
2482  let g:typed2 = ''
2483  let g:regs = []
2484  func TestFunc() abort
2485    let g:typed1 = '?'->inputsecret()
2486    let g:typed2 = inputsecret('password: ')
2487  endfunc
2488  call feedkeys("@qsomething\<CR>else\<CR>", 'xt')
2489  call assert_equal("something", g:typed1)
2490  call assert_equal("else", g:typed2)
2491  delfunc TestFunc
2492  unmap W
2493  unlet g:typed1
2494  unlet g:typed2
2495endfunc
2496
2497func Test_getchar()
2498  call feedkeys('a', '')
2499  call assert_equal(char2nr('a'), getchar())
2500  call assert_equal(0, getchar(0))
2501  call assert_equal(0, getchar(1))
2502
2503  call feedkeys('a', '')
2504  call assert_equal('a', getcharstr())
2505  call assert_equal('', getcharstr(0))
2506  call assert_equal('', getcharstr(1))
2507
2508  call feedkeys("\<M-F2>", '')
2509  call assert_equal("\<M-F2>", getchar(0))
2510  call assert_equal(0, getchar(0))
2511
2512  call feedkeys("\<Tab>", '')
2513  call assert_equal(char2nr("\<Tab>"), getchar())
2514  call feedkeys("\<Tab>", '')
2515  call assert_equal(char2nr("\<Tab>"), getchar(-1))
2516  call feedkeys("\<Tab>", '')
2517  call assert_equal(char2nr("\<Tab>"), getchar(-1, {}))
2518  call feedkeys("\<Tab>", '')
2519  call assert_equal(char2nr("\<Tab>"), getchar(-1, #{number: v:true}))
2520  call assert_equal(0, getchar(0))
2521  call assert_equal(0, getchar(1))
2522  call assert_equal(0, getchar(0, #{number: v:true}))
2523  call assert_equal(0, getchar(1, #{number: v:true}))
2524
2525  call feedkeys("\<Tab>", '')
2526  call assert_equal("\<Tab>", getcharstr())
2527  call feedkeys("\<Tab>", '')
2528  call assert_equal("\<Tab>", getcharstr(-1))
2529  call feedkeys("\<Tab>", '')
2530  call assert_equal("\<Tab>", getcharstr(-1, {}))
2531  call feedkeys("\<Tab>", '')
2532  call assert_equal("\<Tab>", getchar(-1, #{number: v:false}))
2533  call assert_equal('', getcharstr(0))
2534  call assert_equal('', getcharstr(1))
2535  call assert_equal('', getchar(0, #{number: v:false}))
2536  call assert_equal('', getchar(1, #{number: v:false}))
2537
2538  " Nvim: <M-x> is never simplified
2539  " for key in ["C-I", "C-X", "M-x"]
2540  for key in ["C-I", "C-X"]
2541    let lines =<< eval trim END
2542      call feedkeys("\<*{key}>", '')
2543      call assert_equal(char2nr("\<{key}>"), getchar())
2544      call feedkeys("\<*{key}>", '')
2545      call assert_equal(char2nr("\<{key}>"), getchar(-1))
2546      call feedkeys("\<*{key}>", '')
2547      call assert_equal(char2nr("\<{key}>"), getchar(-1, {{}}))
2548      call feedkeys("\<*{key}>", '')
2549      call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'number': 1}}))
2550      call feedkeys("\<*{key}>", '')
2551      call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'simplify': 1}}))
2552      call feedkeys("\<*{key}>", '')
2553      call assert_equal("\<*{key}>", getchar(-1, {{'simplify': v:false}}))
2554      call assert_equal(0, getchar(0))
2555      call assert_equal(0, getchar(1))
2556    END
2557    call CheckLegacyAndVim9Success(lines)
2558
2559    let lines =<< eval trim END
2560      call feedkeys("\<*{key}>", '')
2561      call assert_equal("\<{key}>", getcharstr())
2562      call feedkeys("\<*{key}>", '')
2563      call assert_equal("\<{key}>", getcharstr(-1))
2564      call feedkeys("\<*{key}>", '')
2565      call assert_equal("\<{key}>", getcharstr(-1, {{}}))
2566      call feedkeys("\<*{key}>", '')
2567      call assert_equal("\<{key}>", getchar(-1, {{'number': 0}}))
2568      call feedkeys("\<*{key}>", '')
2569      call assert_equal("\<{key}>", getcharstr(-1, {{'simplify': 1}}))
2570      call feedkeys("\<*{key}>", '')
2571      call assert_equal("\<*{key}>", getcharstr(-1, {{'simplify': v:false}}))
2572      call assert_equal('', getcharstr(0))
2573      call assert_equal('', getcharstr(1))
2574    END
2575    call CheckLegacyAndVim9Success(lines)
2576  endfor
2577
2578  call assert_fails('call getchar(1, 1)', 'E1206:')
2579  call assert_fails('call getcharstr(1, 1)', 'E1206:')
2580  call assert_fails('call getchar(1, #{cursor: "foo"})', 'E475:')
2581  call assert_fails('call getcharstr(1, #{cursor: "foo"})', 'E475:')
2582  call assert_fails('call getchar(1, #{cursor: 0z})', 'E976:')
2583  call assert_fails('call getcharstr(1, #{cursor: 0z})', 'E976:')
2584  call assert_fails('call getchar(1, #{simplify: 0z})', 'E974:')
2585  call assert_fails('call getcharstr(1, #{simplify: 0z})', 'E974:')
2586  call assert_fails('call getchar(1, #{number: []})', 'E745:')
2587  call assert_fails('call getchar(1, #{number: {}})', 'E728:')
2588  call assert_fails('call getcharstr(1, #{number: v:true})', 'E475:')
2589  call assert_fails('call getcharstr(1, #{number: v:false})', 'E475:')
2590
2591  call setline(1, 'xxxx')
2592  call Ntest_setmouse(1, 3)
2593  let v:mouse_win = 9
2594  let v:mouse_winid = 9
2595  let v:mouse_lnum = 9
2596  let v:mouse_col = 9
2597  call feedkeys("\<S-LeftMouse>", '')
2598  call assert_equal("\<S-LeftMouse>", getchar())
2599  call assert_equal(1, v:mouse_win)
2600  call assert_equal(win_getid(1), v:mouse_winid)
2601  call assert_equal(1, v:mouse_lnum)
2602  call assert_equal(3, v:mouse_col)
2603  enew!
2604endfunc
2605
2606func Test_getchar_cursor_position()
2607  CheckRunVimInTerminal
2608
2609  let lines =<< trim END
2610    call setline(1, ['foobar', 'foobar', 'foobar'])
2611    call cursor(3, 6)
2612    nnoremap <F1> <Cmd>echo 1234<Bar>call getchar()<CR>
2613    nnoremap <F2> <Cmd>call getchar()<CR>
2614    nnoremap <F3> <Cmd>call getchar(-1, {})<CR>
2615    nnoremap <F4> <Cmd>call getchar(-1, #{cursor: 'msg'})<CR>
2616    nnoremap <F5> <Cmd>call getchar(-1, #{cursor: 'keep'})<CR>
2617    nnoremap <F6> <Cmd>call getchar(-1, #{cursor: 'hide'})<CR>
2618  END
2619  call writefile(lines, 'XgetcharCursorPos', 'D')
2620  let buf = RunVimInTerminal('-S XgetcharCursorPos', {'rows': 6})
2621  call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2622
2623  call term_sendkeys(buf, "\<F1>")
2624  call WaitForAssert({-> assert_equal([6, 5], term_getcursor(buf)[0:1])})
2625  call assert_true(term_getcursor(buf)[2].visible)
2626  call term_sendkeys(buf, 'a')
2627  call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2628  call assert_true(term_getcursor(buf)[2].visible)
2629
2630  for key in ["\<F2>", "\<F3>", "\<F4>"]
2631    call term_sendkeys(buf, key)
2632    call WaitForAssert({-> assert_equal([6, 1], term_getcursor(buf)[0:1])})
2633    call assert_true(term_getcursor(buf)[2].visible)
2634    call term_sendkeys(buf, 'a')
2635    call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2636    call assert_true(term_getcursor(buf)[2].visible)
2637  endfor
2638
2639  call term_sendkeys(buf, "\<F5>")
2640  call TermWait(buf, 50)
2641  call assert_equal([3, 6], term_getcursor(buf)[0:1])
2642  call assert_true(term_getcursor(buf)[2].visible)
2643  call term_sendkeys(buf, 'a')
2644  call TermWait(buf, 50)
2645  call assert_equal([3, 6], term_getcursor(buf)[0:1])
2646  call assert_true(term_getcursor(buf)[2].visible)
2647
2648  call term_sendkeys(buf, "\<F6>")
2649  call WaitForAssert({-> assert_false(term_getcursor(buf)[2].visible)})
2650  call term_sendkeys(buf, 'a')
2651  call WaitForAssert({-> assert_true(term_getcursor(buf)[2].visible)})
2652  call assert_equal([3, 6], term_getcursor(buf)[0:1])
2653
2654  call StopVimInTerminal(buf)
2655endfunc
2656
2657func Test_libcall_libcallnr()
2658  CheckFeature libcall
2659
2660  if has('win32')
2661    let libc = 'msvcrt.dll'
2662  elseif has('mac')
2663    let libc = 'libSystem.B.dylib'
2664  elseif executable('ldd')
2665    let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
2666  endif
2667  if get(l:, 'libc', '') ==# ''
2668    " On Unix, libc.so can be in various places.
2669    if has('linux')
2670      " There is not documented but regarding the 1st argument of glibc's
2671      " dlopen an empty string and nullptr are equivalent, so using an empty
2672      " string for the 1st argument of libcall allows to call functions.
2673      let libc = ''
2674    elseif has('sun')
2675      " Set the path to libc.so according to the architecture.
2676      let test_bits = system('file ' . GetVimProg())
2677      let test_arch = system('uname -p')
2678      if test_bits =~ '64-bit' && test_arch =~ 'sparc'
2679        let libc = '/usr/lib/sparcv9/libc.so'
2680      elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
2681        let libc = '/usr/lib/amd64/libc.so'
2682      else
2683        let libc = '/usr/lib/libc.so'
2684      endif
2685    else
2686      " Unfortunately skip this test until a good way is found.
2687      return
2688    endif
2689  endif
2690
2691  if has('win32')
2692    call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
2693  else
2694    call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
2695  endif
2696
2697  " If function returns NULL, libcall() should return an empty string.
2698  call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
2699
2700  " Test libcallnr() with string and integer argument.
2701  call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
2702  call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
2703
2704  call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
2705  call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
2706
2707  call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
2708  call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
2709endfunc
2710
2711sandbox function Fsandbox()
2712  normal ix
2713endfunc
2714
2715func Test_func_sandbox()
2716  sandbox let F = {-> 'hello'}
2717  call assert_equal('hello', F())
2718
2719  sandbox let F = {-> "normal ix\<Esc>"->execute()}
2720  call assert_fails('call F()', 'E48:')
2721  unlet F
2722
2723  call assert_fails('call Fsandbox()', 'E48:')
2724  delfunc Fsandbox
2725
2726  " From a sandbox try to set a predefined variable (which cannot be modified
2727  " from a sandbox)
2728  call assert_fails('sandbox let v:lnum = 10', 'E794:')
2729endfunc
2730
2731func EditAnotherFile()
2732  let word = expand('<cword>')
2733  edit Xfuncrange2
2734endfunc
2735
2736func Test_func_range_with_edit()
2737  " Define a function that edits another buffer, then call it with a range that
2738  " is invalid in that buffer.
2739  call writefile(['just one line'], 'Xfuncrange2')
2740  new
2741  eval 10->range()->setline(1)
2742  write Xfuncrange1
2743  call assert_fails('5,8call EditAnotherFile()', 'E16:')
2744
2745  call delete('Xfuncrange1')
2746  call delete('Xfuncrange2')
2747  bwipe!
2748endfunc
2749
2750func Test_func_exists_on_reload()
2751  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists')
2752  call assert_equal(0, exists('*ExistingFunction'))
2753  source Xfuncexists
2754  call assert_equal(1, '*ExistingFunction'->exists())
2755  " Redefining a function when reloading a script is OK.
2756  source Xfuncexists
2757  call assert_equal(1, exists('*ExistingFunction'))
2758
2759  " But redefining in another script is not OK.
2760  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2')
2761  call assert_fails('source Xfuncexists2', 'E122:')
2762
2763  delfunc ExistingFunction
2764  call assert_equal(0, exists('*ExistingFunction'))
2765  call writefile([
2766	\ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
2767	\ 'func ExistingFunction()', 'echo "no"', 'endfunc',
2768	\ ], 'Xfuncexists')
2769  call assert_fails('source Xfuncexists', 'E122:')
2770  call assert_equal(1, exists('*ExistingFunction'))
2771
2772  call delete('Xfuncexists2')
2773  call delete('Xfuncexists')
2774  delfunc ExistingFunction
2775endfunc
2776
2777" Test confirm({msg} [, {choices} [, {default} [, {type}]]])
2778func Test_confirm()
2779  CheckUnix
2780  CheckNotGui
2781
2782  call feedkeys('o', 'L')
2783  let a = confirm('Press O to proceed')
2784  call assert_equal(1, a)
2785
2786  call feedkeys('y', 'L')
2787  let a = 'Are you sure?'->confirm("&Yes\n&No")
2788  call assert_equal(1, a)
2789
2790  call feedkeys('n', 'L')
2791  let a = confirm('Are you sure?', "&Yes\n&No")
2792  call assert_equal(2, a)
2793
2794  " confirm() should return 0 when pressing CTRL-C.
2795  call feedkeys("\<C-C>", 'L')
2796  let a = confirm('Are you sure?', "&Yes\n&No")
2797  call assert_equal(0, a)
2798
2799  " <Esc> requires another character to avoid it being seen as the start of an
2800  " escape sequence.  Zero should be harmless.
2801  eval "\<Esc>0"->feedkeys('L')
2802  let a = confirm('Are you sure?', "&Yes\n&No")
2803  call assert_equal(0, a)
2804
2805  " Default choice is returned when pressing <CR>.
2806  call feedkeys("\<CR>", 'L')
2807  let a = confirm('Are you sure?', "&Yes\n&No")
2808  call assert_equal(1, a)
2809
2810  call feedkeys("\<CR>", 'L')
2811  let a = confirm('Are you sure?', "&Yes\n&No", 2)
2812  call assert_equal(2, a)
2813
2814  call feedkeys("\<CR>", 'L')
2815  let a = confirm('Are you sure?', "&Yes\n&No", 0)
2816  call assert_equal(0, a)
2817
2818  " Test with the {type} 4th argument
2819  for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
2820    call feedkeys('y', 'L')
2821    let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
2822    call assert_equal(1, a)
2823  endfor
2824
2825  call assert_fails('call confirm([])', 'E730:')
2826  call assert_fails('call confirm("Are you sure?", [])', 'E730:')
2827  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
2828  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
2829endfunc
2830
2831func Test_platform_name()
2832  " The system matches at most only one name.
2833  let names = ['amiga', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
2834  call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
2835
2836  " Is Unix?
2837  call assert_equal(has('bsd'), has('bsd') && has('unix'))
2838  call assert_equal(has('hpux'), has('hpux') && has('unix'))
2839  call assert_equal(has('hurd'), has('hurd') && has('unix'))
2840  call assert_equal(has('linux'), has('linux') && has('unix'))
2841  call assert_equal(has('mac'), has('mac') && has('unix'))
2842  call assert_equal(has('qnx'), has('qnx') && has('unix'))
2843  call assert_equal(has('sun'), has('sun') && has('unix'))
2844  call assert_equal(has('win32'), has('win32') && !has('unix'))
2845  call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
2846
2847  if has('unix') && executable('uname')
2848    let uname = system('uname')
2849    " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
2850    call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
2851    call assert_equal(uname =~? 'HP-UX', has('hpux'))
2852    call assert_equal(uname =~? 'Linux', has('linux'))
2853    call assert_equal(uname =~? 'Darwin', has('mac'))
2854    call assert_equal(uname =~? 'QNX', has('qnx'))
2855    call assert_equal(uname =~? 'SunOS', has('sun'))
2856    call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
2857    call assert_equal(uname =~? 'GNU', has('hurd'))
2858  endif
2859endfunc
2860
2861func Test_readdir()
2862  call mkdir('Xdir')
2863  call writefile([], 'Xdir/foo.txt')
2864  call writefile([], 'Xdir/bar.txt')
2865  call mkdir('Xdir/dir')
2866
2867  " All results
2868  let files = readdir('Xdir')
2869  call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
2870
2871  " Only results containing "f"
2872  let files = 'Xdir'->readdir({ x -> stridx(x, 'f') !=- 1 })
2873  call assert_equal(['foo.txt'], sort(files))
2874
2875  " Only .txt files
2876  let files = readdir('Xdir', { x -> x =~ '.txt$' })
2877  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2878
2879  " Only .txt files with string
2880  let files = readdir('Xdir', 'v:val =~ ".txt$"')
2881  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2882
2883  " Limit to 1 result.
2884  let l = []
2885  let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1})
2886  call assert_equal(1, len(files))
2887
2888  " Nested readdir() must not crash
2889  let files = readdir('Xdir', 'readdir("Xdir", "1") != []')
2890  call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
2891
2892  eval 'Xdir'->delete('rf')
2893endfunc
2894
2895func Test_delete_rf()
2896  call mkdir('Xdir')
2897  call writefile([], 'Xdir/foo.txt')
2898  call writefile([], 'Xdir/bar.txt')
2899  call mkdir('Xdir/[a-1]')  " issue #696
2900  call writefile([], 'Xdir/[a-1]/foo.txt')
2901  call writefile([], 'Xdir/[a-1]/bar.txt')
2902  call assert_true(filereadable('Xdir/foo.txt'))
2903  call assert_true('Xdir/[a-1]/foo.txt'->filereadable())
2904
2905  call assert_equal(0, delete('Xdir', 'rf'))
2906  call assert_false(filereadable('Xdir/foo.txt'))
2907  call assert_false(filereadable('Xdir/[a-1]/foo.txt'))
2908
2909  if has('unix')
2910    call mkdir('Xdir/Xdir2', 'p')
2911    silent !chmod 555 Xdir
2912    call assert_equal(-1, delete('Xdir/Xdir2', 'rf'))
2913    call assert_equal(-1, delete('Xdir', 'rf'))
2914    silent !chmod 755 Xdir
2915    call assert_equal(0, delete('Xdir', 'rf'))
2916  endif
2917endfunc
2918
2919func Test_call()
2920  call assert_equal(3, call('len', [123]))
2921  call assert_equal(3, 'len'->call([123]))
2922  call assert_equal(4, call({ x -> len(x) }, ['xxxx']))
2923  call assert_equal(2, call(function('len'), ['xx']))
2924  call assert_fails("call call('len', 123)", 'E1211:')
2925  call assert_equal(0, call('', []))
2926  call assert_equal(0, call('len', v:_null_list))
2927
2928  function Mylen() dict
2929     return len(self.data)
2930  endfunction
2931  let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
2932  eval mydict.len->call([], mydict)->assert_equal(4)
2933  call assert_fails("call call('Mylen', [], 0)", 'E1206:')
2934  call assert_fails('call foo', 'E107:')
2935
2936  " These once caused a crash.
2937  " Nvim doesn't have null functions
2938  " call call(test_null_function(), [])
2939  " Nvim doesn't have null partials
2940  " call call(test_null_partial(), [])
2941  " Nvim doesn't have null functions
2942  " call assert_fails('call test_null_function()()', 'E1192:')
2943  " Nvim doesn't have null partials
2944  " call assert_fails('call test_null_partial()()', 'E117:')
2945
2946  let lines =<< trim END
2947      let Time = 'localtime'
2948      call Time()
2949  END
2950  call CheckScriptFailure(lines, 'E1085:')
2951endfunc
2952
2953func Test_char2nr()
2954  call assert_equal(12354, char2nr('あ', 1))
2955  call assert_equal(120, 'x'->char2nr())
2956  " set encoding=latin1
2957  call assert_equal(120, 'x'->char2nr())
2958  set encoding=utf-8
2959endfunc
2960
2961func Test_charclass()
2962  call assert_equal(0, charclass(' '))
2963  call assert_equal(1, charclass('.'))
2964  call assert_equal(2, charclass('x'))
2965  call assert_equal(3, charclass("\u203c"))
2966  " this used to crash vim
2967  call assert_equal(0, "xxx"[-1]->charclass())
2968endfunc
2969
2970func Test_eventhandler()
2971  call assert_equal(0, eventhandler())
2972endfunc
2973
2974func Test_bufadd_bufload()
2975  call assert_equal(0, bufexists('someName'))
2976  let buf = bufadd('someName')
2977  call assert_notequal(0, buf)
2978  call assert_equal(1, bufexists('someName'))
2979  call assert_equal(0, getbufvar(buf, '&buflisted'))
2980  call assert_equal(0, bufloaded(buf))
2981  call bufload(buf)
2982  call assert_equal(1, bufloaded(buf))
2983  call assert_equal([''], getbufline(buf, 1, '$'))
2984
2985  let curbuf = bufnr('')
2986  eval ['some', 'text']->writefile('XotherName')
2987  let buf = 'XotherName'->bufadd()
2988  call assert_notequal(0, buf)
2989  eval 'XotherName'->bufexists()->assert_equal(1)
2990  call assert_equal(0, getbufvar(buf, '&buflisted'))
2991  call assert_equal(0, bufloaded(buf))
2992  eval buf->bufload()
2993  call assert_equal(1, bufloaded(buf))
2994  call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
2995  call assert_equal(curbuf, bufnr(''))
2996
2997  let buf1 = bufadd('')
2998  let buf2 = bufadd('')
2999  call assert_notequal(0, buf1)
3000  call assert_notequal(0, buf2)
3001  call assert_notequal(buf1, buf2)
3002  call assert_equal(1, bufexists(buf1))
3003  call assert_equal(1, bufexists(buf2))
3004  call assert_equal(0, bufloaded(buf1))
3005  exe 'bwipe ' .. buf1
3006  call assert_equal(0, bufexists(buf1))
3007  call assert_equal(1, bufexists(buf2))
3008  exe 'bwipe ' .. buf2
3009  call assert_equal(0, bufexists(buf2))
3010
3011  " When 'buftype' is "nofile" then bufload() does not read the file.
3012  " Other values too.
3013  for val in [['nofile', 0],
3014            \ ['nowrite', 1],
3015            \ ['acwrite', 1],
3016            \ ['quickfix', 0],
3017            \ ['help', 1],
3018            "\ ['terminal', 0],
3019            \ ['prompt', 0],
3020            "\ ['popup', 0],
3021            \ ]
3022    bwipe! XotherName
3023    let buf = bufadd('XotherName')
3024    call setbufvar(buf, '&bt', val[0])
3025    call bufload(buf)
3026    call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0])
3027  endfor
3028
3029  bwipe someName
3030  bwipe XotherName
3031  call assert_equal(0, bufexists('someName'))
3032  call delete('XotherName')
3033endfunc
3034
3035func Test_state()
3036  CheckRunVimInTerminal
3037
3038  let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
3039
3040  let lines =<< trim END
3041	call setline(1, ['one', 'two', 'three'])
3042	map ;; gg
3043	set complete=.
3044	func RunTimer()
3045	  call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
3046	endfunc
3047	au Filetype foobar let g:state = state()|let g:mode = mode()
3048  END
3049  call writefile(lines, 'XState')
3050  let buf = RunVimInTerminal('-S XState', #{rows: 6})
3051
3052  " Using a ":" command Vim is busy, thus "S" is returned
3053  call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
3054  call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
3055  call term_sendkeys(buf, ":\<CR>")
3056
3057  " Using a timer callback
3058  call term_sendkeys(buf, ":call RunTimer()\<CR>")
3059  call TermWait(buf, 25)
3060  call term_sendkeys(buf, getstate)
3061  call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
3062
3063  " Halfway a mapping
3064  call term_sendkeys(buf, ":call RunTimer()\<CR>;")
3065  call TermWait(buf, 25)
3066  call term_sendkeys(buf, ";")
3067  call term_sendkeys(buf, getstate)
3068  call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
3069
3070  " An operator is pending
3071  call term_sendkeys(buf, ":call RunTimer()\<CR>y")
3072  call TermWait(buf, 25)
3073  call term_sendkeys(buf, "y")
3074  call term_sendkeys(buf, getstate)
3075  call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3076
3077  " A register was specified
3078  call term_sendkeys(buf, ":call RunTimer()\<CR>\"r")
3079  call TermWait(buf, 25)
3080  call term_sendkeys(buf, "yy")
3081  call term_sendkeys(buf, getstate)
3082  call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3083
3084  " Insert mode completion (bit slower on Mac)
3085  call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
3086  call TermWait(buf, 25)
3087  call term_sendkeys(buf, "\<Esc>")
3088  call term_sendkeys(buf, getstate)
3089  call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
3090
3091  " Autocommand executing
3092  call term_sendkeys(buf, ":set filetype=foobar\<CR>")
3093  call TermWait(buf, 25)
3094  call term_sendkeys(buf, getstate)
3095  call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
3096
3097  " Todo: "w" - waiting for ch_evalexpr()
3098
3099  " messages scrolled
3100  call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
3101  call TermWait(buf, 25)
3102  call term_sendkeys(buf, "\<CR>")
3103  call term_sendkeys(buf, getstate)
3104  call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
3105
3106  call StopVimInTerminal(buf)
3107  call delete('XState')
3108endfunc
3109
3110func Test_range()
3111  " destructuring
3112  let [x, y] = range(2)
3113  call assert_equal([0, 1], [x, y])
3114
3115  " index
3116  call assert_equal(4, range(1, 10)[3])
3117
3118  " add()
3119  call assert_equal([0, 1, 2, 3], add(range(3), 3))
3120  call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
3121  call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
3122
3123  " append()
3124  new
3125  call append('.', range(5))
3126  call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
3127  bwipe!
3128
3129  " appendbufline()
3130  new
3131  call appendbufline(bufnr(''), '.', range(5))
3132  call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
3133  bwipe!
3134
3135  " call()
3136  func TwoArgs(a, b)
3137    return [a:a, a:b]
3138  endfunc
3139  call assert_equal([0, 1], call('TwoArgs', range(2)))
3140
3141  " col()
3142  new
3143  call setline(1, ['foo', 'bar'])
3144  call assert_equal(2, col(range(1, 2)))
3145  bwipe!
3146
3147  " complete()
3148  execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
3149  " complete_info()
3150  execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
3151
3152  " copy()
3153  call assert_equal([1, 2, 3], copy(range(1, 3)))
3154
3155  " count()
3156  call assert_equal(0, count(range(0), 3))
3157  call assert_equal(0, count(range(2), 3))
3158  call assert_equal(1, count(range(5), 3))
3159
3160  " cursor()
3161  new
3162  call setline(1, ['aaa', 'bbb', 'ccc'])
3163  call cursor(range(1, 2))
3164  call assert_equal([2, 1], [col('.'), line('.')])
3165  bwipe!
3166
3167  " deepcopy()
3168  call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
3169
3170  " empty()
3171  call assert_true(empty(range(0)))
3172  call assert_false(empty(range(2)))
3173
3174  " execute()
3175  new
3176  call setline(1, ['aaa', 'bbb', 'ccc'])
3177  call execute(range(3))
3178  call assert_equal(2, line('.'))
3179  bwipe!
3180
3181  " extend()
3182  call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
3183  call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
3184  call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
3185
3186  " filter()
3187  call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
3188
3189  " funcref()
3190  call assert_equal([0, 1], funcref('TwoArgs', range(2))())
3191
3192  " function()
3193  call assert_equal([0, 1], function('TwoArgs', range(2))())
3194
3195  " garbagecollect()
3196  let thelist = [1, range(2), 3]
3197  let otherlist = range(3)
3198  call test_garbagecollect_now()
3199
3200  " get()
3201  call assert_equal(4, get(range(1, 10), 3))
3202  call assert_equal(-1, get(range(1, 10), 42, -1))
3203  call assert_equal(0, get(range(1, 0, 2), 0))
3204  call assert_equal(0, get(range(0, -1, 2), 0))
3205  call assert_equal(0, get(range(-2, -1, -2), 0))
3206
3207  " index()
3208  call assert_equal(1, index(range(1, 5), 2))
3209  call assert_fails("echo index([1, 2], 1, [])", 'E745:')
3210
3211  " insert()
3212  call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
3213  call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
3214  call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
3215  call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
3216  call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
3217  call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
3218
3219  " join()
3220  call assert_equal('0 1 2 3 4', join(range(5)))
3221
3222  " json_encode()
3223  " call assert_equal('[0,1,2,3]', json_encode(range(4)))
3224  call assert_equal('[0, 1, 2, 3]', json_encode(range(4)))
3225
3226  " len()
3227  call assert_equal(0, len(range(0)))
3228  call assert_equal(2, len(range(2)))
3229  call assert_equal(5, len(range(0, 12, 3)))
3230  call assert_equal(4, len(range(3, 0, -1)))
3231
3232  " list2str()
3233  call assert_equal('ABC', list2str(range(65, 67)))
3234  call assert_fails('let s = list2str(5)', 'E474:')
3235
3236  " lock()
3237  let thelist = range(5)
3238  lockvar thelist
3239
3240  " map()
3241  call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
3242
3243  " match()
3244  call assert_equal(3, match(range(5), 3))
3245
3246  " matchaddpos()
3247  highlight MyGreenGroup ctermbg=green guibg=green
3248  call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
3249
3250  " matchend()
3251  call assert_equal(4, matchend(range(5), '4'))
3252  call assert_equal(3, matchend(range(1, 5), '4'))
3253  call assert_equal(-1, matchend(range(1, 5), '42'))
3254
3255  " matchstrpos()
3256  call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
3257  call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
3258  call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
3259
3260  " max() reverse()
3261  call assert_equal(0, max(range(0)))
3262  call assert_equal(0, max(range(10, 9)))
3263  call assert_equal(9, max(range(10)))
3264  call assert_equal(18, max(range(0, 20, 3)))
3265  call assert_equal(20, max(range(20, 0, -3)))
3266  call assert_equal(99999, max(range(100000)))
3267  call assert_equal(99999, max(range(99999, 0, -1)))
3268  call assert_equal(99999, max(reverse(range(100000))))
3269  call assert_equal(99999, max(reverse(range(99999, 0, -1))))
3270
3271  " min() reverse()
3272  call assert_equal(0, min(range(0)))
3273  call assert_equal(0, min(range(10, 9)))
3274  call assert_equal(5, min(range(5, 10)))
3275  call assert_equal(5, min(range(5, 10, 3)))
3276  call assert_equal(2, min(range(20, 0, -3)))
3277  call assert_equal(0, min(range(100000)))
3278  call assert_equal(0, min(range(99999, 0, -1)))
3279  call assert_equal(0, min(reverse(range(100000))))
3280  call assert_equal(0, min(reverse(range(99999, 0, -1))))
3281
3282  " remove()
3283  call assert_equal(1, remove(range(1, 10), 0))
3284  call assert_equal(2, remove(range(1, 10), 1))
3285  call assert_equal(9, remove(range(1, 10), 8))
3286  call assert_equal(10, remove(range(1, 10), 9))
3287  call assert_equal(10, remove(range(1, 10), -1))
3288  call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
3289
3290  " repeat()
3291  call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
3292  call assert_equal([0, 1, 2], repeat(range(3), 1))
3293  call assert_equal([], repeat(range(3), 0))
3294  call assert_equal([], repeat(range(5, 4), 2))
3295  call assert_equal([], repeat(range(5, 4), 0))
3296
3297  " reverse()
3298  call assert_equal([2, 1, 0], reverse(range(3)))
3299  call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
3300  call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
3301  call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
3302  call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
3303  call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
3304  call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
3305  call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
3306  call assert_equal([], reverse(range(0)))
3307
3308  " TODO: setpos()
3309  " new
3310  " call setline(1, repeat([''], bufnr('')))
3311  " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
3312  " call setpos('x', range(bufnr(''), bufnr('') + 3))
3313  " bwipe!
3314
3315  " setreg()
3316  call setreg('a', range(3))
3317  call assert_equal("0\n1\n2\n", getreg('a'))
3318
3319  " settagstack()
3320  call settagstack(1, #{items : range(4)})
3321
3322  " sign_define()
3323  call assert_fails("call sign_define(range(5))", "E715:")
3324  call assert_fails("call sign_placelist(range(5))", "E715:")
3325
3326  " sign_undefine()
3327  " call assert_fails("call sign_undefine(range(5))", "E908:")
3328  call assert_fails("call sign_undefine(range(5))", "E155:")
3329
3330  " sign_unplacelist()
3331  call assert_fails("call sign_unplacelist(range(5))", "E715:")
3332
3333  " sort()
3334  call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
3335
3336  " string()
3337  call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
3338
3339  " taglist() with 'tagfunc'
3340  func TagFunc(pattern, flags, info)
3341    return range(10)
3342  endfunc
3343  set tagfunc=TagFunc
3344  call assert_fails("call taglist('asdf')", 'E987:')
3345  set tagfunc=
3346
3347  " term_start()
3348  if has('terminal') && has('termguicolors')
3349    call assert_fails('call term_start(range(3, 4))', 'E474:')
3350    let g:terminal_ansi_colors = range(16)
3351    if has('win32')
3352      let cmd = "cmd /D /c dir"
3353    else
3354      let cmd = "ls"
3355    endif
3356    call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"})', 'E475:')
3357    unlet g:terminal_ansi_colors
3358  endif
3359
3360  " type()
3361  call assert_equal(v:t_list, type(range(5)))
3362
3363  " uniq()
3364  call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
3365
3366  " errors
3367  call assert_fails('let x=range(2, 8, 0)', 'E726:')
3368  call assert_fails('let x=range(3, 1)', 'E727:')
3369  call assert_fails('let x=range(1, 3, -2)', 'E727:')
3370  call assert_fails('let x=range([])', 'E745:')
3371  call assert_fails('let x=range(1, [])', 'E745:')
3372  call assert_fails('let x=range(1, 4, [])', 'E745:')
3373endfunc
3374
3375func Test_garbagecollect_now_fails()
3376  let v:testing = 0
3377  call assert_fails('call test_garbagecollect_now()', 'E1142:')
3378  let v:testing = 1
3379endfunc
3380
3381" Test for echo highlighting
3382func Test_echohl()
3383  echohl Search
3384  echo 'Vim'
3385  call assert_equal('Vim', Screenline(&lines))
3386  " TODO: How to check the highlight group used by echohl?
3387  " ScreenAttrs() returns all zeros.
3388  echohl None
3389endfunc
3390
3391" Test for the eval() function
3392func Test_eval()
3393  call assert_fails("call eval('5 a')", 'E488:')
3394endfunc
3395
3396" Test for the keytrans() function
3397func Test_keytrans()
3398  call assert_equal('<Space>', keytrans(' '))
3399  call assert_equal('<lt>', keytrans('<'))
3400  call assert_equal('<lt>Tab>', keytrans('<Tab>'))
3401  call assert_equal('<Tab>', keytrans("\<Tab>"))
3402  call assert_equal('<C-V>', keytrans("\<C-V>"))
3403  call assert_equal('<BS>', keytrans("\<BS>"))
3404  call assert_equal('<Home>', keytrans("\<Home>"))
3405  call assert_equal('<C-Home>', keytrans("\<C-Home>"))
3406  call assert_equal('<M-Home>', keytrans("\<M-Home>"))
3407  call assert_equal('<C-Space>', keytrans("\<C-Space>"))
3408  call assert_equal('<M-Space>', keytrans("\<*M-Space>"))
3409  call assert_equal('<M-x>', "\<*M-x>"->keytrans())
3410  call assert_equal('<C-I>', "\<*C-I>"->keytrans())
3411  call assert_equal('<S-3>', "\<*S-3>"->keytrans())
3412  call assert_equal('<Bar>', '|'->keytrans())
3413  call assert_equal('<M-Bar>', "\<*M-|>"->keytrans())
3414  call assert_equal('<Bslash>', '\'->keytrans())
3415  call assert_equal('<M-Bslash>', "\<*M-\>"->keytrans())
3416  call assert_equal('π', 'π'->keytrans())
3417  call assert_equal('<M-π>', "\<M-π>"->keytrans())
3418  call assert_equal('ě', 'ě'->keytrans())
3419  call assert_equal('<M-ě>', "\<M-ě>"->keytrans())
3420  call assert_equal('', ''->keytrans())
3421  call assert_equal('', v:_null_string->keytrans())
3422  call assert_fails('call keytrans(1)', 'E1174:')
3423  call assert_fails('call keytrans()', 'E119:')
3424endfunc
3425
3426" Test for the nr2char() function
3427func Test_nr2char()
3428  " set encoding=latin1
3429  call assert_equal('@', nr2char(64))
3430  set encoding=utf8
3431  call assert_equal('a', nr2char(97, 1))
3432  call assert_equal('a', nr2char(97, 0))
3433
3434  call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"'))
3435  call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
3436endfunc
3437
3438" Test for screenattr(), screenchar() and screenchars() functions
3439func Test_screen_functions()
3440  call assert_equal(-1, screenattr(-1, -1))
3441  call assert_equal(-1, screenchar(-1, -1))
3442  call assert_equal([], screenchars(-1, -1))
3443
3444  " Run this in a separate Vim instance to avoid messing up.
3445  let after =<< trim [CODE]
3446    scriptencoding utf-8
3447    call setline(1, '口')
3448    redraw
3449    call assert_equal(0, screenattr(1, 1))
3450    call assert_equal(char2nr('口'), screenchar(1, 1))
3451    call assert_equal([char2nr('口')], screenchars(1, 1))
3452    call assert_equal('口', screenstring(1, 1))
3453    call writefile(v:errors, 'Xresult')
3454    qall!
3455  [CODE]
3456
3457  let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950']
3458  if !has('win32')
3459    let encodings += ['euc-jp']
3460  endif
3461  if has('nvim')
3462    let encodings = ['utf-8']
3463  endif
3464  for enc in encodings
3465    let msg = 'enc=' .. enc
3466    if RunVim([], after, $'--clean --cmd "set encoding={enc}"')
3467      call assert_equal([], readfile('Xresult'), msg)
3468    endif
3469    call delete('Xresult')
3470  endfor
3471endfunc
3472
3473" Test for getcurpos() and setpos()
3474func Test_getcurpos_setpos()
3475  new
3476  call setline(1, ['012345678', '012345678'])
3477  normal gg6l
3478  let sp = getcurpos()
3479  normal 0
3480  call setpos('.', sp)
3481  normal jyl
3482  call assert_equal('6', @")
3483  call assert_equal(-1, setpos('.', v:_null_list))
3484  call assert_equal(-1, setpos('.', {}))
3485
3486  let winid = win_getid()
3487  normal G$
3488  let pos = getcurpos()
3489  wincmd w
3490  call assert_equal(pos, getcurpos(winid))
3491
3492  wincmd w
3493  close!
3494
3495  call assert_equal(getcurpos(), getcurpos(0))
3496  call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
3497  call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
3498endfunc
3499
3500func Test_getmousepos()
3501  enew!
3502  call setline(1, "\t\t\t1234")
3503  call Ntest_setmouse(1, 1)
3504  call assert_equal(#{
3505        \ screenrow: 1,
3506        \ screencol: 1,
3507        \ winid: win_getid(),
3508        \ winrow: 1,
3509        \ wincol: 1,
3510        \ line: 1,
3511        \ column: 1,
3512        \ coladd: 0,
3513        \ }, getmousepos())
3514  call Ntest_setmouse(1, 2)
3515  call assert_equal(#{
3516        \ screenrow: 1,
3517        \ screencol: 2,
3518        \ winid: win_getid(),
3519        \ winrow: 1,
3520        \ wincol: 2,
3521        \ line: 1,
3522        \ column: 1,
3523        \ coladd: 1,
3524        \ }, getmousepos())
3525  call Ntest_setmouse(1, 8)
3526  call assert_equal(#{
3527        \ screenrow: 1,
3528        \ screencol: 8,
3529        \ winid: win_getid(),
3530        \ winrow: 1,
3531        \ wincol: 8,
3532        \ line: 1,
3533        \ column: 1,
3534        \ coladd: 7,
3535        \ }, getmousepos())
3536  call Ntest_setmouse(1, 9)
3537  call assert_equal(#{
3538        \ screenrow: 1,
3539        \ screencol: 9,
3540        \ winid: win_getid(),
3541        \ winrow: 1,
3542        \ wincol: 9,
3543        \ line: 1,
3544        \ column: 2,
3545        \ coladd: 0,
3546        \ }, getmousepos())
3547  call Ntest_setmouse(1, 12)
3548  call assert_equal(#{
3549        \ screenrow: 1,
3550        \ screencol: 12,
3551        \ winid: win_getid(),
3552        \ winrow: 1,
3553        \ wincol: 12,
3554        \ line: 1,
3555        \ column: 2,
3556        \ coladd: 3,
3557        \ }, getmousepos())
3558  call Ntest_setmouse(1, 25)
3559  call assert_equal(#{
3560        \ screenrow: 1,
3561        \ screencol: 25,
3562        \ winid: win_getid(),
3563        \ winrow: 1,
3564        \ wincol: 25,
3565        \ line: 1,
3566        \ column: 4,
3567        \ coladd: 0,
3568        \ }, getmousepos())
3569  call Ntest_setmouse(1, 28)
3570  call assert_equal(#{
3571        \ screenrow: 1,
3572        \ screencol: 28,
3573        \ winid: win_getid(),
3574        \ winrow: 1,
3575        \ wincol: 28,
3576        \ line: 1,
3577        \ column: 7,
3578        \ coladd: 0,
3579        \ }, getmousepos())
3580  call Ntest_setmouse(1, 29)
3581  call assert_equal(#{
3582        \ screenrow: 1,
3583        \ screencol: 29,
3584        \ winid: win_getid(),
3585        \ winrow: 1,
3586        \ wincol: 29,
3587        \ line: 1,
3588        \ column: 8,
3589        \ coladd: 0,
3590        \ }, getmousepos())
3591  call Ntest_setmouse(1, 50)
3592  call assert_equal(#{
3593        \ screenrow: 1,
3594        \ screencol: 50,
3595        \ winid: win_getid(),
3596        \ winrow: 1,
3597        \ wincol: 50,
3598        \ line: 1,
3599        \ column: 8,
3600        \ coladd: 21,
3601        \ }, getmousepos())
3602
3603  " If the mouse is positioned past the last buffer line, "line" and "column"
3604  " should act like it's positioned on the last buffer line.
3605  call Ntest_setmouse(2, 25)
3606  call assert_equal(#{
3607        \ screenrow: 2,
3608        \ screencol: 25,
3609        \ winid: win_getid(),
3610        \ winrow: 2,
3611        \ wincol: 25,
3612        \ line: 1,
3613        \ column: 4,
3614        \ coladd: 0,
3615        \ }, getmousepos())
3616  call Ntest_setmouse(2, 50)
3617  call assert_equal(#{
3618        \ screenrow: 2,
3619        \ screencol: 50,
3620        \ winid: win_getid(),
3621        \ winrow: 2,
3622        \ wincol: 50,
3623        \ line: 1,
3624        \ column: 8,
3625        \ coladd: 21,
3626        \ }, getmousepos())
3627
3628  30vnew
3629  setlocal smoothscroll number
3630  call setline(1, join(range(100)))
3631  exe "normal! \<C-E>"
3632  call Ntest_setmouse(1, 5)
3633  call assert_equal(#{
3634        \ screenrow: 1,
3635        \ screencol: 5,
3636        \ winid: win_getid(),
3637        \ winrow: 1,
3638        \ wincol: 5,
3639        \ line: 1,
3640        \ column: 27,
3641        \ coladd: 0,
3642        \ }, getmousepos())
3643  call Ntest_setmouse(2, 5)
3644  call assert_equal(#{
3645        \ screenrow: 2,
3646        \ screencol: 5,
3647        \ winid: win_getid(),
3648        \ winrow: 2,
3649        \ wincol: 5,
3650        \ line: 1,
3651        \ column: 53,
3652        \ coladd: 0,
3653        \ }, getmousepos())
3654
3655  exe "normal! \<C-E>"
3656  call Ntest_setmouse(1, 5)
3657  call assert_equal(#{
3658        \ screenrow: 1,
3659        \ screencol: 5,
3660        \ winid: win_getid(),
3661        \ winrow: 1,
3662        \ wincol: 5,
3663        \ line: 1,
3664        \ column: 53,
3665        \ coladd: 0,
3666        \ }, getmousepos())
3667  call Ntest_setmouse(2, 5)
3668  call assert_equal(#{
3669        \ screenrow: 2,
3670        \ screencol: 5,
3671        \ winid: win_getid(),
3672        \ winrow: 2,
3673        \ wincol: 5,
3674        \ line: 1,
3675        \ column: 79,
3676        \ coladd: 0,
3677        \ }, getmousepos())
3678
3679  vert resize 4
3680  call Ntest_setmouse(2, 2)
3681  " This used to crash Vim
3682  call assert_equal(#{
3683        \ screenrow: 2,
3684        \ screencol: 2,
3685        \ winid: win_getid(),
3686        \ winrow: 2,
3687        \ wincol: 2,
3688        \ line: 1,
3689        \ column: 53,
3690        \ coladd: 0,
3691        \ }, getmousepos())
3692
3693  bwipe!
3694  bwipe!
3695endfunc
3696
3697" Test for glob()
3698func Test_glob()
3699  call assert_equal('', glob(v:_null_string))
3700  call assert_equal('', globpath(v:_null_string, v:_null_string))
3701  call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
3702
3703  call writefile([], 'Xglob1')
3704  call writefile([], 'XGLOB2')
3705  set wildignorecase
3706  " Sort output of glob() otherwise we end up with different
3707  " ordering depending on whether file system is case-sensitive.
3708  call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
3709  " wildignorecase shall be applied even when the pattern contains no wildcards.
3710  call assert_equal('XGLOB2', glob('xglob2'))
3711  set wildignorecase&
3712
3713  call delete('Xglob1')
3714  call delete('XGLOB2')
3715
3716  call assert_fails("call glob('*', 0, {})", 'E728:')
3717endfunc
3718
3719func Test_glob2()
3720  call mkdir('[XglobDir]', 'R')
3721  call mkdir('abc[glob]def', 'R')
3722
3723  call writefile(['glob'], '[XglobDir]/Xglob')
3724  call writefile(['glob'], 'abc[glob]def/Xglob')
3725  if has("unix")
3726    call assert_equal([], (glob('[XglobDir]/*', 0, 1)))
3727    call assert_equal([], (glob('abc[glob]def/*', 0, 1)))
3728    call assert_equal(['[XglobDir]/Xglob'], (glob('\[XglobDir]/*', 0, 1)))
3729    call assert_equal(['abc[glob]def/Xglob'], (glob('abc\[glob]def/*', 0, 1)))
3730  elseif has("win32")
3731    let _sl=&shellslash
3732    call assert_equal([], (glob('[XglobDir]\*', 0, 1)))
3733    call assert_equal([], (glob('abc[glob]def\*', 0, 1)))
3734    call assert_equal([], (glob('\[XglobDir]\*', 0, 1)))
3735    call assert_equal([], (glob('abc\[glob]def\*', 0, 1)))
3736    " Test that changing 'shellslash' doesn't affect the result of glob()
3737    set noshellslash
3738    call assert_equal(['[XglobDir]/Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
3739    call assert_equal(['abc[glob]def/Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
3740    set shellslash
3741    call assert_equal(['[XglobDir]/Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
3742    call assert_equal(['abc[glob]def/Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
3743    let &shellslash=_sl
3744  endif
3745endfunc
3746
3747func Test_glob_symlinks()
3748  call writefile([], 'Xglob1')
3749
3750  if has("win32")
3751    silent !mklink XglobBad DoesNotExist
3752    if v:shell_error
3753      throw 'Skipped: cannot create symlinks'
3754    endif
3755    silent !mklink XglobOk Xglob1
3756  else
3757    silent !ln -s DoesNotExist XglobBad
3758    silent !ln -s Xglob1 XglobOk
3759  endif
3760
3761  " The broken symlink is excluded when alllinks is false.
3762  call assert_equal(['Xglob1', 'XglobBad', 'XglobOk'], sort(glob('Xglob*', 0, 1, 1)))
3763  call assert_equal(['Xglob1', 'XglobOk'], sort(glob('Xglob*', 0, 1, 0)))
3764
3765  call delete('Xglob1')
3766  call delete('XglobBad')
3767  call delete('XglobOk')
3768endfunc
3769
3770" Test for browse()
3771func Test_browse()
3772  CheckFeature browse
3773  call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
3774endfunc
3775
3776" Test for browsedir()
3777func Test_browsedir()
3778  CheckFeature browse
3779  call assert_fails('call browsedir("open", [])', 'E730:')
3780endfunc
3781
3782func HasDefault(msg = 'msg')
3783  return a:msg
3784endfunc
3785
3786func Test_default_arg_value()
3787  call assert_equal('msg', HasDefault())
3788endfunc
3789
3790" Test for gettext()
3791func Test_gettext()
3792  call assert_fails('call gettext(1)', 'E1174:')
3793endfunc
3794
3795func Test_builtin_check()
3796  call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
3797  call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
3798  call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
3799  call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
3800  let lines =<< trim END
3801    vim9script
3802    var trim = (x) => " " .. x
3803  END
3804  call CheckScriptFailure(lines, 'E704:')
3805
3806  call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
3807  let g:bar = 123
3808  call extend(g:, #{bar: { -> "foo" }}, "keep")
3809  call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
3810  unlet g:bar
3811
3812  call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:')
3813  let bar = 123
3814  call extend(l:, #{bar: { -> "foo" }}, "keep")
3815  call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:')
3816  unlet bar
3817
3818  call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:')
3819  let g:bar = 123
3820  call extend(g:, #{bar: function("extend")}, "keep")
3821  call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:')
3822  unlet g:bar
3823
3824  call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:')
3825  let bar = 123
3826  call extend(l:, #{bar: function("extend")}, "keep")
3827  call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:')
3828  unlet bar
3829endfunc
3830
3831func Test_funcref_to_string()
3832  let Fn = funcref('g:Test_funcref_to_string')
3833  call assert_equal("function('g:Test_funcref_to_string')", string(Fn))
3834endfunc
3835
3836" Test for isabsolutepath()
3837func Test_isabsolutepath()
3838  call assert_false(isabsolutepath(''))
3839  call assert_false(isabsolutepath('.'))
3840  call assert_false(isabsolutepath('../Foo'))
3841  call assert_false(isabsolutepath('Foo/'))
3842  if has('win32')
3843    call assert_true(isabsolutepath('A:\'))
3844    call assert_true(isabsolutepath('A:\Foo'))
3845    call assert_true(isabsolutepath('A:/Foo'))
3846    call assert_false(isabsolutepath('A:Foo'))
3847    call assert_true(isabsolutepath('\Windows'))
3848    call assert_true(isabsolutepath('/Windows'))
3849    call assert_true(isabsolutepath('\\Server2\Share\Test\Foo.txt'))
3850  else
3851    call assert_true(isabsolutepath('/'))
3852    call assert_true(isabsolutepath('/usr/share/'))
3853  endif
3854endfunc
3855
3856" Test for exepath()
3857func Test_exepath()
3858  if has('win32')
3859    call assert_notequal(exepath('cmd'), '')
3860
3861    let oldNoDefaultCurrentDirectoryInExePath = $NoDefaultCurrentDirectoryInExePath
3862    call writefile(['@echo off', 'echo Evil'], 'vim-test-evil.bat')
3863    let $NoDefaultCurrentDirectoryInExePath = ''
3864    call assert_notequal(exepath("vim-test-evil.bat"), '')
3865    let $NoDefaultCurrentDirectoryInExePath = '1'
3866    call assert_equal(exepath("vim-test-evil.bat"), '')
3867    let $NoDefaultCurrentDirectoryInExePath = oldNoDefaultCurrentDirectoryInExePath
3868    call delete('vim-test-evil.bat')
3869  else
3870    call assert_notequal(exepath('sh'), '')
3871  endif
3872endfunc
3873
3874" Test for virtcol()
3875func Test_virtcol()
3876  new
3877  call setline(1, "the\tquick\tbrown\tfox")
3878  norm! 4|
3879  call assert_equal(8, virtcol('.'))
3880  call assert_equal(8, virtcol('.', v:false))
3881  call assert_equal([4, 8], virtcol('.', v:true))
3882
3883  let w = winwidth(0)
3884  call setline(2, repeat('a', w + 2))
3885  let win_nosbr = win_getid()
3886  split
3887  setlocal showbreak=!!
3888  let win_sbr = win_getid()
3889  call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr))
3890  call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr))
3891  call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr))
3892  call assert_equal([w, w], virtcol([2, w], v:true, win_sbr))
3893  call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr))
3894  call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr))
3895  close
3896
3897  call assert_equal(0, virtcol(''))
3898  call assert_equal([0, 0], virtcol('', v:true))
3899  call assert_equal(0, virtcol('.', v:false, 5001))
3900  call assert_equal([0, 0], virtcol('.', v:true, 5001))
3901
3902  bwipe!
3903endfunc
3904
3905func Test_delfunc_while_listing()
3906  CheckRunVimInTerminal
3907
3908  let lines =<< trim END
3909      set nocompatible
3910      for i in range(1, 999)
3911        exe 'func ' .. 'MyFunc' .. i .. '()'
3912        endfunc
3913      endfor
3914      au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')})
3915  END
3916  call writefile(lines, 'Xfunctionclear', 'D')
3917  let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12})
3918
3919  " This was using freed memory.  The height of the terminal must be so that
3920  " the next function to be listed with "j" is the one that is deleted in the
3921  " timer callback, tricky!
3922  call term_sendkeys(buf, ":func /MyFunc\<CR>")
3923  call TermWait(buf, 50)
3924  call term_sendkeys(buf, "j")
3925  call TermWait(buf, 50)
3926  call term_sendkeys(buf, "\<CR>")
3927
3928  call StopVimInTerminal(buf)
3929endfunc
3930
3931" Test for the reverse() function with a string
3932func Test_string_reverse()
3933  let lines =<< trim END
3934    call assert_equal('', reverse(v:_null_string))
3935    for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'],
3936                   \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'],
3937                   \ ['🇦', '🇦'], ['🇦🇧', '🇦🇧'], ['🇦🇧🇨', '🇨🇦🇧'],
3938                   \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']]
3939      call assert_equal(s2, reverse(s1))
3940    endfor
3941  END
3942  call CheckLegacyAndVim9Success(lines)
3943
3944  " test in latin1 encoding
3945  let save_enc = &encoding
3946  " set encoding=latin1
3947  call assert_equal('dcba', reverse('abcd'))
3948  let &encoding = save_enc
3949endfunc
3950
3951func Test_fullcommand()
3952  " this used to crash vim
3953  call assert_equal('', fullcommand(10))
3954endfunc
3955
3956" Test for glob() with shell special patterns
3957func Test_glob_extended_bash()
3958  CheckExecutable bash
3959  CheckNotMSWindows
3960  CheckNotMac   " The default version of bash is old on macOS.
3961
3962  let _shell = &shell
3963  set shell=bash
3964
3965  call mkdir('Xtestglob/foo/bar/src', 'p')
3966  call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
3967  call writefile([], 'Xtestglob/foo/bar/src/foo.h')
3968  call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
3969
3970  " Sort output of glob() otherwise we end up with different
3971  " ordering depending on whether file system is case-sensitive.
3972  let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h']
3973  call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1)))
3974  call delete('Xtestglob', 'rf')
3975  let &shell=_shell
3976endfunc
3977
3978" Test for glob() with extended patterns (MS-Windows)
3979" Vim doesn't use 'shell' to expand wildcards on MS-Windows.
3980" Unlike bash, it doesn't support {,} expansion.
3981func Test_glob_extended_mswin()
3982  CheckMSWindows
3983
3984  call mkdir('Xtestglob/foo/bar/src', 'p')
3985  call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
3986  call writefile([], 'Xtestglob/foo/bar/src/foo.h')
3987  call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
3988
3989  " Sort output of glob() otherwise we end up with different
3990  " ordering depending on whether file system is case-sensitive.
3991  let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh']
3992  call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1)))
3993  call delete('Xtestglob', 'rf')
3994endfunc
3995
3996" Tests for the slice() function.
3997func Test_slice()
3998  let lines =<< trim END
3999    call assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
4000    call assert_equal([2, 3, 4, 5], slice(range(6), 2))
4001    call assert_equal([2, 3], slice(range(6), 2, 4))
4002    call assert_equal([0, 1, 2, 3], slice(range(6), 0, 4))
4003    call assert_equal([1, 2, 3], slice(range(6), 1, 4))
4004    call assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
4005    call assert_equal([1, 2], slice(range(6), 1, -3))
4006    call assert_equal([1], slice(range(6), 1, -4))
4007    call assert_equal([], slice(range(6), 1, -5))
4008    call assert_equal([], slice(range(6), 1, -6))
4009
4010    call assert_equal(0z1122334455, slice(0z001122334455, 1))
4011    call assert_equal(0z22334455, slice(0z001122334455, 2))
4012    call assert_equal(0z2233, slice(0z001122334455, 2, 4))
4013    call assert_equal(0z00112233, slice(0z001122334455, 0, 4))
4014    call assert_equal(0z112233, slice(0z001122334455, 1, 4))
4015    call assert_equal(0z11223344, slice(0z001122334455, 1, -1))
4016    call assert_equal(0z1122, slice(0z001122334455, 1, -3))
4017    call assert_equal(0z11, slice(0z001122334455, 1, -4))
4018    call assert_equal(0z, slice(0z001122334455, 1, -5))
4019    call assert_equal(0z, slice(0z001122334455, 1, -6))
4020
4021    call assert_equal('12345', slice('012345', 1))
4022    call assert_equal('2345', slice('012345', 2))
4023    call assert_equal('23', slice('012345', 2, 4))
4024    call assert_equal('0123', slice('012345', 0, 4))
4025    call assert_equal('123', slice('012345', 1, 4))
4026    call assert_equal('1234', slice('012345', 1, -1))
4027    call assert_equal('12', slice('012345', 1, -3))
4028    call assert_equal('1', slice('012345', 1, -4))
4029    call assert_equal('', slice('012345', 1, -5))
4030    call assert_equal('', slice('012345', 1, -6))
4031
4032    #" Composing chars are treated as a part of the preceding base char.
4033    call assert_equal('β̳́γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1))
4034    call assert_equal('γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2))
4035    call assert_equal('γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2, 4))
4036    call assert_equal('ὰ̳β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(0, 4))
4037    call assert_equal('β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, 4))
4038    call assert_equal('β̳́γ̳̂δ̳̃ε̳̄', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -1))
4039    call assert_equal('β̳́γ̳̂', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -3))
4040    call assert_equal('β̳́', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -4))
4041    call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -5))
4042    call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -6))
4043  END
4044  call CheckLegacyAndVim9Success(lines)
4045
4046  call assert_equal(0, slice(v:true, 1))
4047endfunc
4048
4049" vim: shiftwidth=2 sts=2 expandtab