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