blob: 2a08607ff1fe213c6b6a446d20e30e192a45e756 [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")'))
619 call assert_equal(0z00010203, luaeval('vim.blob("\x00\x01\x02\x03")'))
620 call assert_equal(0z8081FEFF, luaeval('vim.blob("\x80\x81\xfe\xff")'))
621
622 lua b = vim.blob("\x00\x00\x00\x00")
623 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()
820 call delete('Xlua_file')
Bram Moolenaareb04f082020-05-17 14:32:35 +0200821 call writefile(["str = 'hello'", "num = 123" ], 'Xlua_file')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200822 call setfperm('Xlua_file', 'r-xr-xr-x')
823
824 luafile Xlua_file
825 call assert_equal('hello', luaeval('str'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200826 call assert_equal(123, luaeval('num'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200827
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200828 lua str, num = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200829 call delete('Xlua_file')
830endfunc
831
832" Test :luafile %
833func Test_luafile_percent()
834 new Xlua_file
835 append
836 str, num = 'foo', 321.0
837 print(string.format('str=%s, num=%d', str, num))
838.
839 w!
840 luafile %
841 let msg = split(execute('message'), "\n")[-1]
842 call assert_equal('str=foo, num=321', msg)
843
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200844 lua str, num = nil
845 call delete('Xlua_file')
846 bwipe!
847endfunc
848
849" Test :luafile with syntax error
850func Test_luafile_error()
851 new Xlua_file
852 call writefile(['nil = 0' ], 'Xlua_file')
853 call setfperm('Xlua_file', 'r-xr-xr-x')
854
855 call assert_fails('luafile Xlua_file', "Xlua_file:1: unexpected symbol near 'nil'")
856
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200857 call delete('Xlua_file')
Bram Moolenaard58f03b2017-01-29 22:48:45 +0100858 bwipe!
859endfunc
Bram Moolenaar53901442018-07-25 22:02:36 +0200860
Bram Moolenaar78e006b2021-07-28 15:07:01 +0200861" Test :luafile printing a long string
862func Test_luafile_print()
863 new Xlua_file
864 let lines =<< trim END
865 local data = ''
866 for i = 1, 130 do
867 data = data .. 'xxxxx asd as as dad sad sad xz cxz czxcxzczxc ad ad asd asd asd asd asd'
868 end
869 print(data)
870 END
871 call setline(1, lines)
872 w
873 luafile %
874
875 call delete('Xlua_file')
876 bwipe!
877endfunc
878
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200879" Test for dealing with strings containing newlines and null character
880func Test_lua_string_with_newline()
Bram Moolenaar2a4bd002021-07-28 21:48:59 +0200881 let x = execute('lua print("Hello\nWorld", 2)')
882 call assert_equal("\nHello\nWorld 2", x)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200883 new
884 lua k = vim.buffer(vim.eval('bufnr()'))
885 lua k:insert("Hello\0World", 0)
886 call assert_equal(["Hello\nWorld", ''], getline(1, '$'))
887 close!
888endfunc
889
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100890func Test_lua_set_cursor()
Bram Moolenaar53901442018-07-25 22:02:36 +0200891 " Check that setting the cursor position works.
892 new
893 call setline(1, ['first line', 'second line'])
894 normal gg
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200895 lua << trim EOF
896 w = vim.window()
897 w.line = 1
898 w.col = 5
899 EOF
Bram Moolenaar53901442018-07-25 22:02:36 +0200900 call assert_equal([1, 5], [line('.'), col('.')])
901
902 " Check that movement after setting cursor position keeps current column.
903 normal j
904 call assert_equal([2, 5], [line('.'), col('.')])
905endfunc
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200906
907" Test for various heredoc syntax
908func Test_lua_heredoc()
909 lua << END
910vim.command('let s = "A"')
911END
912 lua <<
913vim.command('let s ..= "B"')
914.
915 lua << trim END
916 vim.command('let s ..= "C"')
917 END
918 lua << trim
919 vim.command('let s ..= "D"')
920 .
Bram Moolenaar6ab09532020-05-01 14:10:13 +0200921 lua << trim eof
922 vim.command('let s ..= "E"')
923 eof
924 call assert_equal('ABCDE', s)
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200925endfunc
926
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +0200927" Test for adding, accessing and removing global variables using the vim.g
928" Lua table
929func Test_lua_global_var_table()
930 " Access global variables with different types of values
931 let g:Var1 = 10
932 let g:Var2 = 'Hello'
933 let g:Var3 = ['a', 'b']
934 let g:Var4 = #{x: 'edit', y: 'run'}
935 let g:Var5 = function('min')
936 call assert_equal(10, luaeval('vim.g.Var1'))
937 call assert_equal('Hello', luaeval('vim.g.Var2'))
938 call assert_equal(['a', 'b'], luaeval('vim.g.Var3'))
939 call assert_equal(#{x: 'edit', y: 'run'}, luaeval('vim.g.Var4'))
940 call assert_equal(2, luaeval('vim.g.Var5')([5, 9, 2]))
941
942 " Access list of dictionaries and dictionary of lists
943 let g:Var1 = [#{a: 10}, #{b: 20}]
944 let g:Var2 = #{p: [5, 6], q: [1.1, 2.2]}
945 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
946 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
947
948 " Create new global variables with different types of values
949 unlet g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
950 lua << trim END
951 vim.g.Var1 = 34
952 vim.g.Var2 = 'World'
953 vim.g.Var3 = vim.list({'#', '$'})
954 vim.g.Var4 = vim.dict({model='honda', year=2020})
955 vim.g.Var5 = vim.funcref('max')
956 END
957 call assert_equal(34, g:Var1)
958 call assert_equal('World', g:Var2)
959 call assert_equal(['#', '$'], g:Var3)
960 call assert_equal(#{model: 'honda', year: 2020}, g:Var4)
961 call assert_equal(10, g:Var5([5, 10, 9]))
962
963 " Create list of dictionaries and dictionary of lists
964 unlet g:Var1 g:Var2
965 lua << trim END
966 vim.g.Var1 = vim.list({vim.dict({a=10}), vim.dict({b=20})})
967 vim.g.Var2 = vim.dict({p=vim.list({5, 6}), q=vim.list({1.1, 2.2})})
968 END
969 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
970 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
971
972 " Modify a global variable with a list value or a dictionary value
973 let g:Var1 = [10, 20]
974 let g:Var2 = #{one: 'mercury', two: 'mars'}
975 lua << trim END
976 vim.g.Var1[2] = Nil
977 vim.g.Var1[3] = 15
978 vim.g.Var2['two'] = Nil
979 vim.g.Var2['three'] = 'earth'
980 END
981 call assert_equal([10, 15], g:Var1)
982 call assert_equal(#{one: 'mercury', three: 'earth'}, g:Var2)
983
984 " Remove global variables with different types of values
985 let g:Var1 = 10
986 let g:Var2 = 'Hello'
987 let g:Var3 = ['a', 'b']
988 let g:Var4 = #{x: 'edit', y: 'run'}
989 let g:Var5 = function('min')
990 lua << trim END
991 vim.g.Var1 = Nil
992 vim.g.Var2 = Nil
993 vim.g.Var3 = Nil
994 vim.g.Var4 = Nil
995 vim.g.Var5 = Nil
996 END
997 call assert_false(exists('g:Var1'))
998 call assert_false(exists('g:Var2'))
999 call assert_false(exists('g:Var3'))
1000 call assert_false(exists('g:Var4'))
1001 call assert_false(exists('g:Var5'))
1002
1003 " Try to modify and remove a locked global variable
1004 let g:Var1 = 10
1005 lockvar g:Var1
1006 call assert_fails('lua vim.g.Var1 = 20', 'variable is locked')
1007 call assert_fails('lua vim.g.Var1 = Nil', 'variable is locked')
1008 unlockvar g:Var1
1009 let g:Var2 = [7, 14]
1010 lockvar 0 g:Var2
1011 lua vim.g.Var2[2] = Nil
1012 lua vim.g.Var2[3] = 21
1013 call assert_fails('lua vim.g.Var2 = Nil', 'variable is locked')
1014 call assert_equal([7, 21], g:Var2)
1015 lockvar 1 g:Var2
1016 call assert_fails('lua vim.g.Var2[2] = Nil', 'list is locked')
1017 call assert_fails('lua vim.g.Var2[3] = 21', 'list is locked')
1018 unlockvar g:Var2
1019
Bram Moolenaar4a011592021-08-05 15:11:08 +02001020 let g:TestFunc = function('len')
1021 call assert_fails('lua vim.g.func = vim.g.TestFunc', ['E704:', 'Couldn''t add to dictionary'])
1022 unlet g:TestFunc
1023
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +02001024 " Attempt to access a non-existing global variable
1025 call assert_equal(v:null, luaeval('vim.g.NonExistingVar'))
1026 lua vim.g.NonExisting = Nil
1027
1028 unlet! g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
1029endfunc
1030
1031" Test for accessing and modifying predefined vim variables using the vim.v
1032" Lua table
1033func Test_lua_predefined_var_table()
1034 call assert_equal(v:progpath, luaeval('vim.v.progpath'))
1035 let v:errmsg = 'SomeError'
1036 call assert_equal('SomeError', luaeval('vim.v.errmsg'))
1037 lua vim.v.errmsg = 'OtherError'
1038 call assert_equal('OtherError', v:errmsg)
1039 call assert_fails('lua vim.v.errmsg = Nil', 'variable is fixed')
1040 let v:oldfiles = ['one', 'two']
1041 call assert_equal(['one', 'two'], luaeval('vim.v.oldfiles'))
1042 lua vim.v.oldfiles = vim.list({})
1043 call assert_equal([], v:oldfiles)
1044 call assert_equal(v:null, luaeval('vim.v.null'))
1045 call assert_fails('lua vim.v.argv[1] = Nil', 'list is locked')
1046 call assert_fails('lua vim.v.newvar = 1', 'Dictionary is locked')
1047endfunc
1048
1049" Test for adding, accessing and modifying window-local variables using the
1050" vim.w Lua table
1051func Test_lua_window_var_table()
1052 " Access window variables with different types of values
1053 new
1054 let w:wvar1 = 10
1055 let w:wvar2 = 'edit'
1056 let w:wvar3 = 3.14
1057 let w:wvar4 = 0zdeadbeef
1058 let w:wvar5 = ['a', 'b']
1059 let w:wvar6 = #{action: 'run'}
1060 call assert_equal(10, luaeval('vim.w.wvar1'))
1061 call assert_equal('edit', luaeval('vim.w.wvar2'))
1062 call assert_equal(3.14, luaeval('vim.w.wvar3'))
1063 call assert_equal(0zdeadbeef, luaeval('vim.w.wvar4'))
1064 call assert_equal(['a', 'b'], luaeval('vim.w.wvar5'))
1065 call assert_equal(#{action: 'run'}, luaeval('vim.w.wvar6'))
1066 call assert_equal(v:null, luaeval('vim.w.NonExisting'))
1067
1068 " modify a window variable
1069 lua vim.w.wvar2 = 'paste'
1070 call assert_equal('paste', w:wvar2)
1071
1072 " change the type stored in a variable
1073 let w:wvar2 = [1, 2]
1074 lua vim.w.wvar2 = vim.dict({a=10, b=20})
1075 call assert_equal(#{a: 10, b: 20}, w:wvar2)
1076
1077 " create a new window variable
1078 lua vim.w.wvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1079 call assert_equal(#{a: [1, 2], b: 20}, w:wvar7)
1080
1081 " delete a window variable
1082 lua vim.w.wvar2 = Nil
1083 call assert_false(exists('w:wvar2'))
1084
1085 new
1086 call assert_equal(v:null, luaeval('vim.w.wvar1'))
1087 call assert_equal(v:null, luaeval('vim.w.wvar2'))
1088 %bw!
1089endfunc
1090
1091" Test for adding, accessing and modifying buffer-local variables using the
1092" vim.b Lua table
1093func Test_lua_buffer_var_table()
1094 " Access buffer variables with different types of values
1095 let b:bvar1 = 10
1096 let b:bvar2 = 'edit'
1097 let b:bvar3 = 3.14
1098 let b:bvar4 = 0zdeadbeef
1099 let b:bvar5 = ['a', 'b']
1100 let b:bvar6 = #{action: 'run'}
1101 call assert_equal(10, luaeval('vim.b.bvar1'))
1102 call assert_equal('edit', luaeval('vim.b.bvar2'))
1103 call assert_equal(3.14, luaeval('vim.b.bvar3'))
1104 call assert_equal(0zdeadbeef, luaeval('vim.b.bvar4'))
1105 call assert_equal(['a', 'b'], luaeval('vim.b.bvar5'))
1106 call assert_equal(#{action: 'run'}, luaeval('vim.b.bvar6'))
1107 call assert_equal(v:null, luaeval('vim.b.NonExisting'))
1108
1109 " modify a buffer variable
1110 lua vim.b.bvar2 = 'paste'
1111 call assert_equal('paste', b:bvar2)
1112
1113 " change the type stored in a variable
1114 let b:bvar2 = [1, 2]
1115 lua vim.b.bvar2 = vim.dict({a=10, b=20})
1116 call assert_equal(#{a: 10, b: 20}, b:bvar2)
1117
1118 " create a new buffer variable
1119 lua vim.b.bvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1120 call assert_equal(#{a: [1, 2], b: 20}, b:bvar7)
1121
1122 " delete a buffer variable
1123 lua vim.b.bvar2 = Nil
1124 call assert_false(exists('b:bvar2'))
1125
1126 new
1127 call assert_equal(v:null, luaeval('vim.b.bvar1'))
1128 call assert_equal(v:null, luaeval('vim.b.bvar2'))
1129 %bw!
1130endfunc
1131
1132" Test for adding, accessing and modifying tabpage-local variables using the
1133" vim.t Lua table
1134func Test_lua_tabpage_var_table()
1135 " Access tabpage variables with different types of values
1136 let t:tvar1 = 10
1137 let t:tvar2 = 'edit'
1138 let t:tvar3 = 3.14
1139 let t:tvar4 = 0zdeadbeef
1140 let t:tvar5 = ['a', 'b']
1141 let t:tvar6 = #{action: 'run'}
1142 call assert_equal(10, luaeval('vim.t.tvar1'))
1143 call assert_equal('edit', luaeval('vim.t.tvar2'))
1144 call assert_equal(3.14, luaeval('vim.t.tvar3'))
1145 call assert_equal(0zdeadbeef, luaeval('vim.t.tvar4'))
1146 call assert_equal(['a', 'b'], luaeval('vim.t.tvar5'))
1147 call assert_equal(#{action: 'run'}, luaeval('vim.t.tvar6'))
1148 call assert_equal(v:null, luaeval('vim.t.NonExisting'))
1149
1150 " modify a tabpage variable
1151 lua vim.t.tvar2 = 'paste'
1152 call assert_equal('paste', t:tvar2)
1153
1154 " change the type stored in a variable
1155 let t:tvar2 = [1, 2]
1156 lua vim.t.tvar2 = vim.dict({a=10, b=20})
1157 call assert_equal(#{a: 10, b: 20}, t:tvar2)
1158
1159 " create a new tabpage variable
1160 lua vim.t.tvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1161 call assert_equal(#{a: [1, 2], b: 20}, t:tvar7)
1162
1163 " delete a tabpage variable
1164 lua vim.t.tvar2 = Nil
1165 call assert_false(exists('t:tvar2'))
1166
1167 tabnew
1168 call assert_equal(v:null, luaeval('vim.t.tvar1'))
1169 call assert_equal(v:null, luaeval('vim.t.tvar2'))
1170 %bw!
1171endfunc
1172
Yegappan Lakshmanan11328bc2021-08-06 21:34:38 +02001173" Test for vim.version()
1174func Test_lua_vim_version()
1175 lua << trim END
1176 vimver = vim.version()
1177 vimver_n = vimver.major * 100 + vimver.minor
1178 END
1179 call assert_equal(v:version, luaeval('vimver_n'))
1180endfunc
1181
1182" Test for running multiple commands using vim.command()
1183func Test_lua_multiple_commands()
1184 lua << trim END
1185 vim.command([[
1186 let Var1 = []
1187 for i in range(3)
1188 let Var1 += [#{name: 'x'}]
1189 endfor
1190 augroup Luagroup
1191 autocmd!
1192 autocmd User Luatest echo 'Hello'
1193 augroup END
1194 ]])
1195 END
1196 call assert_equal([{'name': 'x'}, {'name': 'x'}, {'name': 'x'}], Var1)
1197 call assert_true(exists('#Luagroup'))
1198 call assert_true(exists('#Luagroup#User#Luatest'))
1199 augroup Luagroup
1200 autocmd!
1201 augroup END
1202 augroup! Luagroup
1203endfunc
1204
Dominique Pelleb6643d12022-03-20 11:46:01 +00001205func Test_lua_debug()
1206 CheckRunVimInTerminal
1207
1208 let buf = RunVimInTerminal('', {'rows': 10})
1209 call term_sendkeys(buf, ":lua debug.debug()\n")
1210 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1211
1212 call term_sendkeys(buf, "foo = 42\n")
1213 call WaitForAssert({-> assert_equal('lua_debug> foo = 42', term_getline(buf, 9))})
1214 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1215
1216 call term_sendkeys(buf, "print(foo)\n")
1217 call WaitForAssert({-> assert_equal('lua_debug> print(foo)', term_getline(buf, 8))})
1218 call WaitForAssert({-> assert_equal('42', term_getline(buf, 9))})
1219 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1220
Dominique Pelle81b573d2022-03-22 21:14:55 +00001221 call term_sendkeys(buf, "-\n")
1222 call WaitForAssert({-> assert_equal("(debug command):1: unexpected symbol near '-'",
1223 \ term_getline(buf, 9))})
1224 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1225
Dominique Pelleb6643d12022-03-20 11:46:01 +00001226 call term_sendkeys(buf, "cont\n")
1227 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1228
Dominique Pelle81b573d2022-03-22 21:14:55 +00001229 " Entering an empty line also exits the debugger.
1230 call term_sendkeys(buf, ":lua debug.debug()\n")
1231 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1232 call term_sendkeys(buf, "\n")
1233 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1234
Dominique Pelleb6643d12022-03-20 11:46:01 +00001235 call StopVimInTerminal(buf)
Dominique Pelleb6643d12022-03-20 11:46:01 +00001236endfunc
1237
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02001238" vim: shiftwidth=2 sts=2 expandtab