blob: 81e9262ca2536a2b27bea05a189396e917e10f84 [file] [log] [blame]
Bram Moolenaard58f03b2017-01-29 22:48:45 +01001" Tests for Lua.
Bram Moolenaard58f03b2017-01-29 22:48:45 +01002
Bram Moolenaarb46fecd2019-06-15 17:58:09 +02003source check.vim
Bram Moolenaarc8970b92020-10-26 20:18:08 +01004
5" This test also works without the lua feature.
6func Test_skip_lua()
7 if 0
8 lua print("Not executed")
9 endif
10endfunc
11
Bram Moolenaarb46fecd2019-06-15 17:58:09 +020012CheckFeature lua
Bram Moolenaard58f03b2017-01-29 22:48:45 +010013
Bram Moolenaarf65ed862021-04-03 14:13:33 +020014" Depending on the lua version, the error messages are different.
Bram Moolenaar125ed272021-04-07 20:11:12 +020015let [s:major, s:minor, s:patch] = luaeval('vim.lua_version')->split('\.')->map({-> str2nr(v:val)})
Bram Moolenaarf65ed862021-04-03 14:13:33 +020016let s:lua_53_or_later = 0
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +000017let s:lua_543 = 0
Bram Moolenaarf65ed862021-04-03 14:13:33 +020018if (s:major == 5 && s:minor >= 3) || s:major > 5
Bram Moolenaare49b8e82020-07-01 13:52:55 +020019 let s:lua_53_or_later = 1
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +000020 if s:major == 5 && s:minor == 4 && s:patch == 3
21 let s:lua_543 = 1
Bram Moolenaarf65ed862021-04-03 14:13:33 +020022 endif
Bram Moolenaare49b8e82020-07-01 13:52:55 +020023endif
24
Bram Moolenaare165f632019-03-10 09:48:59 +010025func TearDown()
26 " Run garbage collection after each test to exercise luaV_setref().
27 call test_garbagecollect_now()
28endfunc
29
Bram Moolenaar4ff48142018-06-30 21:50:25 +020030" Check that switching to another buffer does not trigger ml_get error.
Bram Moolenaar5feabe02020-01-30 18:24:53 +010031func Test_lua_command_new_no_ml_get_error()
Bram Moolenaard58f03b2017-01-29 22:48:45 +010032 new
33 let wincount = winnr('$')
34 call setline(1, ['one', 'two', 'three'])
35 luado vim.command("new")
36 call assert_equal(wincount + 1, winnr('$'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +020037 %bwipe!
38endfunc
39
40" Test vim.command()
Bram Moolenaar5feabe02020-01-30 18:24:53 +010041func Test_lua_command()
Bram Moolenaar4ff48142018-06-30 21:50:25 +020042 new
43 call setline(1, ['one', 'two', 'three'])
44 luado vim.command("1,2d_")
45 call assert_equal(['three'], getline(1, '$'))
Bram Moolenaard58f03b2017-01-29 22:48:45 +010046 bwipe!
Bram Moolenaar4ff48142018-06-30 21:50:25 +020047endfunc
48
Bram Moolenaare49b8e82020-07-01 13:52:55 +020049func Test_lua_luado()
50 new
51 call setline(1, ['one', 'two'])
52 luado return(linenr)
53 call assert_equal(['1', '2'], getline(1, '$'))
54 close!
55
56 " Error cases
57 call assert_fails('luado string.format()',
58 \ "[string \"vim chunk\"]:1: bad argument #1 to 'format' (string expected, got no value)")
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +000059 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +020060 let msg = "[string \"vim chunk\"]:1: global 'func' is not callable (a nil value)"
61 elseif s:lua_53_or_later
62 let msg = "[string \"vim chunk\"]:1: attempt to call a nil value (global 'func')"
63 else
64 let msg = "[string \"vim chunk\"]:1: attempt to call global 'func' (a nil value)"
65 endif
66 call assert_fails('luado func()', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +020067 call assert_fails('luado error("failed")', "[string \"vim chunk\"]:1: failed")
68endfunc
69
Bram Moolenaar4ff48142018-06-30 21:50:25 +020070" Test vim.eval()
Bram Moolenaar5feabe02020-01-30 18:24:53 +010071func Test_lua_eval()
Bram Moolenaar4ff48142018-06-30 21:50:25 +020072 " lua.eval with a number
73 lua v = vim.eval('123')
74 call assert_equal('number', luaeval('vim.type(v)'))
Bram Moolenaareb04f082020-05-17 14:32:35 +020075 call assert_equal(123, luaeval('v'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +020076
77 " lua.eval with a string
78 lua v = vim.eval('"abc"')
Bram Moolenaar02b31112019-08-31 22:16:38 +020079 call assert_equal('string', 'vim.type(v)'->luaeval())
Bram Moolenaar4ff48142018-06-30 21:50:25 +020080 call assert_equal('abc', luaeval('v'))
81
82 " lua.eval with a list
83 lua v = vim.eval("['a']")
84 call assert_equal('list', luaeval('vim.type(v)'))
85 call assert_equal(['a'], luaeval('v'))
86
87 " lua.eval with a dict
88 lua v = vim.eval("{'a':'b'}")
89 call assert_equal('dict', luaeval('vim.type(v)'))
90 call assert_equal({'a':'b'}, luaeval('v'))
91
Bram Moolenaarb7828692019-03-23 13:57:02 +010092 " lua.eval with a blob
93 lua v = vim.eval("0z00112233.deadbeef")
94 call assert_equal('blob', luaeval('vim.type(v)'))
95 call assert_equal(0z00112233.deadbeef, luaeval('v'))
96
Bram Moolenaare49b8e82020-07-01 13:52:55 +020097 " lua.eval with a float
98 lua v = vim.eval('3.14')
99 call assert_equal('number', luaeval('vim.type(v)'))
100 call assert_equal(3.14, luaeval('v'))
101
102 " lua.eval with a bool
103 lua v = vim.eval('v:true')
104 call assert_equal('number', luaeval('vim.type(v)'))
105 call assert_equal(1, luaeval('v'))
106 lua v = vim.eval('v:false')
107 call assert_equal('number', luaeval('vim.type(v)'))
108 call assert_equal(0, luaeval('v'))
109
110 " lua.eval with a null
111 lua v = vim.eval('v:null')
112 call assert_equal('nil', luaeval('vim.type(v)'))
113 call assert_equal(v:null, luaeval('v'))
114
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200115 call assert_fails('lua v = vim.eval(nil)',
116 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got nil)")
117 call assert_fails('lua v = vim.eval(true)',
118 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got boolean)")
119 call assert_fails('lua v = vim.eval({})',
120 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got table)")
121 call assert_fails('lua v = vim.eval(print)',
122 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got function)")
123 call assert_fails('lua v = vim.eval(vim.buffer())',
124 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got userdata)")
125
126 lua v = nil
127endfunc
128
Bram Moolenaar86c3a212021-03-08 19:50:24 +0100129" Test luaeval() with lambda
130func Test_luaeval_with_lambda()
131 lua function hello_luaeval_lambda(a, cb) return a .. cb() end
132 call assert_equal('helloworld',
133 \ luaeval('hello_luaeval_lambda(_A[1], _A[2])',
134 \ ['hello', {->'world'}]))
135 lua hello_luaeval_lambda = nil
136endfunc
137
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200138" Test vim.window()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100139func Test_lua_window()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200140 e Xfoo2
141 new Xfoo1
142
143 " Window 1 (top window) contains Xfoo1
144 " Window 2 (bottom window) contains Xfoo2
145 call assert_equal('Xfoo1', luaeval('vim.window(1):buffer().name'))
146 call assert_equal('Xfoo2', luaeval('vim.window(2):buffer().name'))
147
148 " Window 3 does not exist so vim.window(3) should return nil
149 call assert_equal('nil', luaeval('tostring(vim.window(3))'))
150
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000151 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200152 let msg = "[string \"luaeval\"]:1: field 'xyz' is not callable (a nil value)"
153 elseif s:lua_53_or_later
154 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (field 'xyz')"
155 else
156 let msg = "[string \"luaeval\"]:1: attempt to call field 'xyz' (a nil value)"
157 endif
158 call assert_fails("let n = luaeval('vim.window().xyz()')", msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200159 call assert_fails('lua vim.window().xyz = 1',
160 \ "[string \"vim chunk\"]:1: invalid window property: `xyz'")
161
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200162 %bwipe!
163endfunc
164
165" Test vim.window().height
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100166func Test_lua_window_height()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200167 new
168 lua vim.window().height = 2
169 call assert_equal(2, winheight(0))
170 lua vim.window().height = vim.window().height + 1
171 call assert_equal(3, winheight(0))
172 bwipe!
173endfunc
174
175" Test vim.window().width
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100176func Test_lua_window_width()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200177 vert new
178 lua vim.window().width = 2
179 call assert_equal(2, winwidth(0))
180 lua vim.window().width = vim.window().width + 1
181 call assert_equal(3, winwidth(0))
182 bwipe!
183endfunc
184
185" Test vim.window().line and vim.window.col
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100186func Test_lua_window_line_col()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200187 new
188 call setline(1, ['line1', 'line2', 'line3'])
189 lua vim.window().line = 2
190 lua vim.window().col = 4
191 call assert_equal([0, 2, 4, 0], getpos('.'))
192 lua vim.window().line = vim.window().line + 1
193 lua vim.window().col = vim.window().col - 1
194 call assert_equal([0, 3, 3, 0], getpos('.'))
195
196 call assert_fails('lua vim.window().line = 10',
197 \ '[string "vim chunk"]:1: line out of range')
198 bwipe!
199endfunc
200
Bram Moolenaareb04f082020-05-17 14:32:35 +0200201" Test vim.call
202func Test_lua_call()
203 call assert_equal(has('lua'), luaeval('vim.call("has", "lua")'))
204 call assert_equal(printf("Hello %s", "vim"), luaeval('vim.call("printf", "Hello %s", "vim")'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200205
206 " Error cases
207 call assert_fails("call luaeval('vim.call(\"min\", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)')",
Bram Moolenaarb898a022020-07-12 18:33:53 +0200208 \ s:lua_53_or_later
209 \ ? '[string "luaeval"]:1: Function called with too many arguments'
210 \ : 'Function called with too many arguments')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200211 lua co = coroutine.create(function () print("hi") end)
212 call assert_fails("call luaeval('vim.call(\"type\", co)')",
Bram Moolenaarb898a022020-07-12 18:33:53 +0200213 \ s:lua_53_or_later
214 \ ? '[string "luaeval"]:1: lua: cannot convert value'
215 \ : 'lua: cannot convert value')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200216 lua co = nil
Bram Moolenaarb898a022020-07-12 18:33:53 +0200217 call assert_fails("call luaeval('vim.call(\"abc\")')",
218 \ ['E117:', s:lua_53_or_later ? '\[string "luaeval"]:1: lua: call_vim_function failed'
219 \ : 'lua: call_vim_function failed'])
Bram Moolenaareb04f082020-05-17 14:32:35 +0200220endfunc
221
222" Test vim.fn.*
223func Test_lua_fn()
224 call assert_equal(has('lua'), luaeval('vim.fn.has("lua")'))
225 call assert_equal(printf("Hello %s", "vim"), luaeval('vim.fn.printf("Hello %s", "vim")'))
226endfunc
227
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200228" Test setting the current window
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100229func Test_lua_window_set_current()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200230 new Xfoo1
231 lua w1 = vim.window()
232 new Xfoo2
233 lua w2 = vim.window()
234
235 call assert_equal('Xfoo2', bufname('%'))
236 lua w1()
237 call assert_equal('Xfoo1', bufname('%'))
238 lua w2()
239 call assert_equal('Xfoo2', bufname('%'))
240
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200241 lua w1, w2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200242 %bwipe!
243endfunc
244
245" Test vim.window().buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100246func Test_lua_window_buffer()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200247 new Xfoo1
248 lua w1 = vim.window()
249 lua b1 = w1.buffer()
250 new Xfoo2
251 lua w2 = vim.window()
252 lua b2 = w2.buffer()
253
254 lua b1()
255 call assert_equal('Xfoo1', bufname('%'))
256 lua b2()
257 call assert_equal('Xfoo2', bufname('%'))
258
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200259 lua b1, b2, w1, w2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200260 %bwipe!
261endfunc
262
263" Test vim.window():previous() and vim.window():next()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100264func Test_lua_window_next_previous()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200265 new Xfoo1
266 new Xfoo2
267 new Xfoo3
268 wincmd j
269
270 call assert_equal('Xfoo2', luaeval('vim.window().buffer().name'))
271 call assert_equal('Xfoo1', luaeval('vim.window():next():buffer().name'))
272 call assert_equal('Xfoo3', luaeval('vim.window():previous():buffer().name'))
273
274 %bwipe!
275endfunc
276
277" Test vim.window():isvalid()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100278func Test_lua_window_isvalid()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200279 new Xfoo
280 lua w = vim.window()
281 call assert_true(luaeval('w:isvalid()'))
282
283 " FIXME: how to test the case when isvalid() returns v:false?
284 " isvalid() gives errors when the window is deleted. Is it a bug?
285
286 lua w = nil
287 bwipe!
288endfunc
289
290" Test vim.buffer() with and without argument
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100291func Test_lua_buffer()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200292 new Xfoo1
293 let bn1 = bufnr('%')
294 new Xfoo2
295 let bn2 = bufnr('%')
296
297 " Test vim.buffer() without argument.
298 call assert_equal('Xfoo2', luaeval("vim.buffer().name"))
299
300 " Test vim.buffer() with string argument.
301 call assert_equal('Xfoo1', luaeval("vim.buffer('Xfoo1').name"))
302 call assert_equal('Xfoo2', luaeval("vim.buffer('Xfoo2').name"))
303
304 " Test vim.buffer() with integer argument.
305 call assert_equal('Xfoo1', luaeval("vim.buffer(" . bn1 . ").name"))
306 call assert_equal('Xfoo2', luaeval("vim.buffer(" . bn2 . ").name"))
307
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200308 lua bn1, bn2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200309 %bwipe!
310endfunc
311
312" Test vim.buffer().name and vim.buffer().fname
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100313func Test_lua_buffer_name()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200314 new
Bram Moolenaarfe08df42018-07-07 23:07:41 +0200315 call assert_equal('', luaeval('vim.buffer().name'))
316 call assert_equal('', luaeval('vim.buffer().fname'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200317 bwipe!
318
319 new Xfoo
320 call assert_equal('Xfoo', luaeval('vim.buffer().name'))
321 call assert_equal(expand('%:p'), luaeval('vim.buffer().fname'))
322 bwipe!
323endfunc
324
325" Test vim.buffer().number
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100326func Test_lua_buffer_number()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200327 " All numbers in Lua are floating points number (no integers).
328 call assert_equal(bufnr('%'), float2nr(luaeval('vim.buffer().number')))
329endfunc
330
331" Test inserting lines in buffer.
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100332func Test_lua_buffer_insert()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200333 new
334 lua vim.buffer()[1] = '3'
335 lua vim.buffer():insert('1', 0)
336 lua vim.buffer():insert('2', 1)
337 lua vim.buffer():insert('4', 10)
338
339 call assert_equal(['1', '2', '3', '4'], getline(1, '$'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200340 call assert_equal('4', luaeval('vim.buffer()[4]'))
341 call assert_equal(v:null, luaeval('vim.buffer()[5]'))
342 call assert_equal(v:null, luaeval('vim.buffer()[{}]'))
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000343 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200344 let msg = "[string \"vim chunk\"]:1: method 'xyz' is not callable (a nil value)"
345 elseif s:lua_53_or_later
346 let msg = "[string \"vim chunk\"]:1: attempt to call a nil value (method 'xyz')"
347 else
348 let msg = "[string \"vim chunk\"]:1: attempt to call method 'xyz' (a nil value)"
349 endif
350 call assert_fails('lua vim.buffer():xyz()', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200351 call assert_fails('lua vim.buffer()[1] = {}',
352 \ '[string "vim chunk"]:1: wrong argument to change')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200353 bwipe!
354endfunc
355
356" Test deleting line in buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100357func Test_lua_buffer_delete()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200358 new
359 call setline(1, ['1', '2', '3'])
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200360 call cursor(3, 1)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200361 lua vim.buffer()[2] = nil
362 call assert_equal(['1', '3'], getline(1, '$'))
363
364 call assert_fails('lua vim.buffer()[3] = nil',
365 \ '[string "vim chunk"]:1: invalid line number')
366 bwipe!
367endfunc
368
369" Test #vim.buffer() i.e. number of lines in buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100370func Test_lua_buffer_number_lines()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200371 new
372 call setline(1, ['a', 'b', 'c'])
Bram Moolenaareb04f082020-05-17 14:32:35 +0200373 call assert_equal(3, luaeval('#vim.buffer()'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200374 bwipe!
375endfunc
376
377" Test vim.buffer():next() and vim.buffer():previous()
378" Note that these functions get the next or previous buffers
379" but do not switch buffer.
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100380func Test_lua_buffer_next_previous()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200381 new Xfoo1
382 new Xfoo2
383 new Xfoo3
384 b Xfoo2
385
386 lua bn = vim.buffer():next()
387 lua bp = vim.buffer():previous()
388
389 call assert_equal('Xfoo2', luaeval('vim.buffer().name'))
390 call assert_equal('Xfoo1', luaeval('bp.name'))
391 call assert_equal('Xfoo3', luaeval('bn.name'))
392
393 call assert_equal('Xfoo2', bufname('%'))
394
395 lua bn()
396 call assert_equal('Xfoo3', luaeval('vim.buffer().name'))
397 call assert_equal('Xfoo3', bufname('%'))
398
399 lua bp()
400 call assert_equal('Xfoo1', luaeval('vim.buffer().name'))
401 call assert_equal('Xfoo1', bufname('%'))
402
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200403 lua bn, bp = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200404 %bwipe!
405endfunc
406
407" Test vim.buffer():isvalid()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100408func Test_lua_buffer_isvalid()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200409 new Xfoo
410 lua b = vim.buffer()
411 call assert_true(luaeval('b:isvalid()'))
412
413 " FIXME: how to test the case when isvalid() returns v:false?
414 " isvalid() gives errors when the buffer is wiped. Is it a bug?
415
416 lua b = nil
417 bwipe!
418endfunc
419
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100420func Test_lua_list()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200421 call assert_equal([], luaeval('vim.list()'))
422
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200423 let l = []
424 lua l = vim.eval('l')
425 lua l:add(123)
426 lua l:add('abc')
427 lua l:add(true)
428 lua l:add(false)
Bram Moolenaar9067cd62019-01-01 00:41:54 +0100429 lua l:add(nil)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200430 lua l:add(vim.eval("[1, 2, 3]"))
431 lua l:add(vim.eval("{'a':1, 'b':2, 'c':3}"))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200432 call assert_equal([123, 'abc', v:true, v:false, v:null, [1, 2, 3], {'a': 1, 'b': 2, 'c': 3}], l)
433 call assert_equal(7, luaeval('#l'))
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200434 call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200435
Bram Moolenaarbd846172020-06-27 12:32:57 +0200436 lua l[1] = 124
437 lua l[6] = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200438 lua l:insert('first')
439 lua l:insert('xx', 3)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200440 call assert_fails('lua l:insert("xx", -20)',
441 \ '[string "vim chunk"]:1: invalid position')
Bram Moolenaareb04f082020-05-17 14:32:35 +0200442 call assert_equal(['first', 124, 'abc', 'xx', v:true, v:false, v:null, {'a': 1, 'b': 2, 'c': 3}], l)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200443
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200444 lockvar 1 l
445 call assert_fails('lua l:add("x")', '[string "vim chunk"]:1: list is locked')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200446 call assert_fails('lua l:insert(2)', '[string "vim chunk"]:1: list is locked')
447 call assert_fails('lua l[9] = 1', '[string "vim chunk"]:1: list is locked')
448
449 unlockvar l
450 let l = [1, 2]
451 lua ll = vim.eval('l')
452 let x = luaeval("ll[3]")
453 call assert_equal(v:null, x)
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000454 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200455 let msg = "[string \"luaeval\"]:1: method 'xyz' is not callable (a nil value)"
456 elseif s:lua_53_or_later
457 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
458 else
459 let msg = "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)"
460 endif
461 call assert_fails('let x = luaeval("ll:xyz(3)")', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200462 let y = luaeval("ll[{}]")
463 call assert_equal(v:null, y)
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200464
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200465 lua l = nil
466endfunc
467
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100468func Test_lua_list_table()
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200469 " See :help lua-vim
470 " Non-numeric keys should not be used to initialize the list
471 " so say = 'hi' should be ignored.
472 lua t = {3.14, 'hello', false, true, say = 'hi'}
473 call assert_equal([3.14, 'hello', v:false, v:true], luaeval('vim.list(t)'))
474 lua t = nil
475
476 call assert_fails('lua vim.list(1)', '[string "vim chunk"]:1: table expected, got number')
477 call assert_fails('lua vim.list("x")', '[string "vim chunk"]:1: table expected, got string')
478 call assert_fails('lua vim.list(print)', '[string "vim chunk"]:1: table expected, got function')
479 call assert_fails('lua vim.list(true)', '[string "vim chunk"]:1: table expected, got boolean')
480endfunc
481
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200482func Test_lua_list_table_insert_remove()
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200483 if !s:lua_53_or_later
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200484 throw 'Skipped: Lua version < 5.3'
485 endif
486
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200487 let l = [1, 2]
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200488 lua t = vim.eval('l')
489 lua table.insert(t, 10)
490 lua t[#t + 1] = 20
491 lua table.insert(t, 2, 30)
492 call assert_equal(l, [1, 30, 2, 10, 20])
493 lua table.remove(t, 2)
494 call assert_equal(l, [1, 2, 10, 20])
495 lua t[3] = nil
496 call assert_equal(l, [1, 2, 20])
497 lua removed_value = table.remove(t, 3)
498 call assert_equal(luaeval('removed_value'), 20)
499 lua t = nil
500 lua removed_value = nil
501 unlet l
502endfunc
503
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200504" Test l() i.e. iterator on list
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100505func Test_lua_list_iter()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200506 lua l = vim.list():add('foo'):add('bar')
507 lua str = ''
508 lua for v in l() do str = str .. v end
509 call assert_equal('foobar', luaeval('str'))
510
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200511 lua str, l = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200512endfunc
513
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100514func Test_lua_recursive_list()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200515 lua l = vim.list():add(1):add(2)
516 lua l = l:add(l)
517
Bram Moolenaarbd846172020-06-27 12:32:57 +0200518 call assert_equal(1, luaeval('l[1]'))
519 call assert_equal(2, luaeval('l[2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200520
Bram Moolenaarbd846172020-06-27 12:32:57 +0200521 call assert_equal(1, luaeval('l[3][1]'))
522 call assert_equal(2, luaeval('l[3][2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200523
Bram Moolenaarbd846172020-06-27 12:32:57 +0200524 call assert_equal(1, luaeval('l[3][3][1]'))
525 call assert_equal(2, luaeval('l[3][3][2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200526
Bram Moolenaareb04f082020-05-17 14:32:35 +0200527 call assert_equal('[1, 2, [...]]', string(luaeval('l')))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200528
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200529 call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
Bram Moolenaarbd846172020-06-27 12:32:57 +0200530 call assert_equal(luaeval('tostring(l)'), luaeval('tostring(l[3])'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200531
Bram Moolenaarbd846172020-06-27 12:32:57 +0200532 call assert_equal(luaeval('l'), luaeval('l[3]'))
533 call assert_equal(luaeval('l'), luaeval('l[3][3]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200534
535 lua l = nil
536endfunc
537
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100538func Test_lua_dict()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200539 call assert_equal({}, luaeval('vim.dict()'))
540
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200541 let d = {}
542 lua d = vim.eval('d')
543 lua d[0] = 123
544 lua d[1] = "abc"
545 lua d[2] = true
546 lua d[3] = false
547 lua d[4] = vim.eval("[1, 2, 3]")
548 lua d[5] = vim.eval("{'a':1, 'b':2, 'c':3}")
Bram Moolenaareb04f082020-05-17 14:32:35 +0200549 call assert_equal({'0':123, '1':'abc', '2':v:true, '3':v:false, '4': [1, 2, 3], '5': {'a':1, 'b':2, 'c':3}}, d)
550 call assert_equal(6, luaeval('#d'))
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200551 call assert_match('^dict: \%(0x\)\?\x\+$', luaeval('tostring(d)'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200552
553 call assert_equal('abc', luaeval('d[1]'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200554 call assert_equal(v:null, luaeval('d[22]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200555
556 lua d[0] = 124
557 lua d[4] = nil
Bram Moolenaareb04f082020-05-17 14:32:35 +0200558 call assert_equal({'0':124, '1':'abc', '2':v:true, '3':v:false, '5': {'a':1, 'b':2, 'c':3}}, d)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200559
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200560 lockvar 1 d
561 call assert_fails('lua d[6] = 1', '[string "vim chunk"]:1: dict is locked')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200562 unlockvar d
563
564 " Error case
565 lua d = {}
566 lua d[''] = 10
567 call assert_fails("let t = luaeval('vim.dict(d)')",
Bram Moolenaarb898a022020-07-12 18:33:53 +0200568 \ s:lua_53_or_later
569 \ ? '[string "luaeval"]:1: table has empty key'
570 \ : 'table has empty key')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200571 let d = {}
572 lua x = vim.eval('d')
573 call assert_fails("lua x[''] = 10", '[string "vim chunk"]:1: empty key')
574 lua x['a'] = nil
575 call assert_equal({}, d)
576
577 " cannot assign funcrefs in the global scope
578 lua x = vim.eval('g:')
579 call assert_fails("lua x['min'] = vim.funcref('max')",
580 \ '[string "vim chunk"]:1: cannot assign funcref to builtin scope')
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200581
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200582 lua d = nil
583endfunc
584
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100585func Test_lua_dict_table()
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200586 lua t = {key1 = 'x', key2 = 3.14, key3 = true, key4 = false}
587 call assert_equal({'key1': 'x', 'key2': 3.14, 'key3': v:true, 'key4': v:false},
588 \ luaeval('vim.dict(t)'))
589
590 " Same example as in :help lua-vim.
591 lua t = {math.pi, false, say = 'hi'}
592 " FIXME: commented out as it currently does not work as documented:
593 " Expected {'say': 'hi'}
594 " but got {'1': 3.141593, '2': v:false, 'say': 'hi'}
595 " Is the documentation or the code wrong?
596 "call assert_equal({'say' : 'hi'}, luaeval('vim.dict(t)'))
597 lua t = nil
598
599 call assert_fails('lua vim.dict(1)', '[string "vim chunk"]:1: table expected, got number')
600 call assert_fails('lua vim.dict("x")', '[string "vim chunk"]:1: table expected, got string')
601 call assert_fails('lua vim.dict(print)', '[string "vim chunk"]:1: table expected, got function')
602 call assert_fails('lua vim.dict(true)', '[string "vim chunk"]:1: table expected, got boolean')
603endfunc
604
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200605" Test d() i.e. iterator on dictionary
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100606func Test_lua_dict_iter()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200607 let d = {'a': 1, 'b':2}
608 lua d = vim.eval('d')
609 lua str = ''
610 lua for k,v in d() do str = str .. k ..':' .. v .. ',' end
611 call assert_equal('a:1,b:2,', luaeval('str'))
612
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200613 lua str, d = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200614endfunc
615
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100616func Test_lua_blob()
Bram Moolenaarb7828692019-03-23 13:57:02 +0100617 call assert_equal(0z, luaeval('vim.blob("")'))
618 call assert_equal(0z31326162, luaeval('vim.blob("12ab")'))
Christian Brabandt6efb1982023-08-10 05:44:25 +0200619 call assert_equal(0z00010203, luaeval('vim.blob("\000\001\002\003")'))
620 call assert_equal(0z8081FEFF, luaeval('vim.blob("\128\129\254\255")'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100621
Christian Brabandt6efb1982023-08-10 05:44:25 +0200622 lua b = vim.blob("\000\000\000\000")
Bram Moolenaarb7828692019-03-23 13:57:02 +0100623 call assert_equal(0z00000000, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200624 call assert_equal(4, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100625 lua b[0], b[1], b[2], b[3] = 1, 32, 256, 0xff
626 call assert_equal(0z012000ff, luaeval('b'))
627 lua b[4] = string.byte("z", 1)
628 call assert_equal(0z012000ff.7a, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200629 call assert_equal(5, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100630 call assert_fails('lua b[#b+1] = 0x80', '[string "vim chunk"]:1: index out of range')
631 lua b:add("12ab")
632 call assert_equal(0z012000ff.7a313261.62, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200633 call assert_equal(9, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100634 call assert_fails('lua b:add(nil)', '[string "vim chunk"]:1: string expected, got nil')
635 call assert_fails('lua b:add(true)', '[string "vim chunk"]:1: string expected, got boolean')
636 call assert_fails('lua b:add({})', '[string "vim chunk"]:1: string expected, got table')
637 lua b = nil
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200638
639 let b = 0z0102
640 lua lb = vim.eval('b')
641 let n = luaeval('lb[1]')
642 call assert_equal(2, n)
643 let n = luaeval('lb[6]')
644 call assert_equal(v:null, n)
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000645 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200646 let msg = "[string \"luaeval\"]:1: method 'xyz' is not callable (a nil value)"
647 elseif s:lua_53_or_later
648 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
649 else
650 let msg = "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)"
651 endif
652 call assert_fails('let x = luaeval("lb:xyz(3)")', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200653 let y = luaeval("lb[{}]")
654 call assert_equal(v:null, y)
655
656 lockvar b
657 call assert_fails('lua lb[1] = 2', '[string "vim chunk"]:1: blob is locked')
658 call assert_fails('lua lb:add("12")', '[string "vim chunk"]:1: blob is locked')
659
660 " Error cases
661 lua t = {}
662 call assert_fails('lua b = vim.blob(t)',
663 \ '[string "vim chunk"]:1: string expected, got table')
Bram Moolenaarb7828692019-03-23 13:57:02 +0100664endfunc
665
Bram Moolenaar7d149f82022-06-17 19:23:34 +0100666def Vim9Test(Callback: func())
667 Callback()
668enddef
669
670func Test_call_lua_func_from_vim9_func()
671 " this only tests that Vim doesn't crash
672 lua << EOF
673vim.fn.Vim9Test(function () print('Hello') end)
674EOF
675endfunc
676
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100677func Test_lua_funcref()
Bram Moolenaarca06da92018-07-01 15:12:05 +0200678 function I(x)
679 return a:x
680 endfunction
681 let R = function('I')
682 lua i1 = vim.funcref"I"
683 lua i2 = vim.eval"R"
684 lua msg = "funcref|test|" .. (#i2(i1) == #i1(i2) and "OK" or "FAIL")
685 lua msg = vim.funcref"tr"(msg, "|", " ")
686 call assert_equal("funcref test OK", luaeval('msg'))
687
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200688 " Error cases
689 call assert_fails('lua f1 = vim.funcref("")',
690 \ '[string "vim chunk"]:1: invalid function name: ')
691 call assert_fails('lua f1 = vim.funcref("10")',
692 \ '[string "vim chunk"]:1: invalid function name: 10')
693 let fname = test_null_string()
694 call assert_fails('lua f1 = vim.funcref(fname)',
695 \ "[string \"vim chunk\"]:1: bad argument #1 to 'funcref' (string expected, got nil)")
696 call assert_fails('lua vim.funcref("abc")()',
Bram Moolenaarecdd14a2020-07-11 22:49:59 +0200697 \ ['E117:', '\[string "vim chunk"]:1: cannot call funcref'])
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200698
Bram Moolenaarca06da92018-07-01 15:12:05 +0200699 " dict funcref
700 function Mylen() dict
701 return len(self.data)
702 endfunction
703 let l = [0, 1, 2, 3]
704 let mydict = {'data': l}
705 lua d = vim.eval"mydict"
706 lua d.len = vim.funcref"Mylen" -- assign d as 'self'
707 lua res = (d.len() == vim.funcref"len"(vim.eval"l")) and "OK" or "FAIL"
708 call assert_equal("OK", luaeval('res'))
Bram Moolenaar4eefe472019-03-19 21:59:19 +0100709 call assert_equal(function('Mylen', {'data': l, 'len': function('Mylen')}), mydict.len)
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200710
711 lua i1, i2, msg, d, res = nil
Bram Moolenaarca06da92018-07-01 15:12:05 +0200712endfunc
713
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200714" Test vim.type()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100715func Test_lua_type()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200716 " The following values are identical to Lua's type function.
717 call assert_equal('string', luaeval('vim.type("foo")'))
718 call assert_equal('number', luaeval('vim.type(1)'))
719 call assert_equal('number', luaeval('vim.type(1.2)'))
720 call assert_equal('function', luaeval('vim.type(print)'))
721 call assert_equal('table', luaeval('vim.type({})'))
722 call assert_equal('boolean', luaeval('vim.type(true)'))
723 call assert_equal('boolean', luaeval('vim.type(false)'))
724 call assert_equal('nil', luaeval('vim.type(nil)'))
725
726 " The following values are specific to Vim.
727 call assert_equal('window', luaeval('vim.type(vim.window())'))
728 call assert_equal('buffer', luaeval('vim.type(vim.buffer())'))
729 call assert_equal('list', luaeval('vim.type(vim.list())'))
730 call assert_equal('dict', luaeval('vim.type(vim.dict())'))
Bram Moolenaarca06da92018-07-01 15:12:05 +0200731 call assert_equal('funcref', luaeval('vim.type(vim.funcref("Test_type"))'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200732endfunc
733
734" Test vim.open()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100735func Test_lua_open()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200736 call assert_notmatch('XOpen', execute('ls'))
737
738 " Open a buffer XOpen1, but do not jump to it.
739 lua b = vim.open('XOpen1')
740 call assert_equal('XOpen1', luaeval('b.name'))
741 call assert_equal('', bufname('%'))
742
743 call assert_match('XOpen1', execute('ls'))
744 call assert_notequal('XOpen2', bufname('%'))
745
746 " Open a buffer XOpen2 and jump to it.
747 lua b = vim.open('XOpen2')()
748 call assert_equal('XOpen2', luaeval('b.name'))
749 call assert_equal('XOpen2', bufname('%'))
750
751 lua b = nil
752 %bwipe!
753endfunc
754
Bram Moolenaar788fbb42020-05-31 14:08:12 +0200755func Test_update_package_paths()
756 set runtimepath+=./testluaplugin
757 call assert_equal("hello from lua", luaeval("require('testluaplugin').hello()"))
758endfunc
759
Bram Moolenaar801ab062020-06-25 19:27:56 +0200760func Vim_func_call_lua_callback(Concat, Cb)
761 let l:message = a:Concat("hello", "vim")
762 call a:Cb(l:message)
763endfunc
764
765func Test_pass_lua_callback_to_vim_from_lua()
766 lua pass_lua_callback_to_vim_from_lua_result = ""
767 call assert_equal("", luaeval("pass_lua_callback_to_vim_from_lua_result"))
768 lua <<EOF
769 vim.funcref('Vim_func_call_lua_callback')(
770 function(greeting, message)
771 return greeting .. " " .. message
772 end,
773 function(message)
774 pass_lua_callback_to_vim_from_lua_result = message
775 end)
776EOF
777 call assert_equal("hello vim", luaeval("pass_lua_callback_to_vim_from_lua_result"))
778endfunc
779
780func Vim_func_call_metatable_lua_callback(Greet)
781 return a:Greet("world")
782endfunc
783
784func Test_pass_lua_metatable_callback_to_vim_from_lua()
785 let result = luaeval("vim.funcref('Vim_func_call_metatable_lua_callback')(setmetatable({ space = ' '}, { __call = function(tbl, msg) return 'hello' .. tbl.space .. msg end }) )")
786 call assert_equal("hello world", result)
787endfunc
788
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200789" Test vim.line()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100790func Test_lua_line()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200791 new
792 call setline(1, ['first line', 'second line'])
793 1
794 call assert_equal('first line', luaeval('vim.line()'))
795 2
796 call assert_equal('second line', luaeval('vim.line()'))
797 bwipe!
798endfunc
799
800" Test vim.beep()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100801func Test_lua_beep()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200802 call assert_beeps('lua vim.beep()')
803endfunc
804
805" Test errors in luaeval()
806func Test_luaeval_error()
807 " Compile error
808 call assert_fails("call luaeval('-nil')",
809 \ '[string "luaeval"]:1: attempt to perform arithmetic on a nil value')
810 call assert_fails("call luaeval(']')",
811 \ "[string \"luaeval\"]:1: unexpected symbol near ']'")
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200812 lua co = coroutine.create(function () print("hi") end)
813 call assert_fails('let i = luaeval("co")', 'luaeval: cannot convert value')
814 lua co = nil
815 call assert_fails('let m = luaeval("{}")', 'luaeval: cannot convert value')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200816endfunc
817
818" Test :luafile foo.lua
819func Test_luafile()
Bram Moolenaar7dd5a782022-09-29 21:01:57 +0100820 call writefile(["str = 'hello'", "num = 123" ], 'Xlua_file', 'D')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200821 call setfperm('Xlua_file', 'r-xr-xr-x')
822
823 luafile Xlua_file
824 call assert_equal('hello', luaeval('str'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200825 call assert_equal(123, luaeval('num'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200826
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200827 lua str, num = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200828endfunc
829
830" Test :luafile %
831func Test_luafile_percent()
832 new Xlua_file
833 append
834 str, num = 'foo', 321.0
835 print(string.format('str=%s, num=%d', str, num))
836.
837 w!
838 luafile %
839 let msg = split(execute('message'), "\n")[-1]
840 call assert_equal('str=foo, num=321', msg)
841
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200842 lua str, num = nil
843 call delete('Xlua_file')
844 bwipe!
845endfunc
846
847" Test :luafile with syntax error
848func Test_luafile_error()
849 new Xlua_file
Bram Moolenaar7dd5a782022-09-29 21:01:57 +0100850 call writefile(['nil = 0' ], 'Xlua_file', 'D')
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200851 call setfperm('Xlua_file', 'r-xr-xr-x')
852
853 call assert_fails('luafile Xlua_file', "Xlua_file:1: unexpected symbol near 'nil'")
854
Bram Moolenaard58f03b2017-01-29 22:48:45 +0100855 bwipe!
856endfunc
Bram Moolenaar53901442018-07-25 22:02:36 +0200857
Bram Moolenaar78e006b2021-07-28 15:07:01 +0200858" Test :luafile printing a long string
859func Test_luafile_print()
860 new Xlua_file
861 let lines =<< trim END
862 local data = ''
863 for i = 1, 130 do
864 data = data .. 'xxxxx asd as as dad sad sad xz cxz czxcxzczxc ad ad asd asd asd asd asd'
865 end
866 print(data)
867 END
868 call setline(1, lines)
869 w
870 luafile %
871
872 call delete('Xlua_file')
873 bwipe!
874endfunc
875
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200876" Test for dealing with strings containing newlines and null character
877func Test_lua_string_with_newline()
Bram Moolenaar2a4bd002021-07-28 21:48:59 +0200878 let x = execute('lua print("Hello\nWorld", 2)')
879 call assert_equal("\nHello\nWorld 2", x)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200880 new
881 lua k = vim.buffer(vim.eval('bufnr()'))
882 lua k:insert("Hello\0World", 0)
883 call assert_equal(["Hello\nWorld", ''], getline(1, '$'))
884 close!
885endfunc
886
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100887func Test_lua_set_cursor()
Bram Moolenaar53901442018-07-25 22:02:36 +0200888 " Check that setting the cursor position works.
889 new
890 call setline(1, ['first line', 'second line'])
891 normal gg
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200892 lua << trim EOF
893 w = vim.window()
894 w.line = 1
895 w.col = 5
896 EOF
Bram Moolenaar53901442018-07-25 22:02:36 +0200897 call assert_equal([1, 5], [line('.'), col('.')])
898
899 " Check that movement after setting cursor position keeps current column.
900 normal j
901 call assert_equal([2, 5], [line('.'), col('.')])
902endfunc
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200903
904" Test for various heredoc syntax
905func Test_lua_heredoc()
906 lua << END
907vim.command('let s = "A"')
908END
909 lua <<
910vim.command('let s ..= "B"')
911.
912 lua << trim END
913 vim.command('let s ..= "C"')
914 END
915 lua << trim
916 vim.command('let s ..= "D"')
917 .
Bram Moolenaar6ab09532020-05-01 14:10:13 +0200918 lua << trim eof
919 vim.command('let s ..= "E"')
920 eof
921 call assert_equal('ABCDE', s)
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200922endfunc
923
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +0200924" Test for adding, accessing and removing global variables using the vim.g
925" Lua table
926func Test_lua_global_var_table()
927 " Access global variables with different types of values
928 let g:Var1 = 10
929 let g:Var2 = 'Hello'
930 let g:Var3 = ['a', 'b']
931 let g:Var4 = #{x: 'edit', y: 'run'}
932 let g:Var5 = function('min')
933 call assert_equal(10, luaeval('vim.g.Var1'))
934 call assert_equal('Hello', luaeval('vim.g.Var2'))
935 call assert_equal(['a', 'b'], luaeval('vim.g.Var3'))
936 call assert_equal(#{x: 'edit', y: 'run'}, luaeval('vim.g.Var4'))
937 call assert_equal(2, luaeval('vim.g.Var5')([5, 9, 2]))
938
939 " Access list of dictionaries and dictionary of lists
940 let g:Var1 = [#{a: 10}, #{b: 20}]
941 let g:Var2 = #{p: [5, 6], q: [1.1, 2.2]}
942 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
943 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
944
945 " Create new global variables with different types of values
946 unlet g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
947 lua << trim END
948 vim.g.Var1 = 34
949 vim.g.Var2 = 'World'
950 vim.g.Var3 = vim.list({'#', '$'})
951 vim.g.Var4 = vim.dict({model='honda', year=2020})
952 vim.g.Var5 = vim.funcref('max')
953 END
954 call assert_equal(34, g:Var1)
955 call assert_equal('World', g:Var2)
956 call assert_equal(['#', '$'], g:Var3)
957 call assert_equal(#{model: 'honda', year: 2020}, g:Var4)
958 call assert_equal(10, g:Var5([5, 10, 9]))
959
960 " Create list of dictionaries and dictionary of lists
961 unlet g:Var1 g:Var2
962 lua << trim END
963 vim.g.Var1 = vim.list({vim.dict({a=10}), vim.dict({b=20})})
964 vim.g.Var2 = vim.dict({p=vim.list({5, 6}), q=vim.list({1.1, 2.2})})
965 END
966 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
967 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
968
969 " Modify a global variable with a list value or a dictionary value
970 let g:Var1 = [10, 20]
971 let g:Var2 = #{one: 'mercury', two: 'mars'}
972 lua << trim END
973 vim.g.Var1[2] = Nil
974 vim.g.Var1[3] = 15
975 vim.g.Var2['two'] = Nil
976 vim.g.Var2['three'] = 'earth'
977 END
978 call assert_equal([10, 15], g:Var1)
979 call assert_equal(#{one: 'mercury', three: 'earth'}, g:Var2)
980
981 " Remove global variables with different types of values
982 let g:Var1 = 10
983 let g:Var2 = 'Hello'
984 let g:Var3 = ['a', 'b']
985 let g:Var4 = #{x: 'edit', y: 'run'}
986 let g:Var5 = function('min')
987 lua << trim END
988 vim.g.Var1 = Nil
989 vim.g.Var2 = Nil
990 vim.g.Var3 = Nil
991 vim.g.Var4 = Nil
992 vim.g.Var5 = Nil
993 END
994 call assert_false(exists('g:Var1'))
995 call assert_false(exists('g:Var2'))
996 call assert_false(exists('g:Var3'))
997 call assert_false(exists('g:Var4'))
998 call assert_false(exists('g:Var5'))
999
1000 " Try to modify and remove a locked global variable
1001 let g:Var1 = 10
1002 lockvar g:Var1
1003 call assert_fails('lua vim.g.Var1 = 20', 'variable is locked')
1004 call assert_fails('lua vim.g.Var1 = Nil', 'variable is locked')
1005 unlockvar g:Var1
1006 let g:Var2 = [7, 14]
1007 lockvar 0 g:Var2
1008 lua vim.g.Var2[2] = Nil
1009 lua vim.g.Var2[3] = 21
1010 call assert_fails('lua vim.g.Var2 = Nil', 'variable is locked')
1011 call assert_equal([7, 21], g:Var2)
1012 lockvar 1 g:Var2
1013 call assert_fails('lua vim.g.Var2[2] = Nil', 'list is locked')
1014 call assert_fails('lua vim.g.Var2[3] = 21', 'list is locked')
1015 unlockvar g:Var2
1016
Bram Moolenaar4a011592021-08-05 15:11:08 +02001017 let g:TestFunc = function('len')
1018 call assert_fails('lua vim.g.func = vim.g.TestFunc', ['E704:', 'Couldn''t add to dictionary'])
1019 unlet g:TestFunc
1020
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +02001021 " Attempt to access a non-existing global variable
1022 call assert_equal(v:null, luaeval('vim.g.NonExistingVar'))
1023 lua vim.g.NonExisting = Nil
1024
1025 unlet! g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
1026endfunc
1027
1028" Test for accessing and modifying predefined vim variables using the vim.v
1029" Lua table
1030func Test_lua_predefined_var_table()
1031 call assert_equal(v:progpath, luaeval('vim.v.progpath'))
1032 let v:errmsg = 'SomeError'
1033 call assert_equal('SomeError', luaeval('vim.v.errmsg'))
1034 lua vim.v.errmsg = 'OtherError'
1035 call assert_equal('OtherError', v:errmsg)
1036 call assert_fails('lua vim.v.errmsg = Nil', 'variable is fixed')
1037 let v:oldfiles = ['one', 'two']
1038 call assert_equal(['one', 'two'], luaeval('vim.v.oldfiles'))
1039 lua vim.v.oldfiles = vim.list({})
1040 call assert_equal([], v:oldfiles)
1041 call assert_equal(v:null, luaeval('vim.v.null'))
1042 call assert_fails('lua vim.v.argv[1] = Nil', 'list is locked')
1043 call assert_fails('lua vim.v.newvar = 1', 'Dictionary is locked')
1044endfunc
1045
1046" Test for adding, accessing and modifying window-local variables using the
1047" vim.w Lua table
1048func Test_lua_window_var_table()
1049 " Access window variables with different types of values
1050 new
1051 let w:wvar1 = 10
1052 let w:wvar2 = 'edit'
1053 let w:wvar3 = 3.14
1054 let w:wvar4 = 0zdeadbeef
1055 let w:wvar5 = ['a', 'b']
1056 let w:wvar6 = #{action: 'run'}
1057 call assert_equal(10, luaeval('vim.w.wvar1'))
1058 call assert_equal('edit', luaeval('vim.w.wvar2'))
1059 call assert_equal(3.14, luaeval('vim.w.wvar3'))
1060 call assert_equal(0zdeadbeef, luaeval('vim.w.wvar4'))
1061 call assert_equal(['a', 'b'], luaeval('vim.w.wvar5'))
1062 call assert_equal(#{action: 'run'}, luaeval('vim.w.wvar6'))
1063 call assert_equal(v:null, luaeval('vim.w.NonExisting'))
1064
1065 " modify a window variable
1066 lua vim.w.wvar2 = 'paste'
1067 call assert_equal('paste', w:wvar2)
1068
1069 " change the type stored in a variable
1070 let w:wvar2 = [1, 2]
1071 lua vim.w.wvar2 = vim.dict({a=10, b=20})
1072 call assert_equal(#{a: 10, b: 20}, w:wvar2)
1073
1074 " create a new window variable
1075 lua vim.w.wvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1076 call assert_equal(#{a: [1, 2], b: 20}, w:wvar7)
1077
1078 " delete a window variable
1079 lua vim.w.wvar2 = Nil
1080 call assert_false(exists('w:wvar2'))
1081
1082 new
1083 call assert_equal(v:null, luaeval('vim.w.wvar1'))
1084 call assert_equal(v:null, luaeval('vim.w.wvar2'))
1085 %bw!
1086endfunc
1087
1088" Test for adding, accessing and modifying buffer-local variables using the
1089" vim.b Lua table
1090func Test_lua_buffer_var_table()
1091 " Access buffer variables with different types of values
1092 let b:bvar1 = 10
1093 let b:bvar2 = 'edit'
1094 let b:bvar3 = 3.14
1095 let b:bvar4 = 0zdeadbeef
1096 let b:bvar5 = ['a', 'b']
1097 let b:bvar6 = #{action: 'run'}
1098 call assert_equal(10, luaeval('vim.b.bvar1'))
1099 call assert_equal('edit', luaeval('vim.b.bvar2'))
1100 call assert_equal(3.14, luaeval('vim.b.bvar3'))
1101 call assert_equal(0zdeadbeef, luaeval('vim.b.bvar4'))
1102 call assert_equal(['a', 'b'], luaeval('vim.b.bvar5'))
1103 call assert_equal(#{action: 'run'}, luaeval('vim.b.bvar6'))
1104 call assert_equal(v:null, luaeval('vim.b.NonExisting'))
1105
1106 " modify a buffer variable
1107 lua vim.b.bvar2 = 'paste'
1108 call assert_equal('paste', b:bvar2)
1109
1110 " change the type stored in a variable
1111 let b:bvar2 = [1, 2]
1112 lua vim.b.bvar2 = vim.dict({a=10, b=20})
1113 call assert_equal(#{a: 10, b: 20}, b:bvar2)
1114
1115 " create a new buffer variable
1116 lua vim.b.bvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1117 call assert_equal(#{a: [1, 2], b: 20}, b:bvar7)
1118
1119 " delete a buffer variable
1120 lua vim.b.bvar2 = Nil
1121 call assert_false(exists('b:bvar2'))
1122
1123 new
1124 call assert_equal(v:null, luaeval('vim.b.bvar1'))
1125 call assert_equal(v:null, luaeval('vim.b.bvar2'))
1126 %bw!
1127endfunc
1128
1129" Test for adding, accessing and modifying tabpage-local variables using the
1130" vim.t Lua table
1131func Test_lua_tabpage_var_table()
1132 " Access tabpage variables with different types of values
1133 let t:tvar1 = 10
1134 let t:tvar2 = 'edit'
1135 let t:tvar3 = 3.14
1136 let t:tvar4 = 0zdeadbeef
1137 let t:tvar5 = ['a', 'b']
1138 let t:tvar6 = #{action: 'run'}
1139 call assert_equal(10, luaeval('vim.t.tvar1'))
1140 call assert_equal('edit', luaeval('vim.t.tvar2'))
1141 call assert_equal(3.14, luaeval('vim.t.tvar3'))
1142 call assert_equal(0zdeadbeef, luaeval('vim.t.tvar4'))
1143 call assert_equal(['a', 'b'], luaeval('vim.t.tvar5'))
1144 call assert_equal(#{action: 'run'}, luaeval('vim.t.tvar6'))
1145 call assert_equal(v:null, luaeval('vim.t.NonExisting'))
1146
1147 " modify a tabpage variable
1148 lua vim.t.tvar2 = 'paste'
1149 call assert_equal('paste', t:tvar2)
1150
1151 " change the type stored in a variable
1152 let t:tvar2 = [1, 2]
1153 lua vim.t.tvar2 = vim.dict({a=10, b=20})
1154 call assert_equal(#{a: 10, b: 20}, t:tvar2)
1155
1156 " create a new tabpage variable
1157 lua vim.t.tvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1158 call assert_equal(#{a: [1, 2], b: 20}, t:tvar7)
1159
1160 " delete a tabpage variable
1161 lua vim.t.tvar2 = Nil
1162 call assert_false(exists('t:tvar2'))
1163
1164 tabnew
1165 call assert_equal(v:null, luaeval('vim.t.tvar1'))
1166 call assert_equal(v:null, luaeval('vim.t.tvar2'))
1167 %bw!
1168endfunc
1169
Yegappan Lakshmanan11328bc2021-08-06 21:34:38 +02001170" Test for vim.version()
1171func Test_lua_vim_version()
1172 lua << trim END
1173 vimver = vim.version()
1174 vimver_n = vimver.major * 100 + vimver.minor
1175 END
1176 call assert_equal(v:version, luaeval('vimver_n'))
1177endfunc
1178
1179" Test for running multiple commands using vim.command()
1180func Test_lua_multiple_commands()
1181 lua << trim END
1182 vim.command([[
1183 let Var1 = []
1184 for i in range(3)
1185 let Var1 += [#{name: 'x'}]
1186 endfor
1187 augroup Luagroup
1188 autocmd!
1189 autocmd User Luatest echo 'Hello'
1190 augroup END
1191 ]])
1192 END
1193 call assert_equal([{'name': 'x'}, {'name': 'x'}, {'name': 'x'}], Var1)
1194 call assert_true(exists('#Luagroup'))
1195 call assert_true(exists('#Luagroup#User#Luatest'))
1196 augroup Luagroup
1197 autocmd!
1198 augroup END
1199 augroup! Luagroup
1200endfunc
1201
Dominique Pelleb6643d12022-03-20 11:46:01 +00001202func Test_lua_debug()
1203 CheckRunVimInTerminal
1204
1205 let buf = RunVimInTerminal('', {'rows': 10})
1206 call term_sendkeys(buf, ":lua debug.debug()\n")
1207 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1208
1209 call term_sendkeys(buf, "foo = 42\n")
1210 call WaitForAssert({-> assert_equal('lua_debug> foo = 42', term_getline(buf, 9))})
1211 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1212
1213 call term_sendkeys(buf, "print(foo)\n")
1214 call WaitForAssert({-> assert_equal('lua_debug> print(foo)', term_getline(buf, 8))})
1215 call WaitForAssert({-> assert_equal('42', term_getline(buf, 9))})
1216 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1217
Dominique Pelle81b573d2022-03-22 21:14:55 +00001218 call term_sendkeys(buf, "-\n")
1219 call WaitForAssert({-> assert_equal("(debug command):1: unexpected symbol near '-'",
1220 \ term_getline(buf, 9))})
1221 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1222
Dominique Pelleb6643d12022-03-20 11:46:01 +00001223 call term_sendkeys(buf, "cont\n")
1224 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1225
Dominique Pelle81b573d2022-03-22 21:14:55 +00001226 " Entering an empty line also exits the debugger.
1227 call term_sendkeys(buf, ":lua debug.debug()\n")
1228 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1229 call term_sendkeys(buf, "\n")
1230 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1231
Dominique Pelleb6643d12022-03-20 11:46:01 +00001232 call StopVimInTerminal(buf)
Dominique Pelleb6643d12022-03-20 11:46:01 +00001233endfunc
1234
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02001235" vim: shiftwidth=2 sts=2 expandtab