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