blob: 847987b55b6bc959eb55e680eb37cab997b96b60 [file] [log] [blame]
Bram Moolenaar08243d22017-01-10 16:12:29 +01001" Tests for various functions.
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002
Bram Moolenaarf1c118b2018-09-03 22:08:10 +02003source shared.vim
Bram Moolenaar8c5a2782019-08-07 23:07:07 +02004source check.vim
Bram Moolenaarc2585492019-09-22 21:29:53 +02005source term_util.vim
Bram Moolenaar4132eb52020-02-14 16:53:00 +01006source screendump.vim
Bram Moolenaar62aec932022-01-29 21:45:34 +00007import './vim9.vim' as v9
Bram Moolenaar08243d22017-01-10 16:12:29 +01008
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +01009" Must be done first, since the alternate buffer must be unset.
10func Test_00_bufexists()
11 call assert_equal(0, bufexists('does_not_exist'))
12 call assert_equal(1, bufexists(bufnr('%')))
13 call assert_equal(0, bufexists(0))
14 new Xfoo
15 let bn = bufnr('%')
16 call assert_equal(1, bufexists(bn))
17 call assert_equal(1, bufexists('Xfoo'))
18 call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
19 call assert_equal(1, bufexists(0))
20 bw
21 call assert_equal(0, bufexists(bn))
22 call assert_equal(0, bufexists('Xfoo'))
23endfunc
24
Bram Moolenaar79296512020-03-22 16:17:14 +010025func Test_has()
26 call assert_equal(1, has('eval'))
27 call assert_equal(1, has('eval', 1))
28
Bram Moolenaar0e05de42020-03-25 22:23:46 +010029 if has('unix')
30 call assert_equal(1, or(has('ttyin'), 1))
31 call assert_equal(0, and(has('ttyout'), 0))
32 call assert_equal(1, has('multi_byte_encoding'))
Bram Moolenaar80adaa82023-07-07 18:57:40 +010033 call assert_equal(0, has(':tearoff'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010034 endif
Bram Moolenaar99fa7212020-04-26 15:59:55 +020035 call assert_equal(1, has('vcon', 1))
36 call assert_equal(1, has('mouse_gpm_enabled', 1))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010037
Bram Moolenaar80adaa82023-07-07 18:57:40 +010038 call assert_equal(has('gui_win32') && has('menu'), has(':tearoff'))
39
Bram Moolenaar79296512020-03-22 16:17:14 +010040 call assert_equal(0, has('nonexistent'))
41 call assert_equal(0, has('nonexistent', 1))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010042
43 " Will we ever have patch 9999?
44 let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999'
45 call assert_equal(0, has(ver))
Bram Moolenaarb0375d42022-06-30 11:03:39 +010046
47 " There actually isn't a patch 9.0.0, but this is more consistent.
48 call assert_equal(1, has('patch-9.0.0'))
Bram Moolenaar79296512020-03-22 16:17:14 +010049endfunc
50
Bram Moolenaar24c2e482017-01-29 15:45:12 +010051func Test_empty()
52 call assert_equal(1, empty(''))
53 call assert_equal(0, empty('a'))
54
55 call assert_equal(1, empty(0))
56 call assert_equal(1, empty(-0))
57 call assert_equal(0, empty(1))
58 call assert_equal(0, empty(-1))
59
Bram Moolenaar73e28dc2022-09-17 21:08:33 +010060 call assert_equal(1, empty(0.0))
61 call assert_equal(1, empty(-0.0))
62 call assert_equal(0, empty(1.0))
63 call assert_equal(0, empty(-1.0))
64 call assert_equal(0, empty(1.0/0.0))
65 call assert_equal(0, empty(0.0/0.0))
Bram Moolenaar24c2e482017-01-29 15:45:12 +010066
67 call assert_equal(1, empty([]))
68 call assert_equal(0, empty(['a']))
69
70 call assert_equal(1, empty({}))
71 call assert_equal(0, empty({'a':1}))
72
73 call assert_equal(1, empty(v:null))
74 call assert_equal(1, empty(v:none))
75 call assert_equal(1, empty(v:false))
76 call assert_equal(0, empty(v:true))
77
Bram Moolenaar41042f32017-03-09 12:09:32 +010078 if has('channel')
79 call assert_equal(1, empty(test_null_channel()))
80 endif
81 if has('job')
82 call assert_equal(1, empty(test_null_job()))
83 endif
84
Bram Moolenaar24c2e482017-01-29 15:45:12 +010085 call assert_equal(0, empty(function('Test_empty')))
Bram Moolenaar17aca702019-05-16 22:24:55 +020086 call assert_equal(0, empty(function('Test_empty', [0])))
Bram Moolenaar7c215c52020-02-29 13:43:27 +010087
Bram Moolenaar097c5372023-05-24 21:02:24 +010088 call assert_fails("call empty(test_void())", ['E340:', 'E685:'])
89 call assert_fails("call empty(test_unknown())", ['E340:', 'E685:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +010090endfunc
91
Bram Moolenaar80adaa82023-07-07 18:57:40 +010092func Test_err_teapot()
93 call assert_fails('call err_teapot()', "E418: I'm a teapot")
94 call assert_fails('call err_teapot(0)', "E418: I'm a teapot")
95 call assert_fails('call err_teapot(v:false)', "E418: I'm a teapot")
96
97 call assert_fails('call err_teapot("1")', "E503: Coffee is currently not available")
98 call assert_fails('call err_teapot(v:true)', "E503: Coffee is currently not available")
99 let expr = 1
100 call assert_fails('call err_teapot(expr)', "E503: Coffee is currently not available")
101endfunc
102
Bram Moolenaardd589232020-02-29 17:38:12 +0100103func Test_test_void()
Bram Moolenaar61a417b2021-06-15 22:54:28 +0200104 call assert_fails('echo 1 == test_void()', 'E1031:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100105 call assert_fails('echo 1.0 == test_void()', 'E1031:')
Bram Moolenaar097c5372023-05-24 21:02:24 +0100106 call assert_fails('let x = json_encode(test_void())', ['E340:', 'E685:'])
107 call assert_fails('let x = copy(test_void())', ['E340:', 'E685:'])
Bram Moolenaar61a417b2021-06-15 22:54:28 +0200108 call assert_fails('let x = copy([test_void()])', 'E1031:')
Bram Moolenaardd589232020-02-29 17:38:12 +0100109endfunc
110
Bram Moolenaar1840a7b2021-07-13 20:32:29 +0200111func Test_islocked()
112 call assert_fails('call islocked(99)', 'E475:')
113 call assert_fails('call islocked("s: x")', 'E488:')
114endfunc
115
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100116func Test_len()
117 call assert_equal(1, len(0))
118 call assert_equal(2, len(12))
119
120 call assert_equal(0, len(''))
121 call assert_equal(2, len('ab'))
122
123 call assert_equal(0, len([]))
Bram Moolenaar08f41572020-04-20 16:50:00 +0200124 call assert_equal(0, len(test_null_list()))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100125 call assert_equal(2, len([2, 1]))
126
127 call assert_equal(0, len({}))
Bram Moolenaar08f41572020-04-20 16:50:00 +0200128 call assert_equal(0, len(test_null_dict()))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100129 call assert_equal(2, len({'a': 1, 'b': 2}))
130
131 call assert_fails('call len(v:none)', 'E701:')
132 call assert_fails('call len({-> 0})', 'E701:')
133endfunc
134
135func Test_max()
136 call assert_equal(0, max([]))
137 call assert_equal(2, max([2]))
138 call assert_equal(2, max([1, 2]))
139 call assert_equal(2, max([1, 2, v:null]))
140
141 call assert_equal(0, max({}))
142 call assert_equal(2, max({'a':1, 'b':2}))
143
144 call assert_fails('call max(1)', 'E712:')
145 call assert_fails('call max(v:none)', 'E712:')
Bram Moolenaarab65fc72021-02-04 22:07:16 +0100146
147 " check we only get one error
148 call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:'])
149 call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100150endfunc
151
152func Test_min()
153 call assert_equal(0, min([]))
154 call assert_equal(2, min([2]))
155 call assert_equal(1, min([1, 2]))
156 call assert_equal(0, min([1, 2, v:null]))
157
158 call assert_equal(0, min({}))
159 call assert_equal(1, min({'a':1, 'b':2}))
160
161 call assert_fails('call min(1)', 'E712:')
162 call assert_fails('call min(v:none)', 'E712:')
Yegappan Lakshmanan34fcb692021-05-25 20:14:00 +0200163 call assert_fails('call min([1, {}])', 'E728:')
Bram Moolenaarab65fc72021-02-04 22:07:16 +0100164
165 " check we only get one error
166 call assert_fails('call min([[1], #{}])', ['E745:', 'E745:'])
167 call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100168endfunc
169
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200170func Test_strwidth()
171 for aw in ['single', 'double']
172 exe 'set ambiwidth=' . aw
173 call assert_equal(0, strwidth(''))
174 call assert_equal(1, strwidth("\t"))
175 call assert_equal(3, strwidth('Vim'))
176 call assert_equal(4, strwidth(1234))
177 call assert_equal(5, strwidth(-1234))
178
Bram Moolenaar30276f22019-01-24 17:59:39 +0100179 call assert_equal(2, strwidth('😉'))
180 call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
181 call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200182
183 call assert_fails('call strwidth({->0})', 'E729:')
184 call assert_fails('call strwidth([])', 'E730:')
185 call assert_fails('call strwidth({})', 'E731:')
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200186 endfor
187
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100188 call assert_equal(3, strwidth(1.2))
189 call v9.CheckDefAndScriptFailure(['echo strwidth(1.2)'], ['E1013: Argument 1: type mismatch, expected string but got float', 'E1174: String required for argument 1'])
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +0200190
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200191 set ambiwidth&
192endfunc
193
Bram Moolenaar08243d22017-01-10 16:12:29 +0100194func Test_str2nr()
195 call assert_equal(0, str2nr(''))
196 call assert_equal(1, str2nr('1'))
197 call assert_equal(1, str2nr(' 1 '))
198
199 call assert_equal(1, str2nr('+1'))
200 call assert_equal(1, str2nr('+ 1'))
201 call assert_equal(1, str2nr(' + 1 '))
202
203 call assert_equal(-1, str2nr('-1'))
204 call assert_equal(-1, str2nr('- 1'))
205 call assert_equal(-1, str2nr(' - 1 '))
206
207 call assert_equal(123456789, str2nr('123456789'))
208 call assert_equal(-123456789, str2nr('-123456789'))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100209
210 call assert_equal(5, str2nr('101', 2))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200211 call assert_equal(5, '0b101'->str2nr(2))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100212 call assert_equal(5, str2nr('0B101', 2))
213 call assert_equal(-5, str2nr('-101', 2))
214 call assert_equal(-5, str2nr('-0b101', 2))
215 call assert_equal(-5, str2nr('-0B101', 2))
216
217 call assert_equal(65, str2nr('101', 8))
218 call assert_equal(65, str2nr('0101', 8))
219 call assert_equal(-65, str2nr('-101', 8))
220 call assert_equal(-65, str2nr('-0101', 8))
Bram Moolenaarc17e66c2020-06-02 21:38:22 +0200221 call assert_equal(65, str2nr('0o101', 8))
222 call assert_equal(65, str2nr('0O0101', 8))
223 call assert_equal(-65, str2nr('-0O101', 8))
224 call assert_equal(-65, str2nr('-0o0101', 8))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100225
226 call assert_equal(11259375, str2nr('abcdef', 16))
227 call assert_equal(11259375, str2nr('ABCDEF', 16))
228 call assert_equal(-11259375, str2nr('-ABCDEF', 16))
229 call assert_equal(11259375, str2nr('0xabcdef', 16))
230 call assert_equal(11259375, str2nr('0Xabcdef', 16))
231 call assert_equal(11259375, str2nr('0XABCDEF', 16))
232 call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
233
Bram Moolenaar60a8de22019-09-15 14:33:22 +0200234 call assert_equal(1, str2nr("1'000'000", 10, 0))
235 call assert_equal(256, str2nr("1'0000'0000", 2, 1))
236 call assert_equal(262144, str2nr("1'000'000", 8, 1))
237 call assert_equal(1000000, str2nr("1'000'000", 10, 1))
Bram Moolenaarea8dcf82019-09-15 21:12:22 +0200238 call assert_equal(1000, str2nr("1'000''000", 10, 1))
Bram Moolenaar60a8de22019-09-15 14:33:22 +0200239 call assert_equal(65536, str2nr("1'00'00", 16, 1))
240
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100241 call assert_equal(0, str2nr('0x10'))
242 call assert_equal(0, str2nr('0b10'))
Bram Moolenaarc17e66c2020-06-02 21:38:22 +0200243 call assert_equal(0, str2nr('0o10'))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100244 call assert_equal(1, str2nr('12', 2))
245 call assert_equal(1, str2nr('18', 8))
246 call assert_equal(1, str2nr('1g', 16))
247
248 call assert_equal(0, str2nr(v:null))
249 call assert_equal(0, str2nr(v:none))
250
251 call assert_fails('call str2nr([])', 'E730:')
252 call assert_fails('call str2nr({->2})', 'E729:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100253 call assert_equal(1, str2nr(1.2))
254 call v9.CheckDefAndScriptFailure(['echo str2nr(1.2)'], ['E1013: Argument 1: type mismatch, expected string but got float', 'E1174: String required for argument 1'])
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200255 call assert_fails('call str2nr(10, [])', 'E745:')
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100256endfunc
257
258func Test_strftime()
Bram Moolenaar10455d42019-11-21 15:36:18 +0100259 CheckFunction strftime
260
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100261 " Format of strftime() depends on system. We assume
262 " that basic formats tested here are available and
263 " identical on all systems which support strftime().
264 "
265 " The 2nd parameter of strftime() is a local time, so the output day
266 " of strftime() can be 17 or 18, depending on timezone.
267 call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
268 "
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200269 call assert_match('^\d\d\d\d-\(0\d\|1[012]\)-\([012]\d\|3[01]\) \([01]\d\|2[0-3]\):[0-5]\d:\([0-5]\d\|60\)$', '%Y-%m-%d %H:%M:%S'->strftime())
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100270
271 call assert_fails('call strftime([])', 'E730:')
272 call assert_fails('call strftime("%Y", [])', 'E745:')
Bram Moolenaardb517302019-06-18 22:53:24 +0200273
274 " Check that the time changes after we change the timezone
275 " Save previous timezone value, if any
276 if exists('$TZ')
277 let tz = $TZ
278 endif
279
James McCoyea997ed2024-10-12 11:36:58 +0200280 " Force different time zones, save the current hour (24-hour clock) for each
281 let $TZ = 'GMT+1' | let one = strftime('%H')
282 let $TZ = 'GMT+2' | let two = strftime('%H')
Bram Moolenaardb517302019-06-18 22:53:24 +0200283
284 " Those hours should be two bytes long, and should not be the same; if they
285 " are, a tzset(3) call may have failed somewhere
James McCoyea997ed2024-10-12 11:36:58 +0200286 call assert_equal(strlen(one), 2)
287 call assert_equal(strlen(two), 2)
Bram Moolenaar87652a72019-06-18 23:07:37 +0200288 " TODO: this fails on MS-Windows
289 if has('unix')
James McCoyea997ed2024-10-12 11:36:58 +0200290 call assert_notequal(one, two)
Bram Moolenaar87652a72019-06-18 23:07:37 +0200291 endif
Bram Moolenaardb517302019-06-18 22:53:24 +0200292
293 " If we cached a timezone value, put it back, otherwise clear it
294 if exists('tz')
295 let $TZ = tz
296 else
297 unlet $TZ
298 endif
Bram Moolenaar10455d42019-11-21 15:36:18 +0100299endfunc
Bram Moolenaardb517302019-06-18 22:53:24 +0200300
Bram Moolenaar10455d42019-11-21 15:36:18 +0100301func Test_strptime()
302 CheckFunction strptime
Christian Brabandt983d8082023-09-10 19:06:09 +0200303 CheckNotBSD
Bram Moolenaar10455d42019-11-21 15:36:18 +0100304
305 if exists('$TZ')
306 let tz = $TZ
307 endif
308 let $TZ = 'UTC'
309
Bram Moolenaar9a838fe2019-12-06 12:45:01 +0100310 call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
Bram Moolenaar10455d42019-11-21 15:36:18 +0100311
Bram Moolenaarea1233f2020-06-10 16:54:13 +0200312 " Force DST and check that it's considered
313 let $TZ = 'WINTER0SUMMER,J1,J365'
314 call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
315
Bram Moolenaar10455d42019-11-21 15:36:18 +0100316 call assert_fails('call strptime()', 'E119:')
317 call assert_fails('call strptime("xxx")', 'E119:')
Christian Brabandte5f7cd02023-09-10 19:25:26 +0200318 " This fails on BSD 14 and returns
Christian Brabandt983d8082023-09-10 19:06:09 +0200319 " -2209078800 instead of 0
Bram Moolenaar10455d42019-11-21 15:36:18 +0100320 call assert_equal(0, strptime("%Y", ''))
321 call assert_equal(0, strptime("%Y", "xxx"))
322
323 if exists('tz')
324 let $TZ = tz
325 else
326 unlet $TZ
327 endif
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100328endfunc
329
Bram Moolenaardce1e892019-02-10 23:18:53 +0100330func Test_resolve_unix()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +0200331 CheckUnix
Bram Moolenaar26109902018-10-06 15:43:17 +0200332
333 " Xlink1 -> Xlink2
334 " Xlink2 -> Xlink3
335 silent !ln -s -f Xlink2 Xlink1
336 silent !ln -s -f Xlink3 Xlink2
337 call assert_equal('Xlink3', resolve('Xlink1'))
338 call assert_equal('./Xlink3', resolve('./Xlink1'))
339 call assert_equal('Xlink3/', resolve('Xlink2/'))
340 " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
341 "call assert_equal('Xlink3/', resolve('Xlink1/'))
342 "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
343 "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
344 call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
345
346 " Test resolve() with a symlink cycle.
347 " Xlink1 -> Xlink2
348 " Xlink2 -> Xlink3
349 " Xlink3 -> Xlink1
350 silent !ln -s -f Xlink1 Xlink3
351 call assert_fails('call resolve("Xlink1")', 'E655:')
352 call assert_fails('call resolve("./Xlink1")', 'E655:')
353 call assert_fails('call resolve("Xlink2")', 'E655:')
354 call assert_fails('call resolve("Xlink3")', 'E655:')
355 call delete('Xlink1')
356 call delete('Xlink2')
357 call delete('Xlink3')
358
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +0100359 silent !ln -s -f Xresolvedir//Xfile Xresolvelink
360 call assert_equal('Xresolvedir/Xfile', resolve('Xresolvelink'))
361 call delete('Xresolvelink')
Bram Moolenaar26109902018-10-06 15:43:17 +0200362
363 silent !ln -s -f Xlink2/ Xlink1
Bram Moolenaara0d1fef2019-09-04 22:29:14 +0200364 call assert_equal('Xlink2', 'Xlink1'->resolve())
Bram Moolenaar26109902018-10-06 15:43:17 +0200365 call assert_equal('Xlink2/', resolve('Xlink1/'))
366 call delete('Xlink1')
367
368 silent !ln -s -f ./Xlink2 Xlink1
369 call assert_equal('Xlink2', resolve('Xlink1'))
370 call assert_equal('./Xlink2', resolve('./Xlink1'))
371 call delete('Xlink1')
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +0200372
373 call assert_equal('/', resolve('/'))
Bram Moolenaar26109902018-10-06 15:43:17 +0200374endfunc
375
Bram Moolenaardce1e892019-02-10 23:18:53 +0100376func s:normalize_fname(fname)
377 let ret = substitute(a:fname, '\', '/', 'g')
378 let ret = substitute(ret, '//', '/', 'g')
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200379 return ret->tolower()
Bram Moolenaardce1e892019-02-10 23:18:53 +0100380endfunc
381
382func Test_resolve_win32()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +0200383 CheckMSWindows
Bram Moolenaardce1e892019-02-10 23:18:53 +0100384
385 " test for shortcut file
386 if executable('cscript')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100387 new Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100388 wq
Bram Moolenaare7eb9272019-06-24 00:58:07 +0200389 let lines =<< trim END
390 Set fs = CreateObject("Scripting.FileSystemObject")
391 Set ws = WScript.CreateObject("WScript.Shell")
392 Set shortcut = ws.CreateShortcut("Xlink.lnk")
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100393 shortcut.TargetPath = fs.BuildPath(ws.CurrentDirectory, "Xresfile")
Bram Moolenaare7eb9272019-06-24 00:58:07 +0200394 shortcut.Save
395 END
396 call writefile(lines, 'link.vbs')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100397 silent !cscript link.vbs
398 call delete('link.vbs')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100399 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink.lnk')))
400 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100401
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100402 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink.lnk')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100403 call delete('Xlink.lnk')
404 else
405 echomsg 'skipped test for shortcut file'
406 endif
407
408 " remove files
409 call delete('Xlink')
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100410 call delete('Xdir', 'd')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100411 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100412
413 " test for symbolic link to a file
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100414 new Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100415 wq
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100416 call assert_equal('Xresfile', resolve('Xresfile'))
417 silent !mklink Xlink Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100418 if !v:shell_error
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100419 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100420 call delete('Xlink')
421 else
422 echomsg 'skipped test for symbolic link to a file'
423 endif
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100424 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100425
426 " test for junction to a directory
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100427 call mkdir('Xdir')
428 silent !mklink /J Xlink Xdir
Bram Moolenaardce1e892019-02-10 23:18:53 +0100429 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100430 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100431
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100432 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100433
434 " test for junction already removed
435 call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
436 call delete('Xlink')
437 else
438 echomsg 'skipped test for junction to a directory'
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100439 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100440 endif
441
442 " test for symbolic link to a directory
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100443 call mkdir('Xdir')
444 silent !mklink /D Xlink Xdir
Bram Moolenaardce1e892019-02-10 23:18:53 +0100445 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100446 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100447
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100448 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100449
450 " test for symbolic link already removed
451 call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
452 call delete('Xlink')
453 else
454 echomsg 'skipped test for symbolic link to a directory'
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100455 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100456 endif
457
458 " test for buffer name
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100459 new Xbuffile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100460 wq
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100461 silent !mklink Xlink Xbuffile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100462 if !v:shell_error
463 edit Xlink
464 call assert_equal('Xlink', bufname('%'))
465 call delete('Xlink')
466 bw!
467 else
468 echomsg 'skipped test for buffer name'
469 endif
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100470 call delete('Xbuffile')
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200471
472 " test for reparse point
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100473 call mkdir('Xdir')
474 call assert_equal('Xdir', resolve('Xdir'))
475 silent !mklink /D Xdirlink Xdir
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200476 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100477 w Xdir/text.txt
478 call assert_equal('Xdir/text.txt', resolve('Xdir/text.txt'))
479 call assert_equal(s:normalize_fname(getcwd() . '\Xdir\text.txt'), s:normalize_fname(resolve('Xdirlink\text.txt')))
480 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve('Xdirlink')))
Bram Moolenaar4a792c82019-06-06 12:22:41 +0200481 call delete('Xdirlink')
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200482 else
483 echomsg 'skipped test for reparse point'
484 endif
485
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100486 call delete('Xdir', 'rf')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100487endfunc
488
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100489func Test_simplify()
490 call assert_equal('', simplify(''))
491 call assert_equal('/', simplify('/'))
492 call assert_equal('/', simplify('/.'))
493 call assert_equal('/', simplify('/..'))
494 call assert_equal('/...', simplify('/...'))
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +0200495 call assert_equal('//path', simplify('//path'))
Bram Moolenaarc70222d2020-06-15 23:18:12 +0200496 if has('unix')
497 call assert_equal('/path', simplify('///path'))
498 call assert_equal('/path', simplify('////path'))
499 endif
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +0200500
Bram Moolenaar7035fd92020-04-08 20:03:52 +0200501 call assert_equal('./dir/file', './dir/file'->simplify())
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100502 call assert_equal('./dir/file', simplify('.///dir//file'))
503 call assert_equal('./dir/file', simplify('./dir/./file'))
504 call assert_equal('./file', simplify('./dir/../file'))
505 call assert_equal('../dir/file', simplify('dir/../../dir/file'))
506 call assert_equal('./file', simplify('dir/.././file'))
Bram Moolenaarbdd2c292020-06-22 21:34:30 +0200507 call assert_equal('../dir', simplify('./../dir'))
508 call assert_equal('..', simplify('../testdir/..'))
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +0100509 call mkdir('Xsimpdir')
510 call assert_equal('.', simplify('Xsimpdir/../.'))
511 call delete('Xsimpdir', 'd')
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100512
513 call assert_fails('call simplify({->0})', 'E729:')
514 call assert_fails('call simplify([])', 'E730:')
515 call assert_fails('call simplify({})', 'E731:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100516 call assert_equal('1.2', simplify(1.2))
517 call v9.CheckDefAndScriptFailure(['echo simplify(1.2)'], ['E1013: Argument 1: type mismatch, expected string but got float', 'E1174: String required for argument 1'])
Bram Moolenaar08243d22017-01-10 16:12:29 +0100518endfunc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100519
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200520func Test_pathshorten()
521 call assert_equal('', pathshorten(''))
522 call assert_equal('foo', pathshorten('foo'))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +0200523 call assert_equal('/foo', '/foo'->pathshorten())
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200524 call assert_equal('f/', pathshorten('foo/'))
525 call assert_equal('f/bar', pathshorten('foo/bar'))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +0200526 call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten())
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200527 call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
528 call assert_equal('.f/bar', pathshorten('.foo/bar'))
529 call assert_equal('~f/bar', pathshorten('~foo/bar'))
530 call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
531 call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
532 call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
Bram Moolenaar92b83cc2020-04-25 15:24:44 +0200533 call assert_fails('call pathshorten([])', 'E730:')
Bram Moolenaar6a33ef02020-09-25 22:42:48 +0200534
535 " test pathshorten with optional variable to set preferred size of shortening
536 call assert_equal('', pathshorten('', 2))
537 call assert_equal('foo', pathshorten('foo', 2))
538 call assert_equal('/foo', pathshorten('/foo', 2))
539 call assert_equal('fo/', pathshorten('foo/', 2))
540 call assert_equal('fo/bar', pathshorten('foo/bar', 2))
541 call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2))
542 call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2))
543 call assert_equal('.fo/bar', pathshorten('.foo/bar', 2))
544 call assert_equal('~fo/bar', pathshorten('~foo/bar', 2))
545 call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2))
546 call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2))
547 call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2))
548 call assert_fails('call pathshorten([],2)', 'E730:')
549 call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3))
550 call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3))
551 call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0))
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200552endfunc
553
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100554func Test_strpart()
555 call assert_equal('de', strpart('abcdefg', 3, 2))
556 call assert_equal('ab', strpart('abcdefg', -2, 4))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200557 call assert_equal('abcdefg', 'abcdefg'->strpart(-2))
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100558 call assert_equal('fg', strpart('abcdefg', 5, 4))
559 call assert_equal('defg', strpart('abcdefg', 3))
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100560 call assert_equal('', strpart('abcdefg', 10))
561 call assert_fails("let s=strpart('abcdef', [])", 'E745:')
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100562
Bram Moolenaar30276f22019-01-24 17:59:39 +0100563 call assert_equal('lép', strpart('éléphant', 2, 4))
564 call assert_equal('léphant', strpart('éléphant', 2))
Bram Moolenaar6c53fca2020-08-23 17:34:46 +0200565
566 call assert_equal('é', strpart('éléphant', 0, 1, 1))
567 call assert_equal('ép', strpart('éléphant', 3, 2, v:true))
568 call assert_equal('ó', strpart('cómposed', 1, 1, 1))
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100569endfunc
570
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100571func Test_tolower()
572 call assert_equal("", tolower(""))
573
574 " Test with all printable ASCII characters.
575 call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
576 \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
577
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100578 " Test with a few uppercase diacritics.
579 call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
580 call assert_equal("bḃḇ", tolower("BḂḆ"))
581 call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
582 call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
583 call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
584 call assert_equal("fḟ ", tolower("FḞ "))
585 call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
586 call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
587 call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
588 call assert_equal("jĵ", tolower("JĴ"))
589 call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
590 call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
591 call assert_equal("mḿṁ", tolower("MḾṀ"))
592 call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
593 call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
594 call assert_equal("pṕṗ", tolower("PṔṖ"))
595 call assert_equal("q", tolower("Q"))
596 call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
597 call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
598 call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
599 call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
600 call assert_equal("vṽ", tolower("VṼ"))
601 call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
602 call assert_equal("xẋẍ", tolower("XẊẌ"))
603 call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
604 call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
605
606 " Test with a few lowercase diacritics, which should remain unchanged.
607 call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
608 call assert_equal("bḃḇ", tolower("bḃḇ"))
609 call assert_equal("cçćĉċč", tolower("cçćĉċč"))
610 call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
611 call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
612 call assert_equal("fḟ", tolower("fḟ"))
613 call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
614 call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
615 call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
616 call assert_equal("jĵǰ", tolower("jĵǰ"))
617 call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
618 call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
619 call assert_equal("mḿṁ ", tolower("mḿṁ "))
620 call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
621 call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
622 call assert_equal("pṕṗ", tolower("pṕṗ"))
623 call assert_equal("q", tolower("q"))
624 call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
625 call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
626 call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
627 call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
628 call assert_equal("vṽ", tolower("vṽ"))
629 call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
630 call assert_equal("ẋẍ", tolower("ẋẍ"))
631 call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
632 call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
633
634 " According to https://twitter.com/jifa/status/625776454479970304
635 " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
636 " in length (2 to 3 bytes) when lowercased. So let's test them.
637 call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
Bram Moolenaare6640ad2017-12-22 21:06:56 +0100638
639 " This call to tolower with invalid utf8 sequence used to cause access to
640 " invalid memory.
641 call tolower("\xC0\x80\xC0")
642 call tolower("123\xC0\x80\xC0")
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +0200643
644 " Test in latin1 encoding
645 let save_enc = &encoding
646 set encoding=latin1
647 call assert_equal("abc", tolower("ABC"))
648 let &encoding = save_enc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100649endfunc
650
651func Test_toupper()
652 call assert_equal("", toupper(""))
653
654 " Test with all printable ASCII characters.
655 call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
656 \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
657
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100658 " Test with a few lowercase diacritics.
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200659 call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper())
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100660 call assert_equal("BḂḆ", toupper("bḃḇ"))
661 call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
662 call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
663 call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
664 call assert_equal("FḞ", toupper("fḟ"))
665 call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
666 call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
667 call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
668 call assert_equal("JĴǰ", toupper("jĵǰ"))
669 call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
670 call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
671 call assert_equal("MḾṀ ", toupper("mḿṁ "))
672 call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
673 call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
674 call assert_equal("PṔṖ", toupper("pṕṗ"))
675 call assert_equal("Q", toupper("q"))
676 call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
677 call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
678 call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
679 call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
680 call assert_equal("VṼ", toupper("vṽ"))
681 call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
682 call assert_equal("ẊẌ", toupper("ẋẍ"))
683 call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
684 call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
685
686 " Test that uppercase diacritics, which should remain unchanged.
687 call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
688 call assert_equal("BḂḆ", toupper("BḂḆ"))
689 call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
690 call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
691 call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
692 call assert_equal("FḞ ", toupper("FḞ "))
693 call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
694 call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
695 call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
696 call assert_equal("JĴ", toupper("JĴ"))
697 call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
698 call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
699 call assert_equal("MḾṀ", toupper("MḾṀ"))
700 call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
701 call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
702 call assert_equal("PṔṖ", toupper("PṔṖ"))
703 call assert_equal("Q", toupper("Q"))
704 call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
705 call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
706 call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
707 call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
708 call assert_equal("VṼ", toupper("VṼ"))
709 call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
710 call assert_equal("XẊẌ", toupper("XẊẌ"))
711 call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
712 call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
713
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100714 call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
Bram Moolenaare6640ad2017-12-22 21:06:56 +0100715
716 " This call to toupper with invalid utf8 sequence used to cause access to
717 " invalid memory.
718 call toupper("\xC0\x80\xC0")
719 call toupper("123\xC0\x80\xC0")
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +0200720
721 " Test in latin1 encoding
722 let save_enc = &encoding
723 set encoding=latin1
724 call assert_equal("ABC", toupper("abc"))
725 let &encoding = save_enc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100726endfunc
727
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200728func Test_tr()
729 call assert_equal('foo', tr('bar', 'bar', 'foo'))
730 call assert_equal('zxy', 'cab'->tr('abc', 'xyz'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100731 call assert_fails("let s=tr([], 'abc', 'def')", 'E730:')
732 call assert_fails("let s=tr('abc', [], 'def')", 'E730:')
733 call assert_fails("let s=tr('abc', 'abc', [])", 'E730:')
734 call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
735 set encoding=latin1
736 call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
737 call assert_equal('hEllO', tr('hello', 'eo', 'EO'))
738 call assert_equal('hello', tr('hello', 'xy', 'ab'))
Yegappan Lakshmanan34fcb692021-05-25 20:14:00 +0200739 call assert_fails('call tr("abc", "123", "₁₂")', 'E475:')
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100740 set encoding=utf8
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200741endfunc
742
Bram Moolenaare90858d2017-02-01 17:24:34 +0100743" Tests for the mode() function
744let current_modes = ''
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100745func Save_mode()
Bram Moolenaare90858d2017-02-01 17:24:34 +0100746 let g:current_modes = mode(0) . '-' . mode(1)
747 return ''
748endfunc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100749
Bram Moolenaarcde0ff32020-04-04 14:00:39 +0200750" Test for the mode() function
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100751func Test_mode()
Bram Moolenaare90858d2017-02-01 17:24:34 +0100752 new
753 call append(0, ["Blue Ball Black", "Brown Band Bowl", ""])
754
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100755 " Only complete from the current buffer.
756 set complete=.
757
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100758 noremap! <F2> <C-R>=Save_mode()<CR>
zeertzjqeaf3f362021-07-28 16:51:53 +0200759 xnoremap <F2> <Cmd>call Save_mode()<CR>
Bram Moolenaare90858d2017-02-01 17:24:34 +0100760
761 normal! 3G
762 exe "normal i\<F2>\<Esc>"
763 call assert_equal('i-i', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100764 " i_CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100765 exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
766 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100767 " i_CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100768 exe "normal iBro\<C-P>\<F2>\<Esc>u"
769 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100770 " i_CTRL-X
Bram Moolenaare90858d2017-02-01 17:24:34 +0100771 exe "normal iBa\<C-X>\<F2>\<Esc>u"
772 call assert_equal('i-ix', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100773 " i_CTRL-X CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100774 exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
775 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100776 " i_CTRL-X CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100777 exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u"
778 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100779 " i_CTRL-X CTRL-P + CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100780 exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
781 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100782 " i_CTRL-X CTRL-L: Multiple matches
783 exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
784 call assert_equal('i-ic', g:current_modes)
785 " i_CTRL-X CTRL-L: Single match
786 exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
787 call assert_equal('i-ic', g:current_modes)
788 " i_CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100789 exe "normal iCom\<C-P>\<F2>\<Esc>u"
790 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100791 " i_CTRL-X CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100792 exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u"
793 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100794 " i_CTRL-X CTRL-L: No match
795 exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
796 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100797
zeertzjqcc8cd442021-10-03 15:19:14 +0100798 exe "normal R\<F2>\<Esc>"
799 call assert_equal('R-R', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100800 " R_CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100801 exe "normal RBa\<C-P>\<F2>\<Esc>u"
802 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100803 " R_CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100804 exe "normal RBro\<C-P>\<F2>\<Esc>u"
805 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100806 " R_CTRL-X
Bram Moolenaare90858d2017-02-01 17:24:34 +0100807 exe "normal RBa\<C-X>\<F2>\<Esc>u"
808 call assert_equal('R-Rx', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100809 " R_CTRL-X CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100810 exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
811 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100812 " R_CTRL-X CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100813 exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u"
814 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100815 " R_CTRL-X CTRL-P + CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100816 exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
817 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100818 " R_CTRL-X CTRL-L: Multiple matches
819 exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
820 call assert_equal('R-Rc', g:current_modes)
821 " R_CTRL-X CTRL-L: Single match
822 exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
823 call assert_equal('R-Rc', g:current_modes)
824 " R_CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100825 exe "normal RCom\<C-P>\<F2>\<Esc>u"
826 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100827 " R_CTRL-X CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100828 exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u"
829 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100830 " R_CTRL-X CTRL-L: No match
831 exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
832 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100833
zeertzjqcc8cd442021-10-03 15:19:14 +0100834 exe "normal gR\<F2>\<Esc>"
835 call assert_equal('R-Rv', g:current_modes)
836 " gR_CTRL-P: Multiple matches
837 exe "normal gRBa\<C-P>\<F2>\<Esc>u"
838 call assert_equal('R-Rvc', g:current_modes)
839 " gR_CTRL-P: Single match
840 exe "normal gRBro\<C-P>\<F2>\<Esc>u"
841 call assert_equal('R-Rvc', g:current_modes)
842 " gR_CTRL-X
843 exe "normal gRBa\<C-X>\<F2>\<Esc>u"
844 call assert_equal('R-Rvx', g:current_modes)
845 " gR_CTRL-X CTRL-P: Multiple matches
846 exe "normal gRBa\<C-X>\<C-P>\<F2>\<Esc>u"
847 call assert_equal('R-Rvc', g:current_modes)
848 " gR_CTRL-X CTRL-P: Single match
849 exe "normal gRBro\<C-X>\<C-P>\<F2>\<Esc>u"
850 call assert_equal('R-Rvc', g:current_modes)
851 " gR_CTRL-X CTRL-P + CTRL-P: Single match
852 exe "normal gRBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
853 call assert_equal('R-Rvc', g:current_modes)
854 " gR_CTRL-X CTRL-L: Multiple matches
855 exe "normal gR\<C-X>\<C-L>\<F2>\<Esc>u"
856 call assert_equal('R-Rvc', g:current_modes)
857 " gR_CTRL-X CTRL-L: Single match
858 exe "normal gRBlu\<C-X>\<C-L>\<F2>\<Esc>u"
859 call assert_equal('R-Rvc', g:current_modes)
860 " gR_CTRL-P: No match
861 exe "normal gRCom\<C-P>\<F2>\<Esc>u"
862 call assert_equal('R-Rvc', g:current_modes)
863 " gR_CTRL-X CTRL-P: No match
864 exe "normal gRCom\<C-X>\<C-P>\<F2>\<Esc>u"
865 call assert_equal('R-Rvc', g:current_modes)
866 " gR_CTRL-X CTRL-L: No match
867 exe "normal gRabc\<C-X>\<C-L>\<F2>\<Esc>u"
868 call assert_equal('R-Rvc', g:current_modes)
869
Bram Moolenaara1449832019-09-01 20:16:52 +0200870 call assert_equal('n', 0->mode())
871 call assert_equal('n', 1->mode())
Bram Moolenaare90858d2017-02-01 17:24:34 +0100872
Bram Moolenaar612cc382018-07-29 15:34:26 +0200873 " i_CTRL-O
874 exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
875 call assert_equal("n-niI", g:current_modes)
876
877 " R_CTRL-O
878 exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
879 call assert_equal("n-niR", g:current_modes)
880
881 " gR_CTRL-O
882 exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
883 call assert_equal("n-niV", g:current_modes)
884
Bram Moolenaare90858d2017-02-01 17:24:34 +0100885 " How to test operator-pending mode?
886
887 call feedkeys("v", 'xt')
888 call assert_equal('v', mode())
889 call assert_equal('v', mode(1))
890 call feedkeys("\<Esc>V", 'xt')
891 call assert_equal('V', mode())
892 call assert_equal('V', mode(1))
893 call feedkeys("\<Esc>\<C-V>", 'xt')
894 call assert_equal("\<C-V>", mode())
895 call assert_equal("\<C-V>", mode(1))
896 call feedkeys("\<Esc>", 'xt')
897
898 call feedkeys("gh", 'xt')
899 call assert_equal('s', mode())
900 call assert_equal('s', mode(1))
901 call feedkeys("\<Esc>gH", 'xt')
902 call assert_equal('S', mode())
903 call assert_equal('S', mode(1))
904 call feedkeys("\<Esc>g\<C-H>", 'xt')
905 call assert_equal("\<C-S>", mode())
906 call assert_equal("\<C-S>", mode(1))
907 call feedkeys("\<Esc>", 'xt')
908
zeertzjqeaf3f362021-07-28 16:51:53 +0200909 " v_CTRL-O
910 exe "normal gh\<C-O>\<F2>\<Esc>"
911 call assert_equal("v-vs", g:current_modes)
912 exe "normal gH\<C-O>\<F2>\<Esc>"
913 call assert_equal("V-Vs", g:current_modes)
914 exe "normal g\<C-H>\<C-O>\<F2>\<Esc>"
915 call assert_equal("\<C-V>-\<C-V>s", g:current_modes)
916
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100917 call feedkeys(":\<F2>\<CR>", 'xt')
Bram Moolenaare90858d2017-02-01 17:24:34 +0100918 call assert_equal('c-c', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100919 call feedkeys(":\<Insert>\<F2>\<CR>", 'xt')
Sam-programsd1c3ef12023-11-27 22:22:51 +0100920 call assert_equal("c-cr", g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100921 call feedkeys("gQ\<F2>vi\<CR>", 'xt')
Bram Moolenaare90858d2017-02-01 17:24:34 +0100922 call assert_equal('c-cv', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100923 call feedkeys("gQ\<Insert>\<F2>vi\<CR>", 'xt')
Sam-programsd1c3ef12023-11-27 22:22:51 +0100924 call assert_equal("c-cvr", g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100925
kuuote0fd1cb12024-08-20 19:53:17 +0200926 " Commandline mode in Visual mode should return "c-c", never "v-v".
927 call feedkeys("v\<Cmd>call input('')\<CR>\<F2>\<CR>\<Esc>", 'xt')
928 call assert_equal("c-c", g:current_modes)
929
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100930 " Executing commands in Vim Ex mode should return "cv", never "cvr",
931 " as Cmdline editing has already ended.
932 call feedkeys("gQcall Save_mode()\<CR>vi\<CR>", 'xt')
933 call assert_equal('c-cv', g:current_modes)
934 call feedkeys("gQ\<Insert>call Save_mode()\<CR>vi\<CR>", 'xt')
935 call assert_equal('c-cv', g:current_modes)
936
Bram Moolenaarcde0ff32020-04-04 14:00:39 +0200937 call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt')
938 call assert_equal('c-ce', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100939
naohiro ono75c30e92021-10-19 11:15:41 +0100940 " Test mode in operatorfunc (it used to be Operator-pending).
941 set operatorfunc=OperatorFunc
942 function OperatorFunc(_)
943 call Save_mode()
944 endfunction
945 execute "normal! g@l\<Esc>"
946 call assert_equal('n-n', g:current_modes)
947 execute "normal! i\<C-o>g@l\<Esc>"
948 call assert_equal('n-niI', g:current_modes)
949 execute "normal! R\<C-o>g@l\<Esc>"
950 call assert_equal('n-niR', g:current_modes)
951 execute "normal! gR\<C-o>g@l\<Esc>"
952 call assert_equal('n-niV', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100953
naohiro ono75c30e92021-10-19 11:15:41 +0100954
Bram Moolenaar72406a42021-10-02 16:34:55 +0100955 if has('terminal')
956 term
h-east71ebf3b2023-09-03 17:12:55 +0200957 " Terminal-Job mode
958 call assert_equal('t', mode())
959 call assert_equal('t', mode(1))
960 call feedkeys("\<C-W>:echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
961 call assert_equal("c-ct", g:current_modes)
962 call feedkeys("\<Esc>", 'xt')
963
964 " Terminal-Normal mode
Bram Moolenaar72406a42021-10-02 16:34:55 +0100965 call feedkeys("\<C-W>N", 'xt')
966 call assert_equal('n', mode())
967 call assert_equal('nt', mode(1))
h-east71ebf3b2023-09-03 17:12:55 +0200968 call feedkeys(":echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
969 call assert_equal("c-c", g:current_modes)
Bram Moolenaar72406a42021-10-02 16:34:55 +0100970 call feedkeys("aexit\<CR>", 'xt')
971 endif
972
Bram Moolenaare90858d2017-02-01 17:24:34 +0100973 bwipe!
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100974 unmap! <F2>
zeertzjqeaf3f362021-07-28 16:51:53 +0200975 xunmap <F2>
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100976 set complete&
naohiro ono75c30e92021-10-19 11:15:41 +0100977 set operatorfunc&
978 delfunction OperatorFunc
Bram Moolenaare90858d2017-02-01 17:24:34 +0100979endfunc
Bram Moolenaar79518e22017-02-17 16:31:35 +0100980
Drew Vogelea67ba72025-05-07 22:05:17 +0200981" Test for the mode() function using Screendump feature
982func Test_mode_screendump()
983 CheckScreendump
984
985 " Test statusline updates for overstrike mode
986 let buf = RunVimInTerminal('', {'rows': 12})
987 call term_sendkeys(buf, ":set laststatus=2 statusline=%!mode(1)\<CR>")
988 call term_sendkeys(buf, ":")
989 call TermWait(buf)
990 call VerifyScreenDump(buf, 'Test_mode_1', {})
991 call term_sendkeys(buf, "\<Insert>")
992 call TermWait(buf)
993 call VerifyScreenDump(buf, 'Test_mode_2', {})
994 call StopVimInTerminal(buf)
995endfunc
996
Bram Moolenaarad48e6c2020-04-21 22:19:45 +0200997" Test for append()
Bram Moolenaard2007022019-08-27 21:56:06 +0200998func Test_append()
999 enew!
1000 split
Bram Moolenaarcd9c8d42022-11-05 23:46:43 +00001001 call assert_equal(0, append(1, []))
1002 call assert_equal(0, append(1, test_null_list()))
1003 call assert_equal(0, append(0, ["foo"]))
1004 call assert_equal(0, append(1, []))
1005 call assert_equal(0, append(1, test_null_list()))
1006 call assert_equal(0, append(8, []))
1007 call assert_equal(0, append(9, test_null_list()))
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001008 call assert_equal(['foo', ''], getline(1, '$'))
Bram Moolenaard2007022019-08-27 21:56:06 +02001009 split
1010 only
1011 undo
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001012 undo
Bram Moolenaar08f41572020-04-20 16:50:00 +02001013
1014 " Using $ instead of '$' must give an error
1015 call assert_fails("call append($, 'foobar')", 'E116:')
Bram Moolenaar801cd352022-10-10 16:08:16 +01001016
1017 call assert_fails("call append({}, '')", ['E728:', 'E728:'])
Bram Moolenaard2007022019-08-27 21:56:06 +02001018endfunc
1019
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001020" Test for setline()
1021func Test_setline()
1022 new
1023 call setline(0, ["foo"])
1024 call setline(0, [])
1025 call setline(0, test_null_list())
1026 call setline(1, ["bar"])
1027 call setline(1, [])
1028 call setline(1, test_null_list())
1029 call setline(2, [])
1030 call setline(2, test_null_list())
1031 call setline(3, [])
1032 call setline(3, test_null_list())
1033 call setline(2, ["baz"])
1034 call assert_equal(['bar', 'baz'], getline(1, '$'))
Drew Vogelea67ba72025-05-07 22:05:17 +02001035 bw!
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001036endfunc
1037
Bram Moolenaar79518e22017-02-17 16:31:35 +01001038func Test_getbufvar()
1039 let bnr = bufnr('%')
1040 let b:var_num = '1234'
1041 let def_num = '5678'
1042 call assert_equal('1234', getbufvar(bnr, 'var_num'))
1043 call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
1044
1045 let bd = getbufvar(bnr, '')
1046 call assert_equal('1234', bd['var_num'])
1047 call assert_true(exists("bd['changedtick']"))
1048 call assert_equal(2, len(bd))
1049
1050 let bd2 = getbufvar(bnr, '', def_num)
1051 call assert_equal(bd, bd2)
1052
1053 unlet b:var_num
1054 call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
1055 call assert_equal('', getbufvar(bnr, 'var_num'))
1056
1057 let bd = getbufvar(bnr, '')
1058 call assert_equal(1, len(bd))
1059 let bd = getbufvar(bnr, '',def_num)
1060 call assert_equal(1, len(bd))
1061
Bram Moolenaar4520d442017-03-19 16:09:46 +01001062 call assert_equal('', getbufvar(9999, ''))
1063 call assert_equal(def_num, getbufvar(9999, '', def_num))
Bram Moolenaar79518e22017-02-17 16:31:35 +01001064 unlet def_num
1065
Bram Moolenaar507647d2017-02-17 16:43:49 +01001066 call assert_equal(0, getbufvar(bnr, '&autoindent'))
1067 call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
Bram Moolenaar79518e22017-02-17 16:31:35 +01001068
Bram Moolenaar8dfcce32020-03-18 19:32:26 +01001069 " Set and get a buffer-local variable
1070 call setbufvar(bnr, 'bufvar_test', ['one', 'two'])
1071 call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test'))
1072
Bram Moolenaar79518e22017-02-17 16:31:35 +01001073 " Open new window with forced option values
1074 set fileformats=unix,dos
1075 new ++ff=dos ++bin ++enc=iso-8859-2
1076 call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
1077 call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
1078 call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
1079 close
1080
Bram Moolenaar52592752020-04-03 18:43:35 +02001081 " Get the b: dict.
1082 let b:testvar = 'one'
1083 new
1084 let b:testvar = 'two'
1085 let thebuf = bufnr()
1086 wincmd w
1087 call assert_equal('two', getbufvar(thebuf, 'testvar'))
1088 call assert_equal('two', getbufvar(thebuf, '').testvar)
1089 bwipe!
1090
Bram Moolenaar79518e22017-02-17 16:31:35 +01001091 set fileformats&
1092endfunc
Bram Moolenaarcaf64342017-03-02 22:11:33 +01001093
Bram Moolenaar41042f32017-03-09 12:09:32 +01001094func Test_last_buffer_nr()
1095 call assert_equal(bufnr('$'), last_buffer_nr())
1096endfunc
1097
1098func Test_stridx()
1099 call assert_equal(-1, stridx('', 'l'))
1100 call assert_equal(0, stridx('', ''))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001101 call assert_equal(0, 'hello'->stridx(''))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001102 call assert_equal(-1, stridx('hello', 'L'))
1103 call assert_equal(2, stridx('hello', 'l', -1))
1104 call assert_equal(2, stridx('hello', 'l', 0))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001105 call assert_equal(2, 'hello'->stridx('l', 1))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001106 call assert_equal(3, stridx('hello', 'l', 3))
1107 call assert_equal(-1, stridx('hello', 'l', 4))
1108 call assert_equal(-1, stridx('hello', 'l', 10))
1109 call assert_equal(2, stridx('hello', 'll'))
1110 call assert_equal(-1, stridx('hello', 'hello world'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001111 call assert_fails("let n=stridx('hello', [])", 'E730:')
1112 call assert_fails("let n=stridx([], 'l')", 'E730:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001113endfunc
1114
1115func Test_strridx()
1116 call assert_equal(-1, strridx('', 'l'))
1117 call assert_equal(0, strridx('', ''))
1118 call assert_equal(5, strridx('hello', ''))
1119 call assert_equal(-1, strridx('hello', 'L'))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001120 call assert_equal(3, 'hello'->strridx('l'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001121 call assert_equal(3, strridx('hello', 'l', 10))
1122 call assert_equal(3, strridx('hello', 'l', 3))
1123 call assert_equal(2, strridx('hello', 'l', 2))
1124 call assert_equal(-1, strridx('hello', 'l', 1))
1125 call assert_equal(-1, strridx('hello', 'l', 0))
1126 call assert_equal(-1, strridx('hello', 'l', -1))
1127 call assert_equal(2, strridx('hello', 'll'))
1128 call assert_equal(-1, strridx('hello', 'hello world'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001129 call assert_fails("let n=strridx('hello', [])", 'E730:')
1130 call assert_fails("let n=strridx([], 'l')", 'E730:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001131endfunc
1132
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001133func Test_match_func()
1134 call assert_equal(4, match('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001135 call assert_equal(4, 'testing'->match('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001136 call assert_equal(-1, match('testing', 'ing', 5))
1137 call assert_equal(-1, match('testing', 'ing', 8))
1138 call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
1139 call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001140 call assert_fails("let x=match('vim', [])", 'E730:')
1141 call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1))
1142 call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5))
1143 call assert_equal(4, match('testing', 'ing', -1))
1144 call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:')
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001145 call assert_equal(-1, match(test_null_list(), 2))
Bram Moolenaar531be472020-09-23 22:38:05 +02001146 call assert_equal(-1, match('abc', '\\%('))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001147endfunc
1148
Bram Moolenaar41042f32017-03-09 12:09:32 +01001149func Test_matchend()
1150 call assert_equal(7, matchend('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001151 call assert_equal(7, 'testing'->matchend('ing', 2))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001152 call assert_equal(-1, matchend('testing', 'ing', 5))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001153 call assert_equal(-1, matchend('testing', 'ing', 8))
1154 call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
1155 call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
1156endfunc
1157
1158func Test_matchlist()
1159 call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001160 call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''], 'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001161 call assert_equal([], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
1162endfunc
1163
1164func Test_matchstr()
1165 call assert_equal('ing', matchstr('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001166 call assert_equal('ing', 'testing'->matchstr('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001167 call assert_equal('', matchstr('testing', 'ing', 5))
1168 call assert_equal('', matchstr('testing', 'ing', 8))
1169 call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
1170 call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
1171endfunc
1172
1173func Test_matchstrpos()
1174 call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001175 call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001176 call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
1177 call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
1178 call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
1179 call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02001180 call assert_equal(['', -1, -1], matchstrpos(test_null_list(), '\a'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001181endfunc
1182
Yegappan Lakshmananf93b1c82024-01-04 22:28:46 +01001183" Test for matchstrlist()
1184func Test_matchstrlist()
1185 let lines =<< trim END
1186 #" Basic match
1187 call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'bout'},
1188 \ {'idx': 1, 'byteidx': 1, 'text': 'bove'}],
1189 \ matchstrlist(['about', 'above'], 'bo.*'))
1190 #" no match
1191 call assert_equal([], matchstrlist(['about', 'above'], 'xy.*'))
1192 #" empty string
1193 call assert_equal([], matchstrlist([''], '.'))
1194 #" empty pattern
1195 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}], matchstrlist(['abc'], ''))
1196 #" method call
1197 call assert_equal([{'idx': 0, 'byteidx': 2, 'text': 'it'}], ['editor']->matchstrlist('ed\zsit\zeor'))
1198 #" single character matches
1199 call assert_equal([{'idx': 0, 'byteidx': 5, 'text': 'r'}],
1200 \ ['editor']->matchstrlist('r'))
1201 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'a'}], ['a']->matchstrlist('a'))
1202 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1203 \ matchstrlist(['foobar'], '\zs'))
1204 #" string with tabs
1205 call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'foo'}],
1206 \ matchstrlist(["\tfoobar"], 'foo'))
1207 #" string with multibyte characters
1208 call assert_equal([{'idx': 0, 'byteidx': 2, 'text': '😊😊'}],
1209 \ matchstrlist(["\t\t😊😊"], '\k\+'))
1210
1211 #" null string
1212 call assert_equal([], matchstrlist(test_null_list(), 'abc'))
1213 call assert_equal([], matchstrlist([test_null_string()], 'abc'))
1214 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1215 \ matchstrlist(['abc'], test_null_string()))
1216
1217 #" sub matches
1218 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}], matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)', {'submatches': v:true}))
1219
1220 #" null dict argument
1221 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'vim'}],
1222 \ matchstrlist(['vim'], '\w\+', test_null_dict()))
1223
1224 #" Error cases
1225 call assert_fails("echo matchstrlist('abc', 'a')", 'E1211: List required for argument 1')
1226 call assert_fails("echo matchstrlist(['abc'], {})", 'E1174: String required for argument 2')
1227 call assert_fails("echo matchstrlist(['abc'], '.', [])", 'E1206: Dictionary required for argument 3')
1228 call assert_fails("echo matchstrlist(['abc'], 'a', {'submatches': []})", 'E475: Invalid value for argument submatches')
1229 call assert_fails("echo matchstrlist(['abc'], '\\@=')", 'E866: (NFA regexp) Misplaced @')
1230 END
1231 call v9.CheckLegacyAndVim9Success(lines)
1232
1233 let lines =<< trim END
1234 vim9script
1235 # non string items
1236 matchstrlist([0z10, {'a': 'x'}], 'x')
1237 END
1238 call v9.CheckSourceSuccess(lines)
1239
1240 let lines =<< trim END
1241 vim9script
1242 def Foo()
1243 # non string items
1244 assert_equal([], matchstrlist([0z10, {'a': 'x'}], 'x'))
1245 enddef
1246 Foo()
1247 END
1248 call v9.CheckSourceFailure(lines, 'E1013: Argument 1: type mismatch, expected list<string> but got list<any>', 2)
1249endfunc
1250
1251" Test for matchbufline()
1252func Test_matchbufline()
1253 let lines =<< trim END
1254 #" Basic match
1255 new
1256 call setline(1, ['about', 'above', 'below'])
1257 VAR bnr = bufnr()
1258 wincmd w
1259 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1260 \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'}],
1261 \ matchbufline(bnr, 'bo.*', 1, '$'))
1262 #" multiple matches in a line
1263 call setbufline(bnr, 1, ['about about', 'above above', 'below'])
1264 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1265 \ {'lnum': 1, 'byteidx': 7, 'text': 'bout'},
1266 \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'},
1267 \ {'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1268 \ matchbufline(bnr, 'bo\k\+', 1, '$'))
1269 #" no match
1270 call assert_equal([], matchbufline(bnr, 'xy.*', 1, '$'))
1271 #" match on a particular line
1272 call assert_equal([{'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1273 \ matchbufline(bnr, 'bo\k\+$', 2, 2))
1274 #" match on a particular line
1275 call assert_equal([], matchbufline(bnr, 'bo.*', 3, 3))
1276 #" empty string
1277 call deletebufline(bnr, 1, '$')
1278 call assert_equal([], matchbufline(bnr, '.', 1, '$'))
1279 #" empty pattern
1280 call setbufline(bnr, 1, 'abc')
1281 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1282 \ matchbufline(bnr, '', 1, '$'))
1283 #" method call
1284 call setbufline(bnr, 1, 'editor')
1285 call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': 'it'}],
1286 \ bnr->matchbufline('ed\zsit\zeor', 1, 1))
1287 #" single character matches
1288 call assert_equal([{'lnum': 1, 'byteidx': 5, 'text': 'r'}],
1289 \ matchbufline(bnr, 'r', 1, '$'))
1290 call setbufline(bnr, 1, 'a')
1291 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'a'}],
1292 \ matchbufline(bnr, 'a', 1, '$'))
1293 #" zero-width match
1294 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1295 \ matchbufline(bnr, '\zs', 1, '$'))
1296 #" string with tabs
1297 call setbufline(bnr, 1, "\tfoobar")
1298 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'foo'}],
1299 \ matchbufline(bnr, 'foo', 1, '$'))
1300 #" string with multibyte characters
1301 call setbufline(bnr, 1, "\t\t😊😊")
1302 call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': '😊😊'}],
1303 \ matchbufline(bnr, '\k\+', 1, '$'))
1304 #" empty buffer
1305 call deletebufline(bnr, 1, '$')
1306 call assert_equal([], matchbufline(bnr, 'abc', 1, '$'))
1307
1308 #" Non existing buffer
1309 call setbufline(bnr, 1, 'abc')
1310 call assert_fails("echo matchbufline(5000, 'abc', 1, 1)", 'E158: Invalid buffer name: 5000')
1311 #" null string
1312 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1313 \ matchbufline(bnr, test_null_string(), 1, 1))
1314 #" invalid starting line number
1315 call assert_equal([], matchbufline(bnr, 'abc', 100, 100))
1316 #" ending line number greater than the last line
1317 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'abc'}],
1318 \ matchbufline(bnr, 'abc', 1, 100))
1319 #" ending line number greater than the starting line number
1320 call setbufline(bnr, 1, ['one', 'two'])
1321 call assert_fails($"echo matchbufline({bnr}, 'abc', 2, 1)", 'E475: Invalid value for argument end_lnum')
1322
1323 #" sub matches
1324 call deletebufline(bnr, 1, '$')
1325 call setbufline(bnr, 1, 'acd')
1326 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}],
1327 \ matchbufline(bnr, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 1, '$', {'submatches': v:true}))
1328
1329 #" null dict argument
1330 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd'}],
1331 \ matchbufline(bnr, '\w\+', '$', '$', test_null_dict()))
1332
1333 #" Error cases
1334 call assert_fails("echo matchbufline([1], 'abc', 1, 1)", 'E1220: String or Number required for argument 1')
1335 call assert_fails("echo matchbufline(1, {}, 1, 1)", 'E1174: String required for argument 2')
1336 call assert_fails("echo matchbufline(1, 'abc', {}, 1)", 'E1220: String or Number required for argument 3')
1337 call assert_fails("echo matchbufline(1, 'abc', 1, {})", 'E1220: String or Number required for argument 4')
1338 call assert_fails($"echo matchbufline({bnr}, 'abc', -1, '$')", 'E475: Invalid value for argument lnum')
1339 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, -1)", 'E475: Invalid value for argument end_lnum')
1340 call assert_fails($"echo matchbufline({bnr}, '\\@=', 1, 1)", 'E866: (NFA regexp) Misplaced @')
1341 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, 1, {{'submatches': []}})", 'E475: Invalid value for argument submatches')
1342 :%bdelete!
1343 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, '$'))", 'E681: Buffer is not loaded')
1344 END
1345 call v9.CheckLegacyAndVim9Success(lines)
1346
1347 call assert_fails($"echo matchbufline('', 'abc', 'abc', 1)", 'E475: Invalid value for argument lnum')
1348 call assert_fails($"echo matchbufline('', 'abc', 1, 'abc')", 'E475: Invalid value for argument end_lnum')
1349
1350 let lines =<< trim END
1351 vim9script
1352 def Foo()
1353 echo matchbufline('', 'abc', 'abc', 1)
1354 enddef
1355 Foo()
1356 END
1357 call v9.CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1358
1359 let lines =<< trim END
1360 vim9script
1361 def Foo()
1362 echo matchbufline('', 'abc', 1, 'abc')
1363 enddef
1364 Foo()
1365 END
1366 call v9.CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1367endfunc
1368
Bram Moolenaar41042f32017-03-09 12:09:32 +01001369func Test_nextnonblank_prevnonblank()
1370 new
1371insert
1372This
1373
1374
1375is
1376
1377a
1378Test
1379.
1380 call assert_equal(0, nextnonblank(-1))
1381 call assert_equal(0, nextnonblank(0))
1382 call assert_equal(1, nextnonblank(1))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001383 call assert_equal(4, 2->nextnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001384 call assert_equal(4, nextnonblank(3))
1385 call assert_equal(4, nextnonblank(4))
1386 call assert_equal(6, nextnonblank(5))
1387 call assert_equal(6, nextnonblank(6))
1388 call assert_equal(7, nextnonblank(7))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001389 call assert_equal(0, 8->nextnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001390
1391 call assert_equal(0, prevnonblank(-1))
1392 call assert_equal(0, prevnonblank(0))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001393 call assert_equal(1, 1->prevnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001394 call assert_equal(1, prevnonblank(2))
1395 call assert_equal(1, prevnonblank(3))
1396 call assert_equal(4, prevnonblank(4))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001397 call assert_equal(4, 5->prevnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001398 call assert_equal(6, prevnonblank(6))
1399 call assert_equal(7, prevnonblank(7))
1400 call assert_equal(0, prevnonblank(8))
1401 bw!
1402endfunc
1403
1404func Test_byte2line_line2byte()
1405 new
Bram Moolenaarc26f7c62018-08-20 22:53:04 +02001406 set endofline
Bram Moolenaar41042f32017-03-09 12:09:32 +01001407 call setline(1, ['a', 'bc', 'd'])
1408
1409 set fileformat=unix
1410 call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1411 \ map(range(-1, 8), 'byte2line(v:val)'))
1412 call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1413 \ map(range(-1, 5), 'line2byte(v:val)'))
1414
1415 set fileformat=mac
1416 call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001417 \ map(range(-1, 8), 'v:val->byte2line()'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001418 call assert_equal([-1, -1, 1, 3, 6, 8, -1],
Bram Moolenaar02b31112019-08-31 22:16:38 +02001419 \ map(range(-1, 5), 'v:val->line2byte()'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001420
1421 set fileformat=dos
1422 call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
1423 \ map(range(-1, 11), 'byte2line(v:val)'))
1424 call assert_equal([-1, -1, 1, 4, 8, 11, -1],
1425 \ map(range(-1, 5), 'line2byte(v:val)'))
1426
Bram Moolenaarc26f7c62018-08-20 22:53:04 +02001427 bw!
1428 set noendofline nofixendofline
1429 normal a-
1430 for ff in ["unix", "mac", "dos"]
1431 let &fileformat = ff
1432 call assert_equal(1, line2byte(1))
1433 call assert_equal(2, line2byte(2)) " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
1434 endfor
1435
1436 set endofline& fixendofline& fileformat&
Bram Moolenaar41042f32017-03-09 12:09:32 +01001437 bw!
1438endfunc
1439
Christian Brabandt67672ef2023-04-24 21:09:54 +01001440" Test for byteidx() using a character index
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001441func Test_byteidx()
1442 let a = '.é.' " one char of two bytes
1443 call assert_equal(0, byteidx(a, 0))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001444 call assert_equal(1, byteidx(a, 1))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001445 call assert_equal(3, byteidx(a, 2))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001446 call assert_equal(4, byteidx(a, 3))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001447 call assert_equal(-1, byteidx(a, 4))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001448
1449 let b = '.é.' " normal e with composing char
1450 call assert_equal(0, b->byteidx(0))
1451 call assert_equal(1, b->byteidx(1))
1452 call assert_equal(4, b->byteidx(2))
1453 call assert_equal(5, b->byteidx(3))
1454 call assert_equal(-1, b->byteidx(4))
1455
Christian Brabandt67672ef2023-04-24 21:09:54 +01001456 " string with multiple composing characters
1457 let str = '-ą́-ą́'
1458 call assert_equal(0, byteidx(str, 0))
1459 call assert_equal(1, byteidx(str, 1))
1460 call assert_equal(6, byteidx(str, 2))
1461 call assert_equal(7, byteidx(str, 3))
1462 call assert_equal(12, byteidx(str, 4))
1463 call assert_equal(-1, byteidx(str, 5))
1464
1465 " empty string
1466 call assert_equal(0, byteidx('', 0))
1467 call assert_equal(-1, byteidx('', 1))
1468
1469 " error cases
1470 call assert_fails("call byteidx([], 0)", 'E730:')
1471 call assert_fails("call byteidx('abc', [])", 'E745:')
Bram Moolenaare4098452023-05-07 18:53:49 +01001472 call assert_fails("call byteidx('abc', 0, {})", ['E728:', 'E728:'])
zeertzjq8cf51372023-05-08 15:31:38 +01001473 call assert_fails("call byteidx('abc', 0, -1)", ['E1023:', 'E1023:'])
Christian Brabandt67672ef2023-04-24 21:09:54 +01001474endfunc
1475
1476" Test for byteidxcomp() using a character index
1477func Test_byteidxcomp()
1478 let a = '.é.' " one char of two bytes
1479 call assert_equal(0, byteidxcomp(a, 0))
1480 call assert_equal(1, byteidxcomp(a, 1))
1481 call assert_equal(3, byteidxcomp(a, 2))
1482 call assert_equal(4, byteidxcomp(a, 3))
1483 call assert_equal(-1, byteidxcomp(a, 4))
1484
1485 let b = '.é.' " normal e with composing char
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001486 call assert_equal(0, b->byteidxcomp(0))
1487 call assert_equal(1, b->byteidxcomp(1))
1488 call assert_equal(2, b->byteidxcomp(2))
1489 call assert_equal(4, b->byteidxcomp(3))
1490 call assert_equal(5, b->byteidxcomp(4))
1491 call assert_equal(-1, b->byteidxcomp(5))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001492
1493 " string with multiple composing characters
1494 let str = '-ą́-ą́'
1495 call assert_equal(0, byteidxcomp(str, 0))
1496 call assert_equal(1, byteidxcomp(str, 1))
1497 call assert_equal(2, byteidxcomp(str, 2))
1498 call assert_equal(4, byteidxcomp(str, 3))
1499 call assert_equal(6, byteidxcomp(str, 4))
1500 call assert_equal(7, byteidxcomp(str, 5))
1501 call assert_equal(8, byteidxcomp(str, 6))
1502 call assert_equal(10, byteidxcomp(str, 7))
1503 call assert_equal(12, byteidxcomp(str, 8))
1504 call assert_equal(-1, byteidxcomp(str, 9))
1505
1506 " empty string
1507 call assert_equal(0, byteidxcomp('', 0))
1508 call assert_equal(-1, byteidxcomp('', 1))
1509
1510 " error cases
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001511 call assert_fails("call byteidxcomp([], 0)", 'E730:')
Christian Brabandt67672ef2023-04-24 21:09:54 +01001512 call assert_fails("call byteidxcomp('abc', [])", 'E745:')
Bram Moolenaare4098452023-05-07 18:53:49 +01001513 call assert_fails("call byteidxcomp('abc', 0, {})", ['E728:', 'E728:'])
zeertzjq8cf51372023-05-08 15:31:38 +01001514 call assert_fails("call byteidxcomp('abc', 0, -1)", ['E1023:', 'E1023:'])
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001515endfunc
1516
Christian Brabandt67672ef2023-04-24 21:09:54 +01001517" Test for byteidx() using a UTF-16 index
1518func Test_byteidx_from_utf16_index()
1519 " string with single byte characters
1520 let str = "abc"
1521 for i in range(3)
1522 call assert_equal(i, byteidx(str, i, v:true))
1523 endfor
1524 call assert_equal(3, byteidx(str, 3, v:true))
1525 call assert_equal(-1, byteidx(str, 4, v:true))
1526
1527 " string with two byte characters
1528 let str = "a©©b"
1529 call assert_equal(0, byteidx(str, 0, v:true))
1530 call assert_equal(1, byteidx(str, 1, v:true))
1531 call assert_equal(3, byteidx(str, 2, v:true))
1532 call assert_equal(5, byteidx(str, 3, v:true))
1533 call assert_equal(6, byteidx(str, 4, v:true))
1534 call assert_equal(-1, byteidx(str, 5, v:true))
1535
1536 " string with two byte characters
1537 let str = "a😊😊b"
1538 call assert_equal(0, byteidx(str, 0, v:true))
1539 call assert_equal(1, byteidx(str, 1, v:true))
1540 call assert_equal(1, byteidx(str, 2, v:true))
1541 call assert_equal(5, byteidx(str, 3, v:true))
1542 call assert_equal(5, byteidx(str, 4, v:true))
1543 call assert_equal(9, byteidx(str, 5, v:true))
1544 call assert_equal(10, byteidx(str, 6, v:true))
1545 call assert_equal(-1, byteidx(str, 7, v:true))
1546
1547 " string with composing characters
1548 let str = '-á-b́'
1549 call assert_equal(0, byteidx(str, 0, v:true))
1550 call assert_equal(1, byteidx(str, 1, v:true))
1551 call assert_equal(4, byteidx(str, 2, v:true))
1552 call assert_equal(5, byteidx(str, 3, v:true))
1553 call assert_equal(8, byteidx(str, 4, v:true))
1554 call assert_equal(-1, byteidx(str, 5, v:true))
1555
1556 " string with multiple composing characters
1557 let str = '-ą́-ą́'
1558 call assert_equal(0, byteidx(str, 0, v:true))
1559 call assert_equal(1, byteidx(str, 1, v:true))
1560 call assert_equal(6, byteidx(str, 2, v:true))
1561 call assert_equal(7, byteidx(str, 3, v:true))
1562 call assert_equal(12, byteidx(str, 4, v:true))
1563 call assert_equal(-1, byteidx(str, 5, v:true))
1564
1565 " empty string
1566 call assert_equal(0, byteidx('', 0, v:true))
1567 call assert_equal(-1, byteidx('', 1, v:true))
1568
1569 " error cases
1570 call assert_fails('call byteidx(str, 0, [])', 'E745:')
1571endfunc
1572
1573" Test for byteidxcomp() using a UTF-16 index
1574func Test_byteidxcomp_from_utf16_index()
1575 " string with single byte characters
1576 let str = "abc"
1577 for i in range(3)
1578 call assert_equal(i, byteidxcomp(str, i, v:true))
1579 endfor
1580 call assert_equal(3, byteidxcomp(str, 3, v:true))
1581 call assert_equal(-1, byteidxcomp(str, 4, v:true))
1582
1583 " string with two byte characters
1584 let str = "a©©b"
1585 call assert_equal(0, byteidxcomp(str, 0, v:true))
1586 call assert_equal(1, byteidxcomp(str, 1, v:true))
1587 call assert_equal(3, byteidxcomp(str, 2, v:true))
1588 call assert_equal(5, byteidxcomp(str, 3, v:true))
1589 call assert_equal(6, byteidxcomp(str, 4, v:true))
1590 call assert_equal(-1, byteidxcomp(str, 5, v:true))
1591
1592 " string with two byte characters
1593 let str = "a😊😊b"
1594 call assert_equal(0, byteidxcomp(str, 0, v:true))
1595 call assert_equal(1, byteidxcomp(str, 1, v:true))
1596 call assert_equal(1, byteidxcomp(str, 2, v:true))
1597 call assert_equal(5, byteidxcomp(str, 3, v:true))
1598 call assert_equal(5, byteidxcomp(str, 4, v:true))
1599 call assert_equal(9, byteidxcomp(str, 5, v:true))
1600 call assert_equal(10, byteidxcomp(str, 6, v:true))
1601 call assert_equal(-1, byteidxcomp(str, 7, v:true))
1602
1603 " string with composing characters
1604 let str = '-á-b́'
1605 call assert_equal(0, byteidxcomp(str, 0, v:true))
1606 call assert_equal(1, byteidxcomp(str, 1, v:true))
1607 call assert_equal(2, byteidxcomp(str, 2, v:true))
1608 call assert_equal(4, byteidxcomp(str, 3, v:true))
1609 call assert_equal(5, byteidxcomp(str, 4, v:true))
1610 call assert_equal(6, byteidxcomp(str, 5, v:true))
1611 call assert_equal(8, byteidxcomp(str, 6, v:true))
1612 call assert_equal(-1, byteidxcomp(str, 7, v:true))
1613 call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1614
1615 " string with multiple composing characters
1616 let str = '-ą́-ą́'
1617 call assert_equal(0, byteidxcomp(str, 0, v:true))
1618 call assert_equal(1, byteidxcomp(str, 1, v:true))
1619 call assert_equal(2, byteidxcomp(str, 2, v:true))
1620 call assert_equal(4, byteidxcomp(str, 3, v:true))
1621 call assert_equal(6, byteidxcomp(str, 4, v:true))
1622 call assert_equal(7, byteidxcomp(str, 5, v:true))
1623 call assert_equal(8, byteidxcomp(str, 6, v:true))
1624 call assert_equal(10, byteidxcomp(str, 7, v:true))
1625 call assert_equal(12, byteidxcomp(str, 8, v:true))
1626 call assert_equal(-1, byteidxcomp(str, 9, v:true))
1627
1628 " empty string
1629 call assert_equal(0, byteidxcomp('', 0, v:true))
1630 call assert_equal(-1, byteidxcomp('', 1, v:true))
1631
1632 " error cases
1633 call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1634endfunc
1635
1636" Test for charidx() using a byte index
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001637func Test_charidx()
1638 let a = 'xáb́y'
1639 call assert_equal(0, charidx(a, 0))
1640 call assert_equal(1, charidx(a, 3))
1641 call assert_equal(2, charidx(a, 4))
1642 call assert_equal(3, charidx(a, 7))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001643 call assert_equal(4, charidx(a, 8))
1644 call assert_equal(-1, charidx(a, 9))
Dominique Pelle6d37e8e2021-05-06 17:36:55 +02001645 call assert_equal(-1, charidx(a, -1))
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001646
1647 " count composing characters
Christian Brabandt67672ef2023-04-24 21:09:54 +01001648 call assert_equal(0, a->charidx(0, 1))
1649 call assert_equal(2, a->charidx(2, 1))
1650 call assert_equal(3, a->charidx(4, 1))
1651 call assert_equal(5, a->charidx(7, 1))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001652 call assert_equal(6, a->charidx(8, 1))
1653 call assert_equal(-1, a->charidx(9, 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001654
1655 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001656 call assert_equal(0, charidx('', 0))
1657 call assert_equal(-1, charidx('', 1))
1658 call assert_equal(0, charidx('', 0, 1))
1659 call assert_equal(-1, charidx('', 1, 1))
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001660
Christian Brabandt67672ef2023-04-24 21:09:54 +01001661 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001662 call assert_equal(0, charidx(test_null_string(), 0))
1663 call assert_equal(-1, charidx(test_null_string(), 1))
Yegappan Lakshmanan8deb2b32022-09-02 15:15:27 +01001664 call assert_fails('let x = charidx([], 1)', 'E1174:')
1665 call assert_fails('let x = charidx("abc", [])', 'E1210:')
1666 call assert_fails('let x = charidx("abc", 1, [])', 'E1212:')
1667 call assert_fails('let x = charidx("abc", 1, -1)', 'E1212:')
1668 call assert_fails('let x = charidx("abc", 1, 2)', 'E1212:')
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001669endfunc
1670
Christian Brabandt67672ef2023-04-24 21:09:54 +01001671" Test for charidx() using a UTF-16 index
1672func Test_charidx_from_utf16_index()
1673 " string with single byte characters
1674 let str = "abc"
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001675 for i in range(4)
Christian Brabandt67672ef2023-04-24 21:09:54 +01001676 call assert_equal(i, charidx(str, i, v:false, v:true))
1677 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001678 call assert_equal(-1, charidx(str, 4, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001679
1680 " string with two byte characters
1681 let str = "a©©b"
1682 call assert_equal(0, charidx(str, 0, v:false, v:true))
1683 call assert_equal(1, charidx(str, 1, v:false, v:true))
1684 call assert_equal(2, charidx(str, 2, v:false, v:true))
1685 call assert_equal(3, charidx(str, 3, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001686 call assert_equal(4, charidx(str, 4, v:false, v:true))
1687 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001688
1689 " string with four byte characters
1690 let str = "a😊😊b"
1691 call assert_equal(0, charidx(str, 0, v:false, v:true))
1692 call assert_equal(1, charidx(str, 1, v:false, v:true))
1693 call assert_equal(1, charidx(str, 2, v:false, v:true))
1694 call assert_equal(2, charidx(str, 3, v:false, v:true))
1695 call assert_equal(2, charidx(str, 4, v:false, v:true))
1696 call assert_equal(3, charidx(str, 5, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001697 call assert_equal(4, charidx(str, 6, v:false, v:true))
1698 call assert_equal(-1, charidx(str, 7, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001699
1700 " string with composing characters
1701 let str = '-á-b́'
1702 for i in str->strcharlen()->range()
1703 call assert_equal(i, charidx(str, i, v:false, v:true))
1704 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001705 call assert_equal(4, charidx(str, 4, v:false, v:true))
1706 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001707 for i in str->strchars()->range()
1708 call assert_equal(i, charidx(str, i, v:true, v:true))
1709 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001710 call assert_equal(6, charidx(str, 6, v:true, v:true))
1711 call assert_equal(-1, charidx(str, 7, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001712
1713 " string with multiple composing characters
1714 let str = '-ą́-ą́'
1715 for i in str->strcharlen()->range()
1716 call assert_equal(i, charidx(str, i, v:false, v:true))
1717 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001718 call assert_equal(4, charidx(str, 4, v:false, v:true))
1719 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001720 for i in str->strchars()->range()
1721 call assert_equal(i, charidx(str, i, v:true, v:true))
1722 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001723 call assert_equal(8, charidx(str, 8, v:true, v:true))
1724 call assert_equal(-1, charidx(str, 9, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001725
1726 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001727 call assert_equal(0, charidx('', 0, v:false, v:true))
1728 call assert_equal(-1, charidx('', 1, v:false, v:true))
1729 call assert_equal(0, charidx('', 0, v:true, v:true))
1730 call assert_equal(-1, charidx('', 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001731
1732 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001733 call assert_equal(0, charidx('', 0, v:false, v:true))
1734 call assert_equal(-1, charidx('', 1, v:false, v:true))
1735 call assert_equal(0, charidx('', 0, v:true, v:true))
1736 call assert_equal(-1, charidx('', 1, v:true, v:true))
1737 call assert_equal(0, charidx(test_null_string(), 0, v:false, v:true))
1738 call assert_equal(-1, charidx(test_null_string(), 1, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001739 call assert_fails('let x = charidx("abc", 1, v:false, [])', 'E1212:')
1740 call assert_fails('let x = charidx("abc", 1, v:true, [])', 'E1212:')
1741endfunc
1742
1743" Test for utf16idx() using a byte index
1744func Test_utf16idx_from_byteidx()
1745 " UTF-16 index of a string with single byte characters
1746 let str = "abc"
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001747 for i in range(4)
Christian Brabandt67672ef2023-04-24 21:09:54 +01001748 call assert_equal(i, utf16idx(str, i))
1749 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001750 call assert_equal(-1, utf16idx(str, 4))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001751
1752 " UTF-16 index of a string with two byte characters
1753 let str = 'a©©b'
1754 call assert_equal(0, str->utf16idx(0))
1755 call assert_equal(1, str->utf16idx(1))
1756 call assert_equal(1, str->utf16idx(2))
1757 call assert_equal(2, str->utf16idx(3))
1758 call assert_equal(2, str->utf16idx(4))
1759 call assert_equal(3, str->utf16idx(5))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001760 call assert_equal(4, str->utf16idx(6))
1761 call assert_equal(-1, str->utf16idx(7))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001762
1763 " UTF-16 index of a string with four byte characters
1764 let str = 'a😊😊b'
1765 call assert_equal(0, utf16idx(str, 0))
Yegappan Lakshmanan95707032023-06-14 13:10:15 +01001766 call assert_equal(1, utf16idx(str, 1))
1767 call assert_equal(1, utf16idx(str, 2))
1768 call assert_equal(1, utf16idx(str, 3))
1769 call assert_equal(1, utf16idx(str, 4))
1770 call assert_equal(3, utf16idx(str, 5))
1771 call assert_equal(3, utf16idx(str, 6))
1772 call assert_equal(3, utf16idx(str, 7))
1773 call assert_equal(3, utf16idx(str, 8))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001774 call assert_equal(5, utf16idx(str, 9))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001775 call assert_equal(6, utf16idx(str, 10))
1776 call assert_equal(-1, utf16idx(str, 11))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001777
1778 " UTF-16 index of a string with composing characters
1779 let str = '-á-b́'
1780 call assert_equal(0, utf16idx(str, 0))
1781 call assert_equal(1, utf16idx(str, 1))
1782 call assert_equal(1, utf16idx(str, 2))
1783 call assert_equal(1, utf16idx(str, 3))
1784 call assert_equal(2, utf16idx(str, 4))
1785 call assert_equal(3, utf16idx(str, 5))
1786 call assert_equal(3, utf16idx(str, 6))
1787 call assert_equal(3, utf16idx(str, 7))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001788 call assert_equal(4, utf16idx(str, 8))
1789 call assert_equal(-1, utf16idx(str, 9))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001790 call assert_equal(0, utf16idx(str, 0, v:true))
1791 call assert_equal(1, utf16idx(str, 1, v:true))
1792 call assert_equal(2, utf16idx(str, 2, v:true))
1793 call assert_equal(2, utf16idx(str, 3, v:true))
1794 call assert_equal(3, utf16idx(str, 4, v:true))
1795 call assert_equal(4, utf16idx(str, 5, v:true))
1796 call assert_equal(5, utf16idx(str, 6, v:true))
1797 call assert_equal(5, utf16idx(str, 7, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001798 call assert_equal(6, utf16idx(str, 8, v:true))
1799 call assert_equal(-1, utf16idx(str, 9, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001800
1801 " string with multiple composing characters
1802 let str = '-ą́-ą́'
1803 call assert_equal(0, utf16idx(str, 0))
1804 call assert_equal(1, utf16idx(str, 1))
1805 call assert_equal(1, utf16idx(str, 2))
1806 call assert_equal(1, utf16idx(str, 3))
1807 call assert_equal(1, utf16idx(str, 4))
1808 call assert_equal(1, utf16idx(str, 5))
1809 call assert_equal(2, utf16idx(str, 6))
1810 call assert_equal(3, utf16idx(str, 7))
1811 call assert_equal(3, utf16idx(str, 8))
1812 call assert_equal(3, utf16idx(str, 9))
1813 call assert_equal(3, utf16idx(str, 10))
1814 call assert_equal(3, utf16idx(str, 11))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001815 call assert_equal(4, utf16idx(str, 12))
1816 call assert_equal(-1, utf16idx(str, 13))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001817 call assert_equal(0, utf16idx(str, 0, v:true))
1818 call assert_equal(1, utf16idx(str, 1, v:true))
1819 call assert_equal(2, utf16idx(str, 2, v:true))
1820 call assert_equal(2, utf16idx(str, 3, v:true))
1821 call assert_equal(3, utf16idx(str, 4, v:true))
1822 call assert_equal(3, utf16idx(str, 5, v:true))
1823 call assert_equal(4, utf16idx(str, 6, v:true))
1824 call assert_equal(5, utf16idx(str, 7, v:true))
1825 call assert_equal(6, utf16idx(str, 8, v:true))
1826 call assert_equal(6, utf16idx(str, 9, v:true))
1827 call assert_equal(7, utf16idx(str, 10, v:true))
1828 call assert_equal(7, utf16idx(str, 11, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001829 call assert_equal(8, utf16idx(str, 12, v:true))
1830 call assert_equal(-1, utf16idx(str, 13, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001831
1832 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001833 call assert_equal(0, utf16idx('', 0))
1834 call assert_equal(-1, utf16idx('', 1))
1835 call assert_equal(0, utf16idx('', 0, v:true))
1836 call assert_equal(-1, utf16idx('', 1, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001837
1838 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001839 call assert_equal(0, utf16idx("", 0))
1840 call assert_equal(-1, utf16idx("", 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001841 call assert_equal(-1, utf16idx("abc", -1))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001842 call assert_equal(0, utf16idx(test_null_string(), 0))
1843 call assert_equal(-1, utf16idx(test_null_string(), 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001844 call assert_fails('let l = utf16idx([], 0)', 'E1174:')
1845 call assert_fails('let l = utf16idx("ab", [])', 'E1210:')
1846 call assert_fails('let l = utf16idx("ab", 0, [])', 'E1212:')
1847endfunc
1848
1849" Test for utf16idx() using a character index
1850func Test_utf16idx_from_charidx()
1851 let str = "abc"
1852 for i in str->strcharlen()->range()
1853 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1854 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001855 call assert_equal(3, utf16idx(str, 3, v:false, v:true))
1856 call assert_equal(-1, utf16idx(str, 4, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001857
1858 " UTF-16 index of a string with two byte characters
1859 let str = "a©©b"
1860 for i in str->strcharlen()->range()
1861 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1862 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001863 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1864 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001865
1866 " UTF-16 index of a string with four byte characters
1867 let str = "a😊😊b"
1868 call assert_equal(0, utf16idx(str, 0, v:false, v:true))
Yegappan Lakshmanan95707032023-06-14 13:10:15 +01001869 call assert_equal(1, utf16idx(str, 1, v:false, v:true))
1870 call assert_equal(3, utf16idx(str, 2, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001871 call assert_equal(5, utf16idx(str, 3, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001872 call assert_equal(6, utf16idx(str, 4, v:false, v:true))
1873 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001874
1875 " UTF-16 index of a string with composing characters
1876 let str = '-á-b́'
1877 for i in str->strcharlen()->range()
1878 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1879 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001880 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1881 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001882 for i in str->strchars()->range()
1883 call assert_equal(i, utf16idx(str, i, v:true, v:true))
1884 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001885 call assert_equal(6, utf16idx(str, 6, v:true, v:true))
1886 call assert_equal(-1, utf16idx(str, 7, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001887
1888 " string with multiple composing characters
1889 let str = '-ą́-ą́'
1890 for i in str->strcharlen()->range()
1891 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1892 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001893 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1894 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001895 for i in str->strchars()->range()
1896 call assert_equal(i, utf16idx(str, i, v:true, v:true))
1897 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001898 call assert_equal(8, utf16idx(str, 8, v:true, v:true))
1899 call assert_equal(-1, utf16idx(str, 9, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001900
1901 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001902 call assert_equal(0, utf16idx('', 0, v:false, v:true))
1903 call assert_equal(-1, utf16idx('', 1, v:false, v:true))
1904 call assert_equal(0, utf16idx('', 0, v:true, v:true))
1905 call assert_equal(-1, utf16idx('', 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001906
1907 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001908 call assert_equal(0, utf16idx(test_null_string(), 0, v:true, v:true))
1909 call assert_equal(-1, utf16idx(test_null_string(), 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001910 call assert_fails('let l = utf16idx("ab", 0, v:false, [])', 'E1212:')
1911endfunc
1912
1913" Test for strutf16len()
1914func Test_strutf16len()
1915 call assert_equal(3, strutf16len('abc'))
1916 call assert_equal(3, 'abc'->strutf16len(v:true))
1917 call assert_equal(4, strutf16len('a©©b'))
1918 call assert_equal(4, strutf16len('a©©b', v:true))
1919 call assert_equal(6, strutf16len('a😊😊b'))
1920 call assert_equal(6, strutf16len('a😊😊b', v:true))
1921 call assert_equal(4, strutf16len('-á-b́'))
1922 call assert_equal(6, strutf16len('-á-b́', v:true))
1923 call assert_equal(4, strutf16len('-ą́-ą́'))
1924 call assert_equal(8, strutf16len('-ą́-ą́', v:true))
1925 call assert_equal(0, strutf16len(''))
1926
1927 " error cases
1928 call assert_fails('let l = strutf16len([])', 'E1174:')
1929 call assert_fails('let l = strutf16len("a", [])', 'E1212:')
1930 call assert_equal(0, strutf16len(test_null_string()))
1931endfunc
1932
Bram Moolenaar41042f32017-03-09 12:09:32 +01001933func Test_count()
1934 let l = ['a', 'a', 'A', 'b']
1935 call assert_equal(2, count(l, 'a'))
1936 call assert_equal(1, count(l, 'A'))
1937 call assert_equal(1, count(l, 'b'))
1938 call assert_equal(0, count(l, 'B'))
1939
1940 call assert_equal(2, count(l, 'a', 0))
1941 call assert_equal(1, count(l, 'A', 0))
1942 call assert_equal(1, count(l, 'b', 0))
1943 call assert_equal(0, count(l, 'B', 0))
1944
1945 call assert_equal(3, count(l, 'a', 1))
1946 call assert_equal(3, count(l, 'A', 1))
1947 call assert_equal(1, count(l, 'b', 1))
1948 call assert_equal(1, count(l, 'B', 1))
1949 call assert_equal(0, count(l, 'c', 1))
1950
1951 call assert_equal(1, count(l, 'a', 0, 1))
1952 call assert_equal(2, count(l, 'a', 1, 1))
1953 call assert_fails('call count(l, "a", 0, 10)', 'E684:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02001954 call assert_fails('call count(l, "a", [])', 'E745:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001955
1956 let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
1957 call assert_equal(2, count(d, 'a'))
1958 call assert_equal(1, count(d, 'A'))
1959 call assert_equal(1, count(d, 'b'))
1960 call assert_equal(0, count(d, 'B'))
1961
1962 call assert_equal(2, count(d, 'a', 0))
1963 call assert_equal(1, count(d, 'A', 0))
1964 call assert_equal(1, count(d, 'b', 0))
1965 call assert_equal(0, count(d, 'B', 0))
1966
1967 call assert_equal(3, count(d, 'a', 1))
1968 call assert_equal(3, count(d, 'A', 1))
1969 call assert_equal(1, count(d, 'b', 1))
1970 call assert_equal(1, count(d, 'B', 1))
1971 call assert_equal(0, count(d, 'c', 1))
1972
1973 call assert_fails('call count(d, "a", 0, 1)', 'E474:')
Bram Moolenaar9966b212017-07-28 16:46:57 +02001974
1975 call assert_equal(0, count("foo", "bar"))
1976 call assert_equal(1, count("foo", "oo"))
1977 call assert_equal(2, count("foo", "o"))
1978 call assert_equal(0, count("foo", "O"))
1979 call assert_equal(2, count("foo", "O", 1))
1980 call assert_equal(2, count("fooooo", "oo"))
Bram Moolenaar338e47f2017-12-19 11:55:26 +01001981 call assert_equal(0, count("foo", ""))
Bram Moolenaar17aca702019-05-16 22:24:55 +02001982
zeertzjq4f389e72023-08-17 22:10:40 +02001983 call assert_fails('call count(0, 0)', 'E706:')
1984 call assert_fails('call count("", "", {})', ['E728:', 'E728:'])
Bram Moolenaar41042f32017-03-09 12:09:32 +01001985endfunc
1986
1987func Test_changenr()
1988 new Xchangenr
1989 call assert_equal(0, changenr())
1990 norm ifoo
1991 call assert_equal(1, changenr())
1992 set undolevels=10
1993 norm Sbar
1994 call assert_equal(2, changenr())
1995 undo
1996 call assert_equal(1, changenr())
1997 redo
1998 call assert_equal(2, changenr())
1999 bw!
2000 set undolevels&
2001endfunc
2002
2003func Test_filewritable()
2004 new Xfilewritable
2005 write!
2006 call assert_equal(1, filewritable('Xfilewritable'))
2007
2008 call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
2009 call assert_equal(0, filewritable('Xfilewritable'))
2010
2011 call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
Bram Moolenaara4208962019-08-24 20:50:19 +02002012 call assert_equal(1, 'Xfilewritable'->filewritable())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002013
2014 call assert_equal(0, filewritable('doesnotexist'))
2015
Bram Moolenaar70e67252022-09-27 19:34:35 +01002016 call mkdir('Xwritedir', 'D')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002017 call assert_equal(2, filewritable('Xwritedir'))
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +02002018
Bram Moolenaar41042f32017-03-09 12:09:32 +01002019 call delete('Xfilewritable')
2020 bw!
2021endfunc
2022
Bram Moolenaar82956662018-10-06 15:18:45 +02002023func Test_Executable()
2024 if has('win32')
2025 call assert_equal(1, executable('notepad'))
Bram Moolenaara4208962019-08-24 20:50:19 +02002026 call assert_equal(1, 'notepad.exe'->executable())
Bram Moolenaar82956662018-10-06 15:18:45 +02002027 call assert_equal(0, executable('notepad.exe.exe'))
2028 call assert_equal(0, executable('shell32.dll'))
2029 call assert_equal(0, executable('win.ini'))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002030
2031 " get "notepad" path and remove the leading drive and sep. (ex. 'C:\')
2032 let notepadcmd = exepath('notepad.exe')
2033 let driveroot = notepadcmd[:2]
2034 let notepadcmd = notepadcmd[3:]
2035 new
2036 " check that the relative path works in /
2037 execute 'lcd' driveroot
2038 call assert_equal(1, executable(notepadcmd))
2039 call assert_equal(driveroot .. notepadcmd, notepadcmd->exepath())
2040 bwipe
2041
2042 " create "notepad.bat"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002043 call mkdir('Xnotedir')
2044 let notepadbat = fnamemodify('Xnotedir/notepad.bat', ':p')
Bram Moolenaar95da1362020-05-30 18:37:55 +02002045 call writefile([], notepadbat)
2046 new
2047 " check that the path and the pathext order is valid
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002048 lcd Xnotedir
Bram Moolenaar95da1362020-05-30 18:37:55 +02002049 let [pathext, $PATHEXT] = [$PATHEXT, '.com;.exe;.bat;.cmd']
2050 call assert_equal(notepadbat, exepath('notepad'))
2051 let $PATHEXT = pathext
AmberArrf5d0f542023-08-20 20:03:45 +02002052 " check for symbolic link
2053 execute 'silent !mklink np.bat "' .. notepadbat .. '"'
2054 call assert_equal(1, executable('./np.bat'))
2055 call assert_equal(1, executable('./np'))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002056 bwipe
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002057 eval 'Xnotedir'->delete('rf')
Bram Moolenaar82956662018-10-06 15:18:45 +02002058 elseif has('unix')
Bram Moolenaara4208962019-08-24 20:50:19 +02002059 call assert_equal(1, 'cat'->executable())
Bram Moolenaara05a0d32018-10-07 18:43:05 +02002060 call assert_equal(0, executable('nodogshere'))
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002061
2062 " get "cat" path and remove the leading /
2063 let catcmd = exepath('cat')[1:]
2064 new
Bram Moolenaara4208962019-08-24 20:50:19 +02002065 " check that the relative path works in /
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002066 lcd /
2067 call assert_equal(1, executable(catcmd))
Bram Moolenaara3870832021-01-01 14:20:44 +01002068 let result = catcmd->exepath()
2069 " when using chroot looking for sbin/cat can return bin/cat, that is OK
2070 if catcmd =~ '\<sbin\>' && result =~ '\<bin\>'
2071 call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result)
2072 else
Bram Moolenaarbf634a02021-07-31 17:20:04 +02002073 " /bin/cat and /usr/bin/cat may be hard linked, we could get either
2074 let result = substitute(result, '/usr/bin/cat', '/bin/cat', '')
2075 let catcmd = substitute(catcmd, 'usr/bin/cat', 'bin/cat', '')
Bram Moolenaara3870832021-01-01 14:20:44 +01002076 call assert_equal('/' .. catcmd, result)
2077 endif
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002078 bwipe
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002079 else
2080 throw 'Skipped: does not work on this platform'
Bram Moolenaar82956662018-10-06 15:18:45 +02002081 endif
2082endfunc
2083
LemonBoy40fd7e62022-05-05 20:18:16 +01002084func Test_executable_windows_store_apps()
2085 CheckMSWindows
2086
2087 " Windows Store apps install some 'decoy' .exe that require some careful
2088 " handling as they behave similarly to symlinks.
2089 let app_dir = expand("$LOCALAPPDATA\\Microsoft\\WindowsApps")
2090 if !isdirectory(app_dir)
2091 return
2092 endif
2093
2094 let save_path = $PATH
2095 let $PATH = app_dir
2096 " Ensure executable() finds all the app .exes
2097 for entry in readdir(app_dir)
2098 if entry =~ '\.exe$'
2099 call assert_true(executable(entry))
2100 endif
2101 endfor
2102
2103 let $PATH = save_path
2104endfunc
2105
Bram Moolenaar86621892019-03-30 21:51:28 +01002106func Test_executable_longname()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002107 CheckMSWindows
Bram Moolenaar86621892019-03-30 21:51:28 +01002108
Bram Moolenaarf637bce2020-11-23 18:14:56 +01002109 " Create a temporary .bat file with 205 characters in the name.
2110 " Maximum length of a filename (including the path) on MS-Windows is 259
2111 " characters.
2112 " See https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
2113 let len = 259 - getcwd()->len() - 6
2114 if len > 200
2115 let len = 200
2116 endif
2117
2118 let fname = 'X' . repeat('あ', len) . '.bat'
Bram Moolenaar86621892019-03-30 21:51:28 +01002119 call writefile([], fname)
2120 call assert_equal(1, executable(fname))
2121 call delete(fname)
2122endfunc
2123
Bram Moolenaar41042f32017-03-09 12:09:32 +01002124func Test_hostname()
2125 let hostname_vim = hostname()
2126 if has('unix')
2127 let hostname_system = systemlist('uname -n')[0]
2128 call assert_equal(hostname_vim, hostname_system)
2129 endif
2130endfunc
2131
2132func Test_getpid()
2133 " getpid() always returns the same value within a vim instance.
2134 call assert_equal(getpid(), getpid())
2135 if has('unix')
2136 call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
2137 endif
2138endfunc
2139
2140func Test_hlexists()
2141 call assert_equal(0, hlexists('does_not_exist'))
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002142 call assert_equal(0, 'Number'->hlexists())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002143 call assert_equal(0, highlight_exists('does_not_exist'))
2144 call assert_equal(0, highlight_exists('Number'))
2145 syntax on
2146 call assert_equal(0, hlexists('does_not_exist'))
2147 call assert_equal(1, hlexists('Number'))
2148 call assert_equal(0, highlight_exists('does_not_exist'))
2149 call assert_equal(1, highlight_exists('Number'))
2150 syntax off
2151endfunc
2152
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02002153" Test for the col() function
Bram Moolenaar41042f32017-03-09 12:09:32 +01002154func Test_col()
2155 new
2156 call setline(1, 'abcdef')
2157 norm gg4|mx6|mY2|
2158 call assert_equal(2, col('.'))
2159 call assert_equal(7, col('$'))
Bram Moolenaar8b633132020-03-20 18:20:51 +01002160 call assert_equal(2, col('v'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01002161 call assert_equal(4, col("'x"))
2162 call assert_equal(6, col("'Y"))
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02002163 call assert_equal(2, [1, 2]->col())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002164 call assert_equal(7, col([1, '$']))
2165
2166 call assert_equal(0, col(''))
2167 call assert_equal(0, col('x'))
2168 call assert_equal(0, col([2, '$']))
2169 call assert_equal(0, col([1, 100]))
2170 call assert_equal(0, col([1]))
Bram Moolenaar9d8d0b52020-04-24 22:47:31 +02002171 call assert_equal(0, col(test_null_list()))
Yegappan Lakshmanan4c8d2f02022-11-12 16:07:47 +00002172 call assert_fails('let c = col({})', 'E1222:')
2173 call assert_fails('let c = col(".", [])', 'E1210:')
Bram Moolenaar8b633132020-03-20 18:20:51 +01002174
2175 " test for getting the visual start column
2176 func T()
2177 let g:Vcol = col('v')
2178 return ''
2179 endfunc
2180 let g:Vcol = 0
2181 xmap <expr> <F2> T()
2182 exe "normal gg3|ve\<F2>"
2183 call assert_equal(3, g:Vcol)
2184 xunmap <F2>
2185 delfunc T
2186
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002187 " Test for the visual line start and end marks '< and '>
2188 call setline(1, ['one', 'one two', 'one two three'])
2189 "normal! ggVG
2190 call feedkeys("ggVG\<Esc>", 'xt')
2191 call assert_equal(1, col("'<"))
2192 call assert_equal(14, col("'>"))
2193 " Delete the last line of the visually selected region
2194 $d
2195 call assert_notequal(14, col("'>"))
2196
2197 " Test with 'virtualedit'
2198 set virtualedit=all
2199 call cursor(1, 10)
2200 call assert_equal(4, col('.'))
2201 set virtualedit&
2202
Yegappan Lakshmanan4c8d2f02022-11-12 16:07:47 +00002203 " Test for getting the column number in another window
2204 let winid = win_getid()
2205 new
2206 call win_execute(winid, 'normal 1G$')
2207 call assert_equal(3, col('.', winid))
2208 call win_execute(winid, 'normal 2G')
2209 call assert_equal(8, col('$', winid))
2210 call assert_equal(0, col('.', 5001))
2211
Bram Moolenaar41042f32017-03-09 12:09:32 +01002212 bw!
2213endfunc
2214
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002215" Test for input()
2216func Test_input_func()
2217 " Test for prompt with multiple lines
2218 redir => v
2219 call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt')
2220 redir END
2221 call assert_equal("B", c)
2222 call assert_equal(['A', 'B', 'C'], split(v, "\n"))
2223
2224 " Test for default value
2225 call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt')
2226 call assert_equal('red', c)
2227
2228 " Test for completion at the input prompt
2229 func! Tcomplete(arglead, cmdline, pos)
2230 return "item1\nitem2\nitem3"
2231 endfunc
Bram Moolenaar9d489562020-07-30 20:08:50 +02002232 call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>"
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002233 \ .. "\<C-A>\<CR>", 'xt')
2234 delfunc Tcomplete
2235 call assert_equal('item1 item2 item3', c)
Bram Moolenaar578fe942020-02-27 21:32:51 +01002236
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002237 " Test for using special characters as default input
Bram Moolenaar1f448d92021-03-22 19:37:06 +01002238 call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt')
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002239 call assert_equal('y', c)
2240
zeertzjqe3a529b2022-06-05 19:01:37 +01002241 " Test for using text with composing characters as default input
2242 call feedkeys(":let c = input('name? ', \"ã̳\")\<CR>\<CR>", 'xt')
2243 call assert_equal('ã̳', c)
2244
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002245 " Test for using <CR> as default input
2246 call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt')
2247 call assert_equal(' x', c)
2248
Bram Moolenaar578fe942020-02-27 21:32:51 +01002249 call assert_fails("call input('F:', '', 'invalid')", 'E180:')
2250 call assert_fails("call input('F:', '', [])", 'E730:')
Jim Zhou3255af82025-02-27 19:29:50 +01002251
zeertzjq7a5115c2025-03-19 20:29:58 +01002252 " Test for using "command" as the completion function
Jim Zhou3255af82025-02-27 19:29:50 +01002253 call feedkeys(":let c = input('Command? ', '', 'command')\<CR>"
2254 \ .. "echo bufnam\<C-A>\<CR>", 'xt')
2255 call assert_equal('echo bufname(', c)
zeertzjq7a5115c2025-03-19 20:29:58 +01002256
2257 " Test for using "shellcmdline" as the completion function
2258 call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2259 \ .. "vim test_functions.\<C-A>\<CR>", 'xt')
2260 call assert_equal('vim test_functions.vim', c)
2261 if executable('whoami')
2262 call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2263 \ .. "whoam\<C-A>\<CR>", 'xt')
2264 call assert_match('\<whoami\>', c)
2265 endif
Bram Moolenaar578fe942020-02-27 21:32:51 +01002266endfunc
2267
2268" Test for the inputdialog() function
2269func Test_inputdialog()
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002270 set timeout timeoutlen=10
Bram Moolenaar99fa7212020-04-26 15:59:55 +02002271 if has('gui_running')
2272 call assert_fails('let v=inputdialog([], "xx")', 'E730:')
2273 call assert_fails('let v=inputdialog("Q", [])', 'E730:')
2274 else
2275 call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt')
2276 call assert_equal('xx', v)
2277 call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt')
2278 call assert_equal('yy', v)
2279 endif
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002280 set timeout& timeoutlen&
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002281endfunc
2282
2283" Test for inputlist()
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002284func Test_inputlist()
2285 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
2286 call assert_equal(1, c)
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002287 call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx')
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002288 call assert_equal(2, c)
2289 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
2290 call assert_equal(3, c)
2291
Bram Moolenaareebd5552020-06-10 15:45:57 +02002292 " CR to cancel
2293 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx')
2294 call assert_equal(0, c)
2295
2296 " Esc to cancel
2297 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx')
2298 call assert_equal(0, c)
2299
2300 " q to cancel
2301 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx')
2302 call assert_equal(0, c)
2303
=?UTF-8?q?Luka=20Marku=C5=A1i=C4=87?=5cf94572021-05-20 21:14:20 +02002304 " Cancel after inputting a number
2305 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx')
2306 call assert_equal(0, c)
2307
Bram Moolenaarcde0ff32020-04-04 14:00:39 +02002308 " Use backspace to delete characters in the prompt
2309 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx')
2310 call assert_equal(2, c)
2311
2312 " Use mouse to make a selection
2313 call test_setmouse(&lines - 3, 2)
2314 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2315 call assert_equal(1, c)
2316 " Mouse click outside of the list
2317 call test_setmouse(&lines - 6, 2)
2318 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2319 call assert_equal(-2, c)
2320
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002321 call assert_fails('call inputlist("")', 'E686:')
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02002322 call assert_fails('call inputlist(test_null_list())', 'E686:')
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002323endfunc
2324
Bram Moolenaar7bdcba02023-01-02 11:59:26 +00002325func Test_range_inputlist()
2326 " flush out any garbage left in the buffer
2327 while getchar(0)
2328 endwhile
2329
2330 call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x')
2331 call assert_equal(1, result)
2332 call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x')
2333 call assert_equal(1, result)
2334
2335 unlet result
2336endfunc
2337
Bram Moolenaarcaf64342017-03-02 22:11:33 +01002338func Test_balloon_show()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002339 CheckFeature balloon_eval
Bram Moolenaarb47bed22021-04-14 17:06:43 +02002340
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002341 " This won't do anything but must not crash either.
2342 call balloon_show('hi!')
2343 if !has('gui_running')
2344 call balloon_show(range(3))
2345 call balloon_show([])
Bram Moolenaara0107bd2017-03-02 22:48:01 +01002346 endif
Bram Moolenaarcaf64342017-03-02 22:11:33 +01002347endfunc
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002348
2349func Test_setbufvar_options()
2350 " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
zeertzjq49f05242023-02-04 10:58:34 +00002351 " window layout and cursor position.
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002352 call assert_equal(1, winnr('$'))
2353 split dummy_preview
2354 resize 2
2355 set winfixheight winfixwidth
2356 let prev_id = win_getid()
2357
2358 wincmd j
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002359 let wh = winheight(0)
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002360 let dummy_buf = bufnr('dummy_buf1', v:true)
2361 call setbufvar(dummy_buf, '&buftype', 'nofile')
2362 execute 'belowright vertical split #' . dummy_buf
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002363 call assert_equal(wh, winheight(0))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002364 let dum1_id = win_getid()
zeertzjq49f05242023-02-04 10:58:34 +00002365 call setline(1, 'foo')
2366 normal! V$
2367 call assert_equal(4, col('.'))
2368 call setbufvar('dummy_preview', '&buftype', 'nofile')
2369 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002370
2371 wincmd h
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002372 let wh = winheight(0)
zeertzjq49f05242023-02-04 10:58:34 +00002373 call setline(1, 'foo')
2374 normal! V$
2375 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002376 let dummy_buf = bufnr('dummy_buf2', v:true)
Bram Moolenaar196b4662019-09-06 21:34:30 +02002377 eval 'nofile'->setbufvar(dummy_buf, '&buftype')
zeertzjq49f05242023-02-04 10:58:34 +00002378 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002379 execute 'belowright vertical split #' . dummy_buf
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002380 call assert_equal(wh, winheight(0))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002381
2382 bwipe!
2383 call win_gotoid(prev_id)
2384 bwipe!
2385 call win_gotoid(dum1_id)
2386 bwipe!
2387endfunc
Bram Moolenaard4863aa2017-04-07 19:50:12 +02002388
Bram Moolenaardff97e62022-01-24 20:00:55 +00002389func Test_setbufvar_keep_window_title()
2390 CheckRunVimInTerminal
Bram Moolenaara6c09a72022-01-24 22:02:15 +00002391 if !has('title') || empty(&t_ts)
2392 throw "Skipped: can't get/set title"
2393 endif
Bram Moolenaardff97e62022-01-24 20:00:55 +00002394
2395 let lines =<< trim END
Bram Moolenaar14501122022-01-24 22:32:28 +00002396 set title
Bram Moolenaardff97e62022-01-24 20:00:55 +00002397 edit Xa.txt
2398 let g:buf = bufadd('Xb.txt')
2399 inoremap <F2> <C-R>=setbufvar(g:buf, '&autoindent', 1) ?? ''<CR>
2400 END
Bram Moolenaar70e67252022-09-27 19:34:35 +01002401 call writefile(lines, 'Xsetbufvar', 'D')
Bram Moolenaardff97e62022-01-24 20:00:55 +00002402 let buf = RunVimInTerminal('-S Xsetbufvar', {})
Bram Moolenaar3a8ad592022-01-24 22:18:24 +00002403 call WaitForAssert({-> assert_match('Xa.txt', term_gettitle(buf))}, 1000)
Bram Moolenaardff97e62022-01-24 20:00:55 +00002404
2405 call term_sendkeys(buf, "i\<F2>")
2406 call TermWait(buf)
2407 call term_sendkeys(buf, "\<Esc>")
2408 call TermWait(buf)
2409 call assert_match('Xa.txt', term_gettitle(buf))
2410
2411 call StopVimInTerminal(buf)
Bram Moolenaardff97e62022-01-24 20:00:55 +00002412endfunc
2413
Bram Moolenaard4863aa2017-04-07 19:50:12 +02002414func Test_redo_in_nested_functions()
2415 nnoremap g. :set opfunc=Operator<CR>g@
2416 function Operator( type, ... )
2417 let @x = 'XXX'
2418 execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
2419 endfunction
2420
2421 function! Apply()
2422 5,6normal! .
2423 endfunction
2424
2425 new
2426 call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
2427 1normal g.i"
2428 call assert_equal('some "XXX" text', getline(1))
2429 3,4normal .
2430 call assert_equal('some "XXX" text', getline(3))
2431 call assert_equal('more "XXX" text', getline(4))
2432 call Apply()
2433 call assert_equal('some "XXX" text', getline(5))
2434 call assert_equal('more "XXX" text', getline(6))
2435 bwipe!
2436
2437 nunmap g.
2438 delfunc Operator
2439 delfunc Apply
2440endfunc
Bram Moolenaar20615522017-06-05 18:46:26 +02002441
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002442func Test_trim()
2443 call assert_equal("Testing", trim(" \t\r\r\x0BTesting \t\n\r\n\t\x0B\x0B"))
Bram Moolenaarf92e58c2019-09-08 21:51:41 +02002444 call assert_equal("Testing", " \t \r\r\n\n\x0BTesting \t\n\r\n\t\x0B\x0B"->trim())
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002445 call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
2446 call assert_equal("wRE \tSERVEzyww", trim("wRE \tSERVEzyww"))
2447 call assert_equal("abcd\t xxxx tail", trim(" \tabcd\t xxxx tail"))
2448 call assert_equal("\tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", " "))
2449 call assert_equal(" \tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", "abx"))
2450 call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
2451 call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
2452 call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r 你好您R E SER V E早好你你 \t \x0B", ))
2453 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" 你好您R E SER V E早好你你 \t \x0B", " 你好"))
2454 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你好tes"))
2455 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你你你好好好tttsses"))
2456 call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
2457 call assert_equal("", trim("", ""))
2458 call assert_equal("a", trim("a", ""))
2459 call assert_equal("", trim("", "a"))
2460
Bram Moolenaar2245ae12020-05-31 22:20:36 +02002461 call assert_equal("vim", trim(" vim ", " ", 0))
2462 call assert_equal("vim ", trim(" vim ", " ", 1))
2463 call assert_equal(" vim", trim(" vim ", " ", 2))
2464 call assert_fails('eval trim(" vim ", " ", [])', 'E745:')
2465 call assert_fails('eval trim(" vim ", " ", -1)', 'E475:')
2466 call assert_fails('eval trim(" vim ", " ", 3)', 'E475:')
Illia Bobyr80799172023-10-17 18:00:50 +02002467 call assert_fails('eval trim(" vim ", 0)', 'E1174:')
Bram Moolenaar2245ae12020-05-31 22:20:36 +02002468
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02002469 let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '')
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002470 call assert_equal("x", trim(chars . "x" . chars))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002471
Illia Bobyr80799172023-10-17 18:00:50 +02002472 call assert_equal("x", trim(chars . "x" . chars, '', 0))
2473 call assert_equal("x" . chars, trim(chars . "x" . chars, '', 1))
2474 call assert_equal(chars . "x", trim(chars . "x" . chars, '', 2))
Illia Bobyr6e638672023-10-17 11:09:45 +02002475
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002476 call assert_fails('let c=trim([])', 'E730:')
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002477endfunc
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02002478
2479" Test for reg_recording() and reg_executing()
2480func Test_reg_executing_and_recording()
2481 let s:reg_stat = ''
2482 func s:save_reg_stat()
2483 let s:reg_stat = reg_recording() . ':' . reg_executing()
2484 return ''
2485 endfunc
2486
2487 new
2488 call s:save_reg_stat()
2489 call assert_equal(':', s:reg_stat)
2490 call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
2491 call assert_equal('a:', s:reg_stat)
2492 call feedkeys("@a", 'xt')
2493 call assert_equal(':a', s:reg_stat)
2494 call feedkeys("qb@aq", 'xt')
2495 call assert_equal('b:a', s:reg_stat)
2496 call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
2497 call assert_equal('":', s:reg_stat)
2498
Bram Moolenaarcce713d2019-03-04 11:40:12 +01002499 " :normal command saves and restores reg_executing
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002500 let s:reg_stat = ''
Bram Moolenaarcce713d2019-03-04 11:40:12 +01002501 let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
2502 func TestFunc() abort
2503 normal! ia
2504 endfunc
2505 call feedkeys("@q", 'xt')
2506 call assert_equal(':q', s:reg_stat)
2507 delfunc TestFunc
2508
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002509 " getchar() command saves and restores reg_executing
2510 map W :call TestFunc()<CR>
2511 let @q = "W"
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002512 let g:typed = ''
2513 let g:regs = []
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002514 func TestFunc() abort
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002515 let g:regs += [reg_executing()]
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002516 let g:typed = getchar(0)
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002517 let g:regs += [reg_executing()]
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002518 endfunc
2519 call feedkeys("@qy", 'xt')
2520 call assert_equal(char2nr("y"), g:typed)
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002521 call assert_equal(['q', 'q'], g:regs)
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002522 delfunc TestFunc
2523 unmap W
2524 unlet g:typed
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002525 unlet g:regs
2526
2527 " input() command saves and restores reg_executing
2528 map W :call TestFunc()<CR>
2529 let @q = "W"
2530 let g:typed = ''
2531 let g:regs = []
2532 func TestFunc() abort
2533 let g:regs += [reg_executing()]
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002534 let g:typed = '?'->input()
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002535 let g:regs += [reg_executing()]
2536 endfunc
2537 call feedkeys("@qy\<CR>", 'xt')
2538 call assert_equal("y", g:typed)
2539 call assert_equal(['q', 'q'], g:regs)
2540 delfunc TestFunc
2541 unmap W
2542 unlet g:typed
2543 unlet g:regs
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002544
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02002545 bwipe!
2546 delfunc s:save_reg_stat
2547 unlet s:reg_stat
2548endfunc
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002549
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002550func Test_inputsecret()
2551 map W :call TestFunc()<CR>
2552 let @q = "W"
2553 let g:typed1 = ''
2554 let g:typed2 = ''
2555 let g:regs = []
2556 func TestFunc() abort
2557 let g:typed1 = '?'->inputsecret()
2558 let g:typed2 = inputsecret('password: ')
2559 endfunc
2560 call feedkeys("@qsomething\<CR>else\<CR>", 'xt')
2561 call assert_equal("something", g:typed1)
2562 call assert_equal("else", g:typed2)
2563 delfunc TestFunc
2564 unmap W
2565 unlet g:typed1
2566 unlet g:typed2
2567endfunc
2568
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002569func Test_getchar()
2570 call feedkeys('a', '')
2571 call assert_equal(char2nr('a'), getchar())
Bram Moolenaar3a7503c2021-06-07 18:29:17 +02002572 call assert_equal(0, getchar(0))
2573 call assert_equal(0, getchar(1))
2574
2575 call feedkeys('a', '')
2576 call assert_equal('a', getcharstr())
2577 call assert_equal('', getcharstr(0))
2578 call assert_equal('', getcharstr(1))
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002579
zeertzjqad6c45f2022-02-20 19:05:10 +00002580 call feedkeys("\<M-F2>", '')
2581 call assert_equal("\<M-F2>", getchar(0))
2582 call assert_equal(0, getchar(0))
2583
zeertzjqe0a2ab32025-02-02 09:14:35 +01002584 call feedkeys("\<Tab>", '')
2585 call assert_equal(char2nr("\<Tab>"), getchar())
2586 call feedkeys("\<Tab>", '')
2587 call assert_equal(char2nr("\<Tab>"), getchar(-1))
2588 call feedkeys("\<Tab>", '')
2589 call assert_equal(char2nr("\<Tab>"), getchar(-1, {}))
2590 call feedkeys("\<Tab>", '')
2591 call assert_equal(char2nr("\<Tab>"), getchar(-1, #{number: v:true}))
2592 call assert_equal(0, getchar(0))
2593 call assert_equal(0, getchar(1))
2594 call assert_equal(0, getchar(0, #{number: v:true}))
2595 call assert_equal(0, getchar(1, #{number: v:true}))
2596
2597 call feedkeys("\<Tab>", '')
2598 call assert_equal("\<Tab>", getcharstr())
2599 call feedkeys("\<Tab>", '')
2600 call assert_equal("\<Tab>", getcharstr(-1))
2601 call feedkeys("\<Tab>", '')
2602 call assert_equal("\<Tab>", getcharstr(-1, {}))
2603 call feedkeys("\<Tab>", '')
2604 call assert_equal("\<Tab>", getchar(-1, #{number: v:false}))
2605 call assert_equal('', getcharstr(0))
2606 call assert_equal('', getcharstr(1))
2607 call assert_equal('', getchar(0, #{number: v:false}))
2608 call assert_equal('', getchar(1, #{number: v:false}))
2609
2610 for key in ["C-I", "C-X", "M-x"]
2611 let lines =<< eval trim END
2612 call feedkeys("\<*{key}>", '')
2613 call assert_equal(char2nr("\<{key}>"), getchar())
2614 call feedkeys("\<*{key}>", '')
2615 call assert_equal(char2nr("\<{key}>"), getchar(-1))
2616 call feedkeys("\<*{key}>", '')
2617 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{}}))
2618 call feedkeys("\<*{key}>", '')
2619 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'number': 1}}))
2620 call feedkeys("\<*{key}>", '')
2621 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'simplify': 1}}))
2622 call feedkeys("\<*{key}>", '')
2623 call assert_equal("\<*{key}>", getchar(-1, {{'simplify': v:false}}))
2624 call assert_equal(0, getchar(0))
2625 call assert_equal(0, getchar(1))
2626 END
2627 call v9.CheckLegacyAndVim9Success(lines)
2628
2629 let lines =<< eval trim END
2630 call feedkeys("\<*{key}>", '')
2631 call assert_equal("\<{key}>", getcharstr())
2632 call feedkeys("\<*{key}>", '')
2633 call assert_equal("\<{key}>", getcharstr(-1))
2634 call feedkeys("\<*{key}>", '')
2635 call assert_equal("\<{key}>", getcharstr(-1, {{}}))
2636 call feedkeys("\<*{key}>", '')
2637 call assert_equal("\<{key}>", getchar(-1, {{'number': 0}}))
2638 call feedkeys("\<*{key}>", '')
2639 call assert_equal("\<{key}>", getcharstr(-1, {{'simplify': 1}}))
2640 call feedkeys("\<*{key}>", '')
2641 call assert_equal("\<*{key}>", getcharstr(-1, {{'simplify': v:false}}))
2642 call assert_equal('', getcharstr(0))
2643 call assert_equal('', getcharstr(1))
2644 END
2645 call v9.CheckLegacyAndVim9Success(lines)
2646 endfor
2647
2648 call assert_fails('call getchar(1, 1)', 'E1206:')
2649 call assert_fails('call getcharstr(1, 1)', 'E1206:')
zeertzjqedf0f7d2025-02-02 19:01:01 +01002650 call assert_fails('call getchar(1, #{cursor: "foo"})', 'E475:')
2651 call assert_fails('call getcharstr(1, #{cursor: "foo"})', 'E475:')
2652 call assert_fails('call getchar(1, #{cursor: 0z})', 'E976:')
2653 call assert_fails('call getcharstr(1, #{cursor: 0z})', 'E976:')
2654 call assert_fails('call getchar(1, #{simplify: 0z})', 'E974:')
2655 call assert_fails('call getcharstr(1, #{simplify: 0z})', 'E974:')
2656 call assert_fails('call getchar(1, #{number: []})', 'E745:')
2657 call assert_fails('call getchar(1, #{number: {}})', 'E728:')
zeertzjqe0a2ab32025-02-02 09:14:35 +01002658 call assert_fails('call getcharstr(1, #{number: v:true})', 'E475:')
2659 call assert_fails('call getcharstr(1, #{number: v:false})', 'E475:')
2660
Bram Moolenaardb3a2052019-11-16 18:22:41 +01002661 call setline(1, 'xxxx')
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002662 call test_setmouse(1, 3)
2663 let v:mouse_win = 9
2664 let v:mouse_winid = 9
2665 let v:mouse_lnum = 9
2666 let v:mouse_col = 9
2667 call feedkeys("\<S-LeftMouse>", '')
2668 call assert_equal("\<S-LeftMouse>", getchar())
2669 call assert_equal(1, v:mouse_win)
2670 call assert_equal(win_getid(1), v:mouse_winid)
2671 call assert_equal(1, v:mouse_lnum)
2672 call assert_equal(3, v:mouse_col)
Bram Moolenaardb3a2052019-11-16 18:22:41 +01002673 enew!
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002674endfunc
2675
zeertzjqedf0f7d2025-02-02 19:01:01 +01002676func Test_getchar_cursor_position()
2677 CheckRunVimInTerminal
2678
2679 let lines =<< trim END
2680 call setline(1, ['foobar', 'foobar', 'foobar'])
2681 call cursor(3, 6)
2682 nnoremap <F1> <Cmd>echo 1234<Bar>call getchar()<CR>
2683 nnoremap <F2> <Cmd>call getchar()<CR>
2684 nnoremap <F3> <Cmd>call getchar(-1, {})<CR>
2685 nnoremap <F4> <Cmd>call getchar(-1, #{cursor: 'msg'})<CR>
2686 nnoremap <F5> <Cmd>call getchar(-1, #{cursor: 'keep'})<CR>
2687 nnoremap <F6> <Cmd>call getchar(-1, #{cursor: 'hide'})<CR>
2688 END
2689 call writefile(lines, 'XgetcharCursorPos', 'D')
2690 let buf = RunVimInTerminal('-S XgetcharCursorPos', {'rows': 6})
2691 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2692
2693 call term_sendkeys(buf, "\<F1>")
2694 call WaitForAssert({-> assert_equal([6, 5], term_getcursor(buf)[0:1])})
2695 call assert_true(term_getcursor(buf)[2].visible)
2696 call term_sendkeys(buf, 'a')
2697 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2698 call assert_true(term_getcursor(buf)[2].visible)
2699
2700 for key in ["\<F2>", "\<F3>", "\<F4>"]
2701 call term_sendkeys(buf, key)
2702 call WaitForAssert({-> assert_equal([6, 1], term_getcursor(buf)[0:1])})
2703 call assert_true(term_getcursor(buf)[2].visible)
2704 call term_sendkeys(buf, 'a')
2705 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2706 call assert_true(term_getcursor(buf)[2].visible)
2707 endfor
2708
2709 call term_sendkeys(buf, "\<F5>")
2710 call TermWait(buf, 50)
2711 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2712 call assert_true(term_getcursor(buf)[2].visible)
2713 call term_sendkeys(buf, 'a')
2714 call TermWait(buf, 50)
2715 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2716 call assert_true(term_getcursor(buf)[2].visible)
2717
2718 call term_sendkeys(buf, "\<F6>")
2719 call WaitForAssert({-> assert_false(term_getcursor(buf)[2].visible)})
2720 call term_sendkeys(buf, 'a')
2721 call WaitForAssert({-> assert_true(term_getcursor(buf)[2].visible)})
2722 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2723
2724 call StopVimInTerminal(buf)
2725endfunc
2726
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002727func Test_libcall_libcallnr()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002728 CheckFeature libcall
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002729
2730 if has('win32')
2731 let libc = 'msvcrt.dll'
2732 elseif has('mac')
2733 let libc = 'libSystem.B.dylib'
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002734 elseif executable('ldd')
2735 let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
2736 endif
2737 if get(l:, 'libc', '') ==# ''
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002738 " On Unix, libc.so can be in various places.
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002739 if has('linux')
2740 " There is not documented but regarding the 1st argument of glibc's
2741 " dlopen an empty string and nullptr are equivalent, so using an empty
2742 " string for the 1st argument of libcall allows to call functions.
2743 let libc = ''
2744 elseif has('sun')
2745 " Set the path to libc.so according to the architecture.
2746 let test_bits = system('file ' . GetVimProg())
2747 let test_arch = system('uname -p')
2748 if test_bits =~ '64-bit' && test_arch =~ 'sparc'
2749 let libc = '/usr/lib/sparcv9/libc.so'
2750 elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
2751 let libc = '/usr/lib/amd64/libc.so'
2752 else
2753 let libc = '/usr/lib/libc.so'
2754 endif
2755 else
2756 " Unfortunately skip this test until a good way is found.
2757 return
2758 endif
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002759 endif
2760
2761 if has('win32')
Bram Moolenaar02b31112019-08-31 22:16:38 +02002762 call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002763 else
Bram Moolenaar02b31112019-08-31 22:16:38 +02002764 call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002765 endif
2766
2767 " If function returns NULL, libcall() should return an empty string.
2768 call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
2769
2770 " Test libcallnr() with string and integer argument.
Bram Moolenaar02b31112019-08-31 22:16:38 +02002771 call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
2772 call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002773
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +02002774 call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
2775 call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002776
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +02002777 call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
2778 call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002779endfunc
Bram Moolenaard90a1442018-07-15 20:24:31 +02002780
2781sandbox function Fsandbox()
2782 normal ix
2783endfunc
2784
2785func Test_func_sandbox()
2786 sandbox let F = {-> 'hello'}
2787 call assert_equal('hello', F())
2788
Bram Moolenaara4208962019-08-24 20:50:19 +02002789 sandbox let F = {-> "normal ix\<Esc>"->execute()}
Bram Moolenaard90a1442018-07-15 20:24:31 +02002790 call assert_fails('call F()', 'E48:')
2791 unlet F
2792
2793 call assert_fails('call Fsandbox()', 'E48:')
2794 delfunc Fsandbox
Bram Moolenaar8dfcce32020-03-18 19:32:26 +01002795
2796 " From a sandbox try to set a predefined variable (which cannot be modified
2797 " from a sandbox)
2798 call assert_fails('sandbox let v:lnum = 10', 'E794:')
Bram Moolenaard90a1442018-07-15 20:24:31 +02002799endfunc
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002800
2801func EditAnotherFile()
2802 let word = expand('<cword>')
2803 edit Xfuncrange2
2804endfunc
2805
2806func Test_func_range_with_edit()
2807 " Define a function that edits another buffer, then call it with a range that
2808 " is invalid in that buffer.
Bram Moolenaar70e67252022-09-27 19:34:35 +01002809 call writefile(['just one line'], 'Xfuncrange2', 'D')
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002810 new
Bram Moolenaar196b4662019-09-06 21:34:30 +02002811 eval 10->range()->setline(1)
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002812 write Xfuncrange1
2813 call assert_fails('5,8call EditAnotherFile()', 'E16:')
2814
2815 call delete('Xfuncrange1')
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002816 bwipe!
2817endfunc
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002818
2819func Test_func_exists_on_reload()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002820 call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists', 'D')
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002821 call assert_equal(0, exists('*ExistingFunction'))
2822 source Xfuncexists
Bram Moolenaara4208962019-08-24 20:50:19 +02002823 call assert_equal(1, '*ExistingFunction'->exists())
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002824 " Redefining a function when reloading a script is OK.
2825 source Xfuncexists
2826 call assert_equal(1, exists('*ExistingFunction'))
2827
2828 " But redefining in another script is not OK.
Bram Moolenaar70e67252022-09-27 19:34:35 +01002829 call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2', 'D')
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002830 call assert_fails('source Xfuncexists2', 'E122:')
2831
Yegappan Lakshmanan611728f2021-05-24 15:15:47 +02002832 " Defining a new function from the cmdline should fail if the function is
2833 " already defined
2834 call assert_fails('call feedkeys(":func ExistingFunction()\<CR>", "xt")', 'E122:')
2835
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002836 delfunc ExistingFunction
2837 call assert_equal(0, exists('*ExistingFunction'))
2838 call writefile([
2839 \ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
2840 \ 'func ExistingFunction()', 'echo "no"', 'endfunc',
2841 \ ], 'Xfuncexists')
2842 call assert_fails('source Xfuncexists', 'E122:')
2843 call assert_equal(1, exists('*ExistingFunction'))
2844
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002845 delfunc ExistingFunction
2846endfunc
Bram Moolenaar2e050092019-01-27 15:00:36 +01002847
2848" Test confirm({msg} [, {choices} [, {default} [, {type}]]])
2849func Test_confirm()
Bram Moolenaar8c5a2782019-08-07 23:07:07 +02002850 CheckUnix
2851 CheckNotGui
Bram Moolenaar2e050092019-01-27 15:00:36 +01002852
2853 call feedkeys('o', 'L')
2854 let a = confirm('Press O to proceed')
2855 call assert_equal(1, a)
2856
2857 call feedkeys('y', 'L')
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02002858 let a = 'Are you sure?'->confirm("&Yes\n&No")
Bram Moolenaar2e050092019-01-27 15:00:36 +01002859 call assert_equal(1, a)
2860
2861 call feedkeys('n', 'L')
2862 let a = confirm('Are you sure?', "&Yes\n&No")
2863 call assert_equal(2, a)
2864
2865 " confirm() should return 0 when pressing CTRL-C.
Bram Moolenaar79296512020-03-22 16:17:14 +01002866 call feedkeys("\<C-C>", 'L')
Bram Moolenaar2e050092019-01-27 15:00:36 +01002867 let a = confirm('Are you sure?', "&Yes\n&No")
2868 call assert_equal(0, a)
2869
2870 " <Esc> requires another character to avoid it being seen as the start of an
2871 " escape sequence. Zero should be harmless.
Bram Moolenaara4208962019-08-24 20:50:19 +02002872 eval "\<Esc>0"->feedkeys('L')
Bram Moolenaar2e050092019-01-27 15:00:36 +01002873 let a = confirm('Are you sure?', "&Yes\n&No")
2874 call assert_equal(0, a)
2875
2876 " Default choice is returned when pressing <CR>.
2877 call feedkeys("\<CR>", 'L')
2878 let a = confirm('Are you sure?', "&Yes\n&No")
2879 call assert_equal(1, a)
2880
2881 call feedkeys("\<CR>", 'L')
2882 let a = confirm('Are you sure?', "&Yes\n&No", 2)
2883 call assert_equal(2, a)
2884
2885 call feedkeys("\<CR>", 'L')
2886 let a = confirm('Are you sure?', "&Yes\n&No", 0)
2887 call assert_equal(0, a)
2888
2889 " Test with the {type} 4th argument
2890 for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
2891 call feedkeys('y', 'L')
2892 let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
2893 call assert_equal(1, a)
2894 endfor
2895
2896 call assert_fails('call confirm([])', 'E730:')
2897 call assert_fails('call confirm("Are you sure?", [])', 'E730:')
2898 call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
2899 call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
2900endfunc
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002901
2902func Test_platform_name()
2903 " The system matches at most only one name.
Bram Moolenaar041c7102020-05-30 18:14:57 +02002904 let names = ['amiga', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002905 call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
2906
2907 " Is Unix?
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002908 call assert_equal(has('bsd'), has('bsd') && has('unix'))
2909 call assert_equal(has('hpux'), has('hpux') && has('unix'))
Zhaoming Luoa41dfcd2025-02-06 21:39:35 +01002910 call assert_equal(has('hurd'), has('hurd') && has('unix'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002911 call assert_equal(has('linux'), has('linux') && has('unix'))
2912 call assert_equal(has('mac'), has('mac') && has('unix'))
2913 call assert_equal(has('qnx'), has('qnx') && has('unix'))
2914 call assert_equal(has('sun'), has('sun') && has('unix'))
2915 call assert_equal(has('win32'), has('win32') && !has('unix'))
2916 call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
2917
2918 if has('unix') && executable('uname')
2919 let uname = system('uname')
Bram Moolenaara02e3f62019-02-07 21:27:14 +01002920 " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
2921 call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002922 call assert_equal(uname =~? 'HP-UX', has('hpux'))
2923 call assert_equal(uname =~? 'Linux', has('linux'))
2924 call assert_equal(uname =~? 'Darwin', has('mac'))
2925 call assert_equal(uname =~? 'QNX', has('qnx'))
2926 call assert_equal(uname =~? 'SunOS', has('sun'))
2927 call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
Zhaoming Luoa41dfcd2025-02-06 21:39:35 +01002928 call assert_equal(uname =~? 'GNU', has('hurd'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002929 endif
2930endfunc
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002931
2932func Test_readdir()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002933 call mkdir('Xreaddir', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002934 call writefile([], 'Xreaddir/foo.txt')
2935 call writefile([], 'Xreaddir/bar.txt')
2936 call mkdir('Xreaddir/dir')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002937
2938 " All results
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002939 let files = readdir('Xreaddir')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002940 call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
2941
2942 " Only results containing "f"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002943 let files = 'Xreaddir'->readdir({ x -> stridx(x, 'f') != -1 })
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002944 call assert_equal(['foo.txt'], sort(files))
2945
2946 " Only .txt files
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002947 let files = readdir('Xreaddir', { x -> x =~ '.txt$' })
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002948 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2949
2950 " Only .txt files with string
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002951 let files = readdir('Xreaddir', 'v:val =~ ".txt$"')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002952 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2953
2954 " Limit to 1 result.
2955 let l = []
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002956 let files = readdir('Xreaddir', {x -> len(add(l, x)) == 2 ? -1 : 1})
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002957 call assert_equal(1, len(files))
2958
Bram Moolenaar27da7de2019-09-03 17:13:37 +02002959 " Nested readdir() must not crash
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002960 let files = readdir('Xreaddir', 'readdir("Xreaddir", "1") != []')
Bram Moolenaar27da7de2019-09-03 17:13:37 +02002961 call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002962endfunc
Bram Moolenaar17aca702019-05-16 22:24:55 +02002963
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002964func Test_readdirex()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002965 call mkdir('Xexdir', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002966 call writefile(['foo'], 'Xexdir/foo.txt')
2967 call writefile(['barbar'], 'Xexdir/bar.txt')
2968 call mkdir('Xexdir/dir')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002969
2970 " All results
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002971 let files = readdirex('Xexdir')->map({-> v:val.name})
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002972 call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002973 let sizes = readdirex('Xexdir')->map({-> v:val.size})
Bram Moolenaar441d60e2020-06-02 22:19:50 +02002974 call assert_equal([0, 4, 7], sort(sizes))
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002975
2976 " Only results containing "f"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002977 let files = 'Xexdir'->readdirex({ e -> stridx(e.name, 'f') != -1 })
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002978 \ ->map({-> v:val.name})
2979 call assert_equal(['foo.txt'], sort(files))
2980
2981 " Only .txt files
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002982 let files = readdirex('Xexdir', { e -> e.name =~ '.txt$' })
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002983 \ ->map({-> v:val.name})
2984 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2985
2986 " Only .txt files with string
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002987 let files = readdirex('Xexdir', 'v:val.name =~ ".txt$"')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002988 \ ->map({-> v:val.name})
2989 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2990
2991 " Limit to 1 result.
2992 let l = []
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002993 let files = readdirex('Xexdir', {e -> len(add(l, e.name)) == 2 ? -1 : 1})
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002994 \ ->map({-> v:val.name})
2995 call assert_equal(1, len(files))
2996
2997 " Nested readdirex() must not crash
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002998 let files = readdirex('Xexdir', 'readdirex("Xexdir", "1") != []')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002999 \ ->map({-> v:val.name})
3000 call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
3001
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02003002 " report broken link correctly
Bram Moolenaarab540322020-06-10 15:55:36 +02003003 if has("unix")
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003004 call writefile([], 'Xexdir/abc.txt')
3005 call system("ln -s Xexdir/abc.txt Xexdir/link")
3006 call delete('Xexdir/abc.txt')
3007 let files = readdirex('Xexdir', 'readdirex("Xexdir", "1") != []')
Bram Moolenaarab540322020-06-10 15:55:36 +02003008 \ ->map({-> v:val.name .. '_' .. v:val.type})
3009 call sort(files)->assert_equal(
3010 \ ['bar.txt_file', 'dir_dir', 'foo.txt_file', 'link_link'])
3011 endif
Bram Moolenaaraab9fad2020-10-11 14:28:11 +02003012
3013 call assert_fails('call readdirex("doesnotexist")', 'E484:')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02003014endfunc
3015
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003016func Test_readdirex_sort()
3017 CheckUnix
3018 " Skip tests on Mac OS X and Cygwin (does not allow several files with different casing)
3019 if has("osxdarwin") || has("osx") || has("macunix") || has("win32unix")
3020 throw 'Skipped: Test_readdirex_sort on systems that do not allow this using the default filesystem'
3021 endif
3022 let _collate = v:collate
Bram Moolenaar70e67252022-09-27 19:34:35 +01003023 call mkdir('Xsortdir2', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003024 call writefile(['1'], 'Xsortdir2/README.txt')
3025 call writefile(['2'], 'Xsortdir2/Readme.txt')
3026 call writefile(['3'], 'Xsortdir2/readme.txt')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003027
3028 " 1) default
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003029 let files = readdirex('Xsortdir2')->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003030 let default = copy(files)
3031 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort using default')
3032
3033 " 2) no sorting
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003034 let files = readdirex('Xsortdir2', 1, #{sort: 'none'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003035 let unsorted = copy(files)
3036 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], sort(files), 'unsorted')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003037 call assert_fails("call readdirex('Xsortdir2', 1, #{slort: 'none'})", 'E857: Dictionary key "sort" required')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003038
3039 " 3) sort by case (same as default)
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003040 let files = readdirex('Xsortdir2', 1, #{sort: 'case'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003041 call assert_equal(default, files, 'sort by case')
3042
3043 " 4) sort by ignoring case
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003044 let files = readdirex('Xsortdir2', 1, #{sort: 'icase'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003045 call assert_equal(unsorted->sort('i'), files, 'sort by icase')
3046
3047 " 5) Default Collation
3048 let collate = v:collate
3049 lang collate C
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003050 let files = readdirex('Xsortdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003051 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort by C collation')
3052
3053 " 6) Collation de_DE
3054 " Switch locale, this may not work on the CI system, if the locale isn't
3055 " available
3056 try
3057 lang collate de_DE
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003058 let files = readdirex('Xsortdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003059 call assert_equal(['readme.txt', 'Readme.txt', 'README.txt'], files, 'sort by de_DE collation')
3060 catch
3061 throw 'Skipped: de_DE collation is not available'
3062
3063 finally
3064 exe 'lang collate' collate
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003065 endtry
3066endfunc
3067
3068func Test_readdir_sort()
3069 " some more cases for testing sorting for readdirex
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003070 let dir = 'Xsortdir3'
Bram Moolenaar70e67252022-09-27 19:34:35 +01003071 call mkdir(dir, 'R')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003072 call writefile(['1'], dir .. '/README.txt')
3073 call writefile(['2'], dir .. '/Readm.txt')
3074 call writefile(['3'], dir .. '/read.txt')
3075 call writefile(['4'], dir .. '/Z.txt')
3076 call writefile(['5'], dir .. '/a.txt')
3077 call writefile(['6'], dir .. '/b.txt')
3078
3079 " 1) default
3080 let files = readdir(dir)
3081 let default = copy(files)
3082 call assert_equal(default->sort(), files, 'sort using default')
3083
3084 " 2) sort by case (same as default)
3085 let files = readdir(dir, '1', #{sort: 'case'})
3086 call assert_equal(default, files, 'sort using default')
3087
3088 " 3) sort by ignoring case
3089 let files = readdir(dir, '1', #{sort: 'icase'})
3090 call assert_equal(default->sort('i'), files, 'sort by ignoring case')
3091
Bram Moolenaare17f8812020-06-17 20:30:44 +02003092 " 4) collation
3093 let collate = v:collate
3094 lang collate C
3095 let files = readdir(dir, 1, #{sort: 'collate'})
3096 call assert_equal(default->sort(), files, 'sort by C collation')
3097 exe "lang collate" collate
3098
3099 " 5) Errors
Bram Moolenaard83392a2022-09-01 12:22:46 +01003100 call assert_fails('call readdir(dir, 1, 1)', 'E1206:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003101 call assert_fails('call readdir(dir, 1, #{sorta: 1})')
Bram Moolenaard83392a2022-09-01 12:22:46 +01003102 call assert_fails('call readdir(dir, 1, test_null_dict())', 'E1297:')
3103 call assert_fails('call readdirex(dir, 1, 1)', 'E1206:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003104 call assert_fails('call readdirex(dir, 1, #{sorta: 1})')
Bram Moolenaard83392a2022-09-01 12:22:46 +01003105 call assert_fails('call readdirex(dir, 1, test_null_dict())', 'E1297:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003106
3107 " 6) ignore other values in dict
3108 let files = readdir(dir, '1', #{sort: 'c'})
3109 call assert_equal(default, files, 'sort using default2')
3110
3111 " Cleanup
3112 exe "lang collate" collate
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003113endfunc
3114
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003115func Test_delete_rf()
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003116 call mkdir('Xrfdir')
3117 call writefile([], 'Xrfdir/foo.txt')
3118 call writefile([], 'Xrfdir/bar.txt')
3119 call mkdir('Xrfdir/[a-1]') " issue #696
3120 call writefile([], 'Xrfdir/[a-1]/foo.txt')
3121 call writefile([], 'Xrfdir/[a-1]/bar.txt')
3122 call assert_true(filereadable('Xrfdir/foo.txt'))
3123 call assert_true('Xrfdir/[a-1]/foo.txt'->filereadable())
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003124
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003125 call assert_equal(0, delete('Xrfdir', 'rf'))
3126 call assert_false(filereadable('Xrfdir/foo.txt'))
3127 call assert_false(filereadable('Xrfdir/[a-1]/foo.txt'))
zeertzjq47870032022-04-05 15:31:01 +01003128
3129 if has('unix')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003130 call mkdir('Xrfdir/Xdir2', 'p')
3131 silent !chmod 555 Xrfdir
3132 call assert_equal(-1, delete('Xrfdir/Xdir2', 'rf'))
3133 call assert_equal(-1, delete('Xrfdir', 'rf'))
3134 silent !chmod 755 Xrfdir
3135 call assert_equal(0, delete('Xrfdir', 'rf'))
zeertzjq47870032022-04-05 15:31:01 +01003136 endif
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003137endfunc
3138
Bram Moolenaar17aca702019-05-16 22:24:55 +02003139func Test_call()
3140 call assert_equal(3, call('len', [123]))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02003141 call assert_equal(3, 'len'->call([123]))
Yegappan Lakshmanan9904cbc2025-01-15 18:25:19 +01003142 call assert_equal(4, call({ x -> len(x) }, ['xxxx']))
3143 call assert_equal(2, call(function('len'), ['xx']))
Bram Moolenaard83392a2022-09-01 12:22:46 +01003144 call assert_fails("call call('len', 123)", 'E1211:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02003145 call assert_equal(0, call('', []))
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02003146 call assert_equal(0, call('len', test_null_list()))
Bram Moolenaar17aca702019-05-16 22:24:55 +02003147
3148 function Mylen() dict
3149 return len(self.data)
3150 endfunction
3151 let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
Bram Moolenaar64b4d732019-08-22 22:18:17 +02003152 eval mydict.len->call([], mydict)->assert_equal(4)
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01003153 call assert_fails("call call('Mylen', [], 0)", 'E1206:')
Bram Moolenaar67322bf2020-12-06 15:03:19 +01003154 call assert_fails('call foo', 'E107:')
Dominique Pellefe8ebdb2021-05-13 14:55:55 +02003155
Bram Moolenaar22db0d52021-06-12 12:16:55 +02003156 " These once caused a crash.
Dominique Pellefe8ebdb2021-05-13 14:55:55 +02003157 call call(test_null_function(), [])
3158 call call(test_null_partial(), [])
Bram Moolenaar22db0d52021-06-12 12:16:55 +02003159 call assert_fails('call test_null_function()()', 'E1192:')
3160 call assert_fails('call test_null_partial()()', 'E117:')
Bram Moolenaar2ef91562021-12-11 16:14:07 +00003161
3162 let lines =<< trim END
3163 let Time = 'localtime'
3164 call Time()
3165 END
Bram Moolenaar62aec932022-01-29 21:45:34 +00003166 call v9.CheckScriptFailure(lines, 'E1085:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02003167endfunc
3168
3169func Test_char2nr()
3170 call assert_equal(12354, char2nr('あ', 1))
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02003171 call assert_equal(120, 'x'->char2nr())
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003172 set encoding=latin1
3173 call assert_equal(120, 'x'->char2nr())
3174 set encoding=utf-8
Bram Moolenaar17aca702019-05-16 22:24:55 +02003175endfunc
3176
Bram Moolenaar4e4473c2020-08-28 22:24:57 +02003177func Test_charclass()
3178 call assert_equal(0, charclass(' '))
3179 call assert_equal(1, charclass('.'))
3180 call assert_equal(2, charclass('x'))
3181 call assert_equal(3, charclass("\u203c"))
Christian Brabandt72463f82021-07-02 20:19:31 +02003182 " this used to crash vim
3183 call assert_equal(0, "xxx"[-1]->charclass())
Bram Moolenaar4e4473c2020-08-28 22:24:57 +02003184endfunc
3185
Bram Moolenaar17aca702019-05-16 22:24:55 +02003186func Test_eventhandler()
3187 call assert_equal(0, eventhandler())
3188endfunc
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003189
3190func Test_bufadd_bufload()
3191 call assert_equal(0, bufexists('someName'))
3192 let buf = bufadd('someName')
3193 call assert_notequal(0, buf)
3194 call assert_equal(1, bufexists('someName'))
3195 call assert_equal(0, getbufvar(buf, '&buflisted'))
3196 call assert_equal(0, bufloaded(buf))
3197 call bufload(buf)
3198 call assert_equal(1, bufloaded(buf))
3199 call assert_equal([''], getbufline(buf, 1, '$'))
3200
3201 let curbuf = bufnr('')
Bram Moolenaarf92e58c2019-09-08 21:51:41 +02003202 eval ['some', 'text']->writefile('XotherName')
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003203 let buf = 'XotherName'->bufadd()
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003204 call assert_notequal(0, buf)
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003205 eval 'XotherName'->bufexists()->assert_equal(1)
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003206 call assert_equal(0, getbufvar(buf, '&buflisted'))
3207 call assert_equal(0, bufloaded(buf))
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003208 eval buf->bufload()
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003209 call assert_equal(1, bufloaded(buf))
3210 call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
3211 call assert_equal(curbuf, bufnr(''))
3212
Bram Moolenaar892ae722019-06-30 20:33:01 +02003213 let buf1 = bufadd('')
3214 let buf2 = bufadd('')
3215 call assert_notequal(0, buf1)
3216 call assert_notequal(0, buf2)
3217 call assert_notequal(buf1, buf2)
3218 call assert_equal(1, bufexists(buf1))
3219 call assert_equal(1, bufexists(buf2))
3220 call assert_equal(0, bufloaded(buf1))
3221 exe 'bwipe ' .. buf1
3222 call assert_equal(0, bufexists(buf1))
3223 call assert_equal(1, bufexists(buf2))
3224 exe 'bwipe ' .. buf2
3225 call assert_equal(0, bufexists(buf2))
3226
zeertzjq93f72cc2022-08-26 15:34:52 +01003227 " When 'buftype' is "nofile" then bufload() does not read the file.
3228 " Other values too.
3229 for val in [['nofile', 0],
3230 \ ['nowrite', 1],
3231 \ ['acwrite', 1],
3232 \ ['quickfix', 0],
3233 \ ['help', 1],
3234 \ ['terminal', 0],
3235 \ ['prompt', 0],
3236 \ ['popup', 0],
3237 \ ]
3238 bwipe! XotherName
3239 let buf = bufadd('XotherName')
3240 call setbufvar(buf, '&bt', val[0])
3241 call bufload(buf)
3242 call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0])
3243 endfor
Bram Moolenaarc3126192022-08-26 12:58:17 +01003244
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003245 bwipe someName
Bram Moolenaar3940ec62019-07-05 21:53:24 +02003246 bwipe XotherName
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003247 call assert_equal(0, bufexists('someName'))
Bram Moolenaar3940ec62019-07-05 21:53:24 +02003248 call delete('XotherName')
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003249endfunc
Bram Moolenaarc2585492019-09-22 21:29:53 +02003250
3251func Test_state()
3252 CheckRunVimInTerminal
3253
Bram Moolenaar3ed9efc2020-03-26 16:50:57 +01003254 let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
3255
Bram Moolenaarc2585492019-09-22 21:29:53 +02003256 let lines =<< trim END
3257 call setline(1, ['one', 'two', 'three'])
3258 map ;; gg
Bram Moolenaarb7a97ef2019-09-28 22:11:56 +02003259 set complete=.
Bram Moolenaarc2585492019-09-22 21:29:53 +02003260 func RunTimer()
3261 call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
3262 endfunc
3263 au Filetype foobar let g:state = state()|let g:mode = mode()
3264 END
3265 call writefile(lines, 'XState')
3266 let buf = RunVimInTerminal('-S XState', #{rows: 6})
3267
3268 " Using a ":" command Vim is busy, thus "S" is returned
3269 call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
3270 call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
3271 call term_sendkeys(buf, ":\<CR>")
3272
3273 " Using a timer callback
3274 call term_sendkeys(buf, ":call RunTimer()\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003275 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003276 call term_sendkeys(buf, getstate)
3277 call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
3278
3279 " Halfway a mapping
3280 call term_sendkeys(buf, ":call RunTimer()\<CR>;")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003281 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003282 call term_sendkeys(buf, ";")
3283 call term_sendkeys(buf, getstate)
3284 call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
3285
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003286 " An operator is pending
zeertzjq8dabccd2023-08-22 21:22:24 +02003287 call term_sendkeys(buf, ":call RunTimer()\<CR>y")
3288 call TermWait(buf, 25)
3289 call term_sendkeys(buf, "y")
3290 call term_sendkeys(buf, getstate)
3291 call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3292
3293 " A register was specified
3294 call term_sendkeys(buf, ":call RunTimer()\<CR>\"r")
3295 call TermWait(buf, 25)
3296 call term_sendkeys(buf, "yy")
3297 call term_sendkeys(buf, getstate)
3298 call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3299
Bram Moolenaarb7a97ef2019-09-28 22:11:56 +02003300 " Insert mode completion (bit slower on Mac)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003301 call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003302 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003303 call term_sendkeys(buf, "\<Esc>")
3304 call term_sendkeys(buf, getstate)
3305 call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
3306
3307 " Autocommand executing
3308 call term_sendkeys(buf, ":set filetype=foobar\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003309 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003310 call term_sendkeys(buf, getstate)
3311 call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
3312
3313 " Todo: "w" - waiting for ch_evalexpr()
3314
3315 " messages scrolled
3316 call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003317 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003318 call term_sendkeys(buf, "\<CR>")
3319 call term_sendkeys(buf, getstate)
3320 call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
3321
3322 call StopVimInTerminal(buf)
3323 call delete('XState')
3324endfunc
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003325
3326func Test_range()
3327 " destructuring
3328 let [x, y] = range(2)
3329 call assert_equal([0, 1], [x, y])
3330
3331 " index
3332 call assert_equal(4, range(1, 10)[3])
3333
3334 " add()
3335 call assert_equal([0, 1, 2, 3], add(range(3), 3))
3336 call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
3337 call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
3338
3339 " append()
3340 new
3341 call append('.', range(5))
3342 call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
3343 bwipe!
3344
3345 " appendbufline()
3346 new
3347 call appendbufline(bufnr(''), '.', range(5))
3348 call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
3349 bwipe!
3350
3351 " call()
3352 func TwoArgs(a, b)
3353 return [a:a, a:b]
3354 endfunc
3355 call assert_equal([0, 1], call('TwoArgs', range(2)))
3356
3357 " col()
3358 new
3359 call setline(1, ['foo', 'bar'])
3360 call assert_equal(2, col(range(1, 2)))
3361 bwipe!
3362
3363 " complete()
3364 execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
3365 " complete_info()
3366 execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
3367
3368 " copy()
3369 call assert_equal([1, 2, 3], copy(range(1, 3)))
3370
3371 " count()
3372 call assert_equal(0, count(range(0), 3))
3373 call assert_equal(0, count(range(2), 3))
3374 call assert_equal(1, count(range(5), 3))
3375
3376 " cursor()
3377 new
3378 call setline(1, ['aaa', 'bbb', 'ccc'])
3379 call cursor(range(1, 2))
3380 call assert_equal([2, 1], [col('.'), line('.')])
3381 bwipe!
3382
3383 " deepcopy()
3384 call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
3385
3386 " empty()
3387 call assert_true(empty(range(0)))
3388 call assert_false(empty(range(2)))
3389
3390 " execute()
3391 new
3392 call setline(1, ['aaa', 'bbb', 'ccc'])
3393 call execute(range(3))
3394 call assert_equal(2, line('.'))
3395 bwipe!
3396
3397 " extend()
3398 call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
3399 call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
3400 call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
3401
3402 " filter()
3403 call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
Bram Moolenaarf8ca03b2020-11-28 20:32:29 +01003404 call assert_equal([1, 5, 7, 11, 13], filter(filter(range(15), 'v:val % 2'), 'v:val % 3'))
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003405
3406 " funcref()
3407 call assert_equal([0, 1], funcref('TwoArgs', range(2))())
3408
3409 " function()
3410 call assert_equal([0, 1], function('TwoArgs', range(2))())
3411
3412 " garbagecollect()
3413 let thelist = [1, range(2), 3]
3414 let otherlist = range(3)
3415 call test_garbagecollect_now()
3416
3417 " get()
3418 call assert_equal(4, get(range(1, 10), 3))
3419 call assert_equal(-1, get(range(1, 10), 42, -1))
Christian Brabandtdf63da92023-11-23 20:14:28 +01003420 call assert_equal(0, get(range(1, 0, 2), 0))
3421 call assert_equal(0, get(range(0, -1, 2), 0))
3422 call assert_equal(0, get(range(-2, -1, -2), 0))
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003423
3424 " index()
3425 call assert_equal(1, index(range(1, 5), 2))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003426 call assert_fails("echo index([1, 2], 1, [])", 'E745:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003427
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003428 " insert()
3429 call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
3430 call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
3431 call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
3432 call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
3433 call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
3434 call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
3435
3436 " join()
3437 call assert_equal('0 1 2 3 4', join(range(5)))
3438
Bram Moolenaar272ca952020-01-28 20:49:11 +01003439 " json_encode()
3440 call assert_equal('[0,1,2,3]', json_encode(range(4)))
3441
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003442 " len()
3443 call assert_equal(0, len(range(0)))
3444 call assert_equal(2, len(range(2)))
3445 call assert_equal(5, len(range(0, 12, 3)))
3446 call assert_equal(4, len(range(3, 0, -1)))
3447
3448 " list2str()
3449 call assert_equal('ABC', list2str(range(65, 67)))
Bram Moolenaard83392a2022-09-01 12:22:46 +01003450 call assert_fails('let s = list2str(5)', 'E1211:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003451
3452 " lock()
3453 let thelist = range(5)
3454 lockvar thelist
3455
3456 " map()
3457 call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
Bram Moolenaarf8ca03b2020-11-28 20:32:29 +01003458 call assert_equal([3, 5, 7, 9, 11], map(map(range(5), 'v:val * 2'), 'v:val + 3'))
3459 call assert_equal([2, 6], map(filter(range(5), 'v:val % 2'), 'v:val * 2'))
3460 call assert_equal([2, 4, 8], filter(map(range(5), 'v:val * 2'), 'v:val % 3'))
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003461
3462 " match()
3463 call assert_equal(3, match(range(5), 3))
3464
3465 " matchaddpos()
3466 highlight MyGreenGroup ctermbg=green guibg=green
3467 call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
3468
3469 " matchend()
3470 call assert_equal(4, matchend(range(5), '4'))
3471 call assert_equal(3, matchend(range(1, 5), '4'))
3472 call assert_equal(-1, matchend(range(1, 5), '42'))
3473
3474 " matchstrpos()
3475 call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
3476 call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
3477 call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
3478
3479 " max() reverse()
3480 call assert_equal(0, max(range(0)))
3481 call assert_equal(0, max(range(10, 9)))
3482 call assert_equal(9, max(range(10)))
3483 call assert_equal(18, max(range(0, 20, 3)))
3484 call assert_equal(20, max(range(20, 0, -3)))
3485 call assert_equal(99999, max(range(100000)))
3486 call assert_equal(99999, max(range(99999, 0, -1)))
3487 call assert_equal(99999, max(reverse(range(100000))))
3488 call assert_equal(99999, max(reverse(range(99999, 0, -1))))
3489
3490 " min() reverse()
3491 call assert_equal(0, min(range(0)))
3492 call assert_equal(0, min(range(10, 9)))
3493 call assert_equal(5, min(range(5, 10)))
3494 call assert_equal(5, min(range(5, 10, 3)))
3495 call assert_equal(2, min(range(20, 0, -3)))
3496 call assert_equal(0, min(range(100000)))
3497 call assert_equal(0, min(range(99999, 0, -1)))
3498 call assert_equal(0, min(reverse(range(100000))))
3499 call assert_equal(0, min(reverse(range(99999, 0, -1))))
3500
3501 " remove()
3502 call assert_equal(1, remove(range(1, 10), 0))
3503 call assert_equal(2, remove(range(1, 10), 1))
3504 call assert_equal(9, remove(range(1, 10), 8))
3505 call assert_equal(10, remove(range(1, 10), 9))
3506 call assert_equal(10, remove(range(1, 10), -1))
3507 call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
3508
3509 " repeat()
3510 call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
3511 call assert_equal([0, 1, 2], repeat(range(3), 1))
3512 call assert_equal([], repeat(range(3), 0))
3513 call assert_equal([], repeat(range(5, 4), 2))
3514 call assert_equal([], repeat(range(5, 4), 0))
3515
3516 " reverse()
3517 call assert_equal([2, 1, 0], reverse(range(3)))
3518 call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
3519 call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
3520 call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
3521 call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
3522 call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
3523 call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
3524 call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
3525 call assert_equal([], reverse(range(0)))
3526
3527 " TODO: setpos()
3528 " new
3529 " call setline(1, repeat([''], bufnr('')))
3530 " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
3531 " call setpos('x', range(bufnr(''), bufnr('') + 3))
3532 " bwipe!
3533
3534 " setreg()
3535 call setreg('a', range(3))
3536 call assert_equal("0\n1\n2\n", getreg('a'))
3537
Bram Moolenaarb0992022020-01-30 14:55:42 +01003538 " settagstack()
3539 call settagstack(1, #{items : range(4)})
Bram Moolenaar94255df2020-02-05 20:10:33 +01003540
Bram Moolenaarb0992022020-01-30 14:55:42 +01003541 " sign_define()
3542 call assert_fails("call sign_define(range(5))", "E715:")
3543 call assert_fails("call sign_placelist(range(5))", "E715:")
3544
3545 " sign_undefine()
3546 call assert_fails("call sign_undefine(range(5))", "E908:")
3547
3548 " sign_unplacelist()
3549 call assert_fails("call sign_unplacelist(range(5))", "E715:")
3550
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003551 " sort()
3552 call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
3553
3554 " string()
3555 call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
3556
Bram Moolenaarb0992022020-01-30 14:55:42 +01003557 " taglist() with 'tagfunc'
3558 func TagFunc(pattern, flags, info)
3559 return range(10)
3560 endfunc
3561 set tagfunc=TagFunc
3562 call assert_fails("call taglist('asdf')", 'E987:')
3563 set tagfunc=
Bram Moolenaar94255df2020-02-05 20:10:33 +01003564
Bram Moolenaarb0992022020-01-30 14:55:42 +01003565 " term_start()
Bram Moolenaar705724e2020-01-31 21:13:42 +01003566 if has('terminal') && has('termguicolors')
Bram Moolenaarb0992022020-01-30 14:55:42 +01003567 call assert_fails('call term_start(range(3, 4))', 'E474:')
3568 let g:terminal_ansi_colors = range(16)
Bram Moolenaar94255df2020-02-05 20:10:33 +01003569 if has('win32')
Milly4f5681d2024-10-20 11:06:00 +02003570 let cmd = "cmd /D /c dir"
Bram Moolenaar94255df2020-02-05 20:10:33 +01003571 else
3572 let cmd = "ls"
3573 endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01003574 call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"'
3575 \ .. ', ansi_colors: range(16)})', 'E475:')
Bram Moolenaarb0855f52022-05-20 10:39:18 +01003576 unlet g:terminal_ansi_colors
Bram Moolenaarb0992022020-01-30 14:55:42 +01003577 endif
3578
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003579 " type()
3580 call assert_equal(v:t_list, type(range(5)))
3581
3582 " uniq()
3583 call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003584
3585 " errors
3586 call assert_fails('let x=range(2, 8, 0)', 'E726:')
3587 call assert_fails('let x=range(3, 1)', 'E727:')
3588 call assert_fails('let x=range(1, 3, -2)', 'E727:')
Bram Moolenaar99fa7212020-04-26 15:59:55 +02003589 call assert_fails('let x=range([])', 'E745:')
3590 call assert_fails('let x=range(1, [])', 'E745:')
3591 call assert_fails('let x=range(1, 4, [])', 'E745:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003592endfunc
Bram Moolenaar4132eb52020-02-14 16:53:00 +01003593
Bram Moolenaarb3d83982022-01-27 19:59:47 +00003594func Test_garbagecollect_now_fails()
3595 let v:testing = 0
3596 call assert_fails('call test_garbagecollect_now()', 'E1142:')
3597 let v:testing = 1
3598endfunc
3599
Bram Moolenaar4132eb52020-02-14 16:53:00 +01003600func Test_echoraw()
3601 CheckScreendump
3602
3603 " Normally used for escape codes, but let's test with a CR.
3604 let lines =<< trim END
3605 call echoraw("hello\<CR>x")
3606 END
3607 call writefile(lines, 'XTest_echoraw')
3608 let buf = RunVimInTerminal('-S XTest_echoraw', {'rows': 5, 'cols': 40})
3609 call VerifyScreenDump(buf, 'Test_functions_echoraw', {})
3610
3611 " clean up
3612 call StopVimInTerminal(buf)
3613 call delete('XTest_echoraw')
3614endfunc
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01003615
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003616" Test for echo highlighting
3617func Test_echohl()
3618 echohl Search
3619 echo 'Vim'
3620 call assert_equal('Vim', Screenline(&lines))
3621 " TODO: How to check the highlight group used by echohl?
3622 " ScreenAttrs() returns all zeros.
3623 echohl None
3624endfunc
3625
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003626" Test for the eval() function
3627func Test_eval()
3628 call assert_fails("call eval('5 a')", 'E488:')
3629endfunc
3630
zeertzjqcdc83932022-09-12 13:38:41 +01003631" Test for the keytrans() function
3632func Test_keytrans()
3633 call assert_equal('<Space>', keytrans(' '))
3634 call assert_equal('<lt>', keytrans('<'))
3635 call assert_equal('<lt>Tab>', keytrans('<Tab>'))
3636 call assert_equal('<Tab>', keytrans("\<Tab>"))
3637 call assert_equal('<C-V>', keytrans("\<C-V>"))
3638 call assert_equal('<BS>', keytrans("\<BS>"))
3639 call assert_equal('<Home>', keytrans("\<Home>"))
3640 call assert_equal('<C-Home>', keytrans("\<C-Home>"))
3641 call assert_equal('<M-Home>', keytrans("\<M-Home>"))
3642 call assert_equal('<C-Space>', keytrans("\<C-Space>"))
3643 call assert_equal('<M-Space>', keytrans("\<*M-Space>"))
3644 call assert_equal('<M-x>', "\<*M-x>"->keytrans())
3645 call assert_equal('<C-I>', "\<*C-I>"->keytrans())
3646 call assert_equal('<S-3>', "\<*S-3>"->keytrans())
3647 call assert_equal('π', 'π'->keytrans())
3648 call assert_equal('<M-π>', "\<M-π>"->keytrans())
3649 call assert_equal('ě', 'ě'->keytrans())
3650 call assert_equal('<M-ě>', "\<M-ě>"->keytrans())
3651 call assert_equal('', ''->keytrans())
3652 call assert_equal('', test_null_string()->keytrans())
3653 call assert_fails('call keytrans(1)', 'E1174:')
3654 call assert_fails('call keytrans()', 'E119:')
3655endfunc
3656
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003657" Test for the nr2char() function
3658func Test_nr2char()
3659 set encoding=latin1
3660 call assert_equal('@', nr2char(64))
3661 set encoding=utf8
3662 call assert_equal('a', nr2char(97, 1))
3663 call assert_equal('a', nr2char(97, 0))
Bram Moolenaarf7271e82020-05-24 18:45:07 +02003664
zeertzjqdb088872022-05-02 22:53:45 +01003665 call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"'))
3666 call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003667endfunc
3668
3669" Test for screenattr(), screenchar() and screenchars() functions
3670func Test_screen_functions()
3671 call assert_equal(-1, screenattr(-1, -1))
3672 call assert_equal(-1, screenchar(-1, -1))
3673 call assert_equal([], screenchars(-1, -1))
zeertzjq47eec672023-06-01 20:26:55 +01003674
3675 " Run this in a separate Vim instance to avoid messing up.
3676 let after =<< trim [CODE]
3677 scriptencoding utf-8
3678 call setline(1, '口')
3679 redraw
3680 call assert_equal(0, screenattr(1, 1))
3681 call assert_equal(char2nr('口'), screenchar(1, 1))
3682 call assert_equal([char2nr('口')], screenchars(1, 1))
3683 call assert_equal('口', screenstring(1, 1))
3684 call writefile(v:errors, 'Xresult')
3685 qall!
3686 [CODE]
3687
3688 let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950']
3689 if !has('win32')
3690 let encodings += ['euc-jp']
3691 endif
3692 for enc in encodings
3693 let msg = 'enc=' .. enc
3694 if RunVim([], after, $'--clean --cmd "set encoding={enc}"')
3695 call assert_equal([], readfile('Xresult'), msg)
3696 endif
3697 call delete('Xresult')
3698 endfor
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003699endfunc
3700
Bram Moolenaar08f41572020-04-20 16:50:00 +02003701" Test for getcurpos() and setpos()
3702func Test_getcurpos_setpos()
3703 new
3704 call setline(1, ['012345678', '012345678'])
3705 normal gg6l
3706 let sp = getcurpos()
3707 normal 0
3708 call setpos('.', sp)
3709 normal jyl
3710 call assert_equal('6', @")
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003711 call assert_equal(-1, setpos('.', test_null_list()))
3712 call assert_equal(-1, setpos('.', {}))
Bram Moolenaar99ca9c42020-09-22 21:55:41 +02003713
3714 let winid = win_getid()
3715 normal G$
3716 let pos = getcurpos()
3717 wincmd w
3718 call assert_equal(pos, getcurpos(winid))
3719
3720 wincmd w
Bram Moolenaar08f41572020-04-20 16:50:00 +02003721 close!
Bram Moolenaar99ca9c42020-09-22 21:55:41 +02003722
3723 call assert_equal(getcurpos(), getcurpos(0))
3724 call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
3725 call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
Bram Moolenaar08f41572020-04-20 16:50:00 +02003726endfunc
3727
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003728func Test_getmousepos()
3729 enew!
3730 call setline(1, "\t\t\t1234")
Bram Moolenaar533870a2022-03-13 15:52:44 +00003731 call test_setmouse(1, 1)
3732 call assert_equal(#{
3733 \ screenrow: 1,
3734 \ screencol: 1,
3735 \ winid: win_getid(),
3736 \ winrow: 1,
3737 \ wincol: 1,
3738 \ line: 1,
3739 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003740 \ coladd: 0,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003741 \ }, getmousepos())
zeertzjqb583eda2023-10-14 11:32:28 +02003742 call test_setmouse(1, 2)
3743 call assert_equal(#{
3744 \ screenrow: 1,
3745 \ screencol: 2,
3746 \ winid: win_getid(),
3747 \ winrow: 1,
3748 \ wincol: 2,
3749 \ line: 1,
3750 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003751 \ coladd: 1,
zeertzjqb583eda2023-10-14 11:32:28 +02003752 \ }, getmousepos())
3753 call test_setmouse(1, 8)
3754 call assert_equal(#{
3755 \ screenrow: 1,
3756 \ screencol: 8,
3757 \ winid: win_getid(),
3758 \ winrow: 1,
3759 \ wincol: 8,
3760 \ line: 1,
3761 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003762 \ coladd: 7,
zeertzjqb583eda2023-10-14 11:32:28 +02003763 \ }, getmousepos())
3764 call test_setmouse(1, 9)
3765 call assert_equal(#{
3766 \ screenrow: 1,
3767 \ screencol: 9,
3768 \ winid: win_getid(),
3769 \ winrow: 1,
3770 \ wincol: 9,
3771 \ line: 1,
3772 \ column: 2,
zeertzjqf5a94d52023-10-15 10:03:30 +02003773 \ coladd: 0,
zeertzjqb583eda2023-10-14 11:32:28 +02003774 \ }, getmousepos())
3775 call test_setmouse(1, 12)
3776 call assert_equal(#{
3777 \ screenrow: 1,
3778 \ screencol: 12,
3779 \ winid: win_getid(),
3780 \ winrow: 1,
3781 \ wincol: 12,
3782 \ line: 1,
3783 \ column: 2,
zeertzjqf5a94d52023-10-15 10:03:30 +02003784 \ coladd: 3,
zeertzjqb583eda2023-10-14 11:32:28 +02003785 \ }, getmousepos())
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003786 call test_setmouse(1, 25)
3787 call assert_equal(#{
3788 \ screenrow: 1,
3789 \ screencol: 25,
3790 \ winid: win_getid(),
3791 \ winrow: 1,
3792 \ wincol: 25,
3793 \ line: 1,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003794 \ column: 4,
zeertzjqf5a94d52023-10-15 10:03:30 +02003795 \ coladd: 0,
3796 \ }, getmousepos())
3797 call test_setmouse(1, 28)
3798 call assert_equal(#{
3799 \ screenrow: 1,
3800 \ screencol: 28,
3801 \ winid: win_getid(),
3802 \ winrow: 1,
3803 \ wincol: 28,
3804 \ line: 1,
3805 \ column: 7,
3806 \ coladd: 0,
3807 \ }, getmousepos())
3808 call test_setmouse(1, 29)
3809 call assert_equal(#{
3810 \ screenrow: 1,
3811 \ screencol: 29,
3812 \ winid: win_getid(),
3813 \ winrow: 1,
3814 \ wincol: 29,
3815 \ line: 1,
3816 \ column: 8,
3817 \ coladd: 0,
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003818 \ }, getmousepos())
3819 call test_setmouse(1, 50)
3820 call assert_equal(#{
3821 \ screenrow: 1,
3822 \ screencol: 50,
3823 \ winid: win_getid(),
3824 \ winrow: 1,
3825 \ wincol: 50,
3826 \ line: 1,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003827 \ column: 8,
zeertzjqf5a94d52023-10-15 10:03:30 +02003828 \ coladd: 21,
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003829 \ }, getmousepos())
Sean Dewar10792fe2022-03-15 09:46:54 +00003830
3831 " If the mouse is positioned past the last buffer line, "line" and "column"
3832 " should act like it's positioned on the last buffer line.
3833 call test_setmouse(2, 25)
3834 call assert_equal(#{
3835 \ screenrow: 2,
3836 \ screencol: 25,
3837 \ winid: win_getid(),
3838 \ winrow: 2,
3839 \ wincol: 25,
3840 \ line: 1,
3841 \ column: 4,
zeertzjqf5a94d52023-10-15 10:03:30 +02003842 \ coladd: 0,
Sean Dewar10792fe2022-03-15 09:46:54 +00003843 \ }, getmousepos())
3844 call test_setmouse(2, 50)
3845 call assert_equal(#{
3846 \ screenrow: 2,
3847 \ screencol: 50,
3848 \ winid: win_getid(),
3849 \ winrow: 2,
3850 \ wincol: 50,
3851 \ line: 1,
3852 \ column: 8,
zeertzjqf5a94d52023-10-15 10:03:30 +02003853 \ coladd: 21,
Sean Dewar10792fe2022-03-15 09:46:54 +00003854 \ }, getmousepos())
zeertzjq031a7452024-05-11 11:23:37 +02003855
3856 30vnew
3857 setlocal smoothscroll number
3858 call setline(1, join(range(100)))
3859 exe "normal! \<C-E>"
3860 call test_setmouse(1, 5)
3861 call assert_equal(#{
3862 \ screenrow: 1,
3863 \ screencol: 5,
3864 \ winid: win_getid(),
3865 \ winrow: 1,
3866 \ wincol: 5,
3867 \ line: 1,
3868 \ column: 27,
3869 \ coladd: 0,
3870 \ }, getmousepos())
3871 call test_setmouse(2, 5)
3872 call assert_equal(#{
3873 \ screenrow: 2,
3874 \ screencol: 5,
3875 \ winid: win_getid(),
3876 \ winrow: 2,
3877 \ wincol: 5,
3878 \ line: 1,
3879 \ column: 53,
3880 \ coladd: 0,
3881 \ }, getmousepos())
3882
3883 exe "normal! \<C-E>"
3884 call test_setmouse(1, 5)
3885 call assert_equal(#{
3886 \ screenrow: 1,
3887 \ screencol: 5,
3888 \ winid: win_getid(),
3889 \ winrow: 1,
3890 \ wincol: 5,
3891 \ line: 1,
3892 \ column: 53,
3893 \ coladd: 0,
3894 \ }, getmousepos())
3895 call test_setmouse(2, 5)
3896 call assert_equal(#{
3897 \ screenrow: 2,
3898 \ screencol: 5,
3899 \ winid: win_getid(),
3900 \ winrow: 2,
3901 \ wincol: 5,
3902 \ line: 1,
3903 \ column: 79,
3904 \ coladd: 0,
3905 \ }, getmousepos())
3906
3907 vert resize 4
3908 call test_setmouse(2, 2)
3909 " This used to crash Vim
3910 call assert_equal(#{
3911 \ screenrow: 2,
3912 \ screencol: 2,
3913 \ winid: win_getid(),
3914 \ winrow: 2,
3915 \ wincol: 2,
3916 \ line: 1,
3917 \ column: 53,
3918 \ coladd: 0,
3919 \ }, getmousepos())
3920
3921 bwipe!
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003922 bwipe!
3923endfunc
3924
Bram Moolenaar24dc19c2022-11-14 19:49:15 +00003925func Test_getmouseshape()
3926 CheckFeature mouseshape
3927
3928 call assert_equal('arrow', getmouseshape())
3929endfunc
3930
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003931" Test for glob()
3932func Test_glob()
3933 call assert_equal('', glob(test_null_string()))
3934 call assert_equal('', globpath(test_null_string(), test_null_string()))
Yegappan Lakshmanan46aa6f92021-05-19 17:15:04 +02003935 call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
Bram Moolenaar1b04ce22020-08-21 22:46:11 +02003936
3937 call writefile([], 'Xglob1')
3938 call writefile([], 'XGLOB2')
3939 set wildignorecase
3940 " Sort output of glob() otherwise we end up with different
3941 " ordering depending on whether file system is case-sensitive.
3942 call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
LemonBoya3157a42022-04-03 11:58:31 +01003943 " wildignorecase shall be applied even when the pattern contains no wildcards.
3944 call assert_equal('XGLOB2', glob('xglob2'))
Bram Moolenaar1b04ce22020-08-21 22:46:11 +02003945 set wildignorecase&
3946
3947 call delete('Xglob1')
3948 call delete('XGLOB2')
3949
3950 call assert_fails("call glob('*', 0, {})", 'E728:')
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003951endfunc
3952
Christian Brabandt8b34aea2024-06-13 21:20:20 +02003953func Test_glob2()
3954 call mkdir('[XglobDir]', 'R')
3955 call mkdir('abc[glob]def', 'R')
3956
3957 call writefile(['glob'], '[XglobDir]/Xglob')
3958 call writefile(['glob'], 'abc[glob]def/Xglob')
3959 if has("unix")
3960 call assert_equal([], (glob('[XglobDir]/*', 0, 1)))
3961 call assert_equal([], (glob('abc[glob]def/*', 0, 1)))
3962 call assert_equal(['[XglobDir]/Xglob'], (glob('\[XglobDir]/*', 0, 1)))
3963 call assert_equal(['abc[glob]def/Xglob'], (glob('abc\[glob]def/*', 0, 1)))
3964 elseif has("win32")
3965 let _sl=&shellslash
3966 call assert_equal([], (glob('[XglobDir]\*', 0, 1)))
3967 call assert_equal([], (glob('abc[glob]def\*', 0, 1)))
3968 call assert_equal([], (glob('\[XglobDir]\*', 0, 1)))
3969 call assert_equal([], (glob('abc\[glob]def\*', 0, 1)))
3970 set noshellslash
3971 call assert_equal(['[XglobDir]\Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
3972 call assert_equal(['abc[glob]def\Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
3973 set shellslash
3974 call assert_equal(['[XglobDir]/Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
3975 call assert_equal(['abc[glob]def/Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
3976 let &shellslash=_sl
3977 endif
3978endfunc
3979
LemonBoy23c5ebe2024-06-18 20:43:51 +02003980func Test_glob_symlinks()
3981 call writefile([], 'Xglob1')
3982
3983 if has("win32")
3984 silent !mklink XglobBad DoesNotExist
3985 if v:shell_error
3986 throw 'Skipped: cannot create symlinks'
3987 endif
3988 silent !mklink XglobOk Xglob1
3989 else
3990 silent !ln -s DoesNotExist XglobBad
3991 silent !ln -s Xglob1 XglobOk
3992 endif
3993
3994 " The broken symlink is excluded when alllinks is false.
3995 call assert_equal(['Xglob1', 'XglobBad', 'XglobOk'], sort(glob('Xglob*', 0, 1, 1)))
3996 call assert_equal(['Xglob1', 'XglobOk'], sort(glob('Xglob*', 0, 1, 0)))
3997
3998 call delete('Xglob1')
3999 call delete('XglobBad')
4000 call delete('XglobOk')
4001endfunc
4002
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02004003" Test for browse()
4004func Test_browse()
4005 CheckFeature browse
4006 call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
4007endfunc
4008
4009" Test for browsedir()
4010func Test_browsedir()
4011 CheckFeature browse
4012 call assert_fails('call browsedir("open", [])', 'E730:')
4013endfunc
4014
Bram Moolenaarb47bed22021-04-14 17:06:43 +02004015func HasDefault(msg = 'msg')
4016 return a:msg
4017endfunc
4018
4019func Test_default_arg_value()
4020 call assert_equal('msg', HasDefault())
4021endfunc
4022
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004023func Test_builtin_check()
4024 call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
4025 call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
Bram Moolenaarb54abee2021-06-02 11:49:23 +02004026 call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
4027 call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
4028 let lines =<< trim END
4029 vim9script
Bram Moolenaar62b191c2022-02-12 20:34:50 +00004030 var trim = (x) => " " .. x
Bram Moolenaarb54abee2021-06-02 11:49:23 +02004031 END
Bram Moolenaar62aec932022-01-29 21:45:34 +00004032 call v9.CheckScriptFailure(lines, 'E704:')
Bram Moolenaar6f1d2aa2021-06-01 21:21:55 +02004033
4034 call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
4035 let g:bar = 123
4036 call extend(g:, #{bar: { -> "foo" }}, "keep")
4037 call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
zeertzjq91c75d12022-11-05 20:21:58 +00004038 unlet g:bar
4039
4040 call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:')
4041 let bar = 123
4042 call extend(l:, #{bar: { -> "foo" }}, "keep")
4043 call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:')
4044 unlet bar
4045
4046 call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:')
4047 let g:bar = 123
4048 call extend(g:, #{bar: function("extend")}, "keep")
4049 call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:')
4050 unlet g:bar
4051
4052 call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:')
4053 let bar = 123
4054 call extend(l:, #{bar: function("extend")}, "keep")
4055 call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:')
4056 unlet bar
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004057endfunc
4058
Bram Moolenaarc4ec3382021-12-09 16:40:18 +00004059func Test_funcref_to_string()
4060 let Fn = funcref('g:Test_funcref_to_string')
4061 call assert_equal("function('g:Test_funcref_to_string')", string(Fn))
4062endfunc
4063
Yegappan Lakshmanan3e336502024-04-04 19:35:59 +02004064" A funcref cannot start with an underscore (except when used as a protected
4065" class or object variable)
4066func Test_funcref_with_underscore()
4067 " at script level
4068 let lines =<< trim END
4069 vim9script
4070 var _Fn = () => 10
4071 END
4072 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn')
4073
4074 " inside a function
4075 let lines =<< trim END
4076 vim9script
4077 def Func()
4078 var _Fn = () => 10
4079 enddef
4080 defcompile
4081 END
4082 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn', 1)
4083
4084 " as a function argument
4085 let lines =<< trim END
4086 vim9script
4087 def Func(_Fn: func)
4088 enddef
4089 defcompile
4090 END
4091 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn', 2)
4092
4093 " as a lambda argument
4094 let lines =<< trim END
4095 vim9script
4096 var Fn = (_Farg: func) => 10
4097 END
4098 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Farg', 2)
4099endfunc
4100
LemonBoydca1d402022-04-28 15:26:33 +01004101" Test for isabsolutepath()
4102func Test_isabsolutepath()
4103 call assert_false(isabsolutepath(''))
4104 call assert_false(isabsolutepath('.'))
4105 call assert_false(isabsolutepath('../Foo'))
4106 call assert_false(isabsolutepath('Foo/'))
4107 if has('win32')
4108 call assert_true(isabsolutepath('A:\'))
4109 call assert_true(isabsolutepath('A:\Foo'))
4110 call assert_true(isabsolutepath('A:/Foo'))
4111 call assert_false(isabsolutepath('A:Foo'))
4112 call assert_false(isabsolutepath('\Windows'))
4113 call assert_true(isabsolutepath('\\Server2\Share\Test\Foo.txt'))
4114 else
4115 call assert_true(isabsolutepath('/'))
4116 call assert_true(isabsolutepath('/usr/share/'))
4117 endif
4118endfunc
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004119
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01004120" Test for exepath()
4121func Test_exepath()
4122 if has('win32')
4123 call assert_notequal(exepath('cmd'), '')
4124
4125 let oldNoDefaultCurrentDirectoryInExePath = $NoDefaultCurrentDirectoryInExePath
4126 call writefile(['@echo off', 'echo Evil'], 'vim-test-evil.bat')
4127 let $NoDefaultCurrentDirectoryInExePath = ''
4128 call assert_notequal(exepath("vim-test-evil.bat"), '')
4129 let $NoDefaultCurrentDirectoryInExePath = '1'
4130 call assert_equal(exepath("vim-test-evil.bat"), '')
4131 let $NoDefaultCurrentDirectoryInExePath = oldNoDefaultCurrentDirectoryInExePath
4132 call delete('vim-test-evil.bat')
4133 else
4134 call assert_notequal(exepath('sh'), '')
4135 endif
4136endfunc
4137
LemonBoy0f7a3e12022-05-26 12:10:37 +01004138" Test for virtcol()
4139func Test_virtcol()
zeertzjq825cf812023-08-17 22:55:25 +02004140 new
LemonBoy0f7a3e12022-05-26 12:10:37 +01004141 call setline(1, "the\tquick\tbrown\tfox")
4142 norm! 4|
4143 call assert_equal(8, virtcol('.'))
4144 call assert_equal(8, virtcol('.', v:false))
4145 call assert_equal([4, 8], virtcol('.', v:true))
zeertzjq825cf812023-08-17 22:55:25 +02004146
4147 let w = winwidth(0)
4148 call setline(2, repeat('a', w + 2))
4149 let win_nosbr = win_getid()
4150 split
4151 setlocal showbreak=!!
4152 let win_sbr = win_getid()
4153 call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr))
4154 call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr))
4155 call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr))
4156 call assert_equal([w, w], virtcol([2, w], v:true, win_sbr))
4157 call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr))
4158 call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr))
4159 close
4160
4161 call assert_equal(0, virtcol(''))
4162 call assert_equal([0, 0], virtcol('', v:true))
4163 call assert_equal(0, virtcol('.', v:false, 5001))
4164 call assert_equal([0, 0], virtcol('.', v:true, 5001))
4165
LemonBoy0f7a3e12022-05-26 12:10:37 +01004166 bwipe!
4167endfunc
4168
Bram Moolenaar398a26f2022-11-13 22:13:33 +00004169func Test_delfunc_while_listing()
4170 CheckRunVimInTerminal
4171
4172 let lines =<< trim END
4173 set nocompatible
4174 for i in range(1, 999)
4175 exe 'func ' .. 'MyFunc' .. i .. '()'
4176 endfunc
4177 endfor
4178 au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')})
4179 END
4180 call writefile(lines, 'Xfunctionclear', 'D')
4181 let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12})
4182
4183 " This was using freed memory. The height of the terminal must be so that
4184 " the next function to be listed with "j" is the one that is deleted in the
4185 " timer callback, tricky!
4186 call term_sendkeys(buf, ":func /MyFunc\<CR>")
4187 call TermWait(buf, 50)
4188 call term_sendkeys(buf, "j")
4189 call TermWait(buf, 50)
4190 call term_sendkeys(buf, "\<CR>")
4191
4192 call StopVimInTerminal(buf)
4193endfunc
4194
Yegappan Lakshmanan03ff1c22023-05-06 14:08:21 +01004195" Test for the reverse() function with a string
4196func Test_string_reverse()
Yegappan Lakshmananf9dc2782023-05-11 15:02:56 +01004197 let lines =<< trim END
4198 call assert_equal('', reverse(test_null_string()))
4199 for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'],
4200 \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'],
4201 \ ['🇦', '🇦'], ['🇦🇧', '🇧🇦'], ['🇦🇧🇨', '🇨🇧🇦'],
4202 \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']]
4203 call assert_equal(s2, reverse(s1))
4204 endfor
4205 END
4206 call v9.CheckLegacyAndVim9Success(lines)
Yegappan Lakshmanan03ff1c22023-05-06 14:08:21 +01004207
4208 " test in latin1 encoding
4209 let save_enc = &encoding
4210 set encoding=latin1
4211 call assert_equal('dcba', reverse('abcd'))
4212 let &encoding = save_enc
4213endfunc
4214
Christian Brabandt4c6fe2e2023-09-02 19:30:03 +02004215func Test_fullcommand()
4216 " this used to crash vim
4217 call assert_equal('', fullcommand(10))
4218endfunc
4219
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02004220" Test for glob() with shell special patterns
4221func Test_glob_extended_bash()
4222 CheckExecutable bash
Ken Takata03ca4002023-09-28 21:59:58 +02004223 CheckNotMSWindows
4224 CheckNotMac " The default version of bash is old on macOS.
4225
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02004226 let _shell = &shell
4227 set shell=bash
4228
4229 call mkdir('Xtestglob/foo/bar/src', 'p')
4230 call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
4231 call writefile([], 'Xtestglob/foo/bar/src/foo.h')
4232 call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
4233
4234 " Sort output of glob() otherwise we end up with different
4235 " ordering depending on whether file system is case-sensitive.
4236 let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h']
4237 call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1)))
4238 call delete('Xtestglob', 'rf')
4239 let &shell=_shell
4240endfunc
4241
Ken Takata4a1ad552023-10-02 21:31:31 +02004242" Test for glob() with extended patterns (MS-Windows)
4243" Vim doesn't use 'shell' to expand wildcards on MS-Windows.
4244" Unlike bash, it doesn't support {,} expansion.
4245func Test_glob_extended_mswin()
4246 CheckMSWindows
4247
4248 call mkdir('Xtestglob/foo/bar/src', 'p')
4249 call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
4250 call writefile([], 'Xtestglob/foo/bar/src/foo.h')
4251 call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
4252
4253 " Sort output of glob() otherwise we end up with different
4254 " ordering depending on whether file system is case-sensitive.
4255 let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh']
4256 call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1)))
4257 call delete('Xtestglob', 'rf')
4258endfunc
4259
zeertzjqad387692024-03-23 08:23:48 +01004260" Tests for the slice() function.
4261func Test_slice()
4262 let lines =<< trim END
4263 call assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
4264 call assert_equal([2, 3, 4, 5], slice(range(6), 2))
4265 call assert_equal([2, 3], slice(range(6), 2, 4))
4266 call assert_equal([0, 1, 2, 3], slice(range(6), 0, 4))
4267 call assert_equal([1, 2, 3], slice(range(6), 1, 4))
4268 call assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
4269 call assert_equal([1, 2], slice(range(6), 1, -3))
4270 call assert_equal([1], slice(range(6), 1, -4))
4271 call assert_equal([], slice(range(6), 1, -5))
4272 call assert_equal([], slice(range(6), 1, -6))
4273
4274 call assert_equal(0z1122334455, slice(0z001122334455, 1))
4275 call assert_equal(0z22334455, slice(0z001122334455, 2))
4276 call assert_equal(0z2233, slice(0z001122334455, 2, 4))
4277 call assert_equal(0z00112233, slice(0z001122334455, 0, 4))
4278 call assert_equal(0z112233, slice(0z001122334455, 1, 4))
4279 call assert_equal(0z11223344, slice(0z001122334455, 1, -1))
4280 call assert_equal(0z1122, slice(0z001122334455, 1, -3))
4281 call assert_equal(0z11, slice(0z001122334455, 1, -4))
4282 call assert_equal(0z, slice(0z001122334455, 1, -5))
4283 call assert_equal(0z, slice(0z001122334455, 1, -6))
4284
4285 call assert_equal('12345', slice('012345', 1))
4286 call assert_equal('2345', slice('012345', 2))
4287 call assert_equal('23', slice('012345', 2, 4))
4288 call assert_equal('0123', slice('012345', 0, 4))
4289 call assert_equal('123', slice('012345', 1, 4))
4290 call assert_equal('1234', slice('012345', 1, -1))
4291 call assert_equal('12', slice('012345', 1, -3))
4292 call assert_equal('1', slice('012345', 1, -4))
4293 call assert_equal('', slice('012345', 1, -5))
4294 call assert_equal('', slice('012345', 1, -6))
4295
4296 #" Composing chars are treated as a part of the preceding base char.
4297 call assert_equal('β̳́γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1))
4298 call assert_equal('γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2))
4299 call assert_equal('γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2, 4))
4300 call assert_equal('ὰ̳β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(0, 4))
4301 call assert_equal('β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, 4))
4302 call assert_equal('β̳́γ̳̂δ̳̃ε̳̄', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -1))
4303 call assert_equal('β̳́γ̳̂', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -3))
4304 call assert_equal('β̳́', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -4))
4305 call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -5))
4306 call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -6))
4307 END
4308 call v9.CheckLegacyAndVim9Success(lines)
Yegappan Lakshmananfe424d12024-05-17 18:20:43 +02004309
4310 call assert_equal(0, slice(v:true, 1))
zeertzjqad387692024-03-23 08:23:48 +01004311endfunc
4312
mikoto2000de094dc2024-11-14 22:13:48 +01004313
mikoto2000a73dfc22024-11-18 21:12:21 +01004314" Test for getcellpixels() for unix system
mikoto2000de094dc2024-11-14 22:13:48 +01004315" Pixel size of a cell is terminal-dependent, so in the test, only the list and size 2 are checked.
mikoto2000a73dfc22024-11-18 21:12:21 +01004316func Test_getcellpixels_for_unix()
mikoto2000de094dc2024-11-14 22:13:48 +01004317 CheckNotMSWindows
4318 CheckRunVimInTerminal
4319
4320 let buf = RunVimInTerminal('', #{rows: 6})
4321
4322 " write getcellpixels() result to current buffer.
4323 call term_sendkeys(buf, ":redi @\"\<CR>")
4324 call term_sendkeys(buf, ":echo getcellpixels()\<CR>")
4325 call term_sendkeys(buf, ":redi END\<CR>")
4326 call term_sendkeys(buf, "P")
4327
4328 call WaitForAssert({-> assert_match("\[\d+, \d+\]", term_getline(buf, 3))}, 1000)
4329
4330 call StopVimInTerminal(buf)
4331endfunc
4332
mikoto2000a73dfc22024-11-18 21:12:21 +01004333" Test for getcellpixels() for windows system
4334" Windows terminal vim is not support. check return `[]`.
4335func Test_getcellpixels_for_windows()
4336 CheckMSWindows
4337 CheckRunVimInTerminal
4338
4339 let buf = RunVimInTerminal('', #{rows: 6})
4340
4341 " write getcellpixels() result to current buffer.
4342 call term_sendkeys(buf, ":redi @\"\<CR>")
4343 call term_sendkeys(buf, ":echo getcellpixels()\<CR>")
4344 call term_sendkeys(buf, ":redi END\<CR>")
4345 call term_sendkeys(buf, "P")
4346
4347 call WaitForAssert({-> assert_match("\[\]", term_getline(buf, 3))}, 1000)
4348
4349 call StopVimInTerminal(buf)
4350endfunc
4351
mikoto2000de094dc2024-11-14 22:13:48 +01004352" Test for getcellpixels() on gVim
4353func Test_getcellpixels_gui()
mikoto2000de094dc2024-11-14 22:13:48 +01004354 if has("gui_running")
4355 let cellpixels = getcellpixels()
mikoto2000a73dfc22024-11-18 21:12:21 +01004356 call assert_equal(2, len(cellpixels))
mikoto2000de094dc2024-11-14 22:13:48 +01004357 endif
4358endfunc
4359
Yegappan Lakshmanan810785c2024-12-30 10:29:44 +01004360func Str2Blob(s)
4361 return list2blob(str2list(a:s))
4362endfunc
4363
4364func Blob2Str(b)
4365 return list2str(blob2list(a:b))
4366endfunc
4367
4368" Test for the base64_encode() and base64_decode() functions
4369func Test_base64_encoding()
4370 let lines =<< trim END
4371 #" Test for encoding/decoding the RFC-4648 alphabets
4372 VAR s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
4373 for i in range(64)
4374 call assert_equal($'{s[i]}A==', base64_encode(list2blob([i << 2])))
4375 call assert_equal(list2blob([i << 2]), base64_decode($'{s[i]}A=='))
4376 endfor
4377
4378 #" Test for encoding with padding
4379 call assert_equal('TQ==', base64_encode(g:Str2Blob("M")))
4380 call assert_equal('TWE=', base64_encode(g:Str2Blob("Ma")))
4381 call assert_equal('TWFu', g:Str2Blob("Man")->base64_encode())
4382 call assert_equal('', base64_encode(0z))
4383 call assert_equal('', base64_encode(g:Str2Blob("")))
4384
4385 #" Test for decoding with padding
4386 call assert_equal('light work.', g:Blob2Str(base64_decode("bGlnaHQgd29yay4=")))
4387 call assert_equal('light work', g:Blob2Str(base64_decode("bGlnaHQgd29yaw==")))
4388 call assert_equal('light wor', g:Blob2Str("bGlnaHQgd29y"->base64_decode()))
4389 call assert_equal(0z00, base64_decode("===="))
4390 call assert_equal(0z, base64_decode(""))
4391
4392 #" Test for invalid padding
4393 call assert_equal('Hello', g:Blob2Str(base64_decode("SGVsbG8=")))
4394 call assert_fails('call base64_decode("SGVsbG9=")', 'E475:')
4395 call assert_fails('call base64_decode("SGVsbG9")', 'E475:')
4396 call assert_equal('Hell', g:Blob2Str(base64_decode("SGVsbA==")))
4397 call assert_fails('call base64_decode("SGVsbA=")', 'E475:')
4398 call assert_fails('call base64_decode("SGVsbA")', 'E475:')
4399 call assert_fails('call base64_decode("SGVsbA====")', 'E475:')
4400
4401 #" Error case
4402 call assert_fails('call base64_decode("b")', 'E475: Invalid argument: b')
4403 call assert_fails('call base64_decode("<<==")', 'E475: Invalid argument: <<==')
4404
4405 call assert_fails('call base64_encode([])', 'E1238: Blob required for argument 1')
4406 call assert_fails('call base64_decode([])', 'E1174: String required for argument 1')
4407 END
4408 call v9.CheckLegacyAndVim9Success(lines)
4409endfunc
4410
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004411" Tests for the str2blob() function
4412func Test_str2blob()
4413 let lines =<< trim END
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004414 call assert_equal(0z, str2blob([""]))
4415 call assert_equal(0z, str2blob([]))
4416 call assert_equal(0z, str2blob(test_null_list()))
4417 call assert_equal(0z, str2blob([test_null_string(), test_null_string()]))
4418 call assert_fails("call str2blob('')", 'E1211: List required for argument 1')
4419 call assert_equal(0z61, str2blob(["a"]))
4420 call assert_equal(0z6162, str2blob(["ab"]))
4421 call assert_equal(0z610062, str2blob(["a\nb"]))
4422 call assert_equal(0z61620A6364, str2blob(["ab", "cd"]))
4423 call assert_equal(0z0A, str2blob(["", ""]))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004424
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004425 call assert_equal(0zC2ABC2BB, str2blob(["«»"]))
4426 call assert_equal(0zC59DC59F, str2blob(["ŝş"]))
4427 call assert_equal(0zE0AE85E0.AE87, str2blob(["அஇ"]))
4428 call assert_equal(0zF09F81B0.F09F81B3, str2blob(["🁰🁳"]))
4429 call assert_equal(0z616263, str2blob(['abc'], {}))
4430 call assert_equal(0zABBB, str2blob(['«»'], {'encoding': 'latin1'}))
4431 call assert_equal(0zABBB0AABBB, str2blob(['«»', '«»'], {'encoding': 'latin1'}))
4432 call assert_equal(0zC2ABC2BB, str2blob(['«»'], {'encoding': 'utf8'}))
4433
Yegappan Lakshmanan5e9aaed2025-01-18 10:24:25 +01004434 call assert_equal(0z62, str2blob(["b"], test_null_dict()))
4435 call assert_equal(0z63, str2blob(["c"], {'encoding': test_null_string()}))
4436
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004437 call assert_fails("call str2blob(['abc'], [])", 'E1206: Dictionary required for argument 2')
4438 call assert_fails("call str2blob(['abc'], {'encoding': []})", 'E730: Using a List as a String')
Christian Brabandtd5afc742025-03-18 20:55:42 +01004439 call assert_fails("call str2blob(['abc'], {'encoding': 'ab12xy'})", 'E1516: Unable to convert to ''ab12xy'' encoding')
4440 call assert_fails("call str2blob(['ŝş'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
4441 call assert_fails("call str2blob(['அஇ'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
4442 call assert_fails("call str2blob(['🁰🁳'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004443 END
4444 call v9.CheckLegacyAndVim9Success(lines)
4445endfunc
4446
4447" Tests for the blob2str() function
4448func Test_blob2str()
4449 let lines =<< trim END
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004450 call assert_equal([], blob2str(0z))
4451 call assert_equal([], blob2str(test_null_blob()))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004452 call assert_fails("call blob2str([])", 'E1238: Blob required for argument 1')
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004453 call assert_equal(["ab"], blob2str(0z6162))
4454 call assert_equal(["a\nb"], blob2str(0z610062))
4455 call assert_equal(["ab", "cd"], blob2str(0z61620A6364))
4456
4457 call assert_equal(["«»"], blob2str(0zC2ABC2BB))
4458 call assert_equal(["ŝş"], blob2str(0zC59DC59F))
4459 call assert_equal(["அஇ"], blob2str(0zE0AE85E0.AE87))
4460 call assert_equal(["🁰🁳"], blob2str(0zF09F81B0.F09F81B3))
4461 call assert_equal(['«»'], blob2str(0zABBB, {'encoding': 'latin1'}))
4462 call assert_equal(['«»'], blob2str(0zC2ABC2BB, {'encoding': 'utf8'}))
Yegappan Lakshmanan90b39752025-01-19 09:37:07 +01004463 call assert_equal(['«»'], blob2str(0zC2ABC2BB, {'encoding': 'utf-8'}))
4464
4465 call assert_equal(['a'], blob2str(0z61, test_null_dict()))
4466 call assert_equal(['a'], blob2str(0z61, {'encoding': test_null_string()}))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004467
Bakudankunb3854bf2025-02-23 20:29:21 +01004468 call assert_equal(["\x80"], blob2str(0z80, {'encoding': 'none'}))
4469 call assert_equal(['a', "\x80"], blob2str(0z610A80, {'encoding': 'none'}))
4470
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004471 #" Invalid encoding
4472 call assert_fails("call blob2str(0z80)", "E1515: Unable to convert from 'utf-8' encoding")
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004473 call assert_fails("call blob2str(0z610A80)", "E1515: Unable to convert from 'utf-8' encoding")
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004474 call assert_fails("call blob2str(0zC0)", "E1515: Unable to convert from 'utf-8' encoding")
4475 call assert_fails("call blob2str(0zE0)", "E1515: Unable to convert from 'utf-8' encoding")
4476 call assert_fails("call blob2str(0zF0)", "E1515: Unable to convert from 'utf-8' encoding")
4477
4478 call assert_fails("call blob2str(0z6180)", "E1515: Unable to convert from 'utf-8' encoding")
4479 call assert_fails("call blob2str(0z61C0)", "E1515: Unable to convert from 'utf-8' encoding")
4480 call assert_fails("call blob2str(0z61E0)", "E1515: Unable to convert from 'utf-8' encoding")
4481 call assert_fails("call blob2str(0z61F0)", "E1515: Unable to convert from 'utf-8' encoding")
4482
4483 call assert_fails("call blob2str(0zC0C0)", "E1515: Unable to convert from 'utf-8' encoding")
4484 call assert_fails("call blob2str(0z61C0C0)", "E1515: Unable to convert from 'utf-8' encoding")
4485
4486 call assert_fails("call blob2str(0zE0)", "E1515: Unable to convert from 'utf-8' encoding")
4487 call assert_fails("call blob2str(0zE080)", "E1515: Unable to convert from 'utf-8' encoding")
4488 call assert_fails("call blob2str(0zE080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4489 call assert_fails("call blob2str(0z61E080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4490
4491 call assert_fails("call blob2str(0zF08080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4492 call assert_fails("call blob2str(0z61F08080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4493 call assert_fails("call blob2str(0zF0)", "E1515: Unable to convert from 'utf-8' encoding")
4494 call assert_fails("call blob2str(0zF080)", "E1515: Unable to convert from 'utf-8' encoding")
4495 call assert_fails("call blob2str(0zF08080)", "E1515: Unable to convert from 'utf-8' encoding")
4496
4497 call assert_fails("call blob2str(0z6162, [])", 'E1206: Dictionary required for argument 2')
4498 call assert_fails("call blob2str(0z6162, {'encoding': []})", 'E730: Using a List as a String')
4499 call assert_fails("call blob2str(0z6162, {'encoding': 'ab12xy'})", 'E1515: Unable to convert from ''ab12xy'' encoding')
4500 END
4501 call v9.CheckLegacyAndVim9Success(lines)
4502endfunc
4503
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01004504" vim: shiftwidth=2 sts=2 expandtab