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