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