1" Tests for various functions.
2source shared.vim
3
4" Must be done first, since the alternate buffer must be unset.
5func Test_00_bufexists()
6  call assert_equal(0, bufexists('does_not_exist'))
7  call assert_equal(1, bufexists(bufnr('%')))
8  call assert_equal(0, bufexists(0))
9  new Xfoo
10  let bn = bufnr('%')
11  call assert_equal(1, bufexists(bn))
12  call assert_equal(1, bufexists('Xfoo'))
13  call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
14  call assert_equal(1, bufexists(0))
15  bw
16  call assert_equal(0, bufexists(bn))
17  call assert_equal(0, bufexists('Xfoo'))
18endfunc
19
20func Test_empty()
21  call assert_equal(1, empty(''))
22  call assert_equal(0, empty('a'))
23
24  call assert_equal(1, empty(0))
25  call assert_equal(1, empty(-0))
26  call assert_equal(0, empty(1))
27  call assert_equal(0, empty(-1))
28
29  call assert_equal(1, empty(0.0))
30  call assert_equal(1, empty(-0.0))
31  call assert_equal(0, empty(1.0))
32  call assert_equal(0, empty(-1.0))
33  call assert_equal(0, empty(1.0/0.0))
34  call assert_equal(0, empty(0.0/0.0))
35
36  call assert_equal(1, empty([]))
37  call assert_equal(0, empty(['a']))
38
39  call assert_equal(1, empty({}))
40  call assert_equal(0, empty({'a':1}))
41
42  call assert_equal(1, empty(v:null))
43  call assert_equal(1, empty(v:none))
44  call assert_equal(1, empty(v:false))
45  call assert_equal(0, empty(v:true))
46
47  if has('channel')
48    call assert_equal(1, empty(test_null_channel()))
49  endif
50  if has('job')
51    call assert_equal(1, empty(test_null_job()))
52  endif
53
54  call assert_equal(0, empty(function('Test_empty')))
55  call assert_equal(0, empty(function('Test_empty', [0])))
56endfunc
57
58func Test_len()
59  call assert_equal(1, len(0))
60  call assert_equal(2, len(12))
61
62  call assert_equal(0, len(''))
63  call assert_equal(2, len('ab'))
64
65  call assert_equal(0, len([]))
66  call assert_equal(2, len([2, 1]))
67
68  call assert_equal(0, len({}))
69  call assert_equal(2, len({'a': 1, 'b': 2}))
70
71  call assert_fails('call len(v:none)', 'E701:')
72  call assert_fails('call len({-> 0})', 'E701:')
73endfunc
74
75func Test_max()
76  call assert_equal(0, max([]))
77  call assert_equal(2, max([2]))
78  call assert_equal(2, max([1, 2]))
79  call assert_equal(2, max([1, 2, v:null]))
80
81  call assert_equal(0, max({}))
82  call assert_equal(2, max({'a':1, 'b':2}))
83
84  call assert_fails('call max(1)', 'E712:')
85  call assert_fails('call max(v:none)', 'E712:')
86endfunc
87
88func Test_min()
89  call assert_equal(0, min([]))
90  call assert_equal(2, min([2]))
91  call assert_equal(1, min([1, 2]))
92  call assert_equal(0, min([1, 2, v:null]))
93
94  call assert_equal(0, min({}))
95  call assert_equal(1, min({'a':1, 'b':2}))
96
97  call assert_fails('call min(1)', 'E712:')
98  call assert_fails('call min(v:none)', 'E712:')
99endfunc
100
101func Test_strwidth()
102  for aw in ['single', 'double']
103    exe 'set ambiwidth=' . aw
104    call assert_equal(0, strwidth(''))
105    call assert_equal(1, strwidth("\t"))
106    call assert_equal(3, strwidth('Vim'))
107    call assert_equal(4, strwidth(1234))
108    call assert_equal(5, strwidth(-1234))
109
110    call assert_equal(2, strwidth('��'))
111    call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
112    call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
113
114    call assert_fails('call strwidth({->0})', 'E729:')
115    call assert_fails('call strwidth([])', 'E730:')
116    call assert_fails('call strwidth({})', 'E731:')
117    call assert_fails('call strwidth(1.2)', 'E806:')
118  endfor
119
120  set ambiwidth&
121endfunc
122
123func Test_str2nr()
124  call assert_equal(0, str2nr(''))
125  call assert_equal(1, str2nr('1'))
126  call assert_equal(1, str2nr(' 1 '))
127
128  call assert_equal(1, str2nr('+1'))
129  call assert_equal(1, str2nr('+ 1'))
130  call assert_equal(1, str2nr(' + 1 '))
131
132  call assert_equal(-1, str2nr('-1'))
133  call assert_equal(-1, str2nr('- 1'))
134  call assert_equal(-1, str2nr(' - 1 '))
135
136  call assert_equal(123456789, str2nr('123456789'))
137  call assert_equal(-123456789, str2nr('-123456789'))
138
139  call assert_equal(5, str2nr('101', 2))
140  call assert_equal(5, str2nr('0b101', 2))
141  call assert_equal(5, str2nr('0B101', 2))
142  call assert_equal(-5, str2nr('-101', 2))
143  call assert_equal(-5, str2nr('-0b101', 2))
144  call assert_equal(-5, str2nr('-0B101', 2))
145
146  call assert_equal(65, str2nr('101', 8))
147  call assert_equal(65, str2nr('0101', 8))
148  call assert_equal(-65, str2nr('-101', 8))
149  call assert_equal(-65, str2nr('-0101', 8))
150
151  call assert_equal(11259375, str2nr('abcdef', 16))
152  call assert_equal(11259375, str2nr('ABCDEF', 16))
153  call assert_equal(-11259375, str2nr('-ABCDEF', 16))
154  call assert_equal(11259375, str2nr('0xabcdef', 16))
155  call assert_equal(11259375, str2nr('0Xabcdef', 16))
156  call assert_equal(11259375, str2nr('0XABCDEF', 16))
157  call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
158
159  call assert_equal(0, str2nr('0x10'))
160  call assert_equal(0, str2nr('0b10'))
161  call assert_equal(1, str2nr('12', 2))
162  call assert_equal(1, str2nr('18', 8))
163  call assert_equal(1, str2nr('1g', 16))
164
165  call assert_equal(0, str2nr(v:null))
166  call assert_equal(0, str2nr(v:none))
167
168  call assert_fails('call str2nr([])', 'E730:')
169  call assert_fails('call str2nr({->2})', 'E729:')
170  call assert_fails('call str2nr(1.2)', 'E806:')
171  call assert_fails('call str2nr(10, [])', 'E474:')
172endfunc
173
174func Test_strftime()
175  if !exists('*strftime')
176    return
177  endif
178  " Format of strftime() depends on system. We assume
179  " that basic formats tested here are available and
180  " identical on all systems which support strftime().
181  "
182  " The 2nd parameter of strftime() is a local time, so the output day
183  " of strftime() can be 17 or 18, depending on timezone.
184  call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
185  "
186  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\)$', strftime('%Y-%m-%d %H:%M:%S'))
187
188  call assert_fails('call strftime([])', 'E730:')
189  call assert_fails('call strftime("%Y", [])', 'E745:')
190endfunc
191
192func Test_resolve_unix()
193  if !has('unix')
194    return
195  endif
196
197  " Xlink1 -> Xlink2
198  " Xlink2 -> Xlink3
199  silent !ln -s -f Xlink2 Xlink1
200  silent !ln -s -f Xlink3 Xlink2
201  call assert_equal('Xlink3', resolve('Xlink1'))
202  call assert_equal('./Xlink3', resolve('./Xlink1'))
203  call assert_equal('Xlink3/', resolve('Xlink2/'))
204  " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
205  "call assert_equal('Xlink3/', resolve('Xlink1/'))
206  "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
207  "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
208  call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
209
210  " Test resolve() with a symlink cycle.
211  " Xlink1 -> Xlink2
212  " Xlink2 -> Xlink3
213  " Xlink3 -> Xlink1
214  silent !ln -s -f Xlink1 Xlink3
215  call assert_fails('call resolve("Xlink1")',   'E655:')
216  call assert_fails('call resolve("./Xlink1")', 'E655:')
217  call assert_fails('call resolve("Xlink2")',   'E655:')
218  call assert_fails('call resolve("Xlink3")',   'E655:')
219  call delete('Xlink1')
220  call delete('Xlink2')
221  call delete('Xlink3')
222
223  silent !ln -s -f Xdir//Xfile Xlink
224  call assert_equal('Xdir/Xfile', resolve('Xlink'))
225  call delete('Xlink')
226
227  silent !ln -s -f Xlink2/ Xlink1
228  call assert_equal('Xlink2', resolve('Xlink1'))
229  call assert_equal('Xlink2/', resolve('Xlink1/'))
230  call delete('Xlink1')
231
232  silent !ln -s -f ./Xlink2 Xlink1
233  call assert_equal('Xlink2', resolve('Xlink1'))
234  call assert_equal('./Xlink2', resolve('./Xlink1'))
235  call delete('Xlink1')
236endfunc
237
238func s:normalize_fname(fname)
239  let ret = substitute(a:fname, '\', '/', 'g')
240  let ret = substitute(ret, '//', '/', 'g')
241  let ret = tolower(ret)
242endfunc
243
244func Test_resolve_win32()
245  if !has('win32')
246    return
247  endif
248
249  " test for shortcut file
250  if executable('cscript')
251    new Xfile
252    wq
253    call writefile([
254    \ 'Set fs = CreateObject("Scripting.FileSystemObject")',
255    \ 'Set ws = WScript.CreateObject("WScript.Shell")',
256    \ 'Set shortcut = ws.CreateShortcut("Xlink.lnk")',
257    \ 'shortcut.TargetPath = fs.BuildPath(ws.CurrentDirectory, "Xfile")',
258    \ 'shortcut.Save'
259    \], 'link.vbs')
260    silent !cscript link.vbs
261    call delete('link.vbs')
262    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink.lnk')))
263    call delete('Xfile')
264
265    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink.lnk')))
266    call delete('Xlink.lnk')
267  else
268    echomsg 'skipped test for shortcut file'
269  endif
270
271  " remove files
272  call delete('Xlink')
273  call delete('Xdir', 'd')
274  call delete('Xfile')
275
276  " test for symbolic link to a file
277  new Xfile
278  wq
279  silent !mklink Xlink Xfile
280  if !v:shell_error
281    call assert_equal(s:normalize_fname(getcwd() . '\Xfile'), s:normalize_fname(resolve('./Xlink')))
282    call delete('Xlink')
283  else
284    echomsg 'skipped test for symbolic link to a file'
285  endif
286  call delete('Xfile')
287
288  " test for junction to a directory
289  call mkdir('Xdir')
290  silent !mklink /J Xlink Xdir
291  if !v:shell_error
292    call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
293
294    call delete('Xdir', 'd')
295
296    " test for junction already removed
297    call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
298    call delete('Xlink')
299  else
300    echomsg 'skipped test for junction to a directory'
301    call delete('Xdir', 'd')
302  endif
303
304  " test for symbolic link to a directory
305  call mkdir('Xdir')
306  silent !mklink /D Xlink Xdir
307  if !v:shell_error
308    call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
309
310    call delete('Xdir', 'd')
311
312    " test for symbolic link already removed
313    call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
314    call delete('Xlink')
315  else
316    echomsg 'skipped test for symbolic link to a directory'
317    call delete('Xdir', 'd')
318  endif
319
320  " test for buffer name
321  new Xfile
322  wq
323  silent !mklink Xlink Xfile
324  if !v:shell_error
325    edit Xlink
326    call assert_equal('Xlink', bufname('%'))
327    call delete('Xlink')
328    bw!
329  else
330    echomsg 'skipped test for buffer name'
331  endif
332  call delete('Xfile')
333endfunc
334
335func Test_simplify()
336  call assert_equal('',            simplify(''))
337  call assert_equal('/',           simplify('/'))
338  call assert_equal('/',           simplify('/.'))
339  call assert_equal('/',           simplify('/..'))
340  call assert_equal('/...',        simplify('/...'))
341  call assert_equal('./dir/file',  simplify('./dir/file'))
342  call assert_equal('./dir/file',  simplify('.///dir//file'))
343  call assert_equal('./dir/file',  simplify('./dir/./file'))
344  call assert_equal('./file',      simplify('./dir/../file'))
345  call assert_equal('../dir/file', simplify('dir/../../dir/file'))
346  call assert_equal('./file',      simplify('dir/.././file'))
347
348  call assert_fails('call simplify({->0})', 'E729:')
349  call assert_fails('call simplify([])', 'E730:')
350  call assert_fails('call simplify({})', 'E731:')
351  call assert_fails('call simplify(1.2)', 'E806:')
352endfunc
353
354func Test_pathshorten()
355  call assert_equal('', pathshorten(''))
356  call assert_equal('foo', pathshorten('foo'))
357  call assert_equal('/foo', pathshorten('/foo'))
358  call assert_equal('f/', pathshorten('foo/'))
359  call assert_equal('f/bar', pathshorten('foo/bar'))
360  call assert_equal('f/b/foobar', pathshorten('foo/bar/foobar'))
361  call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
362  call assert_equal('.f/bar', pathshorten('.foo/bar'))
363  call assert_equal('~f/bar', pathshorten('~foo/bar'))
364  call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
365  call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
366  call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
367endfunc
368
369func Test_strpart()
370  call assert_equal('de', strpart('abcdefg', 3, 2))
371  call assert_equal('ab', strpart('abcdefg', -2, 4))
372  call assert_equal('abcdefg', strpart('abcdefg', -2))
373  call assert_equal('fg', strpart('abcdefg', 5, 4))
374  call assert_equal('defg', strpart('abcdefg', 3))
375
376  call assert_equal('lép', strpart('éléphant', 2, 4))
377  call assert_equal('léphant', strpart('éléphant', 2))
378endfunc
379
380func Test_tolower()
381  call assert_equal("", tolower(""))
382
383  " Test with all printable ASCII characters.
384  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
385          \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
386
387  " Test with a few uppercase diacritics.
388  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
389  call assert_equal("bḃḇ", tolower("BḂḆ"))
390  call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
391  call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
392  call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
393  call assert_equal("fḟ ", tolower("FḞ "))
394  call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
395  call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
396  call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
397  call assert_equal("jĵ", tolower("JĴ"))
398  call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
399  call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
400  call assert_equal("mḿṁ", tolower("MḾṀ"))
401  call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
402  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
403  call assert_equal("pṕṗ", tolower("PṔṖ"))
404  call assert_equal("q", tolower("Q"))
405  call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
406  call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
407  call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
408  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
409  call assert_equal("vṽ", tolower("VṼ"))
410  call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
411  call assert_equal("xẋẍ", tolower("XẊẌ"))
412  call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
413  call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
414
415  " Test with a few lowercase diacritics, which should remain unchanged.
416  call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
417  call assert_equal("bḃḇ", tolower("bḃḇ"))
418  call assert_equal("cçćĉċč", tolower("cçćĉċč"))
419  call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
420  call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
421  call assert_equal("fḟ", tolower("fḟ"))
422  call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
423  call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
424  call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
425  call assert_equal("jĵǰ", tolower("jĵǰ"))
426  call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
427  call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
428  call assert_equal("mḿṁ ", tolower("mḿṁ "))
429  call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
430  call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
431  call assert_equal("pṕṗ", tolower("pṕṗ"))
432  call assert_equal("q", tolower("q"))
433  call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
434  call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
435  call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
436  call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
437  call assert_equal("vṽ", tolower("vṽ"))
438  call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
439  call assert_equal("ẋẍ", tolower("ẋẍ"))
440  call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
441  call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
442
443  " According to https://twitter.com/jifa/status/625776454479970304
444  " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
445  " in length (2 to 3 bytes) when lowercased. So let's test them.
446  call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
447
448  " This call to tolower with invalid utf8 sequence used to cause access to
449  " invalid memory.
450  call tolower("\xC0\x80\xC0")
451  call tolower("123\xC0\x80\xC0")
452endfunc
453
454func Test_toupper()
455  call assert_equal("", toupper(""))
456
457  " Test with all printable ASCII characters.
458  call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
459          \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
460
461  " Test with a few lowercase diacritics.
462  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("aàáâãäåāăąǎǟǡả"))
463  call assert_equal("BḂḆ", toupper("bḃḇ"))
464  call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
465  call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
466  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
467  call assert_equal("FḞ", toupper("fḟ"))
468  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
469  call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
470  call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
471  call assert_equal("JĴǰ", toupper("jĵǰ"))
472  call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
473  call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
474  call assert_equal("MḾṀ ", toupper("mḿṁ "))
475  call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
476  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
477  call assert_equal("PṔṖ", toupper("pṕṗ"))
478  call assert_equal("Q", toupper("q"))
479  call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
480  call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
481  call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
482  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
483  call assert_equal("VṼ", toupper("vṽ"))
484  call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
485  call assert_equal("ẊẌ", toupper("ẋẍ"))
486  call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
487  call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
488
489  " Test that uppercase diacritics, which should remain unchanged.
490  call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
491  call assert_equal("BḂḆ", toupper("BḂḆ"))
492  call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
493  call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
494  call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
495  call assert_equal("FḞ ", toupper("FḞ "))
496  call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
497  call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
498  call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
499  call assert_equal("JĴ", toupper("JĴ"))
500  call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
501  call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
502  call assert_equal("MḾṀ", toupper("MḾṀ"))
503  call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
504  call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
505  call assert_equal("PṔṖ", toupper("PṔṖ"))
506  call assert_equal("Q", toupper("Q"))
507  call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
508  call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
509  call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
510  call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
511  call assert_equal("VṼ", toupper("VṼ"))
512  call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
513  call assert_equal("XẊẌ", toupper("XẊẌ"))
514  call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
515  call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
516
517  call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
518
519  " This call to toupper with invalid utf8 sequence used to cause access to
520  " invalid memory.
521  call toupper("\xC0\x80\xC0")
522  call toupper("123\xC0\x80\xC0")
523endfunc
524
525" Tests for the mode() function
526let current_modes = ''
527func Save_mode()
528  let g:current_modes = mode(0) . '-' . mode(1)
529  return ''
530endfunc
531
532func Test_mode()
533  new
534  call append(0, ["Blue Ball Black", "Brown Band Bowl", ""])
535
536  " Only complete from the current buffer.
537  set complete=.
538
539  inoremap <F2> <C-R>=Save_mode()<CR>
540
541  normal! 3G
542  exe "normal i\<F2>\<Esc>"
543  call assert_equal('i-i', g:current_modes)
544  " i_CTRL-P: Multiple matches
545  exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
546  call assert_equal('i-ic', g:current_modes)
547  " i_CTRL-P: Single match
548  exe "normal iBro\<C-P>\<F2>\<Esc>u"
549  call assert_equal('i-ic', g:current_modes)
550  " i_CTRL-X
551  exe "normal iBa\<C-X>\<F2>\<Esc>u"
552  call assert_equal('i-ix', g:current_modes)
553  " i_CTRL-X CTRL-P: Multiple matches
554  exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
555  call assert_equal('i-ic', g:current_modes)
556  " i_CTRL-X CTRL-P: Single match
557  exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u"
558  call assert_equal('i-ic', g:current_modes)
559  " i_CTRL-X CTRL-P + CTRL-P: Single match
560  exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
561  call assert_equal('i-ic', g:current_modes)
562  " i_CTRL-X CTRL-L: Multiple matches
563  exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
564  call assert_equal('i-ic', g:current_modes)
565  " i_CTRL-X CTRL-L: Single match
566  exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
567  call assert_equal('i-ic', g:current_modes)
568  " i_CTRL-P: No match
569  exe "normal iCom\<C-P>\<F2>\<Esc>u"
570  call assert_equal('i-ic', g:current_modes)
571  " i_CTRL-X CTRL-P: No match
572  exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u"
573  call assert_equal('i-ic', g:current_modes)
574  " i_CTRL-X CTRL-L: No match
575  exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
576  call assert_equal('i-ic', g:current_modes)
577
578  " R_CTRL-P: Multiple matches
579  exe "normal RBa\<C-P>\<F2>\<Esc>u"
580  call assert_equal('R-Rc', g:current_modes)
581  " R_CTRL-P: Single match
582  exe "normal RBro\<C-P>\<F2>\<Esc>u"
583  call assert_equal('R-Rc', g:current_modes)
584  " R_CTRL-X
585  exe "normal RBa\<C-X>\<F2>\<Esc>u"
586  call assert_equal('R-Rx', g:current_modes)
587  " R_CTRL-X CTRL-P: Multiple matches
588  exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
589  call assert_equal('R-Rc', g:current_modes)
590  " R_CTRL-X CTRL-P: Single match
591  exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u"
592  call assert_equal('R-Rc', g:current_modes)
593  " R_CTRL-X CTRL-P + CTRL-P: Single match
594  exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
595  call assert_equal('R-Rc', g:current_modes)
596  " R_CTRL-X CTRL-L: Multiple matches
597  exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
598  call assert_equal('R-Rc', g:current_modes)
599  " R_CTRL-X CTRL-L: Single match
600  exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
601  call assert_equal('R-Rc', g:current_modes)
602  " R_CTRL-P: No match
603  exe "normal RCom\<C-P>\<F2>\<Esc>u"
604  call assert_equal('R-Rc', g:current_modes)
605  " R_CTRL-X CTRL-P: No match
606  exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u"
607  call assert_equal('R-Rc', g:current_modes)
608  " R_CTRL-X CTRL-L: No match
609  exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
610  call assert_equal('R-Rc', g:current_modes)
611
612  call assert_equal('n', mode(0))
613  call assert_equal('n', mode(1))
614
615  " i_CTRL-O
616  exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
617  call assert_equal("n-niI", g:current_modes)
618
619  " R_CTRL-O
620  exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
621  call assert_equal("n-niR", g:current_modes)
622
623  " gR_CTRL-O
624  exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
625  call assert_equal("n-niV", g:current_modes)
626
627  " How to test operator-pending mode?
628
629  call feedkeys("v", 'xt')
630  call assert_equal('v', mode())
631  call assert_equal('v', mode(1))
632  call feedkeys("\<Esc>V", 'xt')
633  call assert_equal('V', mode())
634  call assert_equal('V', mode(1))
635  call feedkeys("\<Esc>\<C-V>", 'xt')
636  call assert_equal("\<C-V>", mode())
637  call assert_equal("\<C-V>", mode(1))
638  call feedkeys("\<Esc>", 'xt')
639
640  call feedkeys("gh", 'xt')
641  call assert_equal('s', mode())
642  call assert_equal('s', mode(1))
643  call feedkeys("\<Esc>gH", 'xt')
644  call assert_equal('S', mode())
645  call assert_equal('S', mode(1))
646  call feedkeys("\<Esc>g\<C-H>", 'xt')
647  call assert_equal("\<C-S>", mode())
648  call assert_equal("\<C-S>", mode(1))
649  call feedkeys("\<Esc>", 'xt')
650
651  call feedkeys(":echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
652  call assert_equal('c-c', g:current_modes)
653  call feedkeys("gQecho \<C-R>=Save_mode()\<CR>\<CR>vi\<CR>", 'xt')
654  call assert_equal('c-cv', g:current_modes)
655  " How to test Ex mode?
656
657  bwipe!
658  iunmap <F2>
659  set complete&
660endfunc
661
662func Test_getbufvar()
663  let bnr = bufnr('%')
664  let b:var_num = '1234'
665  let def_num = '5678'
666  call assert_equal('1234', getbufvar(bnr, 'var_num'))
667  call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
668
669  let bd = getbufvar(bnr, '')
670  call assert_equal('1234', bd['var_num'])
671  call assert_true(exists("bd['changedtick']"))
672  call assert_equal(2, len(bd))
673
674  let bd2 = getbufvar(bnr, '', def_num)
675  call assert_equal(bd, bd2)
676
677  unlet b:var_num
678  call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
679  call assert_equal('', getbufvar(bnr, 'var_num'))
680
681  let bd = getbufvar(bnr, '')
682  call assert_equal(1, len(bd))
683  let bd = getbufvar(bnr, '',def_num)
684  call assert_equal(1, len(bd))
685
686  call assert_equal('', getbufvar(9999, ''))
687  call assert_equal(def_num, getbufvar(9999, '', def_num))
688  unlet def_num
689
690  call assert_equal(0, getbufvar(bnr, '&autoindent'))
691  call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
692
693  " Open new window with forced option values
694  set fileformats=unix,dos
695  new ++ff=dos ++bin ++enc=iso-8859-2
696  call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
697  call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
698  call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
699  close
700
701  set fileformats&
702endfunc
703
704func Test_last_buffer_nr()
705  call assert_equal(bufnr('$'), last_buffer_nr())
706endfunc
707
708func Test_stridx()
709  call assert_equal(-1, stridx('', 'l'))
710  call assert_equal(0,  stridx('', ''))
711  call assert_equal(0,  stridx('hello', ''))
712  call assert_equal(-1, stridx('hello', 'L'))
713  call assert_equal(2,  stridx('hello', 'l', -1))
714  call assert_equal(2,  stridx('hello', 'l', 0))
715  call assert_equal(2,  stridx('hello', 'l', 1))
716  call assert_equal(3,  stridx('hello', 'l', 3))
717  call assert_equal(-1, stridx('hello', 'l', 4))
718  call assert_equal(-1, stridx('hello', 'l', 10))
719  call assert_equal(2,  stridx('hello', 'll'))
720  call assert_equal(-1, stridx('hello', 'hello world'))
721endfunc
722
723func Test_strridx()
724  call assert_equal(-1, strridx('', 'l'))
725  call assert_equal(0,  strridx('', ''))
726  call assert_equal(5,  strridx('hello', ''))
727  call assert_equal(-1, strridx('hello', 'L'))
728  call assert_equal(3,  strridx('hello', 'l'))
729  call assert_equal(3,  strridx('hello', 'l', 10))
730  call assert_equal(3,  strridx('hello', 'l', 3))
731  call assert_equal(2,  strridx('hello', 'l', 2))
732  call assert_equal(-1, strridx('hello', 'l', 1))
733  call assert_equal(-1, strridx('hello', 'l', 0))
734  call assert_equal(-1, strridx('hello', 'l', -1))
735  call assert_equal(2,  strridx('hello', 'll'))
736  call assert_equal(-1, strridx('hello', 'hello world'))
737endfunc
738
739func Test_match_func()
740  call assert_equal(4,  match('testing', 'ing'))
741  call assert_equal(4,  match('testing', 'ing', 2))
742  call assert_equal(-1, match('testing', 'ing', 5))
743  call assert_equal(-1, match('testing', 'ing', 8))
744  call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
745  call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
746endfunc
747
748func Test_matchend()
749  call assert_equal(7,  matchend('testing', 'ing'))
750  call assert_equal(7,  matchend('testing', 'ing', 2))
751  call assert_equal(-1, matchend('testing', 'ing', 5))
752  call assert_equal(-1, matchend('testing', 'ing', 8))
753  call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
754  call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
755endfunc
756
757func Test_matchlist()
758  call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
759  call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
760  call assert_equal([],  matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
761endfunc
762
763func Test_matchstr()
764  call assert_equal('ing',  matchstr('testing', 'ing'))
765  call assert_equal('ing',  matchstr('testing', 'ing', 2))
766  call assert_equal('', matchstr('testing', 'ing', 5))
767  call assert_equal('', matchstr('testing', 'ing', 8))
768  call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
769  call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
770endfunc
771
772func Test_matchstrpos()
773  call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
774  call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing', 2))
775  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
776  call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
777  call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
778  call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
779endfunc
780
781func Test_nextnonblank_prevnonblank()
782  new
783insert
784This
785
786
787is
788
789a
790Test
791.
792  call assert_equal(0, nextnonblank(-1))
793  call assert_equal(0, nextnonblank(0))
794  call assert_equal(1, nextnonblank(1))
795  call assert_equal(4, nextnonblank(2))
796  call assert_equal(4, nextnonblank(3))
797  call assert_equal(4, nextnonblank(4))
798  call assert_equal(6, nextnonblank(5))
799  call assert_equal(6, nextnonblank(6))
800  call assert_equal(7, nextnonblank(7))
801  call assert_equal(0, nextnonblank(8))
802
803  call assert_equal(0, prevnonblank(-1))
804  call assert_equal(0, prevnonblank(0))
805  call assert_equal(1, prevnonblank(1))
806  call assert_equal(1, prevnonblank(2))
807  call assert_equal(1, prevnonblank(3))
808  call assert_equal(4, prevnonblank(4))
809  call assert_equal(4, prevnonblank(5))
810  call assert_equal(6, prevnonblank(6))
811  call assert_equal(7, prevnonblank(7))
812  call assert_equal(0, prevnonblank(8))
813  bw!
814endfunc
815
816func Test_byte2line_line2byte()
817  new
818  set endofline
819  call setline(1, ['a', 'bc', 'd'])
820
821  set fileformat=unix
822  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
823  \                 map(range(-1, 8), 'byte2line(v:val)'))
824  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
825  \                 map(range(-1, 5), 'line2byte(v:val)'))
826
827  set fileformat=mac
828  call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
829  \                 map(range(-1, 8), 'byte2line(v:val)'))
830  call assert_equal([-1, -1, 1, 3, 6, 8, -1],
831  \                 map(range(-1, 5), 'line2byte(v:val)'))
832
833  set fileformat=dos
834  call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
835  \                 map(range(-1, 11), 'byte2line(v:val)'))
836  call assert_equal([-1, -1, 1, 4, 8, 11, -1],
837  \                 map(range(-1, 5), 'line2byte(v:val)'))
838
839  bw!
840  set noendofline nofixendofline
841  normal a-
842  for ff in ["unix", "mac", "dos"]
843    let &fileformat = ff
844    call assert_equal(1, line2byte(1))
845    call assert_equal(2, line2byte(2))  " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
846  endfor
847
848  set endofline& fixendofline& fileformat&
849  bw!
850endfunc
851
852func Test_count()
853  let l = ['a', 'a', 'A', 'b']
854  call assert_equal(2, count(l, 'a'))
855  call assert_equal(1, count(l, 'A'))
856  call assert_equal(1, count(l, 'b'))
857  call assert_equal(0, count(l, 'B'))
858
859  call assert_equal(2, count(l, 'a', 0))
860  call assert_equal(1, count(l, 'A', 0))
861  call assert_equal(1, count(l, 'b', 0))
862  call assert_equal(0, count(l, 'B', 0))
863
864  call assert_equal(3, count(l, 'a', 1))
865  call assert_equal(3, count(l, 'A', 1))
866  call assert_equal(1, count(l, 'b', 1))
867  call assert_equal(1, count(l, 'B', 1))
868  call assert_equal(0, count(l, 'c', 1))
869
870  call assert_equal(1, count(l, 'a', 0, 1))
871  call assert_equal(2, count(l, 'a', 1, 1))
872  call assert_fails('call count(l, "a", 0, 10)', 'E684:')
873  call assert_fails('call count(l, "a", [])', 'E745:')
874
875  let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
876  call assert_equal(2, count(d, 'a'))
877  call assert_equal(1, count(d, 'A'))
878  call assert_equal(1, count(d, 'b'))
879  call assert_equal(0, count(d, 'B'))
880
881  call assert_equal(2, count(d, 'a', 0))
882  call assert_equal(1, count(d, 'A', 0))
883  call assert_equal(1, count(d, 'b', 0))
884  call assert_equal(0, count(d, 'B', 0))
885
886  call assert_equal(3, count(d, 'a', 1))
887  call assert_equal(3, count(d, 'A', 1))
888  call assert_equal(1, count(d, 'b', 1))
889  call assert_equal(1, count(d, 'B', 1))
890  call assert_equal(0, count(d, 'c', 1))
891
892  call assert_fails('call count(d, "a", 0, 1)', 'E474:')
893
894  call assert_equal(0, count("foo", "bar"))
895  call assert_equal(1, count("foo", "oo"))
896  call assert_equal(2, count("foo", "o"))
897  call assert_equal(0, count("foo", "O"))
898  call assert_equal(2, count("foo", "O", 1))
899  call assert_equal(2, count("fooooo", "oo"))
900  call assert_equal(0, count("foo", ""))
901
902  call assert_fails('call count(0, 0)', 'E712:')
903endfunc
904
905func Test_changenr()
906  new Xchangenr
907  call assert_equal(0, changenr())
908  norm ifoo
909  call assert_equal(1, changenr())
910  set undolevels=10
911  norm Sbar
912  call assert_equal(2, changenr())
913  undo
914  call assert_equal(1, changenr())
915  redo
916  call assert_equal(2, changenr())
917  bw!
918  set undolevels&
919endfunc
920
921func Test_filewritable()
922  new Xfilewritable
923  write!
924  call assert_equal(1, filewritable('Xfilewritable'))
925
926  call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
927  call assert_equal(0, filewritable('Xfilewritable'))
928
929  call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
930  call assert_equal(1, filewritable('Xfilewritable'))
931
932  call assert_equal(0, filewritable('doesnotexist'))
933
934  call delete('Xfilewritable')
935  bw!
936endfunc
937
938func Test_Executable()
939  if has('win32')
940    call assert_equal(1, executable('notepad'))
941    call assert_equal(1, executable('notepad.exe'))
942    call assert_equal(0, executable('notepad.exe.exe'))
943    call assert_equal(0, executable('shell32.dll'))
944    call assert_equal(0, executable('win.ini'))
945  elseif has('unix')
946    call assert_equal(1, executable('cat'))
947    call assert_equal(0, executable('nodogshere'))
948  endif
949endfunc
950
951func Test_executable_longname()
952  if !has('win32')
953    return
954  endif
955
956  let fname = 'X' . repeat('あ', 200) . '.bat'
957  call writefile([], fname)
958  call assert_equal(1, executable(fname))
959  call delete(fname)
960endfunc
961
962func Test_hostname()
963  let hostname_vim = hostname()
964  if has('unix')
965    let hostname_system = systemlist('uname -n')[0]
966    call assert_equal(hostname_vim, hostname_system)
967  endif
968endfunc
969
970func Test_getpid()
971  " getpid() always returns the same value within a vim instance.
972  call assert_equal(getpid(), getpid())
973  if has('unix')
974    call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
975  endif
976endfunc
977
978func Test_hlexists()
979  call assert_equal(0, hlexists('does_not_exist'))
980  call assert_equal(0, hlexists('Number'))
981  call assert_equal(0, highlight_exists('does_not_exist'))
982  call assert_equal(0, highlight_exists('Number'))
983  syntax on
984  call assert_equal(0, hlexists('does_not_exist'))
985  call assert_equal(1, hlexists('Number'))
986  call assert_equal(0, highlight_exists('does_not_exist'))
987  call assert_equal(1, highlight_exists('Number'))
988  syntax off
989endfunc
990
991func Test_col()
992  new
993  call setline(1, 'abcdef')
994  norm gg4|mx6|mY2|
995  call assert_equal(2, col('.'))
996  call assert_equal(7, col('$'))
997  call assert_equal(4, col("'x"))
998  call assert_equal(6, col("'Y"))
999  call assert_equal(2, col([1, 2]))
1000  call assert_equal(7, col([1, '$']))
1001
1002  call assert_equal(0, col(''))
1003  call assert_equal(0, col('x'))
1004  call assert_equal(0, col([2, '$']))
1005  call assert_equal(0, col([1, 100]))
1006  call assert_equal(0, col([1]))
1007  bw!
1008endfunc
1009
1010func Test_inputlist()
1011  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
1012  call assert_equal(1, c)
1013  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>2\<cr>", 'tx')
1014  call assert_equal(2, c)
1015  call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
1016  call assert_equal(3, c)
1017
1018  call assert_fails('call inputlist("")', 'E686:')
1019endfunc
1020
1021func Test_balloon_show()
1022  if has('balloon_eval')
1023    " This won't do anything but must not crash either.
1024    call balloon_show('hi!')
1025  endif
1026endfunc
1027
1028func Test_setbufvar_options()
1029  " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
1030  " window layout.
1031  call assert_equal(1, winnr('$'))
1032  split dummy_preview
1033  resize 2
1034  set winfixheight winfixwidth
1035  let prev_id = win_getid()
1036
1037  wincmd j
1038  let wh = winheight('.')
1039  let dummy_buf = bufnr('dummy_buf1', v:true)
1040  call setbufvar(dummy_buf, '&buftype', 'nofile')
1041  execute 'belowright vertical split #' . dummy_buf
1042  call assert_equal(wh, winheight('.'))
1043  let dum1_id = win_getid()
1044
1045  wincmd h
1046  let wh = winheight('.')
1047  let dummy_buf = bufnr('dummy_buf2', v:true)
1048  call setbufvar(dummy_buf, '&buftype', 'nofile')
1049  execute 'belowright vertical split #' . dummy_buf
1050  call assert_equal(wh, winheight('.'))
1051
1052  bwipe!
1053  call win_gotoid(prev_id)
1054  bwipe!
1055  call win_gotoid(dum1_id)
1056  bwipe!
1057endfunc
1058
1059func Test_redo_in_nested_functions()
1060  nnoremap g. :set opfunc=Operator<CR>g@
1061  function Operator( type, ... )
1062     let @x = 'XXX'
1063     execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
1064  endfunction
1065
1066  function! Apply()
1067      5,6normal! .
1068  endfunction
1069
1070  new
1071  call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
1072  1normal g.i"
1073  call assert_equal('some "XXX" text', getline(1))
1074  3,4normal .
1075  call assert_equal('some "XXX" text', getline(3))
1076  call assert_equal('more "XXX" text', getline(4))
1077  call Apply()
1078  call assert_equal('some "XXX" text', getline(5))
1079  call assert_equal('more "XXX" text', getline(6))
1080  bwipe!
1081
1082  nunmap g.
1083  delfunc Operator
1084  delfunc Apply
1085endfunc
1086
1087func Test_shellescape()
1088  let save_shell = &shell
1089  set shell=bash
1090  call assert_equal("'text'", shellescape('text'))
1091  call assert_equal("'te\"xt'", shellescape('te"xt'))
1092  call assert_equal("'te'\\''xt'", shellescape("te'xt"))
1093
1094  call assert_equal("'te%xt'", shellescape("te%xt"))
1095  call assert_equal("'te\\%xt'", shellescape("te%xt", 1))
1096  call assert_equal("'te#xt'", shellescape("te#xt"))
1097  call assert_equal("'te\\#xt'", shellescape("te#xt", 1))
1098  call assert_equal("'te!xt'", shellescape("te!xt"))
1099  call assert_equal("'te\\!xt'", shellescape("te!xt", 1))
1100
1101  call assert_equal("'te\nxt'", shellescape("te\nxt"))
1102  call assert_equal("'te\\\nxt'", shellescape("te\nxt", 1))
1103  set shell=tcsh
1104  call assert_equal("'te\\!xt'", shellescape("te!xt"))
1105  call assert_equal("'te\\\\!xt'", shellescape("te!xt", 1))
1106  call assert_equal("'te\\\nxt'", shellescape("te\nxt"))
1107  call assert_equal("'te\\\\\nxt'", shellescape("te\nxt", 1))
1108
1109  let &shell = save_shell
1110endfunc
1111
1112func Test_trim()
1113  call assert_equal("Testing", trim("  \t\r\r\x0BTesting  \t\n\r\n\t\x0B\x0B"))
1114  call assert_equal("Testing", trim("  \t  \r\r\n\n\x0BTesting  \t\n\r\n\t\x0B\x0B"))
1115  call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
1116  call assert_equal("wRE    \tSERVEzyww", trim("wRE    \tSERVEzyww"))
1117  call assert_equal("abcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail"))
1118  call assert_equal("\tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", " "))
1119  call assert_equal(" \tabcd\t     xxxx   tail", trim(" \tabcd\t     xxxx   tail", "abx"))
1120  call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
1121  call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
1122  call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r   你好您R E SER V E早好你你    \t  \x0B", ))
1123  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    你好您R E SER V E早好你你    \t  \x0B", " 你好"))
1124  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", " 你好tes"))
1125  call assert_equal("您R E SER V E早好你你    \t  \x0B", trim("    tteesstttt你好您R E SER V E早好你你    \t  \x0B ttestt", "   你你你好好好tttsses"))
1126  call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
1127  call assert_equal("", trim("", ""))
1128  call assert_equal("a", trim("a", ""))
1129  call assert_equal("", trim("", "a"))
1130
1131  let chars = join(map(range(1, 0x20) + [0xa0], {n -> nr2char(n)}), '')
1132  call assert_equal("x", trim(chars . "x" . chars))
1133endfunc
1134
1135" Test for reg_recording() and reg_executing()
1136func Test_reg_executing_and_recording()
1137  let s:reg_stat = ''
1138  func s:save_reg_stat()
1139    let s:reg_stat = reg_recording() . ':' . reg_executing()
1140    return ''
1141  endfunc
1142
1143  new
1144  call s:save_reg_stat()
1145  call assert_equal(':', s:reg_stat)
1146  call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
1147  call assert_equal('a:', s:reg_stat)
1148  call feedkeys("@a", 'xt')
1149  call assert_equal(':a', s:reg_stat)
1150  call feedkeys("qb@aq", 'xt')
1151  call assert_equal('b:a', s:reg_stat)
1152  call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
1153  call assert_equal('":', s:reg_stat)
1154
1155  " :normal command saves and restores reg_executing
1156  let s:reg_stat = ''
1157  let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
1158  func TestFunc() abort
1159    normal! ia
1160  endfunc
1161  call feedkeys("@q", 'xt')
1162  call assert_equal(':q', s:reg_stat)
1163  delfunc TestFunc
1164
1165  " getchar() command saves and restores reg_executing
1166  map W :call TestFunc()<CR>
1167  let @q = "W"
1168  let g:typed = ''
1169  let g:regs = []
1170  func TestFunc() abort
1171    let g:regs += [reg_executing()]
1172    let g:typed = getchar(0)
1173    let g:regs += [reg_executing()]
1174  endfunc
1175  call feedkeys("@qy", 'xt')
1176  call assert_equal(char2nr("y"), g:typed)
1177  call assert_equal(['q', 'q'], g:regs)
1178  delfunc TestFunc
1179  unmap W
1180  unlet g:typed
1181  unlet g:regs
1182
1183  " input() command saves and restores reg_executing
1184  map W :call TestFunc()<CR>
1185  let @q = "W"
1186  let g:typed = ''
1187  let g:regs = []
1188  func TestFunc() abort
1189    let g:regs += [reg_executing()]
1190    let g:typed = input('?')
1191    let g:regs += [reg_executing()]
1192  endfunc
1193  call feedkeys("@qy\<CR>", 'xt')
1194  call assert_equal("y", g:typed)
1195  call assert_equal(['q', 'q'], g:regs)
1196  delfunc TestFunc
1197  unmap W
1198  unlet g:typed
1199  unlet g:regs
1200
1201  bwipe!
1202  delfunc s:save_reg_stat
1203  unlet s:reg_stat
1204endfunc
1205
1206func Test_libcall_libcallnr()
1207  if !has('libcall')
1208    return
1209  endif
1210
1211  if has('win32')
1212    let libc = 'msvcrt.dll'
1213  elseif has('mac')
1214    let libc = 'libSystem.B.dylib'
1215  elseif executable('ldd')
1216    let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
1217  endif
1218  if get(l:, 'libc', '') ==# ''
1219    " On Unix, libc.so can be in various places.
1220    if has('linux')
1221      " There is not documented but regarding the 1st argument of glibc's
1222      " dlopen an empty string and nullptr are equivalent, so using an empty
1223      " string for the 1st argument of libcall allows to call functions.
1224      let libc = ''
1225    elseif has('sun')
1226      " Set the path to libc.so according to the architecture.
1227      let test_bits = system('file ' . GetVimProg())
1228      let test_arch = system('uname -p')
1229      if test_bits =~ '64-bit' && test_arch =~ 'sparc'
1230        let libc = '/usr/lib/sparcv9/libc.so'
1231      elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
1232        let libc = '/usr/lib/amd64/libc.so'
1233      else
1234        let libc = '/usr/lib/libc.so'
1235      endif
1236    else
1237      " Unfortunately skip this test until a good way is found.
1238      return
1239    endif
1240  endif
1241
1242  if has('win32')
1243    call assert_equal($USERPROFILE, libcall(libc, 'getenv', 'USERPROFILE'))
1244  else
1245    call assert_equal($HOME, libcall(libc, 'getenv', 'HOME'))
1246  endif
1247
1248  " If function returns NULL, libcall() should return an empty string.
1249  call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
1250
1251  " Test libcallnr() with string and integer argument.
1252  call assert_equal(4, libcallnr(libc, 'strlen', 'abcd'))
1253  call assert_equal(char2nr('A'), libcallnr(libc, 'toupper', char2nr('a')))
1254
1255  call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", 'E364:')
1256  call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", 'E364:')
1257
1258  call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", 'E364:')
1259  call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", 'E364:')
1260endfunc
1261
1262sandbox function Fsandbox()
1263  normal ix
1264endfunc
1265
1266func Test_func_sandbox()
1267  sandbox let F = {-> 'hello'}
1268  call assert_equal('hello', F())
1269
1270  sandbox let F = {-> execute("normal ix\<Esc>")}
1271  call assert_fails('call F()', 'E48:')
1272  unlet F
1273
1274  call assert_fails('call Fsandbox()', 'E48:')
1275  delfunc Fsandbox
1276endfunc
1277
1278func EditAnotherFile()
1279  let word = expand('<cword>')
1280  edit Xfuncrange2
1281endfunc
1282
1283func Test_func_range_with_edit()
1284  " Define a function that edits another buffer, then call it with a range that
1285  " is invalid in that buffer.
1286  call writefile(['just one line'], 'Xfuncrange2')
1287  new
1288  call setline(1, range(10))
1289  write Xfuncrange1
1290  call assert_fails('5,8call EditAnotherFile()', 'E16:')
1291
1292  call delete('Xfuncrange1')
1293  call delete('Xfuncrange2')
1294  bwipe!
1295endfunc
1296
1297func Test_func_exists_on_reload()
1298  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists')
1299  call assert_equal(0, exists('*ExistingFunction'))
1300  source Xfuncexists
1301  call assert_equal(1, exists('*ExistingFunction'))
1302  " Redefining a function when reloading a script is OK.
1303  source Xfuncexists
1304  call assert_equal(1, exists('*ExistingFunction'))
1305
1306  " But redefining in another script is not OK.
1307  call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2')
1308  call assert_fails('source Xfuncexists2', 'E122:')
1309
1310  delfunc ExistingFunction
1311  call assert_equal(0, exists('*ExistingFunction'))
1312  call writefile([
1313	\ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
1314	\ 'func ExistingFunction()', 'echo "no"', 'endfunc',
1315	\ ], 'Xfuncexists')
1316  call assert_fails('source Xfuncexists', 'E122:')
1317  call assert_equal(1, exists('*ExistingFunction'))
1318
1319  call delete('Xfuncexists2')
1320  call delete('Xfuncexists')
1321  delfunc ExistingFunction
1322endfunc
1323
1324" Test confirm({msg} [, {choices} [, {default} [, {type}]]])
1325func Test_confirm()
1326  if !has('unix') || has('gui_running')
1327    return
1328  endif
1329
1330  call feedkeys('o', 'L')
1331  let a = confirm('Press O to proceed')
1332  call assert_equal(1, a)
1333
1334  call feedkeys('y', 'L')
1335  let a = confirm('Are you sure?', "&Yes\n&No")
1336  call assert_equal(1, a)
1337
1338  call feedkeys('n', 'L')
1339  let a = confirm('Are you sure?', "&Yes\n&No")
1340  call assert_equal(2, a)
1341
1342  " confirm() should return 0 when pressing CTRL-C.
1343  call feedkeys("\<C-c>", 'L')
1344  let a = confirm('Are you sure?', "&Yes\n&No")
1345  call assert_equal(0, a)
1346
1347  " <Esc> requires another character to avoid it being seen as the start of an
1348  " escape sequence.  Zero should be harmless.
1349  call feedkeys("\<Esc>0", 'L')
1350  let a = confirm('Are you sure?', "&Yes\n&No")
1351  call assert_equal(0, a)
1352
1353  " Default choice is returned when pressing <CR>.
1354  call feedkeys("\<CR>", 'L')
1355  let a = confirm('Are you sure?', "&Yes\n&No")
1356  call assert_equal(1, a)
1357
1358  call feedkeys("\<CR>", 'L')
1359  let a = confirm('Are you sure?', "&Yes\n&No", 2)
1360  call assert_equal(2, a)
1361
1362  call feedkeys("\<CR>", 'L')
1363  let a = confirm('Are you sure?', "&Yes\n&No", 0)
1364  call assert_equal(0, a)
1365
1366  " Test with the {type} 4th argument
1367  for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
1368    call feedkeys('y', 'L')
1369    let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
1370    call assert_equal(1, a)
1371  endfor
1372
1373  call assert_fails('call confirm([])', 'E730:')
1374  call assert_fails('call confirm("Are you sure?", [])', 'E730:')
1375  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
1376  call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
1377endfunc
1378
1379func Test_platform_name()
1380  " The system matches at most only one name.
1381  let names = ['amiga', 'beos', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
1382  call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
1383
1384  " Is Unix?
1385  call assert_equal(has('beos'), has('beos') && has('unix'))
1386  call assert_equal(has('bsd'), has('bsd') && has('unix'))
1387  call assert_equal(has('hpux'), has('hpux') && has('unix'))
1388  call assert_equal(has('linux'), has('linux') && has('unix'))
1389  call assert_equal(has('mac'), has('mac') && has('unix'))
1390  call assert_equal(has('qnx'), has('qnx') && has('unix'))
1391  call assert_equal(has('sun'), has('sun') && has('unix'))
1392  call assert_equal(has('win32'), has('win32') && !has('unix'))
1393  call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
1394
1395  if has('unix') && executable('uname')
1396    let uname = system('uname')
1397    call assert_equal(uname =~? 'BeOS', has('beos'))
1398    " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
1399    call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
1400    call assert_equal(uname =~? 'HP-UX', has('hpux'))
1401    call assert_equal(uname =~? 'Linux', has('linux'))
1402    call assert_equal(uname =~? 'Darwin', has('mac'))
1403    call assert_equal(uname =~? 'QNX', has('qnx'))
1404    call assert_equal(uname =~? 'SunOS', has('sun'))
1405    call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
1406  endif
1407endfunc
1408
1409func Test_readdir()
1410  call mkdir('Xdir')
1411  call writefile([], 'Xdir/foo.txt')
1412  call writefile([], 'Xdir/bar.txt')
1413  call mkdir('Xdir/dir')
1414
1415  " All results
1416  let files = readdir('Xdir')
1417  call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
1418
1419  " Only results containing "f"
1420  let files = readdir('Xdir', { x -> stridx(x, 'f') !=- 1 })
1421  call assert_equal(['foo.txt'], sort(files))
1422
1423  " Only .txt files
1424  let files = readdir('Xdir', { x -> x =~ '.txt$' })
1425  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
1426
1427  " Only .txt files with string
1428  let files = readdir('Xdir', 'v:val =~ ".txt$"')
1429  call assert_equal(['bar.txt', 'foo.txt'], sort(files))
1430
1431  " Limit to 1 result.
1432  let l = []
1433  let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1})
1434  call assert_equal(1, len(files))
1435
1436  call delete('Xdir', 'rf')
1437endfunc
1438
1439func Test_call()
1440  call assert_equal(3, call('len', [123]))
1441  call assert_fails("call call('len', 123)", 'E714:')
1442  call assert_equal(0, call('', []))
1443
1444  function Mylen() dict
1445     return len(self.data)
1446  endfunction
1447  let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
1448  call assert_fails("call call('Mylen', [], 0)", 'E715:')
1449endfunc
1450
1451func Test_char2nr()
1452  call assert_equal(12354, char2nr('あ', 1))
1453endfunc
1454
1455func Test_eventhandler()
1456  call assert_equal(0, eventhandler())
1457endfunc
1458