blob: 4fac4726fa91a1f5d1fa04b3912fc5a297dada53 [file] [log] [blame]
Bram Moolenaar08243d22017-01-10 16:12:29 +01001" Tests for various functions.
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002
Christian Brabandteb380b92025-07-07 20:53:55 +02003source util/screendump.vim
4import './util/vim9.vim' as v9
Bram Moolenaar08243d22017-01-10 16:12:29 +01005
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +01006" Must be done first, since the alternate buffer must be unset.
7func Test_00_bufexists()
8 call assert_equal(0, bufexists('does_not_exist'))
9 call assert_equal(1, bufexists(bufnr('%')))
10 call assert_equal(0, bufexists(0))
11 new Xfoo
12 let bn = bufnr('%')
13 call assert_equal(1, bufexists(bn))
14 call assert_equal(1, bufexists('Xfoo'))
15 call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
16 call assert_equal(1, bufexists(0))
17 bw
18 call assert_equal(0, bufexists(bn))
19 call assert_equal(0, bufexists('Xfoo'))
20endfunc
21
Bram Moolenaar79296512020-03-22 16:17:14 +010022func Test_has()
23 call assert_equal(1, has('eval'))
24 call assert_equal(1, has('eval', 1))
25
Bram Moolenaar0e05de42020-03-25 22:23:46 +010026 if has('unix')
27 call assert_equal(1, or(has('ttyin'), 1))
28 call assert_equal(0, and(has('ttyout'), 0))
29 call assert_equal(1, has('multi_byte_encoding'))
Bram Moolenaar80adaa82023-07-07 18:57:40 +010030 call assert_equal(0, has(':tearoff'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010031 endif
Bram Moolenaar99fa7212020-04-26 15:59:55 +020032 call assert_equal(1, has('vcon', 1))
33 call assert_equal(1, has('mouse_gpm_enabled', 1))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010034
Bram Moolenaar80adaa82023-07-07 18:57:40 +010035 call assert_equal(has('gui_win32') && has('menu'), has(':tearoff'))
36
Bram Moolenaar79296512020-03-22 16:17:14 +010037 call assert_equal(0, has('nonexistent'))
38 call assert_equal(0, has('nonexistent', 1))
Bram Moolenaar0e05de42020-03-25 22:23:46 +010039
40 " Will we ever have patch 9999?
41 let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999'
42 call assert_equal(0, has(ver))
Bram Moolenaarb0375d42022-06-30 11:03:39 +010043
44 " There actually isn't a patch 9.0.0, but this is more consistent.
45 call assert_equal(1, has('patch-9.0.0'))
Bram Moolenaar79296512020-03-22 16:17:14 +010046endfunc
47
Bram Moolenaar24c2e482017-01-29 15:45:12 +010048func Test_empty()
49 call assert_equal(1, empty(''))
50 call assert_equal(0, empty('a'))
51
52 call assert_equal(1, empty(0))
53 call assert_equal(1, empty(-0))
54 call assert_equal(0, empty(1))
55 call assert_equal(0, empty(-1))
56
Bram Moolenaar73e28dc2022-09-17 21:08:33 +010057 call assert_equal(1, empty(0.0))
58 call assert_equal(1, empty(-0.0))
59 call assert_equal(0, empty(1.0))
60 call assert_equal(0, empty(-1.0))
61 call assert_equal(0, empty(1.0/0.0))
62 call assert_equal(0, empty(0.0/0.0))
Bram Moolenaar24c2e482017-01-29 15:45:12 +010063
64 call assert_equal(1, empty([]))
65 call assert_equal(0, empty(['a']))
66
67 call assert_equal(1, empty({}))
68 call assert_equal(0, empty({'a':1}))
69
70 call assert_equal(1, empty(v:null))
71 call assert_equal(1, empty(v:none))
72 call assert_equal(1, empty(v:false))
73 call assert_equal(0, empty(v:true))
74
Bram Moolenaar41042f32017-03-09 12:09:32 +010075 if has('channel')
76 call assert_equal(1, empty(test_null_channel()))
77 endif
78 if has('job')
79 call assert_equal(1, empty(test_null_job()))
80 endif
81
Bram Moolenaar24c2e482017-01-29 15:45:12 +010082 call assert_equal(0, empty(function('Test_empty')))
Bram Moolenaar17aca702019-05-16 22:24:55 +020083 call assert_equal(0, empty(function('Test_empty', [0])))
Bram Moolenaar7c215c52020-02-29 13:43:27 +010084
Bram Moolenaar097c5372023-05-24 21:02:24 +010085 call assert_fails("call empty(test_void())", ['E340:', 'E685:'])
86 call assert_fails("call empty(test_unknown())", ['E340:', 'E685:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +010087endfunc
88
Bram Moolenaar80adaa82023-07-07 18:57:40 +010089func Test_err_teapot()
90 call assert_fails('call err_teapot()', "E418: I'm a teapot")
91 call assert_fails('call err_teapot(0)', "E418: I'm a teapot")
92 call assert_fails('call err_teapot(v:false)', "E418: I'm a teapot")
93
94 call assert_fails('call err_teapot("1")', "E503: Coffee is currently not available")
95 call assert_fails('call err_teapot(v:true)', "E503: Coffee is currently not available")
96 let expr = 1
97 call assert_fails('call err_teapot(expr)', "E503: Coffee is currently not available")
98endfunc
99
Bram Moolenaardd589232020-02-29 17:38:12 +0100100func Test_test_void()
Bram Moolenaar61a417b2021-06-15 22:54:28 +0200101 call assert_fails('echo 1 == test_void()', 'E1031:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100102 call assert_fails('echo 1.0 == test_void()', 'E1031:')
Bram Moolenaar097c5372023-05-24 21:02:24 +0100103 call assert_fails('let x = json_encode(test_void())', ['E340:', 'E685:'])
104 call assert_fails('let x = copy(test_void())', ['E340:', 'E685:'])
Bram Moolenaar61a417b2021-06-15 22:54:28 +0200105 call assert_fails('let x = copy([test_void()])', 'E1031:')
Bram Moolenaardd589232020-02-29 17:38:12 +0100106endfunc
107
Bram Moolenaar1840a7b2021-07-13 20:32:29 +0200108func Test_islocked()
109 call assert_fails('call islocked(99)', 'E475:')
110 call assert_fails('call islocked("s: x")', 'E488:')
111endfunc
112
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100113func Test_len()
114 call assert_equal(1, len(0))
115 call assert_equal(2, len(12))
116
117 call assert_equal(0, len(''))
118 call assert_equal(2, len('ab'))
119
120 call assert_equal(0, len([]))
Bram Moolenaar08f41572020-04-20 16:50:00 +0200121 call assert_equal(0, len(test_null_list()))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100122 call assert_equal(2, len([2, 1]))
123
124 call assert_equal(0, len({}))
Bram Moolenaar08f41572020-04-20 16:50:00 +0200125 call assert_equal(0, len(test_null_dict()))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100126 call assert_equal(2, len({'a': 1, 'b': 2}))
127
128 call assert_fails('call len(v:none)', 'E701:')
129 call assert_fails('call len({-> 0})', 'E701:')
130endfunc
131
132func Test_max()
133 call assert_equal(0, max([]))
134 call assert_equal(2, max([2]))
135 call assert_equal(2, max([1, 2]))
136 call assert_equal(2, max([1, 2, v:null]))
137
138 call assert_equal(0, max({}))
139 call assert_equal(2, max({'a':1, 'b':2}))
140
141 call assert_fails('call max(1)', 'E712:')
142 call assert_fails('call max(v:none)', 'E712:')
Bram Moolenaarab65fc72021-02-04 22:07:16 +0100143
144 " check we only get one error
145 call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:'])
146 call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100147endfunc
148
149func Test_min()
150 call assert_equal(0, min([]))
151 call assert_equal(2, min([2]))
152 call assert_equal(1, min([1, 2]))
153 call assert_equal(0, min([1, 2, v:null]))
154
155 call assert_equal(0, min({}))
156 call assert_equal(1, min({'a':1, 'b':2}))
157
158 call assert_fails('call min(1)', 'E712:')
159 call assert_fails('call min(v:none)', 'E712:')
Yegappan Lakshmanan34fcb692021-05-25 20:14:00 +0200160 call assert_fails('call min([1, {}])', 'E728:')
Bram Moolenaarab65fc72021-02-04 22:07:16 +0100161
162 " check we only get one error
163 call assert_fails('call min([[1], #{}])', ['E745:', 'E745:'])
164 call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:'])
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100165endfunc
166
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200167func Test_strwidth()
168 for aw in ['single', 'double']
169 exe 'set ambiwidth=' . aw
170 call assert_equal(0, strwidth(''))
171 call assert_equal(1, strwidth("\t"))
172 call assert_equal(3, strwidth('Vim'))
173 call assert_equal(4, strwidth(1234))
174 call assert_equal(5, strwidth(-1234))
175
Bram Moolenaar30276f22019-01-24 17:59:39 +0100176 call assert_equal(2, strwidth('😉'))
177 call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
178 call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200179
180 call assert_fails('call strwidth({->0})', 'E729:')
181 call assert_fails('call strwidth([])', 'E730:')
182 call assert_fails('call strwidth({})', 'E731:')
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200183 endfor
184
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100185 call assert_equal(3, strwidth(1.2))
186 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 +0200187
Bram Moolenaar42ab17b2018-05-20 14:11:10 +0200188 set ambiwidth&
189endfunc
190
Bram Moolenaar08243d22017-01-10 16:12:29 +0100191func Test_str2nr()
192 call assert_equal(0, str2nr(''))
193 call assert_equal(1, str2nr('1'))
194 call assert_equal(1, str2nr(' 1 '))
195
196 call assert_equal(1, str2nr('+1'))
197 call assert_equal(1, str2nr('+ 1'))
198 call assert_equal(1, str2nr(' + 1 '))
199
200 call assert_equal(-1, str2nr('-1'))
201 call assert_equal(-1, str2nr('- 1'))
202 call assert_equal(-1, str2nr(' - 1 '))
203
204 call assert_equal(123456789, str2nr('123456789'))
205 call assert_equal(-123456789, str2nr('-123456789'))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100206
207 call assert_equal(5, str2nr('101', 2))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200208 call assert_equal(5, '0b101'->str2nr(2))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100209 call assert_equal(5, str2nr('0B101', 2))
210 call assert_equal(-5, str2nr('-101', 2))
211 call assert_equal(-5, str2nr('-0b101', 2))
212 call assert_equal(-5, str2nr('-0B101', 2))
213
214 call assert_equal(65, str2nr('101', 8))
215 call assert_equal(65, str2nr('0101', 8))
216 call assert_equal(-65, str2nr('-101', 8))
217 call assert_equal(-65, str2nr('-0101', 8))
Bram Moolenaarc17e66c2020-06-02 21:38:22 +0200218 call assert_equal(65, str2nr('0o101', 8))
219 call assert_equal(65, str2nr('0O0101', 8))
220 call assert_equal(-65, str2nr('-0O101', 8))
221 call assert_equal(-65, str2nr('-0o0101', 8))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100222
223 call assert_equal(11259375, str2nr('abcdef', 16))
224 call assert_equal(11259375, str2nr('ABCDEF', 16))
225 call assert_equal(-11259375, str2nr('-ABCDEF', 16))
226 call assert_equal(11259375, str2nr('0xabcdef', 16))
227 call assert_equal(11259375, str2nr('0Xabcdef', 16))
228 call assert_equal(11259375, str2nr('0XABCDEF', 16))
229 call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
230
Bram Moolenaar60a8de22019-09-15 14:33:22 +0200231 call assert_equal(1, str2nr("1'000'000", 10, 0))
232 call assert_equal(256, str2nr("1'0000'0000", 2, 1))
233 call assert_equal(262144, str2nr("1'000'000", 8, 1))
234 call assert_equal(1000000, str2nr("1'000'000", 10, 1))
Bram Moolenaarea8dcf82019-09-15 21:12:22 +0200235 call assert_equal(1000, str2nr("1'000''000", 10, 1))
Bram Moolenaar60a8de22019-09-15 14:33:22 +0200236 call assert_equal(65536, str2nr("1'00'00", 16, 1))
237
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100238 call assert_equal(0, str2nr('0x10'))
239 call assert_equal(0, str2nr('0b10'))
Bram Moolenaarc17e66c2020-06-02 21:38:22 +0200240 call assert_equal(0, str2nr('0o10'))
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100241 call assert_equal(1, str2nr('12', 2))
242 call assert_equal(1, str2nr('18', 8))
243 call assert_equal(1, str2nr('1g', 16))
244
245 call assert_equal(0, str2nr(v:null))
246 call assert_equal(0, str2nr(v:none))
247
248 call assert_fails('call str2nr([])', 'E730:')
249 call assert_fails('call str2nr({->2})', 'E729:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100250 call assert_equal(1, str2nr(1.2))
251 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 +0200252 call assert_fails('call str2nr(10, [])', 'E745:')
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100253endfunc
254
255func Test_strftime()
Bram Moolenaar10455d42019-11-21 15:36:18 +0100256 CheckFunction strftime
257
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100258 " Format of strftime() depends on system. We assume
259 " that basic formats tested here are available and
260 " identical on all systems which support strftime().
261 "
262 " The 2nd parameter of strftime() is a local time, so the output day
263 " of strftime() can be 17 or 18, depending on timezone.
264 call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
265 "
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200266 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 +0100267
268 call assert_fails('call strftime([])', 'E730:')
269 call assert_fails('call strftime("%Y", [])', 'E745:')
Bram Moolenaardb517302019-06-18 22:53:24 +0200270
271 " Check that the time changes after we change the timezone
272 " Save previous timezone value, if any
273 if exists('$TZ')
274 let tz = $TZ
275 endif
276
James McCoyea997ed2024-10-12 11:36:58 +0200277 " Force different time zones, save the current hour (24-hour clock) for each
278 let $TZ = 'GMT+1' | let one = strftime('%H')
279 let $TZ = 'GMT+2' | let two = strftime('%H')
Bram Moolenaardb517302019-06-18 22:53:24 +0200280
281 " Those hours should be two bytes long, and should not be the same; if they
282 " are, a tzset(3) call may have failed somewhere
James McCoyea997ed2024-10-12 11:36:58 +0200283 call assert_equal(strlen(one), 2)
284 call assert_equal(strlen(two), 2)
Bram Moolenaar87652a72019-06-18 23:07:37 +0200285 " TODO: this fails on MS-Windows
286 if has('unix')
James McCoyea997ed2024-10-12 11:36:58 +0200287 call assert_notequal(one, two)
Bram Moolenaar87652a72019-06-18 23:07:37 +0200288 endif
Bram Moolenaardb517302019-06-18 22:53:24 +0200289
290 " If we cached a timezone value, put it back, otherwise clear it
291 if exists('tz')
292 let $TZ = tz
293 else
294 unlet $TZ
295 endif
Bram Moolenaar10455d42019-11-21 15:36:18 +0100296endfunc
Bram Moolenaardb517302019-06-18 22:53:24 +0200297
Bram Moolenaar10455d42019-11-21 15:36:18 +0100298func Test_strptime()
299 CheckFunction strptime
Christian Brabandt983d8082023-09-10 19:06:09 +0200300 CheckNotBSD
Bram Moolenaar10455d42019-11-21 15:36:18 +0100301
302 if exists('$TZ')
303 let tz = $TZ
304 endif
305 let $TZ = 'UTC'
306
Bram Moolenaar9a838fe2019-12-06 12:45:01 +0100307 call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
Bram Moolenaar10455d42019-11-21 15:36:18 +0100308
Bram Moolenaarea1233f2020-06-10 16:54:13 +0200309 " Force DST and check that it's considered
310 let $TZ = 'WINTER0SUMMER,J1,J365'
311 call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
312
Bram Moolenaar10455d42019-11-21 15:36:18 +0100313 call assert_fails('call strptime()', 'E119:')
314 call assert_fails('call strptime("xxx")', 'E119:')
Christian Brabandte5f7cd02023-09-10 19:25:26 +0200315 " This fails on BSD 14 and returns
Christian Brabandt983d8082023-09-10 19:06:09 +0200316 " -2209078800 instead of 0
Bram Moolenaar10455d42019-11-21 15:36:18 +0100317 call assert_equal(0, strptime("%Y", ''))
318 call assert_equal(0, strptime("%Y", "xxx"))
319
320 if exists('tz')
321 let $TZ = tz
322 else
323 unlet $TZ
324 endif
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100325endfunc
326
Bram Moolenaardce1e892019-02-10 23:18:53 +0100327func Test_resolve_unix()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +0200328 CheckUnix
Bram Moolenaar26109902018-10-06 15:43:17 +0200329
330 " Xlink1 -> Xlink2
331 " Xlink2 -> Xlink3
332 silent !ln -s -f Xlink2 Xlink1
333 silent !ln -s -f Xlink3 Xlink2
334 call assert_equal('Xlink3', resolve('Xlink1'))
335 call assert_equal('./Xlink3', resolve('./Xlink1'))
336 call assert_equal('Xlink3/', resolve('Xlink2/'))
337 " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
338 "call assert_equal('Xlink3/', resolve('Xlink1/'))
339 "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
340 "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
341 call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
342
343 " Test resolve() with a symlink cycle.
344 " Xlink1 -> Xlink2
345 " Xlink2 -> Xlink3
346 " Xlink3 -> Xlink1
347 silent !ln -s -f Xlink1 Xlink3
348 call assert_fails('call resolve("Xlink1")', 'E655:')
349 call assert_fails('call resolve("./Xlink1")', 'E655:')
350 call assert_fails('call resolve("Xlink2")', 'E655:')
351 call assert_fails('call resolve("Xlink3")', 'E655:')
352 call delete('Xlink1')
353 call delete('Xlink2')
354 call delete('Xlink3')
355
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +0100356 silent !ln -s -f Xresolvedir//Xfile Xresolvelink
357 call assert_equal('Xresolvedir/Xfile', resolve('Xresolvelink'))
358 call delete('Xresolvelink')
Bram Moolenaar26109902018-10-06 15:43:17 +0200359
360 silent !ln -s -f Xlink2/ Xlink1
Bram Moolenaara0d1fef2019-09-04 22:29:14 +0200361 call assert_equal('Xlink2', 'Xlink1'->resolve())
Bram Moolenaar26109902018-10-06 15:43:17 +0200362 call assert_equal('Xlink2/', resolve('Xlink1/'))
363 call delete('Xlink1')
364
365 silent !ln -s -f ./Xlink2 Xlink1
366 call assert_equal('Xlink2', resolve('Xlink1'))
367 call assert_equal('./Xlink2', resolve('./Xlink1'))
368 call delete('Xlink1')
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +0200369
370 call assert_equal('/', resolve('/'))
Bram Moolenaar26109902018-10-06 15:43:17 +0200371endfunc
372
Bram Moolenaardce1e892019-02-10 23:18:53 +0100373func s:normalize_fname(fname)
374 let ret = substitute(a:fname, '\', '/', 'g')
375 let ret = substitute(ret, '//', '/', 'g')
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200376 return ret->tolower()
Bram Moolenaardce1e892019-02-10 23:18:53 +0100377endfunc
378
379func Test_resolve_win32()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +0200380 CheckMSWindows
Bram Moolenaardce1e892019-02-10 23:18:53 +0100381
382 " test for shortcut file
383 if executable('cscript')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100384 new Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100385 wq
Bram Moolenaare7eb9272019-06-24 00:58:07 +0200386 let lines =<< trim END
387 Set fs = CreateObject("Scripting.FileSystemObject")
388 Set ws = WScript.CreateObject("WScript.Shell")
389 Set shortcut = ws.CreateShortcut("Xlink.lnk")
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100390 shortcut.TargetPath = fs.BuildPath(ws.CurrentDirectory, "Xresfile")
Bram Moolenaare7eb9272019-06-24 00:58:07 +0200391 shortcut.Save
392 END
393 call writefile(lines, 'link.vbs')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100394 silent !cscript link.vbs
395 call delete('link.vbs')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100396 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink.lnk')))
397 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100398
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100399 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink.lnk')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100400 call delete('Xlink.lnk')
401 else
402 echomsg 'skipped test for shortcut file'
403 endif
404
405 " remove files
406 call delete('Xlink')
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100407 call delete('Xdir', 'd')
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100408 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100409
410 " test for symbolic link to a file
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100411 new Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100412 wq
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100413 call assert_equal('Xresfile', resolve('Xresfile'))
414 silent !mklink Xlink Xresfile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100415 if !v:shell_error
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100416 call assert_equal(s:normalize_fname(getcwd() . '\Xresfile'), s:normalize_fname(resolve('./Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100417 call delete('Xlink')
418 else
419 echomsg 'skipped test for symbolic link to a file'
420 endif
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100421 call delete('Xresfile')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100422
423 " test for junction to a directory
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100424 call mkdir('Xdir')
425 silent !mklink /J Xlink Xdir
Bram Moolenaardce1e892019-02-10 23:18:53 +0100426 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100427 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100428
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100429 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100430
431 " test for junction already removed
432 call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
433 call delete('Xlink')
434 else
435 echomsg 'skipped test for junction to a directory'
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100436 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100437 endif
438
439 " test for symbolic link to a directory
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100440 call mkdir('Xdir')
441 silent !mklink /D Xlink Xdir
Bram Moolenaardce1e892019-02-10 23:18:53 +0100442 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100443 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
Bram Moolenaardce1e892019-02-10 23:18:53 +0100444
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100445 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100446
447 " test for symbolic link already removed
448 call assert_equal(s:normalize_fname(getcwd() . '\Xlink'), s:normalize_fname(resolve(getcwd() . '/Xlink')))
449 call delete('Xlink')
450 else
451 echomsg 'skipped test for symbolic link to a directory'
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100452 call delete('Xdir', 'd')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100453 endif
454
455 " test for buffer name
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100456 new Xbuffile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100457 wq
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100458 silent !mklink Xlink Xbuffile
Bram Moolenaardce1e892019-02-10 23:18:53 +0100459 if !v:shell_error
460 edit Xlink
461 call assert_equal('Xlink', bufname('%'))
462 call delete('Xlink')
463 bw!
464 else
465 echomsg 'skipped test for buffer name'
466 endif
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100467 call delete('Xbuffile')
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200468
469 " test for reparse point
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100470 call mkdir('Xdir')
471 call assert_equal('Xdir', resolve('Xdir'))
472 silent !mklink /D Xdirlink Xdir
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200473 if !v:shell_error
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100474 w Xdir/text.txt
475 call assert_equal('Xdir/text.txt', resolve('Xdir/text.txt'))
476 call assert_equal(s:normalize_fname(getcwd() . '\Xdir\text.txt'), s:normalize_fname(resolve('Xdirlink\text.txt')))
477 call assert_equal(s:normalize_fname(getcwd() . '\Xdir'), s:normalize_fname(resolve('Xdirlink')))
Bram Moolenaar4a792c82019-06-06 12:22:41 +0200478 call delete('Xdirlink')
Bram Moolenaar1bbebab2019-05-29 20:36:54 +0200479 else
480 echomsg 'skipped test for reparse point'
481 endif
482
Bram Moolenaar15cae5c2022-08-29 22:51:38 +0100483 call delete('Xdir', 'rf')
Bram Moolenaardce1e892019-02-10 23:18:53 +0100484endfunc
485
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100486func Test_simplify()
487 call assert_equal('', simplify(''))
488 call assert_equal('/', simplify('/'))
489 call assert_equal('/', simplify('/.'))
490 call assert_equal('/', simplify('/..'))
491 call assert_equal('/...', simplify('/...'))
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +0200492 call assert_equal('//path', simplify('//path'))
Bram Moolenaarc70222d2020-06-15 23:18:12 +0200493 if has('unix')
494 call assert_equal('/path', simplify('///path'))
495 call assert_equal('/path', simplify('////path'))
496 endif
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +0200497
Bram Moolenaar7035fd92020-04-08 20:03:52 +0200498 call assert_equal('./dir/file', './dir/file'->simplify())
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100499 call assert_equal('./dir/file', simplify('.///dir//file'))
500 call assert_equal('./dir/file', simplify('./dir/./file'))
501 call assert_equal('./file', simplify('./dir/../file'))
502 call assert_equal('../dir/file', simplify('dir/../../dir/file'))
503 call assert_equal('./file', simplify('dir/.././file'))
Bram Moolenaarbdd2c292020-06-22 21:34:30 +0200504 call assert_equal('../dir', simplify('./../dir'))
505 call assert_equal('..', simplify('../testdir/..'))
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +0100506 call mkdir('Xsimpdir')
507 call assert_equal('.', simplify('Xsimpdir/../.'))
508 call delete('Xsimpdir', 'd')
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100509
510 call assert_fails('call simplify({->0})', 'E729:')
511 call assert_fails('call simplify([])', 'E730:')
512 call assert_fails('call simplify({})', 'E731:')
Bram Moolenaar73e28dc2022-09-17 21:08:33 +0100513 call assert_equal('1.2', simplify(1.2))
514 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 +0100515endfunc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100516
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200517func Test_pathshorten()
518 call assert_equal('', pathshorten(''))
519 call assert_equal('foo', pathshorten('foo'))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +0200520 call assert_equal('/foo', '/foo'->pathshorten())
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200521 call assert_equal('f/', pathshorten('foo/'))
522 call assert_equal('f/bar', pathshorten('foo/bar'))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +0200523 call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten())
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200524 call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
525 call assert_equal('.f/bar', pathshorten('.foo/bar'))
526 call assert_equal('~f/bar', pathshorten('~foo/bar'))
527 call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
528 call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
529 call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
Bram Moolenaar92b83cc2020-04-25 15:24:44 +0200530 call assert_fails('call pathshorten([])', 'E730:')
Bram Moolenaar6a33ef02020-09-25 22:42:48 +0200531
532 " test pathshorten with optional variable to set preferred size of shortening
533 call assert_equal('', pathshorten('', 2))
534 call assert_equal('foo', pathshorten('foo', 2))
535 call assert_equal('/foo', pathshorten('/foo', 2))
536 call assert_equal('fo/', pathshorten('foo/', 2))
537 call assert_equal('fo/bar', pathshorten('foo/bar', 2))
538 call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2))
539 call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2))
540 call assert_equal('.fo/bar', pathshorten('.foo/bar', 2))
541 call assert_equal('~fo/bar', pathshorten('~foo/bar', 2))
542 call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2))
543 call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2))
544 call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2))
545 call assert_fails('call pathshorten([],2)', 'E730:')
546 call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3))
547 call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3))
548 call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0))
Bram Moolenaarbfde0b42018-08-08 22:27:31 +0200549endfunc
550
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100551func Test_strpart()
552 call assert_equal('de', strpart('abcdefg', 3, 2))
553 call assert_equal('ab', strpart('abcdefg', -2, 4))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200554 call assert_equal('abcdefg', 'abcdefg'->strpart(-2))
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100555 call assert_equal('fg', strpart('abcdefg', 5, 4))
556 call assert_equal('defg', strpart('abcdefg', 3))
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100557 call assert_equal('', strpart('abcdefg', 10))
558 call assert_fails("let s=strpart('abcdef', [])", 'E745:')
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100559
Bram Moolenaar30276f22019-01-24 17:59:39 +0100560 call assert_equal('lép', strpart('éléphant', 2, 4))
561 call assert_equal('léphant', strpart('éléphant', 2))
Bram Moolenaar6c53fca2020-08-23 17:34:46 +0200562
563 call assert_equal('é', strpart('éléphant', 0, 1, 1))
564 call assert_equal('ép', strpart('éléphant', 3, 2, v:true))
565 call assert_equal('ó', strpart('cómposed', 1, 1, 1))
Bram Moolenaarc7d16dc2017-11-18 20:32:03 +0100566endfunc
567
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100568func Test_tolower()
569 call assert_equal("", tolower(""))
570
571 " Test with all printable ASCII characters.
572 call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
573 \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
574
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100575 " Test with a few uppercase diacritics.
576 call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
577 call assert_equal("bḃḇ", tolower("BḂḆ"))
578 call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
579 call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
580 call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
581 call assert_equal("fḟ ", tolower("FḞ "))
582 call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
583 call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
584 call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
585 call assert_equal("jĵ", tolower("JĴ"))
586 call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
587 call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
588 call assert_equal("mḿṁ", tolower("MḾṀ"))
589 call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
590 call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
591 call assert_equal("pṕṗ", tolower("PṔṖ"))
592 call assert_equal("q", tolower("Q"))
593 call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
594 call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
595 call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
596 call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
597 call assert_equal("vṽ", tolower("VṼ"))
598 call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
599 call assert_equal("xẋẍ", tolower("XẊẌ"))
600 call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
601 call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
602
603 " Test with a few lowercase diacritics, which should remain unchanged.
604 call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
605 call assert_equal("bḃḇ", tolower("bḃḇ"))
606 call assert_equal("cçćĉċč", tolower("cçćĉċč"))
607 call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
608 call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
609 call assert_equal("fḟ", tolower("fḟ"))
610 call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
611 call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
612 call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
613 call assert_equal("jĵǰ", tolower("jĵǰ"))
614 call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
615 call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
616 call assert_equal("mḿṁ ", tolower("mḿṁ "))
617 call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
618 call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
619 call assert_equal("pṕṗ", tolower("pṕṗ"))
620 call assert_equal("q", tolower("q"))
621 call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
622 call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
623 call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
624 call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
625 call assert_equal("vṽ", tolower("vṽ"))
626 call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
627 call assert_equal("ẋẍ", tolower("ẋẍ"))
628 call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
629 call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
630
631 " According to https://twitter.com/jifa/status/625776454479970304
632 " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
633 " in length (2 to 3 bytes) when lowercased. So let's test them.
634 call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
Bram Moolenaare6640ad2017-12-22 21:06:56 +0100635
636 " This call to tolower with invalid utf8 sequence used to cause access to
637 " invalid memory.
638 call tolower("\xC0\x80\xC0")
639 call tolower("123\xC0\x80\xC0")
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +0200640
641 " Test in latin1 encoding
642 let save_enc = &encoding
643 set encoding=latin1
644 call assert_equal("abc", tolower("ABC"))
645 let &encoding = save_enc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100646endfunc
647
648func Test_toupper()
649 call assert_equal("", toupper(""))
650
651 " Test with all printable ASCII characters.
652 call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
653 \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
654
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100655 " Test with a few lowercase diacritics.
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200656 call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper())
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100657 call assert_equal("BḂḆ", toupper("bḃḇ"))
658 call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
659 call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
660 call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
661 call assert_equal("FḞ", toupper("fḟ"))
662 call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
663 call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
664 call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
665 call assert_equal("JĴǰ", toupper("jĵǰ"))
666 call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
667 call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
668 call assert_equal("MḾṀ ", toupper("mḿṁ "))
669 call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
670 call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
671 call assert_equal("PṔṖ", toupper("pṕṗ"))
672 call assert_equal("Q", toupper("q"))
673 call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
674 call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
675 call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
676 call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
677 call assert_equal("VṼ", toupper("vṽ"))
678 call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
679 call assert_equal("ẊẌ", toupper("ẋẍ"))
680 call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
681 call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
682
683 " Test that uppercase diacritics, which should remain unchanged.
684 call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
685 call assert_equal("BḂḆ", toupper("BḂḆ"))
686 call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
687 call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
688 call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
689 call assert_equal("FḞ ", toupper("FḞ "))
690 call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
691 call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
692 call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
693 call assert_equal("JĴ", toupper("JĴ"))
694 call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
695 call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
696 call assert_equal("MḾṀ", toupper("MḾṀ"))
697 call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
698 call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
699 call assert_equal("PṔṖ", toupper("PṔṖ"))
700 call assert_equal("Q", toupper("Q"))
701 call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
702 call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
703 call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
704 call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
705 call assert_equal("VṼ", toupper("VṼ"))
706 call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
707 call assert_equal("XẊẌ", toupper("XẊẌ"))
708 call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
709 call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
710
Bram Moolenaar24c2e482017-01-29 15:45:12 +0100711 call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
Bram Moolenaare6640ad2017-12-22 21:06:56 +0100712
713 " This call to toupper with invalid utf8 sequence used to cause access to
714 " invalid memory.
715 call toupper("\xC0\x80\xC0")
716 call toupper("123\xC0\x80\xC0")
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +0200717
718 " Test in latin1 encoding
719 let save_enc = &encoding
720 set encoding=latin1
721 call assert_equal("ABC", toupper("abc"))
722 let &encoding = save_enc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100723endfunc
724
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200725func Test_tr()
726 call assert_equal('foo', tr('bar', 'bar', 'foo'))
727 call assert_equal('zxy', 'cab'->tr('abc', 'xyz'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100728 call assert_fails("let s=tr([], 'abc', 'def')", 'E730:')
729 call assert_fails("let s=tr('abc', [], 'def')", 'E730:')
730 call assert_fails("let s=tr('abc', 'abc', [])", 'E730:')
731 call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
732 set encoding=latin1
733 call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
734 call assert_equal('hEllO', tr('hello', 'eo', 'EO'))
735 call assert_equal('hello', tr('hello', 'xy', 'ab'))
Yegappan Lakshmanan34fcb692021-05-25 20:14:00 +0200736 call assert_fails('call tr("abc", "123", "₁₂")', 'E475:')
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100737 set encoding=utf8
Bram Moolenaarf92e58c2019-09-08 21:51:41 +0200738endfunc
739
Bram Moolenaare90858d2017-02-01 17:24:34 +0100740" Tests for the mode() function
741let current_modes = ''
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100742func Save_mode()
Bram Moolenaare90858d2017-02-01 17:24:34 +0100743 let g:current_modes = mode(0) . '-' . mode(1)
744 return ''
745endfunc
Bram Moolenaarcc5b22b2017-01-26 22:51:56 +0100746
Bram Moolenaarcde0ff32020-04-04 14:00:39 +0200747" Test for the mode() function
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100748func Test_mode()
Bram Moolenaare90858d2017-02-01 17:24:34 +0100749 new
750 call append(0, ["Blue Ball Black", "Brown Band Bowl", ""])
751
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100752 " Only complete from the current buffer.
753 set complete=.
754
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100755 noremap! <F2> <C-R>=Save_mode()<CR>
zeertzjqeaf3f362021-07-28 16:51:53 +0200756 xnoremap <F2> <Cmd>call Save_mode()<CR>
Bram Moolenaare90858d2017-02-01 17:24:34 +0100757
758 normal! 3G
759 exe "normal i\<F2>\<Esc>"
760 call assert_equal('i-i', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100761 " i_CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100762 exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
763 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100764 " i_CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100765 exe "normal iBro\<C-P>\<F2>\<Esc>u"
766 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100767 " i_CTRL-X
Bram Moolenaare90858d2017-02-01 17:24:34 +0100768 exe "normal iBa\<C-X>\<F2>\<Esc>u"
769 call assert_equal('i-ix', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100770 " i_CTRL-X CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100771 exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
772 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100773 " i_CTRL-X CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100774 exe "normal iBro\<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 + CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100777 exe "normal iBro\<C-X>\<C-P>\<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-L: Multiple matches
780 exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
781 call assert_equal('i-ic', g:current_modes)
782 " i_CTRL-X CTRL-L: Single match
783 exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
784 call assert_equal('i-ic', g:current_modes)
785 " i_CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100786 exe "normal iCom\<C-P>\<F2>\<Esc>u"
787 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100788 " i_CTRL-X CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100789 exe "normal iCom\<C-X>\<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-L: No match
792 exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
793 call assert_equal('i-ic', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100794
zeertzjqcc8cd442021-10-03 15:19:14 +0100795 exe "normal R\<F2>\<Esc>"
796 call assert_equal('R-R', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100797 " R_CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100798 exe "normal RBa\<C-P>\<F2>\<Esc>u"
799 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100800 " R_CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100801 exe "normal RBro\<C-P>\<F2>\<Esc>u"
802 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100803 " R_CTRL-X
Bram Moolenaare90858d2017-02-01 17:24:34 +0100804 exe "normal RBa\<C-X>\<F2>\<Esc>u"
805 call assert_equal('R-Rx', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100806 " R_CTRL-X CTRL-P: Multiple matches
Bram Moolenaare90858d2017-02-01 17:24:34 +0100807 exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
808 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100809 " R_CTRL-X CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100810 exe "normal RBro\<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 + CTRL-P: Single match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100813 exe "normal RBro\<C-X>\<C-P>\<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-L: Multiple matches
816 exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
817 call assert_equal('R-Rc', g:current_modes)
818 " R_CTRL-X CTRL-L: Single match
819 exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
820 call assert_equal('R-Rc', g:current_modes)
821 " R_CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100822 exe "normal RCom\<C-P>\<F2>\<Esc>u"
823 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare971df32017-02-05 14:15:29 +0100824 " R_CTRL-X CTRL-P: No match
Bram Moolenaare90858d2017-02-01 17:24:34 +0100825 exe "normal RCom\<C-X>\<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-L: No match
828 exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
829 call assert_equal('R-Rc', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100830
zeertzjqcc8cd442021-10-03 15:19:14 +0100831 exe "normal gR\<F2>\<Esc>"
832 call assert_equal('R-Rv', g:current_modes)
833 " gR_CTRL-P: Multiple matches
834 exe "normal gRBa\<C-P>\<F2>\<Esc>u"
835 call assert_equal('R-Rvc', g:current_modes)
836 " gR_CTRL-P: Single match
837 exe "normal gRBro\<C-P>\<F2>\<Esc>u"
838 call assert_equal('R-Rvc', g:current_modes)
839 " gR_CTRL-X
840 exe "normal gRBa\<C-X>\<F2>\<Esc>u"
841 call assert_equal('R-Rvx', g:current_modes)
842 " gR_CTRL-X CTRL-P: Multiple matches
843 exe "normal gRBa\<C-X>\<C-P>\<F2>\<Esc>u"
844 call assert_equal('R-Rvc', g:current_modes)
845 " gR_CTRL-X CTRL-P: Single match
846 exe "normal gRBro\<C-X>\<C-P>\<F2>\<Esc>u"
847 call assert_equal('R-Rvc', g:current_modes)
848 " gR_CTRL-X CTRL-P + CTRL-P: Single match
849 exe "normal gRBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
850 call assert_equal('R-Rvc', g:current_modes)
851 " gR_CTRL-X CTRL-L: Multiple matches
852 exe "normal gR\<C-X>\<C-L>\<F2>\<Esc>u"
853 call assert_equal('R-Rvc', g:current_modes)
854 " gR_CTRL-X CTRL-L: Single match
855 exe "normal gRBlu\<C-X>\<C-L>\<F2>\<Esc>u"
856 call assert_equal('R-Rvc', g:current_modes)
857 " gR_CTRL-P: No match
858 exe "normal gRCom\<C-P>\<F2>\<Esc>u"
859 call assert_equal('R-Rvc', g:current_modes)
860 " gR_CTRL-X CTRL-P: No match
861 exe "normal gRCom\<C-X>\<C-P>\<F2>\<Esc>u"
862 call assert_equal('R-Rvc', g:current_modes)
863 " gR_CTRL-X CTRL-L: No match
864 exe "normal gRabc\<C-X>\<C-L>\<F2>\<Esc>u"
865 call assert_equal('R-Rvc', g:current_modes)
866
Bram Moolenaara1449832019-09-01 20:16:52 +0200867 call assert_equal('n', 0->mode())
868 call assert_equal('n', 1->mode())
Bram Moolenaare90858d2017-02-01 17:24:34 +0100869
Bram Moolenaar612cc382018-07-29 15:34:26 +0200870 " i_CTRL-O
871 exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
872 call assert_equal("n-niI", g:current_modes)
873
874 " R_CTRL-O
875 exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
876 call assert_equal("n-niR", g:current_modes)
877
878 " gR_CTRL-O
879 exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
880 call assert_equal("n-niV", g:current_modes)
881
Bram Moolenaare90858d2017-02-01 17:24:34 +0100882 " How to test operator-pending mode?
883
884 call feedkeys("v", 'xt')
885 call assert_equal('v', mode())
886 call assert_equal('v', mode(1))
887 call feedkeys("\<Esc>V", 'xt')
888 call assert_equal('V', mode())
889 call assert_equal('V', mode(1))
890 call feedkeys("\<Esc>\<C-V>", 'xt')
891 call assert_equal("\<C-V>", mode())
892 call assert_equal("\<C-V>", mode(1))
893 call feedkeys("\<Esc>", 'xt')
894
895 call feedkeys("gh", 'xt')
896 call assert_equal('s', mode())
897 call assert_equal('s', mode(1))
898 call feedkeys("\<Esc>gH", 'xt')
899 call assert_equal('S', mode())
900 call assert_equal('S', mode(1))
901 call feedkeys("\<Esc>g\<C-H>", 'xt')
902 call assert_equal("\<C-S>", mode())
903 call assert_equal("\<C-S>", mode(1))
904 call feedkeys("\<Esc>", 'xt')
905
zeertzjqeaf3f362021-07-28 16:51:53 +0200906 " v_CTRL-O
907 exe "normal gh\<C-O>\<F2>\<Esc>"
908 call assert_equal("v-vs", g:current_modes)
909 exe "normal gH\<C-O>\<F2>\<Esc>"
910 call assert_equal("V-Vs", g:current_modes)
911 exe "normal g\<C-H>\<C-O>\<F2>\<Esc>"
912 call assert_equal("\<C-V>-\<C-V>s", g:current_modes)
913
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100914 call feedkeys(":\<F2>\<CR>", 'xt')
Bram Moolenaare90858d2017-02-01 17:24:34 +0100915 call assert_equal('c-c', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100916 call feedkeys(":\<Insert>\<F2>\<CR>", 'xt')
Sam-programsd1c3ef12023-11-27 22:22:51 +0100917 call assert_equal("c-cr", g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100918 call feedkeys("gQ\<F2>vi\<CR>", 'xt')
Bram Moolenaare90858d2017-02-01 17:24:34 +0100919 call assert_equal('c-cv', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100920 call feedkeys("gQ\<Insert>\<F2>vi\<CR>", 'xt')
Sam-programsd1c3ef12023-11-27 22:22:51 +0100921 call assert_equal("c-cvr", g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100922
kuuote0fd1cb12024-08-20 19:53:17 +0200923 " Commandline mode in Visual mode should return "c-c", never "v-v".
924 call feedkeys("v\<Cmd>call input('')\<CR>\<F2>\<CR>\<Esc>", 'xt')
925 call assert_equal("c-c", g:current_modes)
926
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100927 " Executing commands in Vim Ex mode should return "cv", never "cvr",
928 " as Cmdline editing has already ended.
929 call feedkeys("gQcall Save_mode()\<CR>vi\<CR>", 'xt')
930 call assert_equal('c-cv', g:current_modes)
931 call feedkeys("gQ\<Insert>call Save_mode()\<CR>vi\<CR>", 'xt')
932 call assert_equal('c-cv', g:current_modes)
933
Bram Moolenaarcde0ff32020-04-04 14:00:39 +0200934 call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt')
935 call assert_equal('c-ce', g:current_modes)
Bram Moolenaare90858d2017-02-01 17:24:34 +0100936
naohiro ono75c30e92021-10-19 11:15:41 +0100937 " Test mode in operatorfunc (it used to be Operator-pending).
938 set operatorfunc=OperatorFunc
939 function OperatorFunc(_)
940 call Save_mode()
941 endfunction
942 execute "normal! g@l\<Esc>"
943 call assert_equal('n-n', g:current_modes)
944 execute "normal! i\<C-o>g@l\<Esc>"
945 call assert_equal('n-niI', g:current_modes)
946 execute "normal! R\<C-o>g@l\<Esc>"
947 call assert_equal('n-niR', g:current_modes)
948 execute "normal! gR\<C-o>g@l\<Esc>"
949 call assert_equal('n-niV', g:current_modes)
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100950
naohiro ono75c30e92021-10-19 11:15:41 +0100951
Bram Moolenaar72406a42021-10-02 16:34:55 +0100952 if has('terminal')
953 term
h-east71ebf3b2023-09-03 17:12:55 +0200954 " Terminal-Job mode
955 call assert_equal('t', mode())
956 call assert_equal('t', mode(1))
957 call feedkeys("\<C-W>:echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
958 call assert_equal("c-ct", g:current_modes)
959 call feedkeys("\<Esc>", 'xt')
960
961 " Terminal-Normal mode
Bram Moolenaar72406a42021-10-02 16:34:55 +0100962 call feedkeys("\<C-W>N", 'xt')
963 call assert_equal('n', mode())
964 call assert_equal('nt', mode(1))
h-east71ebf3b2023-09-03 17:12:55 +0200965 call feedkeys(":echo \<C-R>=Save_mode()\<C-U>\<CR>", 'xt')
966 call assert_equal("c-c", g:current_modes)
Bram Moolenaar72406a42021-10-02 16:34:55 +0100967 call feedkeys("aexit\<CR>", 'xt')
968 endif
969
Bram Moolenaare90858d2017-02-01 17:24:34 +0100970 bwipe!
zeertzjqfcaeb3d2023-11-28 20:46:29 +0100971 unmap! <F2>
zeertzjqeaf3f362021-07-28 16:51:53 +0200972 xunmap <F2>
Bram Moolenaarffea8c92017-03-13 20:37:15 +0100973 set complete&
naohiro ono75c30e92021-10-19 11:15:41 +0100974 set operatorfunc&
975 delfunction OperatorFunc
Bram Moolenaare90858d2017-02-01 17:24:34 +0100976endfunc
Bram Moolenaar79518e22017-02-17 16:31:35 +0100977
Drew Vogelea67ba72025-05-07 22:05:17 +0200978" Test for the mode() function using Screendump feature
979func Test_mode_screendump()
980 CheckScreendump
981
982 " Test statusline updates for overstrike mode
983 let buf = RunVimInTerminal('', {'rows': 12})
984 call term_sendkeys(buf, ":set laststatus=2 statusline=%!mode(1)\<CR>")
985 call term_sendkeys(buf, ":")
986 call TermWait(buf)
987 call VerifyScreenDump(buf, 'Test_mode_1', {})
988 call term_sendkeys(buf, "\<Insert>")
989 call TermWait(buf)
990 call VerifyScreenDump(buf, 'Test_mode_2', {})
991 call StopVimInTerminal(buf)
992endfunc
993
Bram Moolenaarad48e6c2020-04-21 22:19:45 +0200994" Test for append()
Bram Moolenaard2007022019-08-27 21:56:06 +0200995func Test_append()
996 enew!
997 split
Bram Moolenaarcd9c8d42022-11-05 23:46:43 +0000998 call assert_equal(0, append(1, []))
999 call assert_equal(0, append(1, test_null_list()))
1000 call assert_equal(0, append(0, ["foo"]))
1001 call assert_equal(0, append(1, []))
1002 call assert_equal(0, append(1, test_null_list()))
1003 call assert_equal(0, append(8, []))
1004 call assert_equal(0, append(9, test_null_list()))
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001005 call assert_equal(['foo', ''], getline(1, '$'))
Bram Moolenaard2007022019-08-27 21:56:06 +02001006 split
1007 only
1008 undo
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001009 undo
Bram Moolenaar08f41572020-04-20 16:50:00 +02001010
1011 " Using $ instead of '$' must give an error
1012 call assert_fails("call append($, 'foobar')", 'E116:')
Bram Moolenaar801cd352022-10-10 16:08:16 +01001013
1014 call assert_fails("call append({}, '')", ['E728:', 'E728:'])
Bram Moolenaard2007022019-08-27 21:56:06 +02001015endfunc
1016
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001017" Test for setline()
1018func Test_setline()
1019 new
1020 call setline(0, ["foo"])
1021 call setline(0, [])
1022 call setline(0, test_null_list())
1023 call setline(1, ["bar"])
1024 call setline(1, [])
1025 call setline(1, test_null_list())
1026 call setline(2, [])
1027 call setline(2, test_null_list())
1028 call setline(3, [])
1029 call setline(3, test_null_list())
1030 call setline(2, ["baz"])
1031 call assert_equal(['bar', 'baz'], getline(1, '$'))
Drew Vogelea67ba72025-05-07 22:05:17 +02001032 bw!
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001033endfunc
1034
Bram Moolenaar79518e22017-02-17 16:31:35 +01001035func Test_getbufvar()
1036 let bnr = bufnr('%')
1037 let b:var_num = '1234'
1038 let def_num = '5678'
1039 call assert_equal('1234', getbufvar(bnr, 'var_num'))
1040 call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
1041
1042 let bd = getbufvar(bnr, '')
1043 call assert_equal('1234', bd['var_num'])
1044 call assert_true(exists("bd['changedtick']"))
1045 call assert_equal(2, len(bd))
1046
1047 let bd2 = getbufvar(bnr, '', def_num)
1048 call assert_equal(bd, bd2)
1049
1050 unlet b:var_num
1051 call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
1052 call assert_equal('', getbufvar(bnr, 'var_num'))
1053
1054 let bd = getbufvar(bnr, '')
1055 call assert_equal(1, len(bd))
1056 let bd = getbufvar(bnr, '',def_num)
1057 call assert_equal(1, len(bd))
1058
Bram Moolenaar4520d442017-03-19 16:09:46 +01001059 call assert_equal('', getbufvar(9999, ''))
1060 call assert_equal(def_num, getbufvar(9999, '', def_num))
Bram Moolenaar79518e22017-02-17 16:31:35 +01001061 unlet def_num
1062
Bram Moolenaar507647d2017-02-17 16:43:49 +01001063 call assert_equal(0, getbufvar(bnr, '&autoindent'))
1064 call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
Bram Moolenaar79518e22017-02-17 16:31:35 +01001065
Bram Moolenaar8dfcce32020-03-18 19:32:26 +01001066 " Set and get a buffer-local variable
1067 call setbufvar(bnr, 'bufvar_test', ['one', 'two'])
1068 call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test'))
1069
Bram Moolenaar79518e22017-02-17 16:31:35 +01001070 " Open new window with forced option values
1071 set fileformats=unix,dos
1072 new ++ff=dos ++bin ++enc=iso-8859-2
1073 call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
1074 call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
1075 call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
1076 close
1077
Bram Moolenaar52592752020-04-03 18:43:35 +02001078 " Get the b: dict.
1079 let b:testvar = 'one'
1080 new
1081 let b:testvar = 'two'
1082 let thebuf = bufnr()
1083 wincmd w
1084 call assert_equal('two', getbufvar(thebuf, 'testvar'))
1085 call assert_equal('two', getbufvar(thebuf, '').testvar)
1086 bwipe!
1087
Bram Moolenaar79518e22017-02-17 16:31:35 +01001088 set fileformats&
1089endfunc
Bram Moolenaarcaf64342017-03-02 22:11:33 +01001090
Bram Moolenaar41042f32017-03-09 12:09:32 +01001091func Test_last_buffer_nr()
1092 call assert_equal(bufnr('$'), last_buffer_nr())
1093endfunc
1094
1095func Test_stridx()
1096 call assert_equal(-1, stridx('', 'l'))
1097 call assert_equal(0, stridx('', ''))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001098 call assert_equal(0, 'hello'->stridx(''))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001099 call assert_equal(-1, stridx('hello', 'L'))
1100 call assert_equal(2, stridx('hello', 'l', -1))
1101 call assert_equal(2, stridx('hello', 'l', 0))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001102 call assert_equal(2, 'hello'->stridx('l', 1))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001103 call assert_equal(3, stridx('hello', 'l', 3))
1104 call assert_equal(-1, stridx('hello', 'l', 4))
1105 call assert_equal(-1, stridx('hello', 'l', 10))
1106 call assert_equal(2, stridx('hello', 'll'))
1107 call assert_equal(-1, stridx('hello', 'hello world'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001108 call assert_fails("let n=stridx('hello', [])", 'E730:')
1109 call assert_fails("let n=stridx([], 'l')", 'E730:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001110endfunc
1111
1112func Test_strridx()
1113 call assert_equal(-1, strridx('', 'l'))
1114 call assert_equal(0, strridx('', ''))
1115 call assert_equal(5, strridx('hello', ''))
1116 call assert_equal(-1, strridx('hello', 'L'))
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +02001117 call assert_equal(3, 'hello'->strridx('l'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001118 call assert_equal(3, strridx('hello', 'l', 10))
1119 call assert_equal(3, strridx('hello', 'l', 3))
1120 call assert_equal(2, strridx('hello', 'l', 2))
1121 call assert_equal(-1, strridx('hello', 'l', 1))
1122 call assert_equal(-1, strridx('hello', 'l', 0))
1123 call assert_equal(-1, strridx('hello', 'l', -1))
1124 call assert_equal(2, strridx('hello', 'll'))
1125 call assert_equal(-1, strridx('hello', 'hello world'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001126 call assert_fails("let n=strridx('hello', [])", 'E730:')
1127 call assert_fails("let n=strridx([], 'l')", 'E730:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001128endfunc
1129
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001130func Test_match_func()
1131 call assert_equal(4, match('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001132 call assert_equal(4, 'testing'->match('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001133 call assert_equal(-1, match('testing', 'ing', 5))
1134 call assert_equal(-1, match('testing', 'ing', 8))
1135 call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
1136 call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001137 call assert_fails("let x=match('vim', [])", 'E730:')
1138 call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1))
1139 call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5))
1140 call assert_equal(4, match('testing', 'ing', -1))
1141 call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:')
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02001142 call assert_equal(-1, match(test_null_list(), 2))
Bram Moolenaar531be472020-09-23 22:38:05 +02001143 call assert_equal(-1, match('abc', '\\%('))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001144endfunc
1145
Bram Moolenaar41042f32017-03-09 12:09:32 +01001146func Test_matchend()
1147 call assert_equal(7, matchend('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001148 call assert_equal(7, 'testing'->matchend('ing', 2))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001149 call assert_equal(-1, matchend('testing', 'ing', 5))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001150 call assert_equal(-1, matchend('testing', 'ing', 8))
1151 call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
1152 call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
1153endfunc
1154
1155func Test_matchlist()
1156 call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001157 call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''], 'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001158 call assert_equal([], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
1159endfunc
1160
1161func Test_matchstr()
1162 call assert_equal('ing', matchstr('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001163 call assert_equal('ing', 'testing'->matchstr('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001164 call assert_equal('', matchstr('testing', 'ing', 5))
1165 call assert_equal('', matchstr('testing', 'ing', 8))
1166 call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
1167 call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
1168endfunc
1169
1170func Test_matchstrpos()
1171 call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
Bram Moolenaara1449832019-09-01 20:16:52 +02001172 call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2))
Bram Moolenaar1190cf62017-09-14 14:31:18 +02001173 call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
1174 call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
1175 call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
1176 call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02001177 call assert_equal(['', -1, -1], matchstrpos(test_null_list(), '\a'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001178endfunc
1179
Yegappan Lakshmananf93b1c82024-01-04 22:28:46 +01001180" Test for matchstrlist()
1181func Test_matchstrlist()
1182 let lines =<< trim END
1183 #" Basic match
1184 call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'bout'},
1185 \ {'idx': 1, 'byteidx': 1, 'text': 'bove'}],
1186 \ matchstrlist(['about', 'above'], 'bo.*'))
1187 #" no match
1188 call assert_equal([], matchstrlist(['about', 'above'], 'xy.*'))
1189 #" empty string
1190 call assert_equal([], matchstrlist([''], '.'))
1191 #" empty pattern
1192 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}], matchstrlist(['abc'], ''))
1193 #" method call
1194 call assert_equal([{'idx': 0, 'byteidx': 2, 'text': 'it'}], ['editor']->matchstrlist('ed\zsit\zeor'))
1195 #" single character matches
1196 call assert_equal([{'idx': 0, 'byteidx': 5, 'text': 'r'}],
1197 \ ['editor']->matchstrlist('r'))
1198 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'a'}], ['a']->matchstrlist('a'))
1199 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1200 \ matchstrlist(['foobar'], '\zs'))
1201 #" string with tabs
1202 call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'foo'}],
1203 \ matchstrlist(["\tfoobar"], 'foo'))
1204 #" string with multibyte characters
1205 call assert_equal([{'idx': 0, 'byteidx': 2, 'text': '😊😊'}],
1206 \ matchstrlist(["\t\t😊😊"], '\k\+'))
1207
1208 #" null string
1209 call assert_equal([], matchstrlist(test_null_list(), 'abc'))
1210 call assert_equal([], matchstrlist([test_null_string()], 'abc'))
1211 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
1212 \ matchstrlist(['abc'], test_null_string()))
1213
1214 #" sub matches
1215 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}], matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)', {'submatches': v:true}))
1216
1217 #" null dict argument
1218 call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'vim'}],
1219 \ matchstrlist(['vim'], '\w\+', test_null_dict()))
1220
1221 #" Error cases
1222 call assert_fails("echo matchstrlist('abc', 'a')", 'E1211: List required for argument 1')
1223 call assert_fails("echo matchstrlist(['abc'], {})", 'E1174: String required for argument 2')
1224 call assert_fails("echo matchstrlist(['abc'], '.', [])", 'E1206: Dictionary required for argument 3')
1225 call assert_fails("echo matchstrlist(['abc'], 'a', {'submatches': []})", 'E475: Invalid value for argument submatches')
1226 call assert_fails("echo matchstrlist(['abc'], '\\@=')", 'E866: (NFA regexp) Misplaced @')
1227 END
1228 call v9.CheckLegacyAndVim9Success(lines)
1229
1230 let lines =<< trim END
1231 vim9script
1232 # non string items
1233 matchstrlist([0z10, {'a': 'x'}], 'x')
1234 END
1235 call v9.CheckSourceSuccess(lines)
1236
1237 let lines =<< trim END
1238 vim9script
1239 def Foo()
1240 # non string items
1241 assert_equal([], matchstrlist([0z10, {'a': 'x'}], 'x'))
1242 enddef
1243 Foo()
1244 END
1245 call v9.CheckSourceFailure(lines, 'E1013: Argument 1: type mismatch, expected list<string> but got list<any>', 2)
1246endfunc
1247
1248" Test for matchbufline()
1249func Test_matchbufline()
1250 let lines =<< trim END
1251 #" Basic match
1252 new
1253 call setline(1, ['about', 'above', 'below'])
1254 VAR bnr = bufnr()
1255 wincmd w
1256 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1257 \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'}],
1258 \ matchbufline(bnr, 'bo.*', 1, '$'))
1259 #" multiple matches in a line
1260 call setbufline(bnr, 1, ['about about', 'above above', 'below'])
1261 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
1262 \ {'lnum': 1, 'byteidx': 7, 'text': 'bout'},
1263 \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'},
1264 \ {'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1265 \ matchbufline(bnr, 'bo\k\+', 1, '$'))
1266 #" no match
1267 call assert_equal([], matchbufline(bnr, 'xy.*', 1, '$'))
1268 #" match on a particular line
1269 call assert_equal([{'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
1270 \ matchbufline(bnr, 'bo\k\+$', 2, 2))
1271 #" match on a particular line
1272 call assert_equal([], matchbufline(bnr, 'bo.*', 3, 3))
1273 #" empty string
1274 call deletebufline(bnr, 1, '$')
1275 call assert_equal([], matchbufline(bnr, '.', 1, '$'))
1276 #" empty pattern
1277 call setbufline(bnr, 1, 'abc')
1278 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1279 \ matchbufline(bnr, '', 1, '$'))
1280 #" method call
1281 call setbufline(bnr, 1, 'editor')
1282 call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': 'it'}],
1283 \ bnr->matchbufline('ed\zsit\zeor', 1, 1))
1284 #" single character matches
1285 call assert_equal([{'lnum': 1, 'byteidx': 5, 'text': 'r'}],
1286 \ matchbufline(bnr, 'r', 1, '$'))
1287 call setbufline(bnr, 1, 'a')
1288 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'a'}],
1289 \ matchbufline(bnr, 'a', 1, '$'))
1290 #" zero-width match
1291 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1292 \ matchbufline(bnr, '\zs', 1, '$'))
1293 #" string with tabs
1294 call setbufline(bnr, 1, "\tfoobar")
1295 call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'foo'}],
1296 \ matchbufline(bnr, 'foo', 1, '$'))
1297 #" string with multibyte characters
1298 call setbufline(bnr, 1, "\t\t😊😊")
1299 call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': '😊😊'}],
1300 \ matchbufline(bnr, '\k\+', 1, '$'))
1301 #" empty buffer
1302 call deletebufline(bnr, 1, '$')
1303 call assert_equal([], matchbufline(bnr, 'abc', 1, '$'))
1304
1305 #" Non existing buffer
1306 call setbufline(bnr, 1, 'abc')
1307 call assert_fails("echo matchbufline(5000, 'abc', 1, 1)", 'E158: Invalid buffer name: 5000')
1308 #" null string
1309 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
1310 \ matchbufline(bnr, test_null_string(), 1, 1))
1311 #" invalid starting line number
1312 call assert_equal([], matchbufline(bnr, 'abc', 100, 100))
1313 #" ending line number greater than the last line
1314 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'abc'}],
1315 \ matchbufline(bnr, 'abc', 1, 100))
1316 #" ending line number greater than the starting line number
1317 call setbufline(bnr, 1, ['one', 'two'])
1318 call assert_fails($"echo matchbufline({bnr}, 'abc', 2, 1)", 'E475: Invalid value for argument end_lnum')
1319
1320 #" sub matches
1321 call deletebufline(bnr, 1, '$')
1322 call setbufline(bnr, 1, 'acd')
1323 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}],
1324 \ matchbufline(bnr, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 1, '$', {'submatches': v:true}))
1325
1326 #" null dict argument
1327 call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd'}],
1328 \ matchbufline(bnr, '\w\+', '$', '$', test_null_dict()))
1329
1330 #" Error cases
1331 call assert_fails("echo matchbufline([1], 'abc', 1, 1)", 'E1220: String or Number required for argument 1')
1332 call assert_fails("echo matchbufline(1, {}, 1, 1)", 'E1174: String required for argument 2')
1333 call assert_fails("echo matchbufline(1, 'abc', {}, 1)", 'E1220: String or Number required for argument 3')
1334 call assert_fails("echo matchbufline(1, 'abc', 1, {})", 'E1220: String or Number required for argument 4')
1335 call assert_fails($"echo matchbufline({bnr}, 'abc', -1, '$')", 'E475: Invalid value for argument lnum')
1336 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, -1)", 'E475: Invalid value for argument end_lnum')
1337 call assert_fails($"echo matchbufline({bnr}, '\\@=', 1, 1)", 'E866: (NFA regexp) Misplaced @')
1338 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, 1, {{'submatches': []}})", 'E475: Invalid value for argument submatches')
1339 :%bdelete!
1340 call assert_fails($"echo matchbufline({bnr}, 'abc', 1, '$'))", 'E681: Buffer is not loaded')
1341 END
1342 call v9.CheckLegacyAndVim9Success(lines)
1343
1344 call assert_fails($"echo matchbufline('', 'abc', 'abc', 1)", 'E475: Invalid value for argument lnum')
1345 call assert_fails($"echo matchbufline('', 'abc', 1, 'abc')", 'E475: Invalid value for argument end_lnum')
1346
1347 let lines =<< trim END
1348 vim9script
1349 def Foo()
1350 echo matchbufline('', 'abc', 'abc', 1)
1351 enddef
1352 Foo()
1353 END
1354 call v9.CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1355
1356 let lines =<< trim END
1357 vim9script
1358 def Foo()
1359 echo matchbufline('', 'abc', 1, 'abc')
1360 enddef
1361 Foo()
1362 END
1363 call v9.CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
1364endfunc
1365
Bram Moolenaar41042f32017-03-09 12:09:32 +01001366func Test_nextnonblank_prevnonblank()
1367 new
1368insert
1369This
1370
1371
1372is
1373
1374a
1375Test
1376.
1377 call assert_equal(0, nextnonblank(-1))
1378 call assert_equal(0, nextnonblank(0))
1379 call assert_equal(1, nextnonblank(1))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001380 call assert_equal(4, 2->nextnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001381 call assert_equal(4, nextnonblank(3))
1382 call assert_equal(4, nextnonblank(4))
1383 call assert_equal(6, nextnonblank(5))
1384 call assert_equal(6, nextnonblank(6))
1385 call assert_equal(7, nextnonblank(7))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001386 call assert_equal(0, 8->nextnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001387
1388 call assert_equal(0, prevnonblank(-1))
1389 call assert_equal(0, prevnonblank(0))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001390 call assert_equal(1, 1->prevnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001391 call assert_equal(1, prevnonblank(2))
1392 call assert_equal(1, prevnonblank(3))
1393 call assert_equal(4, prevnonblank(4))
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02001394 call assert_equal(4, 5->prevnonblank())
Bram Moolenaar41042f32017-03-09 12:09:32 +01001395 call assert_equal(6, prevnonblank(6))
1396 call assert_equal(7, prevnonblank(7))
1397 call assert_equal(0, prevnonblank(8))
1398 bw!
1399endfunc
1400
1401func Test_byte2line_line2byte()
1402 new
Bram Moolenaarc26f7c62018-08-20 22:53:04 +02001403 set endofline
Bram Moolenaar41042f32017-03-09 12:09:32 +01001404 call setline(1, ['a', 'bc', 'd'])
1405
1406 set fileformat=unix
1407 call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
1408 \ map(range(-1, 8), 'byte2line(v:val)'))
1409 call assert_equal([-1, -1, 1, 3, 6, 8, -1],
1410 \ map(range(-1, 5), 'line2byte(v:val)'))
1411
1412 set fileformat=mac
1413 call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001414 \ map(range(-1, 8), 'v:val->byte2line()'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001415 call assert_equal([-1, -1, 1, 3, 6, 8, -1],
Bram Moolenaar02b31112019-08-31 22:16:38 +02001416 \ map(range(-1, 5), 'v:val->line2byte()'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01001417
1418 set fileformat=dos
1419 call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
1420 \ map(range(-1, 11), 'byte2line(v:val)'))
1421 call assert_equal([-1, -1, 1, 4, 8, 11, -1],
1422 \ map(range(-1, 5), 'line2byte(v:val)'))
1423
Bram Moolenaarc26f7c62018-08-20 22:53:04 +02001424 bw!
1425 set noendofline nofixendofline
1426 normal a-
1427 for ff in ["unix", "mac", "dos"]
1428 let &fileformat = ff
1429 call assert_equal(1, line2byte(1))
1430 call assert_equal(2, line2byte(2)) " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
1431 endfor
1432
1433 set endofline& fixendofline& fileformat&
Bram Moolenaar41042f32017-03-09 12:09:32 +01001434 bw!
1435endfunc
1436
Christian Brabandt67672ef2023-04-24 21:09:54 +01001437" Test for byteidx() using a character index
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001438func Test_byteidx()
1439 let a = '.é.' " one char of two bytes
1440 call assert_equal(0, byteidx(a, 0))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001441 call assert_equal(1, byteidx(a, 1))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001442 call assert_equal(3, byteidx(a, 2))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001443 call assert_equal(4, byteidx(a, 3))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001444 call assert_equal(-1, byteidx(a, 4))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001445
1446 let b = '.é.' " normal e with composing char
1447 call assert_equal(0, b->byteidx(0))
1448 call assert_equal(1, b->byteidx(1))
1449 call assert_equal(4, b->byteidx(2))
1450 call assert_equal(5, b->byteidx(3))
1451 call assert_equal(-1, b->byteidx(4))
1452
Christian Brabandt67672ef2023-04-24 21:09:54 +01001453 " string with multiple composing characters
1454 let str = '-ą́-ą́'
1455 call assert_equal(0, byteidx(str, 0))
1456 call assert_equal(1, byteidx(str, 1))
1457 call assert_equal(6, byteidx(str, 2))
1458 call assert_equal(7, byteidx(str, 3))
1459 call assert_equal(12, byteidx(str, 4))
1460 call assert_equal(-1, byteidx(str, 5))
1461
1462 " empty string
1463 call assert_equal(0, byteidx('', 0))
1464 call assert_equal(-1, byteidx('', 1))
1465
1466 " error cases
1467 call assert_fails("call byteidx([], 0)", 'E730:')
1468 call assert_fails("call byteidx('abc', [])", 'E745:')
Bram Moolenaare4098452023-05-07 18:53:49 +01001469 call assert_fails("call byteidx('abc', 0, {})", ['E728:', 'E728:'])
zeertzjq8cf51372023-05-08 15:31:38 +01001470 call assert_fails("call byteidx('abc', 0, -1)", ['E1023:', 'E1023:'])
Christian Brabandt67672ef2023-04-24 21:09:54 +01001471endfunc
1472
1473" Test for byteidxcomp() using a character index
1474func Test_byteidxcomp()
1475 let a = '.é.' " one char of two bytes
1476 call assert_equal(0, byteidxcomp(a, 0))
1477 call assert_equal(1, byteidxcomp(a, 1))
1478 call assert_equal(3, byteidxcomp(a, 2))
1479 call assert_equal(4, byteidxcomp(a, 3))
1480 call assert_equal(-1, byteidxcomp(a, 4))
1481
1482 let b = '.é.' " normal e with composing char
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001483 call assert_equal(0, b->byteidxcomp(0))
1484 call assert_equal(1, b->byteidxcomp(1))
1485 call assert_equal(2, b->byteidxcomp(2))
1486 call assert_equal(4, b->byteidxcomp(3))
1487 call assert_equal(5, b->byteidxcomp(4))
1488 call assert_equal(-1, b->byteidxcomp(5))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001489
1490 " string with multiple composing characters
1491 let str = '-ą́-ą́'
1492 call assert_equal(0, byteidxcomp(str, 0))
1493 call assert_equal(1, byteidxcomp(str, 1))
1494 call assert_equal(2, byteidxcomp(str, 2))
1495 call assert_equal(4, byteidxcomp(str, 3))
1496 call assert_equal(6, byteidxcomp(str, 4))
1497 call assert_equal(7, byteidxcomp(str, 5))
1498 call assert_equal(8, byteidxcomp(str, 6))
1499 call assert_equal(10, byteidxcomp(str, 7))
1500 call assert_equal(12, byteidxcomp(str, 8))
1501 call assert_equal(-1, byteidxcomp(str, 9))
1502
1503 " empty string
1504 call assert_equal(0, byteidxcomp('', 0))
1505 call assert_equal(-1, byteidxcomp('', 1))
1506
1507 " error cases
Bram Moolenaar0e05de42020-03-25 22:23:46 +01001508 call assert_fails("call byteidxcomp([], 0)", 'E730:')
Christian Brabandt67672ef2023-04-24 21:09:54 +01001509 call assert_fails("call byteidxcomp('abc', [])", 'E745:')
Bram Moolenaare4098452023-05-07 18:53:49 +01001510 call assert_fails("call byteidxcomp('abc', 0, {})", ['E728:', 'E728:'])
zeertzjq8cf51372023-05-08 15:31:38 +01001511 call assert_fails("call byteidxcomp('abc', 0, -1)", ['E1023:', 'E1023:'])
Bram Moolenaar64b4d732019-08-22 22:18:17 +02001512endfunc
1513
Christian Brabandt67672ef2023-04-24 21:09:54 +01001514" Test for byteidx() using a UTF-16 index
1515func Test_byteidx_from_utf16_index()
1516 " string with single byte characters
1517 let str = "abc"
1518 for i in range(3)
1519 call assert_equal(i, byteidx(str, i, v:true))
1520 endfor
1521 call assert_equal(3, byteidx(str, 3, v:true))
1522 call assert_equal(-1, byteidx(str, 4, v:true))
1523
1524 " string with two byte characters
1525 let str = "a©©b"
1526 call assert_equal(0, byteidx(str, 0, v:true))
1527 call assert_equal(1, byteidx(str, 1, v:true))
1528 call assert_equal(3, byteidx(str, 2, v:true))
1529 call assert_equal(5, byteidx(str, 3, v:true))
1530 call assert_equal(6, byteidx(str, 4, v:true))
1531 call assert_equal(-1, byteidx(str, 5, v:true))
1532
1533 " string with two byte characters
1534 let str = "a😊😊b"
1535 call assert_equal(0, byteidx(str, 0, v:true))
1536 call assert_equal(1, byteidx(str, 1, v:true))
1537 call assert_equal(1, byteidx(str, 2, v:true))
1538 call assert_equal(5, byteidx(str, 3, v:true))
1539 call assert_equal(5, byteidx(str, 4, v:true))
1540 call assert_equal(9, byteidx(str, 5, v:true))
1541 call assert_equal(10, byteidx(str, 6, v:true))
1542 call assert_equal(-1, byteidx(str, 7, v:true))
1543
1544 " string with composing characters
1545 let str = '-á-b́'
1546 call assert_equal(0, byteidx(str, 0, v:true))
1547 call assert_equal(1, byteidx(str, 1, v:true))
1548 call assert_equal(4, byteidx(str, 2, v:true))
1549 call assert_equal(5, byteidx(str, 3, v:true))
1550 call assert_equal(8, byteidx(str, 4, v:true))
1551 call assert_equal(-1, byteidx(str, 5, v:true))
1552
1553 " string with multiple composing characters
1554 let str = '-ą́-ą́'
1555 call assert_equal(0, byteidx(str, 0, v:true))
1556 call assert_equal(1, byteidx(str, 1, v:true))
1557 call assert_equal(6, byteidx(str, 2, v:true))
1558 call assert_equal(7, byteidx(str, 3, v:true))
1559 call assert_equal(12, byteidx(str, 4, v:true))
1560 call assert_equal(-1, byteidx(str, 5, v:true))
1561
1562 " empty string
1563 call assert_equal(0, byteidx('', 0, v:true))
1564 call assert_equal(-1, byteidx('', 1, v:true))
1565
1566 " error cases
1567 call assert_fails('call byteidx(str, 0, [])', 'E745:')
1568endfunc
1569
1570" Test for byteidxcomp() using a UTF-16 index
1571func Test_byteidxcomp_from_utf16_index()
1572 " string with single byte characters
1573 let str = "abc"
1574 for i in range(3)
1575 call assert_equal(i, byteidxcomp(str, i, v:true))
1576 endfor
1577 call assert_equal(3, byteidxcomp(str, 3, v:true))
1578 call assert_equal(-1, byteidxcomp(str, 4, v:true))
1579
1580 " string with two byte characters
1581 let str = "a©©b"
1582 call assert_equal(0, byteidxcomp(str, 0, v:true))
1583 call assert_equal(1, byteidxcomp(str, 1, v:true))
1584 call assert_equal(3, byteidxcomp(str, 2, v:true))
1585 call assert_equal(5, byteidxcomp(str, 3, v:true))
1586 call assert_equal(6, byteidxcomp(str, 4, v:true))
1587 call assert_equal(-1, byteidxcomp(str, 5, v:true))
1588
1589 " string with two byte characters
1590 let str = "a😊😊b"
1591 call assert_equal(0, byteidxcomp(str, 0, v:true))
1592 call assert_equal(1, byteidxcomp(str, 1, v:true))
1593 call assert_equal(1, byteidxcomp(str, 2, v:true))
1594 call assert_equal(5, byteidxcomp(str, 3, v:true))
1595 call assert_equal(5, byteidxcomp(str, 4, v:true))
1596 call assert_equal(9, byteidxcomp(str, 5, v:true))
1597 call assert_equal(10, byteidxcomp(str, 6, v:true))
1598 call assert_equal(-1, byteidxcomp(str, 7, v:true))
1599
1600 " string with composing characters
1601 let str = '-á-b́'
1602 call assert_equal(0, byteidxcomp(str, 0, v:true))
1603 call assert_equal(1, byteidxcomp(str, 1, v:true))
1604 call assert_equal(2, byteidxcomp(str, 2, v:true))
1605 call assert_equal(4, byteidxcomp(str, 3, v:true))
1606 call assert_equal(5, byteidxcomp(str, 4, v:true))
1607 call assert_equal(6, byteidxcomp(str, 5, v:true))
1608 call assert_equal(8, byteidxcomp(str, 6, v:true))
1609 call assert_equal(-1, byteidxcomp(str, 7, v:true))
1610 call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1611
1612 " string with multiple composing characters
1613 let str = '-ą́-ą́'
1614 call assert_equal(0, byteidxcomp(str, 0, v:true))
1615 call assert_equal(1, byteidxcomp(str, 1, v:true))
1616 call assert_equal(2, byteidxcomp(str, 2, v:true))
1617 call assert_equal(4, byteidxcomp(str, 3, v:true))
1618 call assert_equal(6, byteidxcomp(str, 4, v:true))
1619 call assert_equal(7, byteidxcomp(str, 5, v:true))
1620 call assert_equal(8, byteidxcomp(str, 6, v:true))
1621 call assert_equal(10, byteidxcomp(str, 7, v:true))
1622 call assert_equal(12, byteidxcomp(str, 8, v:true))
1623 call assert_equal(-1, byteidxcomp(str, 9, v:true))
1624
1625 " empty string
1626 call assert_equal(0, byteidxcomp('', 0, v:true))
1627 call assert_equal(-1, byteidxcomp('', 1, v:true))
1628
1629 " error cases
1630 call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
1631endfunc
1632
1633" Test for charidx() using a byte index
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001634func Test_charidx()
1635 let a = 'xáb́y'
1636 call assert_equal(0, charidx(a, 0))
1637 call assert_equal(1, charidx(a, 3))
1638 call assert_equal(2, charidx(a, 4))
1639 call assert_equal(3, charidx(a, 7))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001640 call assert_equal(4, charidx(a, 8))
1641 call assert_equal(-1, charidx(a, 9))
Dominique Pelle6d37e8e2021-05-06 17:36:55 +02001642 call assert_equal(-1, charidx(a, -1))
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001643
1644 " count composing characters
Christian Brabandt67672ef2023-04-24 21:09:54 +01001645 call assert_equal(0, a->charidx(0, 1))
1646 call assert_equal(2, a->charidx(2, 1))
1647 call assert_equal(3, a->charidx(4, 1))
1648 call assert_equal(5, a->charidx(7, 1))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001649 call assert_equal(6, a->charidx(8, 1))
1650 call assert_equal(-1, a->charidx(9, 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001651
1652 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001653 call assert_equal(0, charidx('', 0))
1654 call assert_equal(-1, charidx('', 1))
1655 call assert_equal(0, charidx('', 0, 1))
1656 call assert_equal(-1, charidx('', 1, 1))
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001657
Christian Brabandt67672ef2023-04-24 21:09:54 +01001658 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001659 call assert_equal(0, charidx(test_null_string(), 0))
1660 call assert_equal(-1, charidx(test_null_string(), 1))
Yegappan Lakshmanan8deb2b32022-09-02 15:15:27 +01001661 call assert_fails('let x = charidx([], 1)', 'E1174:')
1662 call assert_fails('let x = charidx("abc", [])', 'E1210:')
1663 call assert_fails('let x = charidx("abc", 1, [])', 'E1212:')
1664 call assert_fails('let x = charidx("abc", 1, -1)', 'E1212:')
1665 call assert_fails('let x = charidx("abc", 1, 2)', 'E1212:')
Bram Moolenaar17793ef2020-12-28 12:56:58 +01001666endfunc
1667
Christian Brabandt67672ef2023-04-24 21:09:54 +01001668" Test for charidx() using a UTF-16 index
1669func Test_charidx_from_utf16_index()
1670 " string with single byte characters
1671 let str = "abc"
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001672 for i in range(4)
Christian Brabandt67672ef2023-04-24 21:09:54 +01001673 call assert_equal(i, charidx(str, i, v:false, v:true))
1674 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001675 call assert_equal(-1, charidx(str, 4, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001676
1677 " string with two byte characters
1678 let str = "a©©b"
1679 call assert_equal(0, charidx(str, 0, v:false, v:true))
1680 call assert_equal(1, charidx(str, 1, v:false, v:true))
1681 call assert_equal(2, charidx(str, 2, v:false, v:true))
1682 call assert_equal(3, charidx(str, 3, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001683 call assert_equal(4, charidx(str, 4, v:false, v:true))
1684 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001685
1686 " string with four byte characters
1687 let str = "a😊😊b"
1688 call assert_equal(0, charidx(str, 0, v:false, v:true))
1689 call assert_equal(1, charidx(str, 1, v:false, v:true))
1690 call assert_equal(1, charidx(str, 2, v:false, v:true))
1691 call assert_equal(2, charidx(str, 3, v:false, v:true))
1692 call assert_equal(2, charidx(str, 4, v:false, v:true))
1693 call assert_equal(3, charidx(str, 5, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001694 call assert_equal(4, charidx(str, 6, v:false, v:true))
1695 call assert_equal(-1, charidx(str, 7, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001696
1697 " string with composing characters
1698 let str = '-á-b́'
1699 for i in str->strcharlen()->range()
1700 call assert_equal(i, charidx(str, i, v:false, v:true))
1701 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001702 call assert_equal(4, charidx(str, 4, v:false, v:true))
1703 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001704 for i in str->strchars()->range()
1705 call assert_equal(i, charidx(str, i, v:true, v:true))
1706 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001707 call assert_equal(6, charidx(str, 6, v:true, v:true))
1708 call assert_equal(-1, charidx(str, 7, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001709
1710 " string with multiple composing characters
1711 let str = '-ą́-ą́'
1712 for i in str->strcharlen()->range()
1713 call assert_equal(i, charidx(str, i, v:false, v:true))
1714 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001715 call assert_equal(4, charidx(str, 4, v:false, v:true))
1716 call assert_equal(-1, charidx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001717 for i in str->strchars()->range()
1718 call assert_equal(i, charidx(str, i, v:true, v:true))
1719 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001720 call assert_equal(8, charidx(str, 8, v:true, v:true))
1721 call assert_equal(-1, charidx(str, 9, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001722
1723 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001724 call assert_equal(0, charidx('', 0, v:false, v:true))
1725 call assert_equal(-1, charidx('', 1, v:false, v:true))
1726 call assert_equal(0, charidx('', 0, v:true, v:true))
1727 call assert_equal(-1, charidx('', 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001728
1729 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001730 call assert_equal(0, charidx('', 0, v:false, v:true))
1731 call assert_equal(-1, charidx('', 1, v:false, v:true))
1732 call assert_equal(0, charidx('', 0, v:true, v:true))
1733 call assert_equal(-1, charidx('', 1, v:true, v:true))
1734 call assert_equal(0, charidx(test_null_string(), 0, v:false, v:true))
1735 call assert_equal(-1, charidx(test_null_string(), 1, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001736 call assert_fails('let x = charidx("abc", 1, v:false, [])', 'E1212:')
1737 call assert_fails('let x = charidx("abc", 1, v:true, [])', 'E1212:')
1738endfunc
1739
1740" Test for utf16idx() using a byte index
1741func Test_utf16idx_from_byteidx()
1742 " UTF-16 index of a string with single byte characters
1743 let str = "abc"
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001744 for i in range(4)
Christian Brabandt67672ef2023-04-24 21:09:54 +01001745 call assert_equal(i, utf16idx(str, i))
1746 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001747 call assert_equal(-1, utf16idx(str, 4))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001748
1749 " UTF-16 index of a string with two byte characters
1750 let str = 'a©©b'
1751 call assert_equal(0, str->utf16idx(0))
1752 call assert_equal(1, str->utf16idx(1))
1753 call assert_equal(1, str->utf16idx(2))
1754 call assert_equal(2, str->utf16idx(3))
1755 call assert_equal(2, str->utf16idx(4))
1756 call assert_equal(3, str->utf16idx(5))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001757 call assert_equal(4, str->utf16idx(6))
1758 call assert_equal(-1, str->utf16idx(7))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001759
1760 " UTF-16 index of a string with four byte characters
1761 let str = 'a😊😊b'
1762 call assert_equal(0, utf16idx(str, 0))
Yegappan Lakshmanan95707032023-06-14 13:10:15 +01001763 call assert_equal(1, utf16idx(str, 1))
1764 call assert_equal(1, utf16idx(str, 2))
1765 call assert_equal(1, utf16idx(str, 3))
1766 call assert_equal(1, utf16idx(str, 4))
1767 call assert_equal(3, utf16idx(str, 5))
1768 call assert_equal(3, utf16idx(str, 6))
1769 call assert_equal(3, utf16idx(str, 7))
1770 call assert_equal(3, utf16idx(str, 8))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001771 call assert_equal(5, utf16idx(str, 9))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001772 call assert_equal(6, utf16idx(str, 10))
1773 call assert_equal(-1, utf16idx(str, 11))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001774
1775 " UTF-16 index of a string with composing characters
1776 let str = '-á-b́'
1777 call assert_equal(0, utf16idx(str, 0))
1778 call assert_equal(1, utf16idx(str, 1))
1779 call assert_equal(1, utf16idx(str, 2))
1780 call assert_equal(1, utf16idx(str, 3))
1781 call assert_equal(2, utf16idx(str, 4))
1782 call assert_equal(3, utf16idx(str, 5))
1783 call assert_equal(3, utf16idx(str, 6))
1784 call assert_equal(3, utf16idx(str, 7))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001785 call assert_equal(4, utf16idx(str, 8))
1786 call assert_equal(-1, utf16idx(str, 9))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001787 call assert_equal(0, utf16idx(str, 0, v:true))
1788 call assert_equal(1, utf16idx(str, 1, v:true))
1789 call assert_equal(2, utf16idx(str, 2, v:true))
1790 call assert_equal(2, utf16idx(str, 3, v:true))
1791 call assert_equal(3, utf16idx(str, 4, v:true))
1792 call assert_equal(4, utf16idx(str, 5, v:true))
1793 call assert_equal(5, utf16idx(str, 6, v:true))
1794 call assert_equal(5, utf16idx(str, 7, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001795 call assert_equal(6, utf16idx(str, 8, v:true))
1796 call assert_equal(-1, utf16idx(str, 9, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001797
1798 " string with multiple composing characters
1799 let str = '-ą́-ą́'
1800 call assert_equal(0, utf16idx(str, 0))
1801 call assert_equal(1, utf16idx(str, 1))
1802 call assert_equal(1, utf16idx(str, 2))
1803 call assert_equal(1, utf16idx(str, 3))
1804 call assert_equal(1, utf16idx(str, 4))
1805 call assert_equal(1, utf16idx(str, 5))
1806 call assert_equal(2, utf16idx(str, 6))
1807 call assert_equal(3, utf16idx(str, 7))
1808 call assert_equal(3, utf16idx(str, 8))
1809 call assert_equal(3, utf16idx(str, 9))
1810 call assert_equal(3, utf16idx(str, 10))
1811 call assert_equal(3, utf16idx(str, 11))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001812 call assert_equal(4, utf16idx(str, 12))
1813 call assert_equal(-1, utf16idx(str, 13))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001814 call assert_equal(0, utf16idx(str, 0, v:true))
1815 call assert_equal(1, utf16idx(str, 1, v:true))
1816 call assert_equal(2, utf16idx(str, 2, v:true))
1817 call assert_equal(2, utf16idx(str, 3, v:true))
1818 call assert_equal(3, utf16idx(str, 4, v:true))
1819 call assert_equal(3, utf16idx(str, 5, v:true))
1820 call assert_equal(4, utf16idx(str, 6, v:true))
1821 call assert_equal(5, utf16idx(str, 7, v:true))
1822 call assert_equal(6, utf16idx(str, 8, v:true))
1823 call assert_equal(6, utf16idx(str, 9, v:true))
1824 call assert_equal(7, utf16idx(str, 10, v:true))
1825 call assert_equal(7, utf16idx(str, 11, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001826 call assert_equal(8, utf16idx(str, 12, v:true))
1827 call assert_equal(-1, utf16idx(str, 13, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001828
1829 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001830 call assert_equal(0, utf16idx('', 0))
1831 call assert_equal(-1, utf16idx('', 1))
1832 call assert_equal(0, utf16idx('', 0, v:true))
1833 call assert_equal(-1, utf16idx('', 1, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001834
1835 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001836 call assert_equal(0, utf16idx("", 0))
1837 call assert_equal(-1, utf16idx("", 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001838 call assert_equal(-1, utf16idx("abc", -1))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001839 call assert_equal(0, utf16idx(test_null_string(), 0))
1840 call assert_equal(-1, utf16idx(test_null_string(), 1))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001841 call assert_fails('let l = utf16idx([], 0)', 'E1174:')
1842 call assert_fails('let l = utf16idx("ab", [])', 'E1210:')
1843 call assert_fails('let l = utf16idx("ab", 0, [])', 'E1212:')
1844endfunc
1845
1846" Test for utf16idx() using a character index
1847func Test_utf16idx_from_charidx()
1848 let str = "abc"
1849 for i in str->strcharlen()->range()
1850 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1851 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001852 call assert_equal(3, utf16idx(str, 3, v:false, v:true))
1853 call assert_equal(-1, utf16idx(str, 4, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001854
1855 " UTF-16 index of a string with two byte characters
1856 let str = "a©©b"
1857 for i in str->strcharlen()->range()
1858 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1859 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001860 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1861 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001862
1863 " UTF-16 index of a string with four byte characters
1864 let str = "a😊😊b"
1865 call assert_equal(0, utf16idx(str, 0, v:false, v:true))
Yegappan Lakshmanan95707032023-06-14 13:10:15 +01001866 call assert_equal(1, utf16idx(str, 1, v:false, v:true))
1867 call assert_equal(3, utf16idx(str, 2, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001868 call assert_equal(5, utf16idx(str, 3, v:false, v:true))
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001869 call assert_equal(6, utf16idx(str, 4, v:false, v:true))
1870 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001871
1872 " UTF-16 index of a string with composing characters
1873 let str = '-á-b́'
1874 for i in str->strcharlen()->range()
1875 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1876 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001877 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1878 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001879 for i in str->strchars()->range()
1880 call assert_equal(i, utf16idx(str, i, v:true, v:true))
1881 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001882 call assert_equal(6, utf16idx(str, 6, v:true, v:true))
1883 call assert_equal(-1, utf16idx(str, 7, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001884
1885 " string with multiple composing characters
1886 let str = '-ą́-ą́'
1887 for i in str->strcharlen()->range()
1888 call assert_equal(i, utf16idx(str, i, v:false, v:true))
1889 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001890 call assert_equal(4, utf16idx(str, 4, v:false, v:true))
1891 call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001892 for i in str->strchars()->range()
1893 call assert_equal(i, utf16idx(str, i, v:true, v:true))
1894 endfor
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001895 call assert_equal(8, utf16idx(str, 8, v:true, v:true))
1896 call assert_equal(-1, utf16idx(str, 9, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001897
1898 " empty string
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001899 call assert_equal(0, utf16idx('', 0, v:false, v:true))
1900 call assert_equal(-1, utf16idx('', 1, v:false, v:true))
1901 call assert_equal(0, utf16idx('', 0, v:true, v:true))
1902 call assert_equal(-1, utf16idx('', 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001903
1904 " error cases
Yegappan Lakshmanan577922b2023-06-08 17:09:45 +01001905 call assert_equal(0, utf16idx(test_null_string(), 0, v:true, v:true))
1906 call assert_equal(-1, utf16idx(test_null_string(), 1, v:true, v:true))
Christian Brabandt67672ef2023-04-24 21:09:54 +01001907 call assert_fails('let l = utf16idx("ab", 0, v:false, [])', 'E1212:')
1908endfunc
1909
1910" Test for strutf16len()
1911func Test_strutf16len()
1912 call assert_equal(3, strutf16len('abc'))
1913 call assert_equal(3, 'abc'->strutf16len(v:true))
1914 call assert_equal(4, strutf16len('a©©b'))
1915 call assert_equal(4, strutf16len('a©©b', v:true))
1916 call assert_equal(6, strutf16len('a😊😊b'))
1917 call assert_equal(6, strutf16len('a😊😊b', v:true))
1918 call assert_equal(4, strutf16len('-á-b́'))
1919 call assert_equal(6, strutf16len('-á-b́', v:true))
1920 call assert_equal(4, strutf16len('-ą́-ą́'))
1921 call assert_equal(8, strutf16len('-ą́-ą́', v:true))
1922 call assert_equal(0, strutf16len(''))
1923
1924 " error cases
1925 call assert_fails('let l = strutf16len([])', 'E1174:')
1926 call assert_fails('let l = strutf16len("a", [])', 'E1212:')
1927 call assert_equal(0, strutf16len(test_null_string()))
1928endfunc
1929
Bram Moolenaar41042f32017-03-09 12:09:32 +01001930func Test_count()
1931 let l = ['a', 'a', 'A', 'b']
1932 call assert_equal(2, count(l, 'a'))
1933 call assert_equal(1, count(l, 'A'))
1934 call assert_equal(1, count(l, 'b'))
1935 call assert_equal(0, count(l, 'B'))
1936
1937 call assert_equal(2, count(l, 'a', 0))
1938 call assert_equal(1, count(l, 'A', 0))
1939 call assert_equal(1, count(l, 'b', 0))
1940 call assert_equal(0, count(l, 'B', 0))
1941
1942 call assert_equal(3, count(l, 'a', 1))
1943 call assert_equal(3, count(l, 'A', 1))
1944 call assert_equal(1, count(l, 'b', 1))
1945 call assert_equal(1, count(l, 'B', 1))
1946 call assert_equal(0, count(l, 'c', 1))
1947
1948 call assert_equal(1, count(l, 'a', 0, 1))
1949 call assert_equal(2, count(l, 'a', 1, 1))
1950 call assert_fails('call count(l, "a", 0, 10)', 'E684:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02001951 call assert_fails('call count(l, "a", [])', 'E745:')
Bram Moolenaar41042f32017-03-09 12:09:32 +01001952
1953 let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
1954 call assert_equal(2, count(d, 'a'))
1955 call assert_equal(1, count(d, 'A'))
1956 call assert_equal(1, count(d, 'b'))
1957 call assert_equal(0, count(d, 'B'))
1958
1959 call assert_equal(2, count(d, 'a', 0))
1960 call assert_equal(1, count(d, 'A', 0))
1961 call assert_equal(1, count(d, 'b', 0))
1962 call assert_equal(0, count(d, 'B', 0))
1963
1964 call assert_equal(3, count(d, 'a', 1))
1965 call assert_equal(3, count(d, 'A', 1))
1966 call assert_equal(1, count(d, 'b', 1))
1967 call assert_equal(1, count(d, 'B', 1))
1968 call assert_equal(0, count(d, 'c', 1))
1969
1970 call assert_fails('call count(d, "a", 0, 1)', 'E474:')
Bram Moolenaar9966b212017-07-28 16:46:57 +02001971
1972 call assert_equal(0, count("foo", "bar"))
1973 call assert_equal(1, count("foo", "oo"))
1974 call assert_equal(2, count("foo", "o"))
1975 call assert_equal(0, count("foo", "O"))
1976 call assert_equal(2, count("foo", "O", 1))
1977 call assert_equal(2, count("fooooo", "oo"))
Bram Moolenaar338e47f2017-12-19 11:55:26 +01001978 call assert_equal(0, count("foo", ""))
Bram Moolenaar17aca702019-05-16 22:24:55 +02001979
zeertzjq4f389e72023-08-17 22:10:40 +02001980 call assert_fails('call count(0, 0)', 'E706:')
1981 call assert_fails('call count("", "", {})', ['E728:', 'E728:'])
Bram Moolenaar41042f32017-03-09 12:09:32 +01001982endfunc
1983
1984func Test_changenr()
1985 new Xchangenr
1986 call assert_equal(0, changenr())
1987 norm ifoo
1988 call assert_equal(1, changenr())
1989 set undolevels=10
1990 norm Sbar
1991 call assert_equal(2, changenr())
1992 undo
1993 call assert_equal(1, changenr())
1994 redo
1995 call assert_equal(2, changenr())
1996 bw!
1997 set undolevels&
1998endfunc
1999
2000func Test_filewritable()
2001 new Xfilewritable
2002 write!
2003 call assert_equal(1, filewritable('Xfilewritable'))
2004
2005 call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
2006 call assert_equal(0, filewritable('Xfilewritable'))
2007
2008 call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
Bram Moolenaara4208962019-08-24 20:50:19 +02002009 call assert_equal(1, 'Xfilewritable'->filewritable())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002010
2011 call assert_equal(0, filewritable('doesnotexist'))
2012
Bram Moolenaar70e67252022-09-27 19:34:35 +01002013 call mkdir('Xwritedir', 'D')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002014 call assert_equal(2, filewritable('Xwritedir'))
Bram Moolenaar0ff5ded2020-05-07 18:43:44 +02002015
Bram Moolenaar41042f32017-03-09 12:09:32 +01002016 call delete('Xfilewritable')
2017 bw!
2018endfunc
2019
Bram Moolenaar82956662018-10-06 15:18:45 +02002020func Test_Executable()
2021 if has('win32')
2022 call assert_equal(1, executable('notepad'))
Bram Moolenaara4208962019-08-24 20:50:19 +02002023 call assert_equal(1, 'notepad.exe'->executable())
Bram Moolenaar82956662018-10-06 15:18:45 +02002024 call assert_equal(0, executable('notepad.exe.exe'))
2025 call assert_equal(0, executable('shell32.dll'))
2026 call assert_equal(0, executable('win.ini'))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002027
2028 " get "notepad" path and remove the leading drive and sep. (ex. 'C:\')
2029 let notepadcmd = exepath('notepad.exe')
2030 let driveroot = notepadcmd[:2]
2031 let notepadcmd = notepadcmd[3:]
2032 new
2033 " check that the relative path works in /
2034 execute 'lcd' driveroot
2035 call assert_equal(1, executable(notepadcmd))
2036 call assert_equal(driveroot .. notepadcmd, notepadcmd->exepath())
2037 bwipe
2038
2039 " create "notepad.bat"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002040 call mkdir('Xnotedir')
2041 let notepadbat = fnamemodify('Xnotedir/notepad.bat', ':p')
Bram Moolenaar95da1362020-05-30 18:37:55 +02002042 call writefile([], notepadbat)
2043 new
2044 " check that the path and the pathext order is valid
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002045 lcd Xnotedir
Bram Moolenaar95da1362020-05-30 18:37:55 +02002046 let [pathext, $PATHEXT] = [$PATHEXT, '.com;.exe;.bat;.cmd']
2047 call assert_equal(notepadbat, exepath('notepad'))
2048 let $PATHEXT = pathext
AmberArrf5d0f542023-08-20 20:03:45 +02002049 " check for symbolic link
2050 execute 'silent !mklink np.bat "' .. notepadbat .. '"'
2051 call assert_equal(1, executable('./np.bat'))
2052 call assert_equal(1, executable('./np'))
Bram Moolenaar95da1362020-05-30 18:37:55 +02002053 bwipe
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002054 eval 'Xnotedir'->delete('rf')
Bram Moolenaar82956662018-10-06 15:18:45 +02002055 elseif has('unix')
Bram Moolenaara4208962019-08-24 20:50:19 +02002056 call assert_equal(1, 'cat'->executable())
Bram Moolenaara05a0d32018-10-07 18:43:05 +02002057 call assert_equal(0, executable('nodogshere'))
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002058
2059 " get "cat" path and remove the leading /
2060 let catcmd = exepath('cat')[1:]
2061 new
Bram Moolenaara4208962019-08-24 20:50:19 +02002062 " check that the relative path works in /
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002063 lcd /
2064 call assert_equal(1, executable(catcmd))
Bram Moolenaara3870832021-01-01 14:20:44 +01002065 let result = catcmd->exepath()
2066 " when using chroot looking for sbin/cat can return bin/cat, that is OK
2067 if catcmd =~ '\<sbin\>' && result =~ '\<bin\>'
2068 call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result)
2069 else
Bram Moolenaarbf634a02021-07-31 17:20:04 +02002070 " /bin/cat and /usr/bin/cat may be hard linked, we could get either
2071 let result = substitute(result, '/usr/bin/cat', '/bin/cat', '')
2072 let catcmd = substitute(catcmd, 'usr/bin/cat', 'bin/cat', '')
Bram Moolenaara3870832021-01-01 14:20:44 +01002073 call assert_equal('/' .. catcmd, result)
2074 endif
Bram Moolenaard08b8c42019-07-24 14:59:45 +02002075 bwipe
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002076 else
2077 throw 'Skipped: does not work on this platform'
Bram Moolenaar82956662018-10-06 15:18:45 +02002078 endif
2079endfunc
2080
LemonBoy40fd7e62022-05-05 20:18:16 +01002081func Test_executable_windows_store_apps()
2082 CheckMSWindows
2083
2084 " Windows Store apps install some 'decoy' .exe that require some careful
2085 " handling as they behave similarly to symlinks.
2086 let app_dir = expand("$LOCALAPPDATA\\Microsoft\\WindowsApps")
2087 if !isdirectory(app_dir)
2088 return
2089 endif
2090
2091 let save_path = $PATH
2092 let $PATH = app_dir
2093 " Ensure executable() finds all the app .exes
2094 for entry in readdir(app_dir)
2095 if entry =~ '\.exe$'
2096 call assert_true(executable(entry))
2097 endif
2098 endfor
2099
2100 let $PATH = save_path
2101endfunc
2102
Bram Moolenaar86621892019-03-30 21:51:28 +01002103func Test_executable_longname()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002104 CheckMSWindows
Bram Moolenaar86621892019-03-30 21:51:28 +01002105
Bram Moolenaarf637bce2020-11-23 18:14:56 +01002106 " Create a temporary .bat file with 205 characters in the name.
2107 " Maximum length of a filename (including the path) on MS-Windows is 259
2108 " characters.
2109 " See https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
2110 let len = 259 - getcwd()->len() - 6
2111 if len > 200
2112 let len = 200
2113 endif
2114
2115 let fname = 'X' . repeat('あ', len) . '.bat'
Bram Moolenaar86621892019-03-30 21:51:28 +01002116 call writefile([], fname)
2117 call assert_equal(1, executable(fname))
2118 call delete(fname)
2119endfunc
2120
Bram Moolenaar41042f32017-03-09 12:09:32 +01002121func Test_hostname()
2122 let hostname_vim = hostname()
2123 if has('unix')
2124 let hostname_system = systemlist('uname -n')[0]
2125 call assert_equal(hostname_vim, hostname_system)
2126 endif
2127endfunc
2128
2129func Test_getpid()
2130 " getpid() always returns the same value within a vim instance.
2131 call assert_equal(getpid(), getpid())
2132 if has('unix')
2133 call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
2134 endif
2135endfunc
2136
2137func Test_hlexists()
2138 call assert_equal(0, hlexists('does_not_exist'))
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002139 call assert_equal(0, 'Number'->hlexists())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002140 call assert_equal(0, highlight_exists('does_not_exist'))
2141 call assert_equal(0, highlight_exists('Number'))
2142 syntax on
2143 call assert_equal(0, hlexists('does_not_exist'))
2144 call assert_equal(1, hlexists('Number'))
2145 call assert_equal(0, highlight_exists('does_not_exist'))
2146 call assert_equal(1, highlight_exists('Number'))
2147 syntax off
2148endfunc
2149
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02002150" Test for the col() function
Bram Moolenaar41042f32017-03-09 12:09:32 +01002151func Test_col()
2152 new
2153 call setline(1, 'abcdef')
2154 norm gg4|mx6|mY2|
2155 call assert_equal(2, col('.'))
2156 call assert_equal(7, col('$'))
Bram Moolenaar8b633132020-03-20 18:20:51 +01002157 call assert_equal(2, col('v'))
Bram Moolenaar41042f32017-03-09 12:09:32 +01002158 call assert_equal(4, col("'x"))
2159 call assert_equal(6, col("'Y"))
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02002160 call assert_equal(2, [1, 2]->col())
Bram Moolenaar41042f32017-03-09 12:09:32 +01002161 call assert_equal(7, col([1, '$']))
2162
2163 call assert_equal(0, col(''))
2164 call assert_equal(0, col('x'))
2165 call assert_equal(0, col([2, '$']))
2166 call assert_equal(0, col([1, 100]))
2167 call assert_equal(0, col([1]))
Bram Moolenaar9d8d0b52020-04-24 22:47:31 +02002168 call assert_equal(0, col(test_null_list()))
Yegappan Lakshmanan4c8d2f02022-11-12 16:07:47 +00002169 call assert_fails('let c = col({})', 'E1222:')
2170 call assert_fails('let c = col(".", [])', 'E1210:')
Bram Moolenaar8b633132020-03-20 18:20:51 +01002171
2172 " test for getting the visual start column
2173 func T()
2174 let g:Vcol = col('v')
2175 return ''
2176 endfunc
2177 let g:Vcol = 0
2178 xmap <expr> <F2> T()
2179 exe "normal gg3|ve\<F2>"
2180 call assert_equal(3, g:Vcol)
2181 xunmap <F2>
2182 delfunc T
2183
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002184 " Test for the visual line start and end marks '< and '>
2185 call setline(1, ['one', 'one two', 'one two three'])
2186 "normal! ggVG
2187 call feedkeys("ggVG\<Esc>", 'xt')
2188 call assert_equal(1, col("'<"))
2189 call assert_equal(14, col("'>"))
2190 " Delete the last line of the visually selected region
2191 $d
2192 call assert_notequal(14, col("'>"))
2193
2194 " Test with 'virtualedit'
2195 set virtualedit=all
2196 call cursor(1, 10)
2197 call assert_equal(4, col('.'))
2198 set virtualedit&
2199
Yegappan Lakshmanan4c8d2f02022-11-12 16:07:47 +00002200 " Test for getting the column number in another window
2201 let winid = win_getid()
2202 new
2203 call win_execute(winid, 'normal 1G$')
2204 call assert_equal(3, col('.', winid))
2205 call win_execute(winid, 'normal 2G')
2206 call assert_equal(8, col('$', winid))
2207 call assert_equal(0, col('.', 5001))
2208
Bram Moolenaar41042f32017-03-09 12:09:32 +01002209 bw!
2210endfunc
2211
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002212" Test for input()
2213func Test_input_func()
2214 " Test for prompt with multiple lines
2215 redir => v
2216 call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt')
2217 redir END
2218 call assert_equal("B", c)
2219 call assert_equal(['A', 'B', 'C'], split(v, "\n"))
2220
2221 " Test for default value
2222 call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt')
2223 call assert_equal('red', c)
2224
2225 " Test for completion at the input prompt
2226 func! Tcomplete(arglead, cmdline, pos)
2227 return "item1\nitem2\nitem3"
2228 endfunc
Bram Moolenaar9d489562020-07-30 20:08:50 +02002229 call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>"
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002230 \ .. "\<C-A>\<CR>", 'xt')
2231 delfunc Tcomplete
2232 call assert_equal('item1 item2 item3', c)
Bram Moolenaar578fe942020-02-27 21:32:51 +01002233
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002234 " Test for using special characters as default input
Bram Moolenaar1f448d92021-03-22 19:37:06 +01002235 call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt')
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002236 call assert_equal('y', c)
2237
zeertzjqe3a529b2022-06-05 19:01:37 +01002238 " Test for using text with composing characters as default input
2239 call feedkeys(":let c = input('name? ', \"ã̳\")\<CR>\<CR>", 'xt')
2240 call assert_equal('ã̳', c)
2241
Bram Moolenaarf4fcedc2021-03-15 18:36:20 +01002242 " Test for using <CR> as default input
2243 call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt')
2244 call assert_equal(' x', c)
2245
Bram Moolenaar578fe942020-02-27 21:32:51 +01002246 call assert_fails("call input('F:', '', 'invalid')", 'E180:')
2247 call assert_fails("call input('F:', '', [])", 'E730:')
Jim Zhou3255af82025-02-27 19:29:50 +01002248
zeertzjq7a5115c2025-03-19 20:29:58 +01002249 " Test for using "command" as the completion function
Jim Zhou3255af82025-02-27 19:29:50 +01002250 call feedkeys(":let c = input('Command? ', '', 'command')\<CR>"
2251 \ .. "echo bufnam\<C-A>\<CR>", 'xt')
2252 call assert_equal('echo bufname(', c)
zeertzjq7a5115c2025-03-19 20:29:58 +01002253
2254 " Test for using "shellcmdline" as the completion function
2255 call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2256 \ .. "vim test_functions.\<C-A>\<CR>", 'xt')
2257 call assert_equal('vim test_functions.vim', c)
2258 if executable('whoami')
2259 call feedkeys(":let c = input('Shell? ', '', 'shellcmdline')\<CR>"
2260 \ .. "whoam\<C-A>\<CR>", 'xt')
2261 call assert_match('\<whoami\>', c)
2262 endif
Bram Moolenaar578fe942020-02-27 21:32:51 +01002263endfunc
2264
2265" Test for the inputdialog() function
2266func Test_inputdialog()
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002267 set timeout timeoutlen=10
Bram Moolenaar99fa7212020-04-26 15:59:55 +02002268 if has('gui_running')
2269 call assert_fails('let v=inputdialog([], "xx")', 'E730:')
2270 call assert_fails('let v=inputdialog("Q", [])', 'E730:')
2271 else
2272 call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt')
2273 call assert_equal('xx', v)
2274 call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt')
2275 call assert_equal('yy', v)
2276 endif
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002277 set timeout& timeoutlen&
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01002278endfunc
2279
2280" Test for inputlist()
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002281func Test_inputlist()
2282 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
2283 call assert_equal(1, c)
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002284 call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx')
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002285 call assert_equal(2, c)
2286 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
2287 call assert_equal(3, c)
2288
Bram Moolenaareebd5552020-06-10 15:45:57 +02002289 " CR to cancel
2290 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx')
2291 call assert_equal(0, c)
2292
2293 " Esc to cancel
2294 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx')
2295 call assert_equal(0, c)
2296
2297 " q to cancel
2298 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx')
2299 call assert_equal(0, c)
2300
=?UTF-8?q?Luka=20Marku=C5=A1i=C4=87?=5cf94572021-05-20 21:14:20 +02002301 " Cancel after inputting a number
2302 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx')
2303 call assert_equal(0, c)
2304
Bram Moolenaarcde0ff32020-04-04 14:00:39 +02002305 " Use backspace to delete characters in the prompt
2306 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx')
2307 call assert_equal(2, c)
2308
2309 " Use mouse to make a selection
2310 call test_setmouse(&lines - 3, 2)
2311 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2312 call assert_equal(1, c)
2313 " Mouse click outside of the list
2314 call test_setmouse(&lines - 6, 2)
2315 call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
2316 call assert_equal(-2, c)
2317
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002318 call assert_fails('call inputlist("")', 'E686:')
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02002319 call assert_fails('call inputlist(test_null_list())', 'E686:')
Bram Moolenaar947b39e2018-07-22 19:36:37 +02002320endfunc
2321
Bram Moolenaar7bdcba02023-01-02 11:59:26 +00002322func Test_range_inputlist()
2323 " flush out any garbage left in the buffer
2324 while getchar(0)
2325 endwhile
2326
2327 call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x')
2328 call assert_equal(1, result)
2329 call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x')
2330 call assert_equal(1, result)
2331
2332 unlet result
2333endfunc
2334
Bram Moolenaarcaf64342017-03-02 22:11:33 +01002335func Test_balloon_show()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002336 CheckFeature balloon_eval
Bram Moolenaarb47bed22021-04-14 17:06:43 +02002337
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002338 " This won't do anything but must not crash either.
2339 call balloon_show('hi!')
2340 if !has('gui_running')
2341 call balloon_show(range(3))
2342 call balloon_show([])
Bram Moolenaara0107bd2017-03-02 22:48:01 +01002343 endif
Bram Moolenaarcaf64342017-03-02 22:11:33 +01002344endfunc
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002345
2346func Test_setbufvar_options()
2347 " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
zeertzjq49f05242023-02-04 10:58:34 +00002348 " window layout and cursor position.
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002349 call assert_equal(1, winnr('$'))
2350 split dummy_preview
2351 resize 2
2352 set winfixheight winfixwidth
2353 let prev_id = win_getid()
2354
2355 wincmd j
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002356 let wh = winheight(0)
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002357 let dummy_buf = bufnr('dummy_buf1', v:true)
2358 call setbufvar(dummy_buf, '&buftype', 'nofile')
2359 execute 'belowright vertical split #' . dummy_buf
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002360 call assert_equal(wh, winheight(0))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002361 let dum1_id = win_getid()
zeertzjq49f05242023-02-04 10:58:34 +00002362 call setline(1, 'foo')
2363 normal! V$
2364 call assert_equal(4, col('.'))
2365 call setbufvar('dummy_preview', '&buftype', 'nofile')
2366 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002367
2368 wincmd h
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002369 let wh = winheight(0)
zeertzjq49f05242023-02-04 10:58:34 +00002370 call setline(1, 'foo')
2371 normal! V$
2372 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002373 let dummy_buf = bufnr('dummy_buf2', v:true)
Bram Moolenaar196b4662019-09-06 21:34:30 +02002374 eval 'nofile'->setbufvar(dummy_buf, '&buftype')
zeertzjq49f05242023-02-04 10:58:34 +00002375 call assert_equal(4, col('.'))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002376 execute 'belowright vertical split #' . dummy_buf
Bram Moolenaarc05d1c02020-09-04 18:38:06 +02002377 call assert_equal(wh, winheight(0))
Bram Moolenaar2c90d512017-03-18 22:35:30 +01002378
2379 bwipe!
2380 call win_gotoid(prev_id)
2381 bwipe!
2382 call win_gotoid(dum1_id)
2383 bwipe!
2384endfunc
Bram Moolenaard4863aa2017-04-07 19:50:12 +02002385
Bram Moolenaardff97e62022-01-24 20:00:55 +00002386func Test_setbufvar_keep_window_title()
2387 CheckRunVimInTerminal
Bram Moolenaara6c09a72022-01-24 22:02:15 +00002388 if !has('title') || empty(&t_ts)
2389 throw "Skipped: can't get/set title"
2390 endif
Bram Moolenaardff97e62022-01-24 20:00:55 +00002391
2392 let lines =<< trim END
Bram Moolenaar14501122022-01-24 22:32:28 +00002393 set title
Bram Moolenaardff97e62022-01-24 20:00:55 +00002394 edit Xa.txt
2395 let g:buf = bufadd('Xb.txt')
2396 inoremap <F2> <C-R>=setbufvar(g:buf, '&autoindent', 1) ?? ''<CR>
2397 END
Bram Moolenaar70e67252022-09-27 19:34:35 +01002398 call writefile(lines, 'Xsetbufvar', 'D')
Bram Moolenaardff97e62022-01-24 20:00:55 +00002399 let buf = RunVimInTerminal('-S Xsetbufvar', {})
Bram Moolenaar3a8ad592022-01-24 22:18:24 +00002400 call WaitForAssert({-> assert_match('Xa.txt', term_gettitle(buf))}, 1000)
Bram Moolenaardff97e62022-01-24 20:00:55 +00002401
2402 call term_sendkeys(buf, "i\<F2>")
2403 call TermWait(buf)
2404 call term_sendkeys(buf, "\<Esc>")
2405 call TermWait(buf)
2406 call assert_match('Xa.txt', term_gettitle(buf))
2407
2408 call StopVimInTerminal(buf)
Bram Moolenaardff97e62022-01-24 20:00:55 +00002409endfunc
2410
Bram Moolenaard4863aa2017-04-07 19:50:12 +02002411func Test_redo_in_nested_functions()
2412 nnoremap g. :set opfunc=Operator<CR>g@
2413 function Operator( type, ... )
2414 let @x = 'XXX'
2415 execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
2416 endfunction
2417
2418 function! Apply()
2419 5,6normal! .
2420 endfunction
2421
2422 new
2423 call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
2424 1normal g.i"
2425 call assert_equal('some "XXX" text', getline(1))
2426 3,4normal .
2427 call assert_equal('some "XXX" text', getline(3))
2428 call assert_equal('more "XXX" text', getline(4))
2429 call Apply()
2430 call assert_equal('some "XXX" text', getline(5))
2431 call assert_equal('more "XXX" text', getline(6))
2432 bwipe!
2433
2434 nunmap g.
2435 delfunc Operator
2436 delfunc Apply
2437endfunc
Bram Moolenaar20615522017-06-05 18:46:26 +02002438
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002439func Test_trim()
2440 call assert_equal("Testing", trim(" \t\r\r\x0BTesting \t\n\r\n\t\x0B\x0B"))
Bram Moolenaarf92e58c2019-09-08 21:51:41 +02002441 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 +01002442 call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
2443 call assert_equal("wRE \tSERVEzyww", trim("wRE \tSERVEzyww"))
2444 call assert_equal("abcd\t xxxx tail", trim(" \tabcd\t xxxx tail"))
2445 call assert_equal("\tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", " "))
2446 call assert_equal(" \tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", "abx"))
2447 call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
2448 call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
2449 call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r 你好您R E SER V E早好你你 \t \x0B", ))
2450 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" 你好您R E SER V E早好你你 \t \x0B", " 你好"))
2451 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你好tes"))
2452 call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你你你好好好tttsses"))
2453 call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
2454 call assert_equal("", trim("", ""))
2455 call assert_equal("a", trim("a", ""))
2456 call assert_equal("", trim("", "a"))
2457
Bram Moolenaar2245ae12020-05-31 22:20:36 +02002458 call assert_equal("vim", trim(" vim ", " ", 0))
2459 call assert_equal("vim ", trim(" vim ", " ", 1))
2460 call assert_equal(" vim", trim(" vim ", " ", 2))
2461 call assert_fails('eval trim(" vim ", " ", [])', 'E745:')
2462 call assert_fails('eval trim(" vim ", " ", -1)', 'E475:')
2463 call assert_fails('eval trim(" vim ", " ", 3)', 'E475:')
Illia Bobyr80799172023-10-17 18:00:50 +02002464 call assert_fails('eval trim(" vim ", 0)', 'E1174:')
Bram Moolenaar2245ae12020-05-31 22:20:36 +02002465
Bram Moolenaar3f4f3d82019-09-04 20:05:59 +02002466 let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '')
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002467 call assert_equal("x", trim(chars . "x" . chars))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002468
Illia Bobyr80799172023-10-17 18:00:50 +02002469 call assert_equal("x", trim(chars . "x" . chars, '', 0))
2470 call assert_equal("x" . chars, trim(chars . "x" . chars, '', 1))
2471 call assert_equal(chars . "x", trim(chars . "x" . chars, '', 2))
Illia Bobyr6e638672023-10-17 11:09:45 +02002472
Bram Moolenaar0e05de42020-03-25 22:23:46 +01002473 call assert_fails('let c=trim([])', 'E730:')
Bram Moolenaar295ac5a2018-03-22 23:04:02 +01002474endfunc
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02002475
2476" Test for reg_recording() and reg_executing()
2477func Test_reg_executing_and_recording()
2478 let s:reg_stat = ''
2479 func s:save_reg_stat()
2480 let s:reg_stat = reg_recording() . ':' . reg_executing()
2481 return ''
2482 endfunc
2483
2484 new
2485 call s:save_reg_stat()
2486 call assert_equal(':', s:reg_stat)
2487 call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
2488 call assert_equal('a:', s:reg_stat)
2489 call feedkeys("@a", 'xt')
2490 call assert_equal(':a', s:reg_stat)
2491 call feedkeys("qb@aq", 'xt')
2492 call assert_equal('b:a', s:reg_stat)
2493 call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
2494 call assert_equal('":', s:reg_stat)
2495
Bram Moolenaarcce713d2019-03-04 11:40:12 +01002496 " :normal command saves and restores reg_executing
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002497 let s:reg_stat = ''
Bram Moolenaarcce713d2019-03-04 11:40:12 +01002498 let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
2499 func TestFunc() abort
2500 normal! ia
2501 endfunc
2502 call feedkeys("@q", 'xt')
2503 call assert_equal(':q', s:reg_stat)
2504 delfunc TestFunc
2505
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002506 " getchar() command saves and restores reg_executing
2507 map W :call TestFunc()<CR>
2508 let @q = "W"
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002509 let g:typed = ''
2510 let g:regs = []
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002511 func TestFunc() abort
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002512 let g:regs += [reg_executing()]
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002513 let g:typed = getchar(0)
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002514 let g:regs += [reg_executing()]
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002515 endfunc
2516 call feedkeys("@qy", 'xt')
2517 call assert_equal(char2nr("y"), g:typed)
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002518 call assert_equal(['q', 'q'], g:regs)
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002519 delfunc TestFunc
2520 unmap W
2521 unlet g:typed
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002522 unlet g:regs
2523
2524 " input() command saves and restores reg_executing
2525 map W :call TestFunc()<CR>
2526 let @q = "W"
2527 let g:typed = ''
2528 let g:regs = []
2529 func TestFunc() abort
2530 let g:regs += [reg_executing()]
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002531 let g:typed = '?'->input()
Bram Moolenaar9a2c0912019-03-30 14:26:18 +01002532 let g:regs += [reg_executing()]
2533 endfunc
2534 call feedkeys("@qy\<CR>", 'xt')
2535 call assert_equal("y", g:typed)
2536 call assert_equal(['q', 'q'], g:regs)
2537 delfunc TestFunc
2538 unmap W
2539 unlet g:typed
2540 unlet g:regs
Bram Moolenaarf0fab302019-03-05 12:24:10 +01002541
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02002542 bwipe!
2543 delfunc s:save_reg_stat
2544 unlet s:reg_stat
2545endfunc
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002546
Bram Moolenaarf9f24ce2019-08-31 21:17:39 +02002547func Test_inputsecret()
2548 map W :call TestFunc()<CR>
2549 let @q = "W"
2550 let g:typed1 = ''
2551 let g:typed2 = ''
2552 let g:regs = []
2553 func TestFunc() abort
2554 let g:typed1 = '?'->inputsecret()
2555 let g:typed2 = inputsecret('password: ')
2556 endfunc
2557 call feedkeys("@qsomething\<CR>else\<CR>", 'xt')
2558 call assert_equal("something", g:typed1)
2559 call assert_equal("else", g:typed2)
2560 delfunc TestFunc
2561 unmap W
2562 unlet g:typed1
2563 unlet g:typed2
2564endfunc
2565
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002566func Test_getchar()
2567 call feedkeys('a', '')
2568 call assert_equal(char2nr('a'), getchar())
Bram Moolenaar3a7503c2021-06-07 18:29:17 +02002569 call assert_equal(0, getchar(0))
2570 call assert_equal(0, getchar(1))
2571
2572 call feedkeys('a', '')
2573 call assert_equal('a', getcharstr())
2574 call assert_equal('', getcharstr(0))
2575 call assert_equal('', getcharstr(1))
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002576
zeertzjqad6c45f2022-02-20 19:05:10 +00002577 call feedkeys("\<M-F2>", '')
2578 call assert_equal("\<M-F2>", getchar(0))
2579 call assert_equal(0, getchar(0))
2580
zeertzjqe0a2ab32025-02-02 09:14:35 +01002581 call feedkeys("\<Tab>", '')
2582 call assert_equal(char2nr("\<Tab>"), getchar())
2583 call feedkeys("\<Tab>", '')
2584 call assert_equal(char2nr("\<Tab>"), getchar(-1))
2585 call feedkeys("\<Tab>", '')
2586 call assert_equal(char2nr("\<Tab>"), getchar(-1, {}))
2587 call feedkeys("\<Tab>", '')
2588 call assert_equal(char2nr("\<Tab>"), getchar(-1, #{number: v:true}))
2589 call assert_equal(0, getchar(0))
2590 call assert_equal(0, getchar(1))
2591 call assert_equal(0, getchar(0, #{number: v:true}))
2592 call assert_equal(0, getchar(1, #{number: v:true}))
2593
2594 call feedkeys("\<Tab>", '')
2595 call assert_equal("\<Tab>", getcharstr())
2596 call feedkeys("\<Tab>", '')
2597 call assert_equal("\<Tab>", getcharstr(-1))
2598 call feedkeys("\<Tab>", '')
2599 call assert_equal("\<Tab>", getcharstr(-1, {}))
2600 call feedkeys("\<Tab>", '')
2601 call assert_equal("\<Tab>", getchar(-1, #{number: v:false}))
2602 call assert_equal('', getcharstr(0))
2603 call assert_equal('', getcharstr(1))
2604 call assert_equal('', getchar(0, #{number: v:false}))
2605 call assert_equal('', getchar(1, #{number: v:false}))
2606
2607 for key in ["C-I", "C-X", "M-x"]
2608 let lines =<< eval trim END
2609 call feedkeys("\<*{key}>", '')
2610 call assert_equal(char2nr("\<{key}>"), getchar())
2611 call feedkeys("\<*{key}>", '')
2612 call assert_equal(char2nr("\<{key}>"), getchar(-1))
2613 call feedkeys("\<*{key}>", '')
2614 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{}}))
2615 call feedkeys("\<*{key}>", '')
2616 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'number': 1}}))
2617 call feedkeys("\<*{key}>", '')
2618 call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'simplify': 1}}))
2619 call feedkeys("\<*{key}>", '')
2620 call assert_equal("\<*{key}>", getchar(-1, {{'simplify': v:false}}))
2621 call assert_equal(0, getchar(0))
2622 call assert_equal(0, getchar(1))
2623 END
2624 call v9.CheckLegacyAndVim9Success(lines)
2625
2626 let lines =<< eval trim END
2627 call feedkeys("\<*{key}>", '')
2628 call assert_equal("\<{key}>", getcharstr())
2629 call feedkeys("\<*{key}>", '')
2630 call assert_equal("\<{key}>", getcharstr(-1))
2631 call feedkeys("\<*{key}>", '')
2632 call assert_equal("\<{key}>", getcharstr(-1, {{}}))
2633 call feedkeys("\<*{key}>", '')
2634 call assert_equal("\<{key}>", getchar(-1, {{'number': 0}}))
2635 call feedkeys("\<*{key}>", '')
2636 call assert_equal("\<{key}>", getcharstr(-1, {{'simplify': 1}}))
2637 call feedkeys("\<*{key}>", '')
2638 call assert_equal("\<*{key}>", getcharstr(-1, {{'simplify': v:false}}))
2639 call assert_equal('', getcharstr(0))
2640 call assert_equal('', getcharstr(1))
2641 END
2642 call v9.CheckLegacyAndVim9Success(lines)
2643 endfor
2644
2645 call assert_fails('call getchar(1, 1)', 'E1206:')
2646 call assert_fails('call getcharstr(1, 1)', 'E1206:')
zeertzjqedf0f7d2025-02-02 19:01:01 +01002647 call assert_fails('call getchar(1, #{cursor: "foo"})', 'E475:')
2648 call assert_fails('call getcharstr(1, #{cursor: "foo"})', 'E475:')
2649 call assert_fails('call getchar(1, #{cursor: 0z})', 'E976:')
2650 call assert_fails('call getcharstr(1, #{cursor: 0z})', 'E976:')
2651 call assert_fails('call getchar(1, #{simplify: 0z})', 'E974:')
2652 call assert_fails('call getcharstr(1, #{simplify: 0z})', 'E974:')
2653 call assert_fails('call getchar(1, #{number: []})', 'E745:')
2654 call assert_fails('call getchar(1, #{number: {}})', 'E728:')
zeertzjqe0a2ab32025-02-02 09:14:35 +01002655 call assert_fails('call getcharstr(1, #{number: v:true})', 'E475:')
2656 call assert_fails('call getcharstr(1, #{number: v:false})', 'E475:')
2657
Bram Moolenaardb3a2052019-11-16 18:22:41 +01002658 call setline(1, 'xxxx')
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002659 call test_setmouse(1, 3)
2660 let v:mouse_win = 9
2661 let v:mouse_winid = 9
2662 let v:mouse_lnum = 9
2663 let v:mouse_col = 9
2664 call feedkeys("\<S-LeftMouse>", '')
2665 call assert_equal("\<S-LeftMouse>", getchar())
2666 call assert_equal(1, v:mouse_win)
2667 call assert_equal(win_getid(1), v:mouse_winid)
2668 call assert_equal(1, v:mouse_lnum)
2669 call assert_equal(3, v:mouse_col)
Bram Moolenaardb3a2052019-11-16 18:22:41 +01002670 enew!
Bram Moolenaar5d712e42019-09-03 23:37:01 +02002671endfunc
2672
zeertzjqedf0f7d2025-02-02 19:01:01 +01002673func Test_getchar_cursor_position()
2674 CheckRunVimInTerminal
2675
2676 let lines =<< trim END
2677 call setline(1, ['foobar', 'foobar', 'foobar'])
2678 call cursor(3, 6)
2679 nnoremap <F1> <Cmd>echo 1234<Bar>call getchar()<CR>
2680 nnoremap <F2> <Cmd>call getchar()<CR>
2681 nnoremap <F3> <Cmd>call getchar(-1, {})<CR>
2682 nnoremap <F4> <Cmd>call getchar(-1, #{cursor: 'msg'})<CR>
2683 nnoremap <F5> <Cmd>call getchar(-1, #{cursor: 'keep'})<CR>
2684 nnoremap <F6> <Cmd>call getchar(-1, #{cursor: 'hide'})<CR>
2685 END
2686 call writefile(lines, 'XgetcharCursorPos', 'D')
2687 let buf = RunVimInTerminal('-S XgetcharCursorPos', {'rows': 6})
2688 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2689
2690 call term_sendkeys(buf, "\<F1>")
2691 call WaitForAssert({-> assert_equal([6, 5], term_getcursor(buf)[0:1])})
2692 call assert_true(term_getcursor(buf)[2].visible)
2693 call term_sendkeys(buf, 'a')
2694 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2695 call assert_true(term_getcursor(buf)[2].visible)
2696
2697 for key in ["\<F2>", "\<F3>", "\<F4>"]
2698 call term_sendkeys(buf, key)
2699 call WaitForAssert({-> assert_equal([6, 1], term_getcursor(buf)[0:1])})
2700 call assert_true(term_getcursor(buf)[2].visible)
2701 call term_sendkeys(buf, 'a')
2702 call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
2703 call assert_true(term_getcursor(buf)[2].visible)
2704 endfor
2705
2706 call term_sendkeys(buf, "\<F5>")
2707 call TermWait(buf, 50)
2708 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2709 call assert_true(term_getcursor(buf)[2].visible)
2710 call term_sendkeys(buf, 'a')
2711 call TermWait(buf, 50)
2712 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2713 call assert_true(term_getcursor(buf)[2].visible)
2714
2715 call term_sendkeys(buf, "\<F6>")
2716 call WaitForAssert({-> assert_false(term_getcursor(buf)[2].visible)})
2717 call term_sendkeys(buf, 'a')
2718 call WaitForAssert({-> assert_true(term_getcursor(buf)[2].visible)})
2719 call assert_equal([3, 6], term_getcursor(buf)[0:1])
2720
2721 call StopVimInTerminal(buf)
2722endfunc
2723
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002724func Test_libcall_libcallnr()
Bram Moolenaar6d91bcb2020-08-12 18:50:36 +02002725 CheckFeature libcall
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002726
2727 if has('win32')
2728 let libc = 'msvcrt.dll'
2729 elseif has('mac')
2730 let libc = 'libSystem.B.dylib'
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002731 elseif executable('ldd')
2732 let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
2733 endif
2734 if get(l:, 'libc', '') ==# ''
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002735 " On Unix, libc.so can be in various places.
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002736 if has('linux')
2737 " There is not documented but regarding the 1st argument of glibc's
2738 " dlopen an empty string and nullptr are equivalent, so using an empty
2739 " string for the 1st argument of libcall allows to call functions.
2740 let libc = ''
2741 elseif has('sun')
2742 " Set the path to libc.so according to the architecture.
2743 let test_bits = system('file ' . GetVimProg())
2744 let test_arch = system('uname -p')
2745 if test_bits =~ '64-bit' && test_arch =~ 'sparc'
2746 let libc = '/usr/lib/sparcv9/libc.so'
2747 elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
2748 let libc = '/usr/lib/amd64/libc.so'
2749 else
2750 let libc = '/usr/lib/libc.so'
2751 endif
2752 else
2753 " Unfortunately skip this test until a good way is found.
2754 return
2755 endif
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002756 endif
2757
2758 if has('win32')
Bram Moolenaar02b31112019-08-31 22:16:38 +02002759 call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002760 else
Bram Moolenaar02b31112019-08-31 22:16:38 +02002761 call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002762 endif
2763
2764 " If function returns NULL, libcall() should return an empty string.
2765 call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
2766
2767 " Test libcallnr() with string and integer argument.
Bram Moolenaar02b31112019-08-31 22:16:38 +02002768 call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
2769 call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002770
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +02002771 call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
2772 call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002773
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +02002774 call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
2775 call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
Bram Moolenaar1ceebb42018-06-19 19:46:06 +02002776endfunc
Bram Moolenaard90a1442018-07-15 20:24:31 +02002777
2778sandbox function Fsandbox()
2779 normal ix
2780endfunc
2781
2782func Test_func_sandbox()
2783 sandbox let F = {-> 'hello'}
2784 call assert_equal('hello', F())
2785
Bram Moolenaara4208962019-08-24 20:50:19 +02002786 sandbox let F = {-> "normal ix\<Esc>"->execute()}
Bram Moolenaard90a1442018-07-15 20:24:31 +02002787 call assert_fails('call F()', 'E48:')
2788 unlet F
2789
2790 call assert_fails('call Fsandbox()', 'E48:')
2791 delfunc Fsandbox
Bram Moolenaar8dfcce32020-03-18 19:32:26 +01002792
2793 " From a sandbox try to set a predefined variable (which cannot be modified
2794 " from a sandbox)
2795 call assert_fails('sandbox let v:lnum = 10', 'E794:')
Bram Moolenaard90a1442018-07-15 20:24:31 +02002796endfunc
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002797
2798func EditAnotherFile()
2799 let word = expand('<cword>')
2800 edit Xfuncrange2
2801endfunc
2802
2803func Test_func_range_with_edit()
2804 " Define a function that edits another buffer, then call it with a range that
2805 " is invalid in that buffer.
Bram Moolenaar70e67252022-09-27 19:34:35 +01002806 call writefile(['just one line'], 'Xfuncrange2', 'D')
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002807 new
Bram Moolenaar196b4662019-09-06 21:34:30 +02002808 eval 10->range()->setline(1)
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002809 write Xfuncrange1
2810 call assert_fails('5,8call EditAnotherFile()', 'E16:')
2811
2812 call delete('Xfuncrange1')
Bram Moolenaar9e353b52018-11-04 23:39:38 +01002813 bwipe!
2814endfunc
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002815
2816func Test_func_exists_on_reload()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002817 call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists', 'D')
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002818 call assert_equal(0, exists('*ExistingFunction'))
2819 source Xfuncexists
Bram Moolenaara4208962019-08-24 20:50:19 +02002820 call assert_equal(1, '*ExistingFunction'->exists())
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002821 " Redefining a function when reloading a script is OK.
2822 source Xfuncexists
2823 call assert_equal(1, exists('*ExistingFunction'))
2824
2825 " But redefining in another script is not OK.
Bram Moolenaar70e67252022-09-27 19:34:35 +01002826 call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2', 'D')
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002827 call assert_fails('source Xfuncexists2', 'E122:')
2828
Yegappan Lakshmanan611728f2021-05-24 15:15:47 +02002829 " Defining a new function from the cmdline should fail if the function is
2830 " already defined
2831 call assert_fails('call feedkeys(":func ExistingFunction()\<CR>", "xt")', 'E122:')
2832
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002833 delfunc ExistingFunction
2834 call assert_equal(0, exists('*ExistingFunction'))
2835 call writefile([
2836 \ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
2837 \ 'func ExistingFunction()', 'echo "no"', 'endfunc',
2838 \ ], 'Xfuncexists')
2839 call assert_fails('source Xfuncexists', 'E122:')
2840 call assert_equal(1, exists('*ExistingFunction'))
2841
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002842 delfunc ExistingFunction
2843endfunc
Bram Moolenaar2e050092019-01-27 15:00:36 +01002844
2845" Test confirm({msg} [, {choices} [, {default} [, {type}]]])
2846func Test_confirm()
Bram Moolenaar8c5a2782019-08-07 23:07:07 +02002847 CheckUnix
2848 CheckNotGui
Bram Moolenaar2e050092019-01-27 15:00:36 +01002849
2850 call feedkeys('o', 'L')
2851 let a = confirm('Press O to proceed')
2852 call assert_equal(1, a)
2853
2854 call feedkeys('y', 'L')
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02002855 let a = 'Are you sure?'->confirm("&Yes\n&No")
Bram Moolenaar2e050092019-01-27 15:00:36 +01002856 call assert_equal(1, a)
2857
2858 call feedkeys('n', 'L')
2859 let a = confirm('Are you sure?', "&Yes\n&No")
2860 call assert_equal(2, a)
2861
2862 " confirm() should return 0 when pressing CTRL-C.
Bram Moolenaar79296512020-03-22 16:17:14 +01002863 call feedkeys("\<C-C>", 'L')
Bram Moolenaar2e050092019-01-27 15:00:36 +01002864 let a = confirm('Are you sure?', "&Yes\n&No")
2865 call assert_equal(0, a)
2866
2867 " <Esc> requires another character to avoid it being seen as the start of an
2868 " escape sequence. Zero should be harmless.
Bram Moolenaara4208962019-08-24 20:50:19 +02002869 eval "\<Esc>0"->feedkeys('L')
Bram Moolenaar2e050092019-01-27 15:00:36 +01002870 let a = confirm('Are you sure?', "&Yes\n&No")
2871 call assert_equal(0, a)
2872
2873 " Default choice is returned when pressing <CR>.
2874 call feedkeys("\<CR>", 'L')
2875 let a = confirm('Are you sure?', "&Yes\n&No")
2876 call assert_equal(1, a)
2877
2878 call feedkeys("\<CR>", 'L')
2879 let a = confirm('Are you sure?', "&Yes\n&No", 2)
2880 call assert_equal(2, a)
2881
2882 call feedkeys("\<CR>", 'L')
2883 let a = confirm('Are you sure?', "&Yes\n&No", 0)
2884 call assert_equal(0, a)
2885
2886 " Test with the {type} 4th argument
2887 for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
2888 call feedkeys('y', 'L')
2889 let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
2890 call assert_equal(1, a)
2891 endfor
2892
2893 call assert_fails('call confirm([])', 'E730:')
2894 call assert_fails('call confirm("Are you sure?", [])', 'E730:')
2895 call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
2896 call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
2897endfunc
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002898
2899func Test_platform_name()
2900 " The system matches at most only one name.
Bram Moolenaar041c7102020-05-30 18:14:57 +02002901 let names = ['amiga', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002902 call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
2903
2904 " Is Unix?
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002905 call assert_equal(has('bsd'), has('bsd') && has('unix'))
2906 call assert_equal(has('hpux'), has('hpux') && has('unix'))
Zhaoming Luoa41dfcd2025-02-06 21:39:35 +01002907 call assert_equal(has('hurd'), has('hurd') && has('unix'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002908 call assert_equal(has('linux'), has('linux') && has('unix'))
2909 call assert_equal(has('mac'), has('mac') && has('unix'))
2910 call assert_equal(has('qnx'), has('qnx') && has('unix'))
2911 call assert_equal(has('sun'), has('sun') && has('unix'))
2912 call assert_equal(has('win32'), has('win32') && !has('unix'))
2913 call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
2914
2915 if has('unix') && executable('uname')
2916 let uname = system('uname')
Bram Moolenaara02e3f62019-02-07 21:27:14 +01002917 " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
2918 call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002919 call assert_equal(uname =~? 'HP-UX', has('hpux'))
2920 call assert_equal(uname =~? 'Linux', has('linux'))
2921 call assert_equal(uname =~? 'Darwin', has('mac'))
2922 call assert_equal(uname =~? 'QNX', has('qnx'))
2923 call assert_equal(uname =~? 'SunOS', has('sun'))
2924 call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
Zhaoming Luoa41dfcd2025-02-06 21:39:35 +01002925 call assert_equal(uname =~? 'GNU', has('hurd'))
Bram Moolenaar39536dd2019-01-29 22:58:21 +01002926 endif
2927endfunc
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002928
2929func Test_readdir()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002930 call mkdir('Xreaddir', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002931 call writefile([], 'Xreaddir/foo.txt')
2932 call writefile([], 'Xreaddir/bar.txt')
2933 call mkdir('Xreaddir/dir')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002934
2935 " All results
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002936 let files = readdir('Xreaddir')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002937 call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
2938
2939 " Only results containing "f"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002940 let files = 'Xreaddir'->readdir({ x -> stridx(x, 'f') != -1 })
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002941 call assert_equal(['foo.txt'], sort(files))
2942
2943 " Only .txt files
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002944 let files = readdir('Xreaddir', { x -> x =~ '.txt$' })
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002945 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2946
2947 " Only .txt files with string
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002948 let files = readdir('Xreaddir', 'v:val =~ ".txt$"')
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002949 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2950
2951 " Limit to 1 result.
2952 let l = []
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002953 let files = readdir('Xreaddir', {x -> len(add(l, x)) == 2 ? -1 : 1})
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002954 call assert_equal(1, len(files))
2955
Bram Moolenaar27da7de2019-09-03 17:13:37 +02002956 " Nested readdir() must not crash
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002957 let files = readdir('Xreaddir', 'readdir("Xreaddir", "1") != []')
Bram Moolenaar27da7de2019-09-03 17:13:37 +02002958 call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
Bram Moolenaar543c9b12019-04-05 22:50:40 +02002959endfunc
Bram Moolenaar17aca702019-05-16 22:24:55 +02002960
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002961func Test_readdirex()
Bram Moolenaar70e67252022-09-27 19:34:35 +01002962 call mkdir('Xexdir', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002963 call writefile(['foo'], 'Xexdir/foo.txt')
2964 call writefile(['barbar'], 'Xexdir/bar.txt')
2965 call mkdir('Xexdir/dir')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002966
2967 " All results
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002968 let files = readdirex('Xexdir')->map({-> v:val.name})
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002969 call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002970 let sizes = readdirex('Xexdir')->map({-> v:val.size})
Bram Moolenaar441d60e2020-06-02 22:19:50 +02002971 call assert_equal([0, 4, 7], sort(sizes))
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002972
2973 " Only results containing "f"
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002974 let files = 'Xexdir'->readdirex({ e -> stridx(e.name, 'f') != -1 })
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002975 \ ->map({-> v:val.name})
2976 call assert_equal(['foo.txt'], sort(files))
2977
2978 " Only .txt files
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002979 let files = readdirex('Xexdir', { e -> e.name =~ '.txt$' })
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002980 \ ->map({-> v:val.name})
2981 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2982
2983 " Only .txt files with string
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002984 let files = readdirex('Xexdir', 'v:val.name =~ ".txt$"')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002985 \ ->map({-> v:val.name})
2986 call assert_equal(['bar.txt', 'foo.txt'], sort(files))
2987
2988 " Limit to 1 result.
2989 let l = []
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002990 let files = readdirex('Xexdir', {e -> len(add(l, e.name)) == 2 ? -1 : 1})
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002991 \ ->map({-> v:val.name})
2992 call assert_equal(1, len(files))
2993
2994 " Nested readdirex() must not crash
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01002995 let files = readdirex('Xexdir', 'readdirex("Xexdir", "1") != []')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02002996 \ ->map({-> v:val.name})
2997 call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
2998
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002999 " report broken link correctly
Bram Moolenaarab540322020-06-10 15:55:36 +02003000 if has("unix")
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003001 call writefile([], 'Xexdir/abc.txt')
3002 call system("ln -s Xexdir/abc.txt Xexdir/link")
3003 call delete('Xexdir/abc.txt')
3004 let files = readdirex('Xexdir', 'readdirex("Xexdir", "1") != []')
Bram Moolenaarab540322020-06-10 15:55:36 +02003005 \ ->map({-> v:val.name .. '_' .. v:val.type})
3006 call sort(files)->assert_equal(
3007 \ ['bar.txt_file', 'dir_dir', 'foo.txt_file', 'link_link'])
3008 endif
Bram Moolenaaraab9fad2020-10-11 14:28:11 +02003009
3010 call assert_fails('call readdirex("doesnotexist")', 'E484:')
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02003011endfunc
3012
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003013func Test_readdirex_sort()
3014 CheckUnix
3015 " Skip tests on Mac OS X and Cygwin (does not allow several files with different casing)
3016 if has("osxdarwin") || has("osx") || has("macunix") || has("win32unix")
3017 throw 'Skipped: Test_readdirex_sort on systems that do not allow this using the default filesystem'
3018 endif
3019 let _collate = v:collate
Bram Moolenaar70e67252022-09-27 19:34:35 +01003020 call mkdir('Xsortdir2', 'R')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003021 call writefile(['1'], 'Xsortdir2/README.txt')
3022 call writefile(['2'], 'Xsortdir2/Readme.txt')
3023 call writefile(['3'], 'Xsortdir2/readme.txt')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003024
3025 " 1) default
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003026 let files = readdirex('Xsortdir2')->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003027 let default = copy(files)
3028 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort using default')
3029
3030 " 2) no sorting
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003031 let files = readdirex('Xsortdir2', 1, #{sort: 'none'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003032 let unsorted = copy(files)
3033 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], sort(files), 'unsorted')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003034 call assert_fails("call readdirex('Xsortdir2', 1, #{slort: 'none'})", 'E857: Dictionary key "sort" required')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003035
3036 " 3) sort by case (same as default)
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003037 let files = readdirex('Xsortdir2', 1, #{sort: 'case'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003038 call assert_equal(default, files, 'sort by case')
3039
3040 " 4) sort by ignoring case
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003041 let files = readdirex('Xsortdir2', 1, #{sort: 'icase'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003042 call assert_equal(unsorted->sort('i'), files, 'sort by icase')
3043
3044 " 5) Default Collation
3045 let collate = v:collate
3046 lang collate C
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003047 let files = readdirex('Xsortdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003048 call assert_equal(['README.txt', 'Readme.txt', 'readme.txt'], files, 'sort by C collation')
3049
3050 " 6) Collation de_DE
3051 " Switch locale, this may not work on the CI system, if the locale isn't
3052 " available
3053 try
3054 lang collate de_DE
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003055 let files = readdirex('Xsortdir2', 1, #{sort: 'collate'})->map({-> v:val.name})
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003056 call assert_equal(['readme.txt', 'Readme.txt', 'README.txt'], files, 'sort by de_DE collation')
3057 catch
3058 throw 'Skipped: de_DE collation is not available'
3059
3060 finally
3061 exe 'lang collate' collate
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003062 endtry
3063endfunc
3064
3065func Test_readdir_sort()
3066 " some more cases for testing sorting for readdirex
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003067 let dir = 'Xsortdir3'
Bram Moolenaar70e67252022-09-27 19:34:35 +01003068 call mkdir(dir, 'R')
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003069 call writefile(['1'], dir .. '/README.txt')
3070 call writefile(['2'], dir .. '/Readm.txt')
3071 call writefile(['3'], dir .. '/read.txt')
3072 call writefile(['4'], dir .. '/Z.txt')
3073 call writefile(['5'], dir .. '/a.txt')
3074 call writefile(['6'], dir .. '/b.txt')
3075
3076 " 1) default
3077 let files = readdir(dir)
3078 let default = copy(files)
3079 call assert_equal(default->sort(), files, 'sort using default')
3080
3081 " 2) sort by case (same as default)
3082 let files = readdir(dir, '1', #{sort: 'case'})
3083 call assert_equal(default, files, 'sort using default')
3084
3085 " 3) sort by ignoring case
3086 let files = readdir(dir, '1', #{sort: 'icase'})
3087 call assert_equal(default->sort('i'), files, 'sort by ignoring case')
3088
Bram Moolenaare17f8812020-06-17 20:30:44 +02003089 " 4) collation
3090 let collate = v:collate
3091 lang collate C
3092 let files = readdir(dir, 1, #{sort: 'collate'})
3093 call assert_equal(default->sort(), files, 'sort by C collation')
3094 exe "lang collate" collate
3095
3096 " 5) Errors
Bram Moolenaard83392a2022-09-01 12:22:46 +01003097 call assert_fails('call readdir(dir, 1, 1)', 'E1206:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003098 call assert_fails('call readdir(dir, 1, #{sorta: 1})')
Bram Moolenaard83392a2022-09-01 12:22:46 +01003099 call assert_fails('call readdir(dir, 1, test_null_dict())', 'E1297:')
3100 call assert_fails('call readdirex(dir, 1, 1)', 'E1206:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003101 call assert_fails('call readdirex(dir, 1, #{sorta: 1})')
Bram Moolenaard83392a2022-09-01 12:22:46 +01003102 call assert_fails('call readdirex(dir, 1, test_null_dict())', 'E1297:')
Bram Moolenaare17f8812020-06-17 20:30:44 +02003103
3104 " 6) ignore other values in dict
3105 let files = readdir(dir, '1', #{sort: 'c'})
3106 call assert_equal(default, files, 'sort using default2')
3107
3108 " Cleanup
3109 exe "lang collate" collate
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02003110endfunc
3111
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003112func Test_delete_rf()
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003113 call mkdir('Xrfdir')
3114 call writefile([], 'Xrfdir/foo.txt')
3115 call writefile([], 'Xrfdir/bar.txt')
3116 call mkdir('Xrfdir/[a-1]') " issue #696
3117 call writefile([], 'Xrfdir/[a-1]/foo.txt')
3118 call writefile([], 'Xrfdir/[a-1]/bar.txt')
3119 call assert_true(filereadable('Xrfdir/foo.txt'))
3120 call assert_true('Xrfdir/[a-1]/foo.txt'->filereadable())
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003121
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003122 call assert_equal(0, delete('Xrfdir', 'rf'))
3123 call assert_false(filereadable('Xrfdir/foo.txt'))
3124 call assert_false(filereadable('Xrfdir/[a-1]/foo.txt'))
zeertzjq47870032022-04-05 15:31:01 +01003125
3126 if has('unix')
Bram Moolenaar3b0d70f2022-08-29 22:31:20 +01003127 call mkdir('Xrfdir/Xdir2', 'p')
3128 silent !chmod 555 Xrfdir
3129 call assert_equal(-1, delete('Xrfdir/Xdir2', 'rf'))
3130 call assert_equal(-1, delete('Xrfdir', 'rf'))
3131 silent !chmod 755 Xrfdir
3132 call assert_equal(0, delete('Xrfdir', 'rf'))
zeertzjq47870032022-04-05 15:31:01 +01003133 endif
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02003134endfunc
3135
Bram Moolenaar17aca702019-05-16 22:24:55 +02003136func Test_call()
3137 call assert_equal(3, call('len', [123]))
Bram Moolenaar64b4d732019-08-22 22:18:17 +02003138 call assert_equal(3, 'len'->call([123]))
Yegappan Lakshmanan9904cbc2025-01-15 18:25:19 +01003139 call assert_equal(4, call({ x -> len(x) }, ['xxxx']))
3140 call assert_equal(2, call(function('len'), ['xx']))
Bram Moolenaard83392a2022-09-01 12:22:46 +01003141 call assert_fails("call call('len', 123)", 'E1211:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02003142 call assert_equal(0, call('', []))
Bram Moolenaarad48e6c2020-04-21 22:19:45 +02003143 call assert_equal(0, call('len', test_null_list()))
Bram Moolenaar17aca702019-05-16 22:24:55 +02003144
3145 function Mylen() dict
3146 return len(self.data)
3147 endfunction
3148 let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
Bram Moolenaar64b4d732019-08-22 22:18:17 +02003149 eval mydict.len->call([], mydict)->assert_equal(4)
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01003150 call assert_fails("call call('Mylen', [], 0)", 'E1206:')
Bram Moolenaar67322bf2020-12-06 15:03:19 +01003151 call assert_fails('call foo', 'E107:')
Dominique Pellefe8ebdb2021-05-13 14:55:55 +02003152
Bram Moolenaar22db0d52021-06-12 12:16:55 +02003153 " These once caused a crash.
Dominique Pellefe8ebdb2021-05-13 14:55:55 +02003154 call call(test_null_function(), [])
3155 call call(test_null_partial(), [])
Bram Moolenaar22db0d52021-06-12 12:16:55 +02003156 call assert_fails('call test_null_function()()', 'E1192:')
3157 call assert_fails('call test_null_partial()()', 'E117:')
Bram Moolenaar2ef91562021-12-11 16:14:07 +00003158
3159 let lines =<< trim END
3160 let Time = 'localtime'
3161 call Time()
3162 END
Bram Moolenaar62aec932022-01-29 21:45:34 +00003163 call v9.CheckScriptFailure(lines, 'E1085:')
Bram Moolenaar17aca702019-05-16 22:24:55 +02003164endfunc
3165
3166func Test_char2nr()
3167 call assert_equal(12354, char2nr('あ', 1))
Bram Moolenaar1a3a8912019-08-23 22:31:37 +02003168 call assert_equal(120, 'x'->char2nr())
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003169 set encoding=latin1
3170 call assert_equal(120, 'x'->char2nr())
3171 set encoding=utf-8
Bram Moolenaar17aca702019-05-16 22:24:55 +02003172endfunc
3173
Bram Moolenaar4e4473c2020-08-28 22:24:57 +02003174func Test_charclass()
3175 call assert_equal(0, charclass(' '))
3176 call assert_equal(1, charclass('.'))
3177 call assert_equal(2, charclass('x'))
3178 call assert_equal(3, charclass("\u203c"))
Christian Brabandt72463f82021-07-02 20:19:31 +02003179 " this used to crash vim
3180 call assert_equal(0, "xxx"[-1]->charclass())
Bram Moolenaar4e4473c2020-08-28 22:24:57 +02003181endfunc
3182
Bram Moolenaar17aca702019-05-16 22:24:55 +02003183func Test_eventhandler()
3184 call assert_equal(0, eventhandler())
3185endfunc
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003186
3187func Test_bufadd_bufload()
3188 call assert_equal(0, bufexists('someName'))
3189 let buf = bufadd('someName')
3190 call assert_notequal(0, buf)
3191 call assert_equal(1, bufexists('someName'))
3192 call assert_equal(0, getbufvar(buf, '&buflisted'))
3193 call assert_equal(0, bufloaded(buf))
3194 call bufload(buf)
3195 call assert_equal(1, bufloaded(buf))
3196 call assert_equal([''], getbufline(buf, 1, '$'))
3197
3198 let curbuf = bufnr('')
Bram Moolenaarf92e58c2019-09-08 21:51:41 +02003199 eval ['some', 'text']->writefile('XotherName')
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003200 let buf = 'XotherName'->bufadd()
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003201 call assert_notequal(0, buf)
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003202 eval 'XotherName'->bufexists()->assert_equal(1)
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003203 call assert_equal(0, getbufvar(buf, '&buflisted'))
3204 call assert_equal(0, bufloaded(buf))
Bram Moolenaar073e4b92019-08-18 23:01:56 +02003205 eval buf->bufload()
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003206 call assert_equal(1, bufloaded(buf))
3207 call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
3208 call assert_equal(curbuf, bufnr(''))
3209
Bram Moolenaar892ae722019-06-30 20:33:01 +02003210 let buf1 = bufadd('')
3211 let buf2 = bufadd('')
3212 call assert_notequal(0, buf1)
3213 call assert_notequal(0, buf2)
3214 call assert_notequal(buf1, buf2)
3215 call assert_equal(1, bufexists(buf1))
3216 call assert_equal(1, bufexists(buf2))
3217 call assert_equal(0, bufloaded(buf1))
3218 exe 'bwipe ' .. buf1
3219 call assert_equal(0, bufexists(buf1))
3220 call assert_equal(1, bufexists(buf2))
3221 exe 'bwipe ' .. buf2
3222 call assert_equal(0, bufexists(buf2))
3223
zeertzjq93f72cc2022-08-26 15:34:52 +01003224 " When 'buftype' is "nofile" then bufload() does not read the file.
3225 " Other values too.
3226 for val in [['nofile', 0],
3227 \ ['nowrite', 1],
3228 \ ['acwrite', 1],
3229 \ ['quickfix', 0],
3230 \ ['help', 1],
3231 \ ['terminal', 0],
3232 \ ['prompt', 0],
3233 \ ['popup', 0],
3234 \ ]
3235 bwipe! XotherName
3236 let buf = bufadd('XotherName')
3237 call setbufvar(buf, '&bt', val[0])
3238 call bufload(buf)
3239 call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0])
3240 endfor
Bram Moolenaarc3126192022-08-26 12:58:17 +01003241
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003242 bwipe someName
Bram Moolenaar3940ec62019-07-05 21:53:24 +02003243 bwipe XotherName
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003244 call assert_equal(0, bufexists('someName'))
Bram Moolenaar3940ec62019-07-05 21:53:24 +02003245 call delete('XotherName')
Bram Moolenaar15e248e2019-06-30 20:21:37 +02003246endfunc
Bram Moolenaarc2585492019-09-22 21:29:53 +02003247
3248func Test_state()
3249 CheckRunVimInTerminal
3250
Bram Moolenaar3ed9efc2020-03-26 16:50:57 +01003251 let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
3252
Bram Moolenaarc2585492019-09-22 21:29:53 +02003253 let lines =<< trim END
3254 call setline(1, ['one', 'two', 'three'])
3255 map ;; gg
Bram Moolenaarb7a97ef2019-09-28 22:11:56 +02003256 set complete=.
Bram Moolenaarc2585492019-09-22 21:29:53 +02003257 func RunTimer()
3258 call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
3259 endfunc
3260 au Filetype foobar let g:state = state()|let g:mode = mode()
3261 END
3262 call writefile(lines, 'XState')
3263 let buf = RunVimInTerminal('-S XState', #{rows: 6})
3264
3265 " Using a ":" command Vim is busy, thus "S" is returned
3266 call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
3267 call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
3268 call term_sendkeys(buf, ":\<CR>")
3269
3270 " Using a timer callback
3271 call term_sendkeys(buf, ":call RunTimer()\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003272 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003273 call term_sendkeys(buf, getstate)
3274 call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
3275
3276 " Halfway a mapping
3277 call term_sendkeys(buf, ":call RunTimer()\<CR>;")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003278 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003279 call term_sendkeys(buf, ";")
3280 call term_sendkeys(buf, getstate)
3281 call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
3282
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003283 " An operator is pending
zeertzjq8dabccd2023-08-22 21:22:24 +02003284 call term_sendkeys(buf, ":call RunTimer()\<CR>y")
3285 call TermWait(buf, 25)
3286 call term_sendkeys(buf, "y")
3287 call term_sendkeys(buf, getstate)
3288 call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3289
3290 " A register was specified
3291 call term_sendkeys(buf, ":call RunTimer()\<CR>\"r")
3292 call TermWait(buf, 25)
3293 call term_sendkeys(buf, "yy")
3294 call term_sendkeys(buf, getstate)
3295 call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
3296
Bram Moolenaarb7a97ef2019-09-28 22:11:56 +02003297 " Insert mode completion (bit slower on Mac)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003298 call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003299 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003300 call term_sendkeys(buf, "\<Esc>")
3301 call term_sendkeys(buf, getstate)
3302 call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
3303
3304 " Autocommand executing
3305 call term_sendkeys(buf, ":set filetype=foobar\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003306 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003307 call term_sendkeys(buf, getstate)
3308 call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
3309
3310 " Todo: "w" - waiting for ch_evalexpr()
3311
3312 " messages scrolled
3313 call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
Bram Moolenaar6a2c5a72020-04-08 21:50:25 +02003314 call TermWait(buf, 25)
Bram Moolenaarc2585492019-09-22 21:29:53 +02003315 call term_sendkeys(buf, "\<CR>")
3316 call term_sendkeys(buf, getstate)
3317 call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
3318
3319 call StopVimInTerminal(buf)
3320 call delete('XState')
3321endfunc
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003322
3323func Test_range()
3324 " destructuring
3325 let [x, y] = range(2)
3326 call assert_equal([0, 1], [x, y])
3327
3328 " index
3329 call assert_equal(4, range(1, 10)[3])
3330
3331 " add()
3332 call assert_equal([0, 1, 2, 3], add(range(3), 3))
3333 call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
3334 call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
3335
3336 " append()
3337 new
3338 call append('.', range(5))
3339 call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
3340 bwipe!
3341
3342 " appendbufline()
3343 new
3344 call appendbufline(bufnr(''), '.', range(5))
3345 call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
3346 bwipe!
3347
3348 " call()
3349 func TwoArgs(a, b)
3350 return [a:a, a:b]
3351 endfunc
3352 call assert_equal([0, 1], call('TwoArgs', range(2)))
3353
3354 " col()
3355 new
3356 call setline(1, ['foo', 'bar'])
3357 call assert_equal(2, col(range(1, 2)))
3358 bwipe!
3359
3360 " complete()
3361 execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
3362 " complete_info()
3363 execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
3364
3365 " copy()
3366 call assert_equal([1, 2, 3], copy(range(1, 3)))
3367
3368 " count()
3369 call assert_equal(0, count(range(0), 3))
3370 call assert_equal(0, count(range(2), 3))
3371 call assert_equal(1, count(range(5), 3))
3372
3373 " cursor()
3374 new
3375 call setline(1, ['aaa', 'bbb', 'ccc'])
3376 call cursor(range(1, 2))
3377 call assert_equal([2, 1], [col('.'), line('.')])
3378 bwipe!
3379
3380 " deepcopy()
3381 call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
3382
3383 " empty()
3384 call assert_true(empty(range(0)))
3385 call assert_false(empty(range(2)))
3386
3387 " execute()
3388 new
3389 call setline(1, ['aaa', 'bbb', 'ccc'])
3390 call execute(range(3))
3391 call assert_equal(2, line('.'))
3392 bwipe!
3393
3394 " extend()
3395 call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
3396 call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
3397 call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
3398
3399 " filter()
3400 call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
Bram Moolenaarf8ca03b2020-11-28 20:32:29 +01003401 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 +01003402
3403 " funcref()
3404 call assert_equal([0, 1], funcref('TwoArgs', range(2))())
3405
3406 " function()
3407 call assert_equal([0, 1], function('TwoArgs', range(2))())
3408
3409 " garbagecollect()
3410 let thelist = [1, range(2), 3]
3411 let otherlist = range(3)
3412 call test_garbagecollect_now()
3413
3414 " get()
3415 call assert_equal(4, get(range(1, 10), 3))
3416 call assert_equal(-1, get(range(1, 10), 42, -1))
Christian Brabandtdf63da92023-11-23 20:14:28 +01003417 call assert_equal(0, get(range(1, 0, 2), 0))
3418 call assert_equal(0, get(range(0, -1, 2), 0))
3419 call assert_equal(0, get(range(-2, -1, -2), 0))
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003420
3421 " index()
3422 call assert_equal(1, index(range(1, 5), 2))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003423 call assert_fails("echo index([1, 2], 1, [])", 'E745:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003424
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003425 " insert()
3426 call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
3427 call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
3428 call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
3429 call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
3430 call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
3431 call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
3432
3433 " join()
3434 call assert_equal('0 1 2 3 4', join(range(5)))
3435
Bram Moolenaar272ca952020-01-28 20:49:11 +01003436 " json_encode()
3437 call assert_equal('[0,1,2,3]', json_encode(range(4)))
3438
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003439 " len()
3440 call assert_equal(0, len(range(0)))
3441 call assert_equal(2, len(range(2)))
3442 call assert_equal(5, len(range(0, 12, 3)))
3443 call assert_equal(4, len(range(3, 0, -1)))
3444
3445 " list2str()
3446 call assert_equal('ABC', list2str(range(65, 67)))
Bram Moolenaard83392a2022-09-01 12:22:46 +01003447 call assert_fails('let s = list2str(5)', 'E1211:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003448
3449 " lock()
3450 let thelist = range(5)
3451 lockvar thelist
3452
3453 " map()
3454 call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
Bram Moolenaarf8ca03b2020-11-28 20:32:29 +01003455 call assert_equal([3, 5, 7, 9, 11], map(map(range(5), 'v:val * 2'), 'v:val + 3'))
3456 call assert_equal([2, 6], map(filter(range(5), 'v:val % 2'), 'v:val * 2'))
3457 call assert_equal([2, 4, 8], filter(map(range(5), 'v:val * 2'), 'v:val % 3'))
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003458
3459 " match()
3460 call assert_equal(3, match(range(5), 3))
3461
3462 " matchaddpos()
3463 highlight MyGreenGroup ctermbg=green guibg=green
3464 call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
3465
3466 " matchend()
3467 call assert_equal(4, matchend(range(5), '4'))
3468 call assert_equal(3, matchend(range(1, 5), '4'))
3469 call assert_equal(-1, matchend(range(1, 5), '42'))
3470
3471 " matchstrpos()
3472 call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
3473 call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
3474 call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
3475
3476 " max() reverse()
3477 call assert_equal(0, max(range(0)))
3478 call assert_equal(0, max(range(10, 9)))
3479 call assert_equal(9, max(range(10)))
3480 call assert_equal(18, max(range(0, 20, 3)))
3481 call assert_equal(20, max(range(20, 0, -3)))
3482 call assert_equal(99999, max(range(100000)))
3483 call assert_equal(99999, max(range(99999, 0, -1)))
3484 call assert_equal(99999, max(reverse(range(100000))))
3485 call assert_equal(99999, max(reverse(range(99999, 0, -1))))
3486
3487 " min() reverse()
3488 call assert_equal(0, min(range(0)))
3489 call assert_equal(0, min(range(10, 9)))
3490 call assert_equal(5, min(range(5, 10)))
3491 call assert_equal(5, min(range(5, 10, 3)))
3492 call assert_equal(2, min(range(20, 0, -3)))
3493 call assert_equal(0, min(range(100000)))
3494 call assert_equal(0, min(range(99999, 0, -1)))
3495 call assert_equal(0, min(reverse(range(100000))))
3496 call assert_equal(0, min(reverse(range(99999, 0, -1))))
3497
3498 " remove()
3499 call assert_equal(1, remove(range(1, 10), 0))
3500 call assert_equal(2, remove(range(1, 10), 1))
3501 call assert_equal(9, remove(range(1, 10), 8))
3502 call assert_equal(10, remove(range(1, 10), 9))
3503 call assert_equal(10, remove(range(1, 10), -1))
3504 call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
3505
3506 " repeat()
3507 call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
3508 call assert_equal([0, 1, 2], repeat(range(3), 1))
3509 call assert_equal([], repeat(range(3), 0))
3510 call assert_equal([], repeat(range(5, 4), 2))
3511 call assert_equal([], repeat(range(5, 4), 0))
3512
3513 " reverse()
3514 call assert_equal([2, 1, 0], reverse(range(3)))
3515 call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
3516 call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
3517 call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
3518 call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
3519 call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
3520 call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
3521 call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
3522 call assert_equal([], reverse(range(0)))
3523
3524 " TODO: setpos()
3525 " new
3526 " call setline(1, repeat([''], bufnr('')))
3527 " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
3528 " call setpos('x', range(bufnr(''), bufnr('') + 3))
3529 " bwipe!
3530
3531 " setreg()
3532 call setreg('a', range(3))
3533 call assert_equal("0\n1\n2\n", getreg('a'))
3534
Bram Moolenaarb0992022020-01-30 14:55:42 +01003535 " settagstack()
3536 call settagstack(1, #{items : range(4)})
Bram Moolenaar94255df2020-02-05 20:10:33 +01003537
Bram Moolenaarb0992022020-01-30 14:55:42 +01003538 " sign_define()
3539 call assert_fails("call sign_define(range(5))", "E715:")
3540 call assert_fails("call sign_placelist(range(5))", "E715:")
3541
3542 " sign_undefine()
3543 call assert_fails("call sign_undefine(range(5))", "E908:")
3544
3545 " sign_unplacelist()
3546 call assert_fails("call sign_unplacelist(range(5))", "E715:")
3547
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003548 " sort()
3549 call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
3550
3551 " string()
3552 call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
3553
Bram Moolenaarb0992022020-01-30 14:55:42 +01003554 " taglist() with 'tagfunc'
3555 func TagFunc(pattern, flags, info)
3556 return range(10)
3557 endfunc
3558 set tagfunc=TagFunc
3559 call assert_fails("call taglist('asdf')", 'E987:')
3560 set tagfunc=
Bram Moolenaar94255df2020-02-05 20:10:33 +01003561
Bram Moolenaarb0992022020-01-30 14:55:42 +01003562 " term_start()
Bram Moolenaar705724e2020-01-31 21:13:42 +01003563 if has('terminal') && has('termguicolors')
Bram Moolenaarb0992022020-01-30 14:55:42 +01003564 call assert_fails('call term_start(range(3, 4))', 'E474:')
3565 let g:terminal_ansi_colors = range(16)
Bram Moolenaar94255df2020-02-05 20:10:33 +01003566 if has('win32')
Milly4f5681d2024-10-20 11:06:00 +02003567 let cmd = "cmd /D /c dir"
Bram Moolenaar94255df2020-02-05 20:10:33 +01003568 else
3569 let cmd = "ls"
3570 endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01003571 call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"'
3572 \ .. ', ansi_colors: range(16)})', 'E475:')
Bram Moolenaarb0855f52022-05-20 10:39:18 +01003573 unlet g:terminal_ansi_colors
Bram Moolenaarb0992022020-01-30 14:55:42 +01003574 endif
3575
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003576 " type()
3577 call assert_equal(v:t_list, type(range(5)))
3578
3579 " uniq()
3580 call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003581
3582 " errors
3583 call assert_fails('let x=range(2, 8, 0)', 'E726:')
3584 call assert_fails('let x=range(3, 1)', 'E727:')
3585 call assert_fails('let x=range(1, 3, -2)', 'E727:')
Bram Moolenaar99fa7212020-04-26 15:59:55 +02003586 call assert_fails('let x=range([])', 'E745:')
3587 call assert_fails('let x=range(1, [])', 'E745:')
3588 call assert_fails('let x=range(1, 4, [])', 'E745:')
Bram Moolenaar50985eb2020-01-27 22:09:39 +01003589endfunc
Bram Moolenaar4132eb52020-02-14 16:53:00 +01003590
Bram Moolenaarb3d83982022-01-27 19:59:47 +00003591func Test_garbagecollect_now_fails()
3592 let v:testing = 0
3593 call assert_fails('call test_garbagecollect_now()', 'E1142:')
3594 let v:testing = 1
3595endfunc
3596
Bram Moolenaar4132eb52020-02-14 16:53:00 +01003597func Test_echoraw()
3598 CheckScreendump
3599
3600 " Normally used for escape codes, but let's test with a CR.
3601 let lines =<< trim END
3602 call echoraw("hello\<CR>x")
3603 END
3604 call writefile(lines, 'XTest_echoraw')
3605 let buf = RunVimInTerminal('-S XTest_echoraw', {'rows': 5, 'cols': 40})
3606 call VerifyScreenDump(buf, 'Test_functions_echoraw', {})
3607
3608 " clean up
3609 call StopVimInTerminal(buf)
3610 call delete('XTest_echoraw')
3611endfunc
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01003612
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003613" Test for echo highlighting
3614func Test_echohl()
3615 echohl Search
3616 echo 'Vim'
3617 call assert_equal('Vim', Screenline(&lines))
3618 " TODO: How to check the highlight group used by echohl?
3619 " ScreenAttrs() returns all zeros.
3620 echohl None
3621endfunc
3622
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003623" Test for the eval() function
3624func Test_eval()
3625 call assert_fails("call eval('5 a')", 'E488:')
3626endfunc
3627
zeertzjqcdc83932022-09-12 13:38:41 +01003628" Test for the keytrans() function
3629func Test_keytrans()
3630 call assert_equal('<Space>', keytrans(' '))
3631 call assert_equal('<lt>', keytrans('<'))
3632 call assert_equal('<lt>Tab>', keytrans('<Tab>'))
3633 call assert_equal('<Tab>', keytrans("\<Tab>"))
3634 call assert_equal('<C-V>', keytrans("\<C-V>"))
3635 call assert_equal('<BS>', keytrans("\<BS>"))
3636 call assert_equal('<Home>', keytrans("\<Home>"))
3637 call assert_equal('<C-Home>', keytrans("\<C-Home>"))
3638 call assert_equal('<M-Home>', keytrans("\<M-Home>"))
3639 call assert_equal('<C-Space>', keytrans("\<C-Space>"))
3640 call assert_equal('<M-Space>', keytrans("\<*M-Space>"))
3641 call assert_equal('<M-x>', "\<*M-x>"->keytrans())
3642 call assert_equal('<C-I>', "\<*C-I>"->keytrans())
3643 call assert_equal('<S-3>', "\<*S-3>"->keytrans())
3644 call assert_equal('π', 'π'->keytrans())
3645 call assert_equal('<M-π>', "\<M-π>"->keytrans())
3646 call assert_equal('ě', 'ě'->keytrans())
3647 call assert_equal('<M-ě>', "\<M-ě>"->keytrans())
3648 call assert_equal('', ''->keytrans())
3649 call assert_equal('', test_null_string()->keytrans())
3650 call assert_fails('call keytrans(1)', 'E1174:')
3651 call assert_fails('call keytrans()', 'E119:')
3652endfunc
3653
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003654" Test for the nr2char() function
3655func Test_nr2char()
3656 set encoding=latin1
3657 call assert_equal('@', nr2char(64))
3658 set encoding=utf8
3659 call assert_equal('a', nr2char(97, 1))
3660 call assert_equal('a', nr2char(97, 0))
Bram Moolenaarf7271e82020-05-24 18:45:07 +02003661
zeertzjqdb088872022-05-02 22:53:45 +01003662 call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"'))
3663 call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003664endfunc
3665
3666" Test for screenattr(), screenchar() and screenchars() functions
3667func Test_screen_functions()
3668 call assert_equal(-1, screenattr(-1, -1))
3669 call assert_equal(-1, screenchar(-1, -1))
3670 call assert_equal([], screenchars(-1, -1))
zeertzjq47eec672023-06-01 20:26:55 +01003671
3672 " Run this in a separate Vim instance to avoid messing up.
3673 let after =<< trim [CODE]
3674 scriptencoding utf-8
3675 call setline(1, '口')
3676 redraw
3677 call assert_equal(0, screenattr(1, 1))
3678 call assert_equal(char2nr('口'), screenchar(1, 1))
3679 call assert_equal([char2nr('口')], screenchars(1, 1))
3680 call assert_equal('口', screenstring(1, 1))
3681 call writefile(v:errors, 'Xresult')
3682 qall!
3683 [CODE]
3684
3685 let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950']
3686 if !has('win32')
3687 let encodings += ['euc-jp']
3688 endif
3689 for enc in encodings
3690 let msg = 'enc=' .. enc
3691 if RunVim([], after, $'--clean --cmd "set encoding={enc}"')
3692 call assert_equal([], readfile('Xresult'), msg)
3693 endif
3694 call delete('Xresult')
3695 endfor
Bram Moolenaar0e05de42020-03-25 22:23:46 +01003696endfunc
3697
Bram Moolenaar08f41572020-04-20 16:50:00 +02003698" Test for getcurpos() and setpos()
3699func Test_getcurpos_setpos()
3700 new
3701 call setline(1, ['012345678', '012345678'])
3702 normal gg6l
3703 let sp = getcurpos()
3704 normal 0
3705 call setpos('.', sp)
3706 normal jyl
3707 call assert_equal('6', @")
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003708 call assert_equal(-1, setpos('.', test_null_list()))
3709 call assert_equal(-1, setpos('.', {}))
Bram Moolenaar99ca9c42020-09-22 21:55:41 +02003710
3711 let winid = win_getid()
3712 normal G$
3713 let pos = getcurpos()
3714 wincmd w
3715 call assert_equal(pos, getcurpos(winid))
3716
3717 wincmd w
Bram Moolenaar08f41572020-04-20 16:50:00 +02003718 close!
Bram Moolenaar99ca9c42020-09-22 21:55:41 +02003719
3720 call assert_equal(getcurpos(), getcurpos(0))
3721 call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
3722 call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
Bram Moolenaar08f41572020-04-20 16:50:00 +02003723endfunc
3724
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003725func Test_getmousepos()
3726 enew!
3727 call setline(1, "\t\t\t1234")
Bram Moolenaar533870a2022-03-13 15:52:44 +00003728 call test_setmouse(1, 1)
3729 call assert_equal(#{
3730 \ screenrow: 1,
3731 \ screencol: 1,
3732 \ winid: win_getid(),
3733 \ winrow: 1,
3734 \ wincol: 1,
3735 \ line: 1,
3736 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003737 \ coladd: 0,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003738 \ }, getmousepos())
zeertzjqb583eda2023-10-14 11:32:28 +02003739 call test_setmouse(1, 2)
3740 call assert_equal(#{
3741 \ screenrow: 1,
3742 \ screencol: 2,
3743 \ winid: win_getid(),
3744 \ winrow: 1,
3745 \ wincol: 2,
3746 \ line: 1,
3747 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003748 \ coladd: 1,
zeertzjqb583eda2023-10-14 11:32:28 +02003749 \ }, getmousepos())
3750 call test_setmouse(1, 8)
3751 call assert_equal(#{
3752 \ screenrow: 1,
3753 \ screencol: 8,
3754 \ winid: win_getid(),
3755 \ winrow: 1,
3756 \ wincol: 8,
3757 \ line: 1,
3758 \ column: 1,
zeertzjqf5a94d52023-10-15 10:03:30 +02003759 \ coladd: 7,
zeertzjqb583eda2023-10-14 11:32:28 +02003760 \ }, getmousepos())
3761 call test_setmouse(1, 9)
3762 call assert_equal(#{
3763 \ screenrow: 1,
3764 \ screencol: 9,
3765 \ winid: win_getid(),
3766 \ winrow: 1,
3767 \ wincol: 9,
3768 \ line: 1,
3769 \ column: 2,
zeertzjqf5a94d52023-10-15 10:03:30 +02003770 \ coladd: 0,
zeertzjqb583eda2023-10-14 11:32:28 +02003771 \ }, getmousepos())
3772 call test_setmouse(1, 12)
3773 call assert_equal(#{
3774 \ screenrow: 1,
3775 \ screencol: 12,
3776 \ winid: win_getid(),
3777 \ winrow: 1,
3778 \ wincol: 12,
3779 \ line: 1,
3780 \ column: 2,
zeertzjqf5a94d52023-10-15 10:03:30 +02003781 \ coladd: 3,
zeertzjqb583eda2023-10-14 11:32:28 +02003782 \ }, getmousepos())
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003783 call test_setmouse(1, 25)
3784 call assert_equal(#{
3785 \ screenrow: 1,
3786 \ screencol: 25,
3787 \ winid: win_getid(),
3788 \ winrow: 1,
3789 \ wincol: 25,
3790 \ line: 1,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003791 \ column: 4,
zeertzjqf5a94d52023-10-15 10:03:30 +02003792 \ coladd: 0,
3793 \ }, getmousepos())
3794 call test_setmouse(1, 28)
3795 call assert_equal(#{
3796 \ screenrow: 1,
3797 \ screencol: 28,
3798 \ winid: win_getid(),
3799 \ winrow: 1,
3800 \ wincol: 28,
3801 \ line: 1,
3802 \ column: 7,
3803 \ coladd: 0,
3804 \ }, getmousepos())
3805 call test_setmouse(1, 29)
3806 call assert_equal(#{
3807 \ screenrow: 1,
3808 \ screencol: 29,
3809 \ winid: win_getid(),
3810 \ winrow: 1,
3811 \ wincol: 29,
3812 \ line: 1,
3813 \ column: 8,
3814 \ coladd: 0,
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003815 \ }, getmousepos())
3816 call test_setmouse(1, 50)
3817 call assert_equal(#{
3818 \ screenrow: 1,
3819 \ screencol: 50,
3820 \ winid: win_getid(),
3821 \ winrow: 1,
3822 \ wincol: 50,
3823 \ line: 1,
Bram Moolenaar533870a2022-03-13 15:52:44 +00003824 \ column: 8,
zeertzjqf5a94d52023-10-15 10:03:30 +02003825 \ coladd: 21,
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003826 \ }, getmousepos())
Sean Dewar10792fe2022-03-15 09:46:54 +00003827
3828 " If the mouse is positioned past the last buffer line, "line" and "column"
3829 " should act like it's positioned on the last buffer line.
3830 call test_setmouse(2, 25)
3831 call assert_equal(#{
3832 \ screenrow: 2,
3833 \ screencol: 25,
3834 \ winid: win_getid(),
3835 \ winrow: 2,
3836 \ wincol: 25,
3837 \ line: 1,
3838 \ column: 4,
zeertzjqf5a94d52023-10-15 10:03:30 +02003839 \ coladd: 0,
Sean Dewar10792fe2022-03-15 09:46:54 +00003840 \ }, getmousepos())
3841 call test_setmouse(2, 50)
3842 call assert_equal(#{
3843 \ screenrow: 2,
3844 \ screencol: 50,
3845 \ winid: win_getid(),
3846 \ winrow: 2,
3847 \ wincol: 50,
3848 \ line: 1,
3849 \ column: 8,
zeertzjqf5a94d52023-10-15 10:03:30 +02003850 \ coladd: 21,
Sean Dewar10792fe2022-03-15 09:46:54 +00003851 \ }, getmousepos())
zeertzjq031a7452024-05-11 11:23:37 +02003852
3853 30vnew
3854 setlocal smoothscroll number
3855 call setline(1, join(range(100)))
3856 exe "normal! \<C-E>"
3857 call test_setmouse(1, 5)
3858 call assert_equal(#{
3859 \ screenrow: 1,
3860 \ screencol: 5,
3861 \ winid: win_getid(),
3862 \ winrow: 1,
3863 \ wincol: 5,
3864 \ line: 1,
3865 \ column: 27,
3866 \ coladd: 0,
3867 \ }, getmousepos())
3868 call test_setmouse(2, 5)
3869 call assert_equal(#{
3870 \ screenrow: 2,
3871 \ screencol: 5,
3872 \ winid: win_getid(),
3873 \ winrow: 2,
3874 \ wincol: 5,
3875 \ line: 1,
3876 \ column: 53,
3877 \ coladd: 0,
3878 \ }, getmousepos())
3879
3880 exe "normal! \<C-E>"
3881 call test_setmouse(1, 5)
3882 call assert_equal(#{
3883 \ screenrow: 1,
3884 \ screencol: 5,
3885 \ winid: win_getid(),
3886 \ winrow: 1,
3887 \ wincol: 5,
3888 \ line: 1,
3889 \ column: 53,
3890 \ coladd: 0,
3891 \ }, getmousepos())
3892 call test_setmouse(2, 5)
3893 call assert_equal(#{
3894 \ screenrow: 2,
3895 \ screencol: 5,
3896 \ winid: win_getid(),
3897 \ winrow: 2,
3898 \ wincol: 5,
3899 \ line: 1,
3900 \ column: 79,
3901 \ coladd: 0,
3902 \ }, getmousepos())
3903
3904 vert resize 4
3905 call test_setmouse(2, 2)
3906 " This used to crash Vim
3907 call assert_equal(#{
3908 \ screenrow: 2,
3909 \ screencol: 2,
3910 \ winid: win_getid(),
3911 \ winrow: 2,
3912 \ wincol: 2,
3913 \ line: 1,
3914 \ column: 53,
3915 \ coladd: 0,
3916 \ }, getmousepos())
3917
3918 bwipe!
Bram Moolenaar986b0fd2022-03-13 12:06:07 +00003919 bwipe!
3920endfunc
3921
Bram Moolenaar24dc19c2022-11-14 19:49:15 +00003922func Test_getmouseshape()
3923 CheckFeature mouseshape
3924
3925 call assert_equal('arrow', getmouseshape())
3926endfunc
3927
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003928" Test for glob()
3929func Test_glob()
3930 call assert_equal('', glob(test_null_string()))
3931 call assert_equal('', globpath(test_null_string(), test_null_string()))
Yegappan Lakshmanan46aa6f92021-05-19 17:15:04 +02003932 call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
Bram Moolenaar1b04ce22020-08-21 22:46:11 +02003933
3934 call writefile([], 'Xglob1')
3935 call writefile([], 'XGLOB2')
3936 set wildignorecase
3937 " Sort output of glob() otherwise we end up with different
3938 " ordering depending on whether file system is case-sensitive.
3939 call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
LemonBoya3157a42022-04-03 11:58:31 +01003940 " wildignorecase shall be applied even when the pattern contains no wildcards.
3941 call assert_equal('XGLOB2', glob('xglob2'))
Bram Moolenaar1b04ce22020-08-21 22:46:11 +02003942 set wildignorecase&
3943
3944 call delete('Xglob1')
3945 call delete('XGLOB2')
3946
3947 call assert_fails("call glob('*', 0, {})", 'E728:')
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02003948endfunc
3949
Christian Brabandt8b34aea2024-06-13 21:20:20 +02003950func Test_glob2()
3951 call mkdir('[XglobDir]', 'R')
3952 call mkdir('abc[glob]def', 'R')
3953
3954 call writefile(['glob'], '[XglobDir]/Xglob')
3955 call writefile(['glob'], 'abc[glob]def/Xglob')
3956 if has("unix")
3957 call assert_equal([], (glob('[XglobDir]/*', 0, 1)))
3958 call assert_equal([], (glob('abc[glob]def/*', 0, 1)))
3959 call assert_equal(['[XglobDir]/Xglob'], (glob('\[XglobDir]/*', 0, 1)))
3960 call assert_equal(['abc[glob]def/Xglob'], (glob('abc\[glob]def/*', 0, 1)))
3961 elseif has("win32")
3962 let _sl=&shellslash
3963 call assert_equal([], (glob('[XglobDir]\*', 0, 1)))
3964 call assert_equal([], (glob('abc[glob]def\*', 0, 1)))
3965 call assert_equal([], (glob('\[XglobDir]\*', 0, 1)))
3966 call assert_equal([], (glob('abc\[glob]def\*', 0, 1)))
3967 set noshellslash
3968 call assert_equal(['[XglobDir]\Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
3969 call assert_equal(['abc[glob]def\Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
3970 set shellslash
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 let &shellslash=_sl
3974 endif
3975endfunc
3976
LemonBoy23c5ebe2024-06-18 20:43:51 +02003977func Test_glob_symlinks()
3978 call writefile([], 'Xglob1')
3979
3980 if has("win32")
3981 silent !mklink XglobBad DoesNotExist
3982 if v:shell_error
3983 throw 'Skipped: cannot create symlinks'
3984 endif
3985 silent !mklink XglobOk Xglob1
3986 else
3987 silent !ln -s DoesNotExist XglobBad
3988 silent !ln -s Xglob1 XglobOk
3989 endif
3990
3991 " The broken symlink is excluded when alllinks is false.
3992 call assert_equal(['Xglob1', 'XglobBad', 'XglobOk'], sort(glob('Xglob*', 0, 1, 1)))
3993 call assert_equal(['Xglob1', 'XglobOk'], sort(glob('Xglob*', 0, 1, 0)))
3994
3995 call delete('Xglob1')
3996 call delete('XglobBad')
3997 call delete('XglobOk')
3998endfunc
3999
Bram Moolenaar92b83cc2020-04-25 15:24:44 +02004000" Test for browse()
4001func Test_browse()
4002 CheckFeature browse
4003 call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
4004endfunc
4005
4006" Test for browsedir()
4007func Test_browsedir()
4008 CheckFeature browse
4009 call assert_fails('call browsedir("open", [])', 'E730:')
4010endfunc
4011
Bram Moolenaarb47bed22021-04-14 17:06:43 +02004012func HasDefault(msg = 'msg')
4013 return a:msg
4014endfunc
4015
4016func Test_default_arg_value()
4017 call assert_equal('msg', HasDefault())
4018endfunc
4019
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004020func Test_builtin_check()
4021 call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
4022 call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
Bram Moolenaarb54abee2021-06-02 11:49:23 +02004023 call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
4024 call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
4025 let lines =<< trim END
4026 vim9script
Bram Moolenaar62b191c2022-02-12 20:34:50 +00004027 var trim = (x) => " " .. x
Bram Moolenaarb54abee2021-06-02 11:49:23 +02004028 END
Bram Moolenaar62aec932022-01-29 21:45:34 +00004029 call v9.CheckScriptFailure(lines, 'E704:')
Bram Moolenaar6f1d2aa2021-06-01 21:21:55 +02004030
4031 call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
4032 let g:bar = 123
4033 call extend(g:, #{bar: { -> "foo" }}, "keep")
4034 call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
zeertzjq91c75d12022-11-05 20:21:58 +00004035 unlet g:bar
4036
4037 call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:')
4038 let bar = 123
4039 call extend(l:, #{bar: { -> "foo" }}, "keep")
4040 call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:')
4041 unlet bar
4042
4043 call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:')
4044 let g:bar = 123
4045 call extend(g:, #{bar: function("extend")}, "keep")
4046 call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:')
4047 unlet g:bar
4048
4049 call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:')
4050 let bar = 123
4051 call extend(l:, #{bar: function("extend")}, "keep")
4052 call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:')
4053 unlet bar
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004054endfunc
4055
Bram Moolenaarc4ec3382021-12-09 16:40:18 +00004056func Test_funcref_to_string()
4057 let Fn = funcref('g:Test_funcref_to_string')
4058 call assert_equal("function('g:Test_funcref_to_string')", string(Fn))
4059endfunc
4060
Yegappan Lakshmanan3e336502024-04-04 19:35:59 +02004061" A funcref cannot start with an underscore (except when used as a protected
4062" class or object variable)
4063func Test_funcref_with_underscore()
4064 " at script level
4065 let lines =<< trim END
4066 vim9script
4067 var _Fn = () => 10
4068 END
4069 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn')
4070
4071 " inside a function
4072 let lines =<< trim END
4073 vim9script
4074 def Func()
4075 var _Fn = () => 10
4076 enddef
4077 defcompile
4078 END
4079 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn', 1)
4080
4081 " as a function argument
4082 let lines =<< trim END
4083 vim9script
4084 def Func(_Fn: func)
4085 enddef
4086 defcompile
4087 END
4088 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Fn', 2)
4089
4090 " as a lambda argument
4091 let lines =<< trim END
4092 vim9script
4093 var Fn = (_Farg: func) => 10
4094 END
4095 call v9.CheckSourceFailure(lines, 'E704: Funcref variable name must start with a capital: _Farg', 2)
4096endfunc
4097
LemonBoydca1d402022-04-28 15:26:33 +01004098" Test for isabsolutepath()
4099func Test_isabsolutepath()
4100 call assert_false(isabsolutepath(''))
4101 call assert_false(isabsolutepath('.'))
4102 call assert_false(isabsolutepath('../Foo'))
4103 call assert_false(isabsolutepath('Foo/'))
4104 if has('win32')
4105 call assert_true(isabsolutepath('A:\'))
4106 call assert_true(isabsolutepath('A:\Foo'))
4107 call assert_true(isabsolutepath('A:/Foo'))
4108 call assert_false(isabsolutepath('A:Foo'))
4109 call assert_false(isabsolutepath('\Windows'))
4110 call assert_true(isabsolutepath('\\Server2\Share\Test\Foo.txt'))
4111 else
4112 call assert_true(isabsolutepath('/'))
4113 call assert_true(isabsolutepath('/usr/share/'))
4114 endif
4115endfunc
Bram Moolenaar3d9c4ee2021-05-31 22:15:26 +02004116
Yasuhiro Matsumoto05cf63e2022-05-03 11:02:28 +01004117" Test for exepath()
4118func Test_exepath()
4119 if has('win32')
4120 call assert_notequal(exepath('cmd'), '')
4121
4122 let oldNoDefaultCurrentDirectoryInExePath = $NoDefaultCurrentDirectoryInExePath
4123 call writefile(['@echo off', 'echo Evil'], 'vim-test-evil.bat')
4124 let $NoDefaultCurrentDirectoryInExePath = ''
4125 call assert_notequal(exepath("vim-test-evil.bat"), '')
4126 let $NoDefaultCurrentDirectoryInExePath = '1'
4127 call assert_equal(exepath("vim-test-evil.bat"), '')
4128 let $NoDefaultCurrentDirectoryInExePath = oldNoDefaultCurrentDirectoryInExePath
4129 call delete('vim-test-evil.bat')
4130 else
4131 call assert_notequal(exepath('sh'), '')
4132 endif
4133endfunc
4134
LemonBoy0f7a3e12022-05-26 12:10:37 +01004135" Test for virtcol()
4136func Test_virtcol()
zeertzjq825cf812023-08-17 22:55:25 +02004137 new
LemonBoy0f7a3e12022-05-26 12:10:37 +01004138 call setline(1, "the\tquick\tbrown\tfox")
4139 norm! 4|
4140 call assert_equal(8, virtcol('.'))
4141 call assert_equal(8, virtcol('.', v:false))
4142 call assert_equal([4, 8], virtcol('.', v:true))
zeertzjq825cf812023-08-17 22:55:25 +02004143
4144 let w = winwidth(0)
4145 call setline(2, repeat('a', w + 2))
4146 let win_nosbr = win_getid()
4147 split
4148 setlocal showbreak=!!
4149 let win_sbr = win_getid()
4150 call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr))
4151 call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr))
4152 call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr))
4153 call assert_equal([w, w], virtcol([2, w], v:true, win_sbr))
4154 call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr))
4155 call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr))
4156 close
4157
4158 call assert_equal(0, virtcol(''))
4159 call assert_equal([0, 0], virtcol('', v:true))
4160 call assert_equal(0, virtcol('.', v:false, 5001))
4161 call assert_equal([0, 0], virtcol('.', v:true, 5001))
4162
LemonBoy0f7a3e12022-05-26 12:10:37 +01004163 bwipe!
4164endfunc
4165
Bram Moolenaar398a26f2022-11-13 22:13:33 +00004166func Test_delfunc_while_listing()
4167 CheckRunVimInTerminal
4168
4169 let lines =<< trim END
4170 set nocompatible
4171 for i in range(1, 999)
4172 exe 'func ' .. 'MyFunc' .. i .. '()'
4173 endfunc
4174 endfor
4175 au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')})
4176 END
4177 call writefile(lines, 'Xfunctionclear', 'D')
4178 let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12})
4179
4180 " This was using freed memory. The height of the terminal must be so that
4181 " the next function to be listed with "j" is the one that is deleted in the
4182 " timer callback, tricky!
4183 call term_sendkeys(buf, ":func /MyFunc\<CR>")
4184 call TermWait(buf, 50)
4185 call term_sendkeys(buf, "j")
4186 call TermWait(buf, 50)
4187 call term_sendkeys(buf, "\<CR>")
4188
4189 call StopVimInTerminal(buf)
4190endfunc
4191
Yegappan Lakshmanan03ff1c22023-05-06 14:08:21 +01004192" Test for the reverse() function with a string
4193func Test_string_reverse()
Yegappan Lakshmananf9dc2782023-05-11 15:02:56 +01004194 let lines =<< trim END
4195 call assert_equal('', reverse(test_null_string()))
4196 for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'],
4197 \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'],
4198 \ ['🇦', '🇦'], ['🇦🇧', '🇧🇦'], ['🇦🇧🇨', '🇨🇧🇦'],
4199 \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']]
4200 call assert_equal(s2, reverse(s1))
4201 endfor
4202 END
4203 call v9.CheckLegacyAndVim9Success(lines)
Yegappan Lakshmanan03ff1c22023-05-06 14:08:21 +01004204
4205 " test in latin1 encoding
4206 let save_enc = &encoding
4207 set encoding=latin1
4208 call assert_equal('dcba', reverse('abcd'))
4209 let &encoding = save_enc
4210endfunc
4211
Christian Brabandt4c6fe2e2023-09-02 19:30:03 +02004212func Test_fullcommand()
4213 " this used to crash vim
4214 call assert_equal('', fullcommand(10))
4215endfunc
4216
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02004217" Test for glob() with shell special patterns
4218func Test_glob_extended_bash()
4219 CheckExecutable bash
Ken Takata03ca4002023-09-28 21:59:58 +02004220 CheckNotMSWindows
4221 CheckNotMac " The default version of bash is old on macOS.
4222
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02004223 let _shell = &shell
4224 set shell=bash
4225
4226 call mkdir('Xtestglob/foo/bar/src', 'p')
4227 call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
4228 call writefile([], 'Xtestglob/foo/bar/src/foo.h')
4229 call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
4230
4231 " Sort output of glob() otherwise we end up with different
4232 " ordering depending on whether file system is case-sensitive.
4233 let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h']
4234 call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1)))
4235 call delete('Xtestglob', 'rf')
4236 let &shell=_shell
4237endfunc
4238
Ken Takata4a1ad552023-10-02 21:31:31 +02004239" Test for glob() with extended patterns (MS-Windows)
4240" Vim doesn't use 'shell' to expand wildcards on MS-Windows.
4241" Unlike bash, it doesn't support {,} expansion.
4242func Test_glob_extended_mswin()
4243 CheckMSWindows
4244
4245 call mkdir('Xtestglob/foo/bar/src', 'p')
4246 call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
4247 call writefile([], 'Xtestglob/foo/bar/src/foo.h')
4248 call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
4249
4250 " Sort output of glob() otherwise we end up with different
4251 " ordering depending on whether file system is case-sensitive.
4252 let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh']
4253 call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1)))
4254 call delete('Xtestglob', 'rf')
4255endfunc
4256
zeertzjqad387692024-03-23 08:23:48 +01004257" Tests for the slice() function.
4258func Test_slice()
4259 let lines =<< trim END
4260 call assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
4261 call assert_equal([2, 3, 4, 5], slice(range(6), 2))
4262 call assert_equal([2, 3], slice(range(6), 2, 4))
4263 call assert_equal([0, 1, 2, 3], slice(range(6), 0, 4))
4264 call assert_equal([1, 2, 3], slice(range(6), 1, 4))
4265 call assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
4266 call assert_equal([1, 2], slice(range(6), 1, -3))
4267 call assert_equal([1], slice(range(6), 1, -4))
4268 call assert_equal([], slice(range(6), 1, -5))
4269 call assert_equal([], slice(range(6), 1, -6))
4270
4271 call assert_equal(0z1122334455, slice(0z001122334455, 1))
4272 call assert_equal(0z22334455, slice(0z001122334455, 2))
4273 call assert_equal(0z2233, slice(0z001122334455, 2, 4))
4274 call assert_equal(0z00112233, slice(0z001122334455, 0, 4))
4275 call assert_equal(0z112233, slice(0z001122334455, 1, 4))
4276 call assert_equal(0z11223344, slice(0z001122334455, 1, -1))
4277 call assert_equal(0z1122, slice(0z001122334455, 1, -3))
4278 call assert_equal(0z11, slice(0z001122334455, 1, -4))
4279 call assert_equal(0z, slice(0z001122334455, 1, -5))
4280 call assert_equal(0z, slice(0z001122334455, 1, -6))
4281
4282 call assert_equal('12345', slice('012345', 1))
4283 call assert_equal('2345', slice('012345', 2))
4284 call assert_equal('23', slice('012345', 2, 4))
4285 call assert_equal('0123', slice('012345', 0, 4))
4286 call assert_equal('123', slice('012345', 1, 4))
4287 call assert_equal('1234', slice('012345', 1, -1))
4288 call assert_equal('12', slice('012345', 1, -3))
4289 call assert_equal('1', slice('012345', 1, -4))
4290 call assert_equal('', slice('012345', 1, -5))
4291 call assert_equal('', slice('012345', 1, -6))
4292
4293 #" Composing chars are treated as a part of the preceding base char.
4294 call assert_equal('β̳́γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1))
4295 call assert_equal('γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2))
4296 call assert_equal('γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2, 4))
4297 call assert_equal('ὰ̳β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(0, 4))
4298 call assert_equal('β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, 4))
4299 call assert_equal('β̳́γ̳̂δ̳̃ε̳̄', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -1))
4300 call assert_equal('β̳́γ̳̂', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -3))
4301 call assert_equal('β̳́', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -4))
4302 call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -5))
4303 call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -6))
4304 END
4305 call v9.CheckLegacyAndVim9Success(lines)
Yegappan Lakshmananfe424d12024-05-17 18:20:43 +02004306
4307 call assert_equal(0, slice(v:true, 1))
zeertzjqad387692024-03-23 08:23:48 +01004308endfunc
4309
mikoto2000de094dc2024-11-14 22:13:48 +01004310
mikoto2000a73dfc22024-11-18 21:12:21 +01004311" Test for getcellpixels() for unix system
mikoto2000de094dc2024-11-14 22:13:48 +01004312" 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 +01004313func Test_getcellpixels_for_unix()
mikoto2000de094dc2024-11-14 22:13:48 +01004314 CheckNotMSWindows
4315 CheckRunVimInTerminal
4316
4317 let buf = RunVimInTerminal('', #{rows: 6})
4318
4319 " write getcellpixels() result to current buffer.
4320 call term_sendkeys(buf, ":redi @\"\<CR>")
4321 call term_sendkeys(buf, ":echo getcellpixels()\<CR>")
4322 call term_sendkeys(buf, ":redi END\<CR>")
4323 call term_sendkeys(buf, "P")
4324
4325 call WaitForAssert({-> assert_match("\[\d+, \d+\]", term_getline(buf, 3))}, 1000)
4326
4327 call StopVimInTerminal(buf)
4328endfunc
4329
mikoto2000a73dfc22024-11-18 21:12:21 +01004330" Test for getcellpixels() for windows system
4331" Windows terminal vim is not support. check return `[]`.
4332func Test_getcellpixels_for_windows()
4333 CheckMSWindows
4334 CheckRunVimInTerminal
4335
4336 let buf = RunVimInTerminal('', #{rows: 6})
4337
4338 " write getcellpixels() result to current buffer.
4339 call term_sendkeys(buf, ":redi @\"\<CR>")
4340 call term_sendkeys(buf, ":echo getcellpixels()\<CR>")
4341 call term_sendkeys(buf, ":redi END\<CR>")
4342 call term_sendkeys(buf, "P")
4343
4344 call WaitForAssert({-> assert_match("\[\]", term_getline(buf, 3))}, 1000)
4345
4346 call StopVimInTerminal(buf)
4347endfunc
4348
mikoto2000de094dc2024-11-14 22:13:48 +01004349" Test for getcellpixels() on gVim
4350func Test_getcellpixels_gui()
mikoto2000de094dc2024-11-14 22:13:48 +01004351 if has("gui_running")
4352 let cellpixels = getcellpixels()
mikoto2000a73dfc22024-11-18 21:12:21 +01004353 call assert_equal(2, len(cellpixels))
mikoto2000de094dc2024-11-14 22:13:48 +01004354 endif
4355endfunc
4356
Yegappan Lakshmanan810785c2024-12-30 10:29:44 +01004357func Str2Blob(s)
4358 return list2blob(str2list(a:s))
4359endfunc
4360
4361func Blob2Str(b)
4362 return list2str(blob2list(a:b))
4363endfunc
4364
4365" Test for the base64_encode() and base64_decode() functions
4366func Test_base64_encoding()
4367 let lines =<< trim END
4368 #" Test for encoding/decoding the RFC-4648 alphabets
4369 VAR s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
4370 for i in range(64)
4371 call assert_equal($'{s[i]}A==', base64_encode(list2blob([i << 2])))
4372 call assert_equal(list2blob([i << 2]), base64_decode($'{s[i]}A=='))
4373 endfor
4374
4375 #" Test for encoding with padding
4376 call assert_equal('TQ==', base64_encode(g:Str2Blob("M")))
4377 call assert_equal('TWE=', base64_encode(g:Str2Blob("Ma")))
4378 call assert_equal('TWFu', g:Str2Blob("Man")->base64_encode())
4379 call assert_equal('', base64_encode(0z))
4380 call assert_equal('', base64_encode(g:Str2Blob("")))
4381
4382 #" Test for decoding with padding
4383 call assert_equal('light work.', g:Blob2Str(base64_decode("bGlnaHQgd29yay4=")))
4384 call assert_equal('light work', g:Blob2Str(base64_decode("bGlnaHQgd29yaw==")))
4385 call assert_equal('light wor', g:Blob2Str("bGlnaHQgd29y"->base64_decode()))
4386 call assert_equal(0z00, base64_decode("===="))
4387 call assert_equal(0z, base64_decode(""))
4388
4389 #" Test for invalid padding
4390 call assert_equal('Hello', g:Blob2Str(base64_decode("SGVsbG8=")))
4391 call assert_fails('call base64_decode("SGVsbG9=")', 'E475:')
4392 call assert_fails('call base64_decode("SGVsbG9")', 'E475:')
4393 call assert_equal('Hell', g:Blob2Str(base64_decode("SGVsbA==")))
4394 call assert_fails('call base64_decode("SGVsbA=")', 'E475:')
4395 call assert_fails('call base64_decode("SGVsbA")', 'E475:')
4396 call assert_fails('call base64_decode("SGVsbA====")', 'E475:')
4397
4398 #" Error case
4399 call assert_fails('call base64_decode("b")', 'E475: Invalid argument: b')
4400 call assert_fails('call base64_decode("<<==")', 'E475: Invalid argument: <<==')
4401
4402 call assert_fails('call base64_encode([])', 'E1238: Blob required for argument 1')
4403 call assert_fails('call base64_decode([])', 'E1174: String required for argument 1')
4404 END
4405 call v9.CheckLegacyAndVim9Success(lines)
4406endfunc
4407
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004408" Tests for the str2blob() function
4409func Test_str2blob()
4410 let lines =<< trim END
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004411 call assert_equal(0z, str2blob([""]))
4412 call assert_equal(0z, str2blob([]))
4413 call assert_equal(0z, str2blob(test_null_list()))
4414 call assert_equal(0z, str2blob([test_null_string(), test_null_string()]))
4415 call assert_fails("call str2blob('')", 'E1211: List required for argument 1')
4416 call assert_equal(0z61, str2blob(["a"]))
4417 call assert_equal(0z6162, str2blob(["ab"]))
4418 call assert_equal(0z610062, str2blob(["a\nb"]))
4419 call assert_equal(0z61620A6364, str2blob(["ab", "cd"]))
4420 call assert_equal(0z0A, str2blob(["", ""]))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004421
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004422 call assert_equal(0zC2ABC2BB, str2blob(["«»"]))
4423 call assert_equal(0zC59DC59F, str2blob(["ŝş"]))
4424 call assert_equal(0zE0AE85E0.AE87, str2blob(["அஇ"]))
4425 call assert_equal(0zF09F81B0.F09F81B3, str2blob(["🁰🁳"]))
4426 call assert_equal(0z616263, str2blob(['abc'], {}))
4427 call assert_equal(0zABBB, str2blob(['«»'], {'encoding': 'latin1'}))
4428 call assert_equal(0zABBB0AABBB, str2blob(['«»', '«»'], {'encoding': 'latin1'}))
4429 call assert_equal(0zC2ABC2BB, str2blob(['«»'], {'encoding': 'utf8'}))
4430
Yegappan Lakshmanan5e9aaed2025-01-18 10:24:25 +01004431 call assert_equal(0z62, str2blob(["b"], test_null_dict()))
4432 call assert_equal(0z63, str2blob(["c"], {'encoding': test_null_string()}))
4433
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004434 call assert_fails("call str2blob(['abc'], [])", 'E1206: Dictionary required for argument 2')
4435 call assert_fails("call str2blob(['abc'], {'encoding': []})", 'E730: Using a List as a String')
Christian Brabandtd5afc742025-03-18 20:55:42 +01004436 call assert_fails("call str2blob(['abc'], {'encoding': 'ab12xy'})", 'E1516: Unable to convert to ''ab12xy'' encoding')
4437 call assert_fails("call str2blob(['ŝş'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
4438 call assert_fails("call str2blob(['அஇ'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
4439 call assert_fails("call str2blob(['🁰🁳'], {'encoding': 'latin1'})", 'E1516: Unable to convert to ''latin1'' encoding')
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004440 END
4441 call v9.CheckLegacyAndVim9Success(lines)
4442endfunc
4443
4444" Tests for the blob2str() function
4445func Test_blob2str()
4446 let lines =<< trim END
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004447 call assert_equal([], blob2str(0z))
4448 call assert_equal([], blob2str(test_null_blob()))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004449 call assert_fails("call blob2str([])", 'E1238: Blob required for argument 1')
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004450 call assert_equal(["ab"], blob2str(0z6162))
4451 call assert_equal(["a\nb"], blob2str(0z610062))
4452 call assert_equal(["ab", "cd"], blob2str(0z61620A6364))
4453
4454 call assert_equal(["«»"], blob2str(0zC2ABC2BB))
4455 call assert_equal(["ŝş"], blob2str(0zC59DC59F))
4456 call assert_equal(["அஇ"], blob2str(0zE0AE85E0.AE87))
4457 call assert_equal(["🁰🁳"], blob2str(0zF09F81B0.F09F81B3))
4458 call assert_equal(['«»'], blob2str(0zABBB, {'encoding': 'latin1'}))
4459 call assert_equal(['«»'], blob2str(0zC2ABC2BB, {'encoding': 'utf8'}))
Yegappan Lakshmanan90b39752025-01-19 09:37:07 +01004460 call assert_equal(['«»'], blob2str(0zC2ABC2BB, {'encoding': 'utf-8'}))
4461
4462 call assert_equal(['a'], blob2str(0z61, test_null_dict()))
4463 call assert_equal(['a'], blob2str(0z61, {'encoding': test_null_string()}))
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004464
Bakudankunb3854bf2025-02-23 20:29:21 +01004465 call assert_equal(["\x80"], blob2str(0z80, {'encoding': 'none'}))
4466 call assert_equal(['a', "\x80"], blob2str(0z610A80, {'encoding': 'none'}))
4467
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004468 #" Invalid encoding
4469 call assert_fails("call blob2str(0z80)", "E1515: Unable to convert from 'utf-8' encoding")
Yegappan Lakshmanana11b23c2025-01-16 19:16:42 +01004470 call assert_fails("call blob2str(0z610A80)", "E1515: Unable to convert from 'utf-8' encoding")
Yegappan Lakshmanan1aefe1d2025-01-14 17:29:42 +01004471 call assert_fails("call blob2str(0zC0)", "E1515: Unable to convert from 'utf-8' encoding")
4472 call assert_fails("call blob2str(0zE0)", "E1515: Unable to convert from 'utf-8' encoding")
4473 call assert_fails("call blob2str(0zF0)", "E1515: Unable to convert from 'utf-8' encoding")
4474
4475 call assert_fails("call blob2str(0z6180)", "E1515: Unable to convert from 'utf-8' encoding")
4476 call assert_fails("call blob2str(0z61C0)", "E1515: Unable to convert from 'utf-8' encoding")
4477 call assert_fails("call blob2str(0z61E0)", "E1515: Unable to convert from 'utf-8' encoding")
4478 call assert_fails("call blob2str(0z61F0)", "E1515: Unable to convert from 'utf-8' encoding")
4479
4480 call assert_fails("call blob2str(0zC0C0)", "E1515: Unable to convert from 'utf-8' encoding")
4481 call assert_fails("call blob2str(0z61C0C0)", "E1515: Unable to convert from 'utf-8' encoding")
4482
4483 call assert_fails("call blob2str(0zE0)", "E1515: Unable to convert from 'utf-8' encoding")
4484 call assert_fails("call blob2str(0zE080)", "E1515: Unable to convert from 'utf-8' encoding")
4485 call assert_fails("call blob2str(0zE080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4486 call assert_fails("call blob2str(0z61E080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4487
4488 call assert_fails("call blob2str(0zF08080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4489 call assert_fails("call blob2str(0z61F08080C0)", "E1515: Unable to convert from 'utf-8' encoding")
4490 call assert_fails("call blob2str(0zF0)", "E1515: Unable to convert from 'utf-8' encoding")
4491 call assert_fails("call blob2str(0zF080)", "E1515: Unable to convert from 'utf-8' encoding")
4492 call assert_fails("call blob2str(0zF08080)", "E1515: Unable to convert from 'utf-8' encoding")
4493
4494 call assert_fails("call blob2str(0z6162, [])", 'E1206: Dictionary required for argument 2')
4495 call assert_fails("call blob2str(0z6162, {'encoding': []})", 'E730: Using a List as a String')
4496 call assert_fails("call blob2str(0z6162, {'encoding': 'ab12xy'})", 'E1515: Unable to convert from ''ab12xy'' encoding')
4497 END
4498 call v9.CheckLegacyAndVim9Success(lines)
4499endfunc
4500
Bram Moolenaar8d588cc2020-02-25 21:47:45 +01004501" vim: shiftwidth=2 sts=2 expandtab