blob: 7fcd13d7dafad16266e1b33e6c33db5103b845ff [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 Moolenaar5feabe02020-01-30 18:24:53 +010013CheckFeature float
Bram Moolenaard58f03b2017-01-29 22:48:45 +010014
Bram Moolenaarf65ed862021-04-03 14:13:33 +020015" Depending on the lua version, the error messages are different.
Bram Moolenaar125ed272021-04-07 20:11:12 +020016let [s:major, s:minor, s:patch] = luaeval('vim.lua_version')->split('\.')->map({-> str2nr(v:val)})
Bram Moolenaarf65ed862021-04-03 14:13:33 +020017let s:lua_53_or_later = 0
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +000018let s:lua_543 = 0
Bram Moolenaarf65ed862021-04-03 14:13:33 +020019if (s:major == 5 && s:minor >= 3) || s:major > 5
Bram Moolenaare49b8e82020-07-01 13:52:55 +020020 let s:lua_53_or_later = 1
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +000021 if s:major == 5 && s:minor == 4 && s:patch == 3
22 let s:lua_543 = 1
Bram Moolenaarf65ed862021-04-03 14:13:33 +020023 endif
Bram Moolenaare49b8e82020-07-01 13:52:55 +020024endif
25
Bram Moolenaare165f632019-03-10 09:48:59 +010026func TearDown()
27 " Run garbage collection after each test to exercise luaV_setref().
28 call test_garbagecollect_now()
29endfunc
30
Bram Moolenaar4ff48142018-06-30 21:50:25 +020031" Check that switching to another buffer does not trigger ml_get error.
Bram Moolenaar5feabe02020-01-30 18:24:53 +010032func Test_lua_command_new_no_ml_get_error()
Bram Moolenaard58f03b2017-01-29 22:48:45 +010033 new
34 let wincount = winnr('$')
35 call setline(1, ['one', 'two', 'three'])
36 luado vim.command("new")
37 call assert_equal(wincount + 1, winnr('$'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +020038 %bwipe!
39endfunc
40
41" Test vim.command()
Bram Moolenaar5feabe02020-01-30 18:24:53 +010042func Test_lua_command()
Bram Moolenaar4ff48142018-06-30 21:50:25 +020043 new
44 call setline(1, ['one', 'two', 'three'])
45 luado vim.command("1,2d_")
46 call assert_equal(['three'], getline(1, '$'))
Bram Moolenaard58f03b2017-01-29 22:48:45 +010047 bwipe!
Bram Moolenaar4ff48142018-06-30 21:50:25 +020048endfunc
49
Bram Moolenaare49b8e82020-07-01 13:52:55 +020050func Test_lua_luado()
51 new
52 call setline(1, ['one', 'two'])
53 luado return(linenr)
54 call assert_equal(['1', '2'], getline(1, '$'))
55 close!
56
57 " Error cases
58 call assert_fails('luado string.format()',
59 \ "[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 +000060 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +020061 let msg = "[string \"vim chunk\"]:1: global 'func' is not callable (a nil value)"
62 elseif s:lua_53_or_later
63 let msg = "[string \"vim chunk\"]:1: attempt to call a nil value (global 'func')"
64 else
65 let msg = "[string \"vim chunk\"]:1: attempt to call global 'func' (a nil value)"
66 endif
67 call assert_fails('luado func()', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +020068 call assert_fails('luado error("failed")', "[string \"vim chunk\"]:1: failed")
69endfunc
70
Bram Moolenaar4ff48142018-06-30 21:50:25 +020071" Test vim.eval()
Bram Moolenaar5feabe02020-01-30 18:24:53 +010072func Test_lua_eval()
Bram Moolenaar4ff48142018-06-30 21:50:25 +020073 " lua.eval with a number
74 lua v = vim.eval('123')
75 call assert_equal('number', luaeval('vim.type(v)'))
Bram Moolenaareb04f082020-05-17 14:32:35 +020076 call assert_equal(123, luaeval('v'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +020077
78 " lua.eval with a string
79 lua v = vim.eval('"abc"')
Bram Moolenaar02b31112019-08-31 22:16:38 +020080 call assert_equal('string', 'vim.type(v)'->luaeval())
Bram Moolenaar4ff48142018-06-30 21:50:25 +020081 call assert_equal('abc', luaeval('v'))
82
83 " lua.eval with a list
84 lua v = vim.eval("['a']")
85 call assert_equal('list', luaeval('vim.type(v)'))
86 call assert_equal(['a'], luaeval('v'))
87
88 " lua.eval with a dict
89 lua v = vim.eval("{'a':'b'}")
90 call assert_equal('dict', luaeval('vim.type(v)'))
91 call assert_equal({'a':'b'}, luaeval('v'))
92
Bram Moolenaarb7828692019-03-23 13:57:02 +010093 " lua.eval with a blob
94 lua v = vim.eval("0z00112233.deadbeef")
95 call assert_equal('blob', luaeval('vim.type(v)'))
96 call assert_equal(0z00112233.deadbeef, luaeval('v'))
97
Bram Moolenaare49b8e82020-07-01 13:52:55 +020098 " lua.eval with a float
99 lua v = vim.eval('3.14')
100 call assert_equal('number', luaeval('vim.type(v)'))
101 call assert_equal(3.14, luaeval('v'))
102
103 " lua.eval with a bool
104 lua v = vim.eval('v:true')
105 call assert_equal('number', luaeval('vim.type(v)'))
106 call assert_equal(1, luaeval('v'))
107 lua v = vim.eval('v:false')
108 call assert_equal('number', luaeval('vim.type(v)'))
109 call assert_equal(0, luaeval('v'))
110
111 " lua.eval with a null
112 lua v = vim.eval('v:null')
113 call assert_equal('nil', luaeval('vim.type(v)'))
114 call assert_equal(v:null, luaeval('v'))
115
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200116 call assert_fails('lua v = vim.eval(nil)',
117 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got nil)")
118 call assert_fails('lua v = vim.eval(true)',
119 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got boolean)")
120 call assert_fails('lua v = vim.eval({})',
121 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got table)")
122 call assert_fails('lua v = vim.eval(print)',
123 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got function)")
124 call assert_fails('lua v = vim.eval(vim.buffer())',
125 \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got userdata)")
126
127 lua v = nil
128endfunc
129
Bram Moolenaar86c3a212021-03-08 19:50:24 +0100130" Test luaeval() with lambda
131func Test_luaeval_with_lambda()
132 lua function hello_luaeval_lambda(a, cb) return a .. cb() end
133 call assert_equal('helloworld',
134 \ luaeval('hello_luaeval_lambda(_A[1], _A[2])',
135 \ ['hello', {->'world'}]))
136 lua hello_luaeval_lambda = nil
137endfunc
138
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200139" Test vim.window()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100140func Test_lua_window()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200141 e Xfoo2
142 new Xfoo1
143
144 " Window 1 (top window) contains Xfoo1
145 " Window 2 (bottom window) contains Xfoo2
146 call assert_equal('Xfoo1', luaeval('vim.window(1):buffer().name'))
147 call assert_equal('Xfoo2', luaeval('vim.window(2):buffer().name'))
148
149 " Window 3 does not exist so vim.window(3) should return nil
150 call assert_equal('nil', luaeval('tostring(vim.window(3))'))
151
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000152 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200153 let msg = "[string \"luaeval\"]:1: field 'xyz' is not callable (a nil value)"
154 elseif s:lua_53_or_later
155 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (field 'xyz')"
156 else
157 let msg = "[string \"luaeval\"]:1: attempt to call field 'xyz' (a nil value)"
158 endif
159 call assert_fails("let n = luaeval('vim.window().xyz()')", msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200160 call assert_fails('lua vim.window().xyz = 1',
161 \ "[string \"vim chunk\"]:1: invalid window property: `xyz'")
162
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200163 %bwipe!
164endfunc
165
166" Test vim.window().height
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100167func Test_lua_window_height()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200168 new
169 lua vim.window().height = 2
170 call assert_equal(2, winheight(0))
171 lua vim.window().height = vim.window().height + 1
172 call assert_equal(3, winheight(0))
173 bwipe!
174endfunc
175
176" Test vim.window().width
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100177func Test_lua_window_width()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200178 vert new
179 lua vim.window().width = 2
180 call assert_equal(2, winwidth(0))
181 lua vim.window().width = vim.window().width + 1
182 call assert_equal(3, winwidth(0))
183 bwipe!
184endfunc
185
186" Test vim.window().line and vim.window.col
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100187func Test_lua_window_line_col()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200188 new
189 call setline(1, ['line1', 'line2', 'line3'])
190 lua vim.window().line = 2
191 lua vim.window().col = 4
192 call assert_equal([0, 2, 4, 0], getpos('.'))
193 lua vim.window().line = vim.window().line + 1
194 lua vim.window().col = vim.window().col - 1
195 call assert_equal([0, 3, 3, 0], getpos('.'))
196
197 call assert_fails('lua vim.window().line = 10',
198 \ '[string "vim chunk"]:1: line out of range')
199 bwipe!
200endfunc
201
Bram Moolenaareb04f082020-05-17 14:32:35 +0200202" Test vim.call
203func Test_lua_call()
204 call assert_equal(has('lua'), luaeval('vim.call("has", "lua")'))
205 call assert_equal(printf("Hello %s", "vim"), luaeval('vim.call("printf", "Hello %s", "vim")'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200206
207 " Error cases
208 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 +0200209 \ s:lua_53_or_later
210 \ ? '[string "luaeval"]:1: Function called with too many arguments'
211 \ : 'Function called with too many arguments')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200212 lua co = coroutine.create(function () print("hi") end)
213 call assert_fails("call luaeval('vim.call(\"type\", co)')",
Bram Moolenaarb898a022020-07-12 18:33:53 +0200214 \ s:lua_53_or_later
215 \ ? '[string "luaeval"]:1: lua: cannot convert value'
216 \ : 'lua: cannot convert value')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200217 lua co = nil
Bram Moolenaarb898a022020-07-12 18:33:53 +0200218 call assert_fails("call luaeval('vim.call(\"abc\")')",
219 \ ['E117:', s:lua_53_or_later ? '\[string "luaeval"]:1: lua: call_vim_function failed'
220 \ : 'lua: call_vim_function failed'])
Bram Moolenaareb04f082020-05-17 14:32:35 +0200221endfunc
222
223" Test vim.fn.*
224func Test_lua_fn()
225 call assert_equal(has('lua'), luaeval('vim.fn.has("lua")'))
226 call assert_equal(printf("Hello %s", "vim"), luaeval('vim.fn.printf("Hello %s", "vim")'))
227endfunc
228
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200229" Test setting the current window
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100230func Test_lua_window_set_current()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200231 new Xfoo1
232 lua w1 = vim.window()
233 new Xfoo2
234 lua w2 = vim.window()
235
236 call assert_equal('Xfoo2', bufname('%'))
237 lua w1()
238 call assert_equal('Xfoo1', bufname('%'))
239 lua w2()
240 call assert_equal('Xfoo2', bufname('%'))
241
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200242 lua w1, w2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200243 %bwipe!
244endfunc
245
246" Test vim.window().buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100247func Test_lua_window_buffer()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200248 new Xfoo1
249 lua w1 = vim.window()
250 lua b1 = w1.buffer()
251 new Xfoo2
252 lua w2 = vim.window()
253 lua b2 = w2.buffer()
254
255 lua b1()
256 call assert_equal('Xfoo1', bufname('%'))
257 lua b2()
258 call assert_equal('Xfoo2', bufname('%'))
259
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200260 lua b1, b2, w1, w2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200261 %bwipe!
262endfunc
263
264" Test vim.window():previous() and vim.window():next()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100265func Test_lua_window_next_previous()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200266 new Xfoo1
267 new Xfoo2
268 new Xfoo3
269 wincmd j
270
271 call assert_equal('Xfoo2', luaeval('vim.window().buffer().name'))
272 call assert_equal('Xfoo1', luaeval('vim.window():next():buffer().name'))
273 call assert_equal('Xfoo3', luaeval('vim.window():previous():buffer().name'))
274
275 %bwipe!
276endfunc
277
278" Test vim.window():isvalid()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100279func Test_lua_window_isvalid()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200280 new Xfoo
281 lua w = vim.window()
282 call assert_true(luaeval('w:isvalid()'))
283
284 " FIXME: how to test the case when isvalid() returns v:false?
285 " isvalid() gives errors when the window is deleted. Is it a bug?
286
287 lua w = nil
288 bwipe!
289endfunc
290
291" Test vim.buffer() with and without argument
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100292func Test_lua_buffer()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200293 new Xfoo1
294 let bn1 = bufnr('%')
295 new Xfoo2
296 let bn2 = bufnr('%')
297
298 " Test vim.buffer() without argument.
299 call assert_equal('Xfoo2', luaeval("vim.buffer().name"))
300
301 " Test vim.buffer() with string argument.
302 call assert_equal('Xfoo1', luaeval("vim.buffer('Xfoo1').name"))
303 call assert_equal('Xfoo2', luaeval("vim.buffer('Xfoo2').name"))
304
305 " Test vim.buffer() with integer argument.
306 call assert_equal('Xfoo1', luaeval("vim.buffer(" . bn1 . ").name"))
307 call assert_equal('Xfoo2', luaeval("vim.buffer(" . bn2 . ").name"))
308
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200309 lua bn1, bn2 = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200310 %bwipe!
311endfunc
312
313" Test vim.buffer().name and vim.buffer().fname
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100314func Test_lua_buffer_name()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200315 new
Bram Moolenaarfe08df42018-07-07 23:07:41 +0200316 call assert_equal('', luaeval('vim.buffer().name'))
317 call assert_equal('', luaeval('vim.buffer().fname'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200318 bwipe!
319
320 new Xfoo
321 call assert_equal('Xfoo', luaeval('vim.buffer().name'))
322 call assert_equal(expand('%:p'), luaeval('vim.buffer().fname'))
323 bwipe!
324endfunc
325
326" Test vim.buffer().number
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100327func Test_lua_buffer_number()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200328 " All numbers in Lua are floating points number (no integers).
329 call assert_equal(bufnr('%'), float2nr(luaeval('vim.buffer().number')))
330endfunc
331
332" Test inserting lines in buffer.
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100333func Test_lua_buffer_insert()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200334 new
335 lua vim.buffer()[1] = '3'
336 lua vim.buffer():insert('1', 0)
337 lua vim.buffer():insert('2', 1)
338 lua vim.buffer():insert('4', 10)
339
340 call assert_equal(['1', '2', '3', '4'], getline(1, '$'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200341 call assert_equal('4', luaeval('vim.buffer()[4]'))
342 call assert_equal(v:null, luaeval('vim.buffer()[5]'))
343 call assert_equal(v:null, luaeval('vim.buffer()[{}]'))
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000344 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200345 let msg = "[string \"vim chunk\"]:1: method 'xyz' is not callable (a nil value)"
346 elseif s:lua_53_or_later
347 let msg = "[string \"vim chunk\"]:1: attempt to call a nil value (method 'xyz')"
348 else
349 let msg = "[string \"vim chunk\"]:1: attempt to call method 'xyz' (a nil value)"
350 endif
351 call assert_fails('lua vim.buffer():xyz()', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200352 call assert_fails('lua vim.buffer()[1] = {}',
353 \ '[string "vim chunk"]:1: wrong argument to change')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200354 bwipe!
355endfunc
356
357" Test deleting line in buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100358func Test_lua_buffer_delete()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200359 new
360 call setline(1, ['1', '2', '3'])
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200361 call cursor(3, 1)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200362 lua vim.buffer()[2] = nil
363 call assert_equal(['1', '3'], getline(1, '$'))
364
365 call assert_fails('lua vim.buffer()[3] = nil',
366 \ '[string "vim chunk"]:1: invalid line number')
367 bwipe!
368endfunc
369
370" Test #vim.buffer() i.e. number of lines in buffer
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100371func Test_lua_buffer_number_lines()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200372 new
373 call setline(1, ['a', 'b', 'c'])
Bram Moolenaareb04f082020-05-17 14:32:35 +0200374 call assert_equal(3, luaeval('#vim.buffer()'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200375 bwipe!
376endfunc
377
378" Test vim.buffer():next() and vim.buffer():previous()
379" Note that these functions get the next or previous buffers
380" but do not switch buffer.
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100381func Test_lua_buffer_next_previous()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200382 new Xfoo1
383 new Xfoo2
384 new Xfoo3
385 b Xfoo2
386
387 lua bn = vim.buffer():next()
388 lua bp = vim.buffer():previous()
389
390 call assert_equal('Xfoo2', luaeval('vim.buffer().name'))
391 call assert_equal('Xfoo1', luaeval('bp.name'))
392 call assert_equal('Xfoo3', luaeval('bn.name'))
393
394 call assert_equal('Xfoo2', bufname('%'))
395
396 lua bn()
397 call assert_equal('Xfoo3', luaeval('vim.buffer().name'))
398 call assert_equal('Xfoo3', bufname('%'))
399
400 lua bp()
401 call assert_equal('Xfoo1', luaeval('vim.buffer().name'))
402 call assert_equal('Xfoo1', bufname('%'))
403
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200404 lua bn, bp = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200405 %bwipe!
406endfunc
407
408" Test vim.buffer():isvalid()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100409func Test_lua_buffer_isvalid()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200410 new Xfoo
411 lua b = vim.buffer()
412 call assert_true(luaeval('b:isvalid()'))
413
414 " FIXME: how to test the case when isvalid() returns v:false?
415 " isvalid() gives errors when the buffer is wiped. Is it a bug?
416
417 lua b = nil
418 bwipe!
419endfunc
420
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100421func Test_lua_list()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200422 call assert_equal([], luaeval('vim.list()'))
423
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200424 let l = []
425 lua l = vim.eval('l')
426 lua l:add(123)
427 lua l:add('abc')
428 lua l:add(true)
429 lua l:add(false)
Bram Moolenaar9067cd62019-01-01 00:41:54 +0100430 lua l:add(nil)
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200431 lua l:add(vim.eval("[1, 2, 3]"))
432 lua l:add(vim.eval("{'a':1, 'b':2, 'c':3}"))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200433 call assert_equal([123, 'abc', v:true, v:false, v:null, [1, 2, 3], {'a': 1, 'b': 2, 'c': 3}], l)
434 call assert_equal(7, luaeval('#l'))
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200435 call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200436
Bram Moolenaarbd846172020-06-27 12:32:57 +0200437 lua l[1] = 124
438 lua l[6] = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200439 lua l:insert('first')
440 lua l:insert('xx', 3)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200441 call assert_fails('lua l:insert("xx", -20)',
442 \ '[string "vim chunk"]:1: invalid position')
Bram Moolenaareb04f082020-05-17 14:32:35 +0200443 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 +0200444
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200445 lockvar 1 l
446 call assert_fails('lua l:add("x")', '[string "vim chunk"]:1: list is locked')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200447 call assert_fails('lua l:insert(2)', '[string "vim chunk"]:1: list is locked')
448 call assert_fails('lua l[9] = 1', '[string "vim chunk"]:1: list is locked')
449
450 unlockvar l
451 let l = [1, 2]
452 lua ll = vim.eval('l')
453 let x = luaeval("ll[3]")
454 call assert_equal(v:null, x)
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000455 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200456 let msg = "[string \"luaeval\"]:1: method 'xyz' is not callable (a nil value)"
457 elseif s:lua_53_or_later
458 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
459 else
460 let msg = "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)"
461 endif
462 call assert_fails('let x = luaeval("ll:xyz(3)")', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200463 let y = luaeval("ll[{}]")
464 call assert_equal(v:null, y)
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200465
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200466 lua l = nil
467endfunc
468
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100469func Test_lua_list_table()
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200470 " See :help lua-vim
471 " Non-numeric keys should not be used to initialize the list
472 " so say = 'hi' should be ignored.
473 lua t = {3.14, 'hello', false, true, say = 'hi'}
474 call assert_equal([3.14, 'hello', v:false, v:true], luaeval('vim.list(t)'))
475 lua t = nil
476
477 call assert_fails('lua vim.list(1)', '[string "vim chunk"]:1: table expected, got number')
478 call assert_fails('lua vim.list("x")', '[string "vim chunk"]:1: table expected, got string')
479 call assert_fails('lua vim.list(print)', '[string "vim chunk"]:1: table expected, got function')
480 call assert_fails('lua vim.list(true)', '[string "vim chunk"]:1: table expected, got boolean')
481endfunc
482
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200483func Test_lua_list_table_insert_remove()
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200484 if !s:lua_53_or_later
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200485 throw 'Skipped: Lua version < 5.3'
486 endif
487
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200488 let l = [1, 2]
Bram Moolenaara1f9f862020-06-28 22:41:26 +0200489 lua t = vim.eval('l')
490 lua table.insert(t, 10)
491 lua t[#t + 1] = 20
492 lua table.insert(t, 2, 30)
493 call assert_equal(l, [1, 30, 2, 10, 20])
494 lua table.remove(t, 2)
495 call assert_equal(l, [1, 2, 10, 20])
496 lua t[3] = nil
497 call assert_equal(l, [1, 2, 20])
498 lua removed_value = table.remove(t, 3)
499 call assert_equal(luaeval('removed_value'), 20)
500 lua t = nil
501 lua removed_value = nil
502 unlet l
503endfunc
504
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200505" Test l() i.e. iterator on list
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100506func Test_lua_list_iter()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200507 lua l = vim.list():add('foo'):add('bar')
508 lua str = ''
509 lua for v in l() do str = str .. v end
510 call assert_equal('foobar', luaeval('str'))
511
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200512 lua str, l = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200513endfunc
514
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100515func Test_lua_recursive_list()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200516 lua l = vim.list():add(1):add(2)
517 lua l = l:add(l)
518
Bram Moolenaarbd846172020-06-27 12:32:57 +0200519 call assert_equal(1, luaeval('l[1]'))
520 call assert_equal(2, luaeval('l[2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200521
Bram Moolenaarbd846172020-06-27 12:32:57 +0200522 call assert_equal(1, luaeval('l[3][1]'))
523 call assert_equal(2, luaeval('l[3][2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200524
Bram Moolenaarbd846172020-06-27 12:32:57 +0200525 call assert_equal(1, luaeval('l[3][3][1]'))
526 call assert_equal(2, luaeval('l[3][3][2]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200527
Bram Moolenaareb04f082020-05-17 14:32:35 +0200528 call assert_equal('[1, 2, [...]]', string(luaeval('l')))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200529
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200530 call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
Bram Moolenaarbd846172020-06-27 12:32:57 +0200531 call assert_equal(luaeval('tostring(l)'), luaeval('tostring(l[3])'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200532
Bram Moolenaarbd846172020-06-27 12:32:57 +0200533 call assert_equal(luaeval('l'), luaeval('l[3]'))
534 call assert_equal(luaeval('l'), luaeval('l[3][3]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200535
536 lua l = nil
537endfunc
538
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100539func Test_lua_dict()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200540 call assert_equal({}, luaeval('vim.dict()'))
541
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200542 let d = {}
543 lua d = vim.eval('d')
544 lua d[0] = 123
545 lua d[1] = "abc"
546 lua d[2] = true
547 lua d[3] = false
548 lua d[4] = vim.eval("[1, 2, 3]")
549 lua d[5] = vim.eval("{'a':1, 'b':2, 'c':3}")
Bram Moolenaareb04f082020-05-17 14:32:35 +0200550 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)
551 call assert_equal(6, luaeval('#d'))
Bram Moolenaara8a60d02018-07-02 22:54:36 +0200552 call assert_match('^dict: \%(0x\)\?\x\+$', luaeval('tostring(d)'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200553
554 call assert_equal('abc', luaeval('d[1]'))
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200555 call assert_equal(v:null, luaeval('d[22]'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200556
557 lua d[0] = 124
558 lua d[4] = nil
Bram Moolenaareb04f082020-05-17 14:32:35 +0200559 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 +0200560
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200561 lockvar 1 d
562 call assert_fails('lua d[6] = 1', '[string "vim chunk"]:1: dict is locked')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200563 unlockvar d
564
565 " Error case
566 lua d = {}
567 lua d[''] = 10
568 call assert_fails("let t = luaeval('vim.dict(d)')",
Bram Moolenaarb898a022020-07-12 18:33:53 +0200569 \ s:lua_53_or_later
570 \ ? '[string "luaeval"]:1: table has empty key'
571 \ : 'table has empty key')
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200572 let d = {}
573 lua x = vim.eval('d')
574 call assert_fails("lua x[''] = 10", '[string "vim chunk"]:1: empty key')
575 lua x['a'] = nil
576 call assert_equal({}, d)
577
578 " cannot assign funcrefs in the global scope
579 lua x = vim.eval('g:')
580 call assert_fails("lua x['min'] = vim.funcref('max')",
581 \ '[string "vim chunk"]:1: cannot assign funcref to builtin scope')
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200582
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200583 lua d = nil
584endfunc
585
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100586func Test_lua_dict_table()
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200587 lua t = {key1 = 'x', key2 = 3.14, key3 = true, key4 = false}
588 call assert_equal({'key1': 'x', 'key2': 3.14, 'key3': v:true, 'key4': v:false},
589 \ luaeval('vim.dict(t)'))
590
591 " Same example as in :help lua-vim.
592 lua t = {math.pi, false, say = 'hi'}
593 " FIXME: commented out as it currently does not work as documented:
594 " Expected {'say': 'hi'}
595 " but got {'1': 3.141593, '2': v:false, 'say': 'hi'}
596 " Is the documentation or the code wrong?
597 "call assert_equal({'say' : 'hi'}, luaeval('vim.dict(t)'))
598 lua t = nil
599
600 call assert_fails('lua vim.dict(1)', '[string "vim chunk"]:1: table expected, got number')
601 call assert_fails('lua vim.dict("x")', '[string "vim chunk"]:1: table expected, got string')
602 call assert_fails('lua vim.dict(print)', '[string "vim chunk"]:1: table expected, got function')
603 call assert_fails('lua vim.dict(true)', '[string "vim chunk"]:1: table expected, got boolean')
604endfunc
605
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200606" Test d() i.e. iterator on dictionary
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100607func Test_lua_dict_iter()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200608 let d = {'a': 1, 'b':2}
609 lua d = vim.eval('d')
610 lua str = ''
611 lua for k,v in d() do str = str .. k ..':' .. v .. ',' end
612 call assert_equal('a:1,b:2,', luaeval('str'))
613
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200614 lua str, d = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200615endfunc
616
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100617func Test_lua_blob()
Bram Moolenaarb7828692019-03-23 13:57:02 +0100618 call assert_equal(0z, luaeval('vim.blob("")'))
619 call assert_equal(0z31326162, luaeval('vim.blob("12ab")'))
620 call assert_equal(0z00010203, luaeval('vim.blob("\x00\x01\x02\x03")'))
621 call assert_equal(0z8081FEFF, luaeval('vim.blob("\x80\x81\xfe\xff")'))
622
623 lua b = vim.blob("\x00\x00\x00\x00")
624 call assert_equal(0z00000000, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200625 call assert_equal(4, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100626 lua b[0], b[1], b[2], b[3] = 1, 32, 256, 0xff
627 call assert_equal(0z012000ff, luaeval('b'))
628 lua b[4] = string.byte("z", 1)
629 call assert_equal(0z012000ff.7a, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200630 call assert_equal(5, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100631 call assert_fails('lua b[#b+1] = 0x80', '[string "vim chunk"]:1: index out of range')
632 lua b:add("12ab")
633 call assert_equal(0z012000ff.7a313261.62, luaeval('b'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200634 call assert_equal(9, luaeval('#b'))
Bram Moolenaarb7828692019-03-23 13:57:02 +0100635 call assert_fails('lua b:add(nil)', '[string "vim chunk"]:1: string expected, got nil')
636 call assert_fails('lua b:add(true)', '[string "vim chunk"]:1: string expected, got boolean')
637 call assert_fails('lua b:add({})', '[string "vim chunk"]:1: string expected, got table')
638 lua b = nil
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200639
640 let b = 0z0102
641 lua lb = vim.eval('b')
642 let n = luaeval('lb[1]')
643 call assert_equal(2, n)
644 let n = luaeval('lb[6]')
645 call assert_equal(v:null, n)
=?UTF-8?q?Jakub=20Kul=C3=ADk?=57ff2b72022-01-28 17:20:03 +0000646 if s:lua_543
Bram Moolenaarf65ed862021-04-03 14:13:33 +0200647 let msg = "[string \"luaeval\"]:1: method 'xyz' is not callable (a nil value)"
648 elseif s:lua_53_or_later
649 let msg = "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
650 else
651 let msg = "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)"
652 endif
653 call assert_fails('let x = luaeval("lb:xyz(3)")', msg)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200654 let y = luaeval("lb[{}]")
655 call assert_equal(v:null, y)
656
657 lockvar b
658 call assert_fails('lua lb[1] = 2', '[string "vim chunk"]:1: blob is locked')
659 call assert_fails('lua lb:add("12")', '[string "vim chunk"]:1: blob is locked')
660
661 " Error cases
662 lua t = {}
663 call assert_fails('lua b = vim.blob(t)',
664 \ '[string "vim chunk"]:1: string expected, got table')
Bram Moolenaarb7828692019-03-23 13:57:02 +0100665endfunc
666
Bram Moolenaar7d149f82022-06-17 19:23:34 +0100667def Vim9Test(Callback: func())
668 Callback()
669enddef
670
671func Test_call_lua_func_from_vim9_func()
672 " this only tests that Vim doesn't crash
673 lua << EOF
674vim.fn.Vim9Test(function () print('Hello') end)
675EOF
676endfunc
677
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100678func Test_lua_funcref()
Bram Moolenaarca06da92018-07-01 15:12:05 +0200679 function I(x)
680 return a:x
681 endfunction
682 let R = function('I')
683 lua i1 = vim.funcref"I"
684 lua i2 = vim.eval"R"
685 lua msg = "funcref|test|" .. (#i2(i1) == #i1(i2) and "OK" or "FAIL")
686 lua msg = vim.funcref"tr"(msg, "|", " ")
687 call assert_equal("funcref test OK", luaeval('msg'))
688
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200689 " Error cases
690 call assert_fails('lua f1 = vim.funcref("")',
691 \ '[string "vim chunk"]:1: invalid function name: ')
692 call assert_fails('lua f1 = vim.funcref("10")',
693 \ '[string "vim chunk"]:1: invalid function name: 10')
694 let fname = test_null_string()
695 call assert_fails('lua f1 = vim.funcref(fname)',
696 \ "[string \"vim chunk\"]:1: bad argument #1 to 'funcref' (string expected, got nil)")
697 call assert_fails('lua vim.funcref("abc")()',
Bram Moolenaarecdd14a2020-07-11 22:49:59 +0200698 \ ['E117:', '\[string "vim chunk"]:1: cannot call funcref'])
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200699
Bram Moolenaarca06da92018-07-01 15:12:05 +0200700 " dict funcref
701 function Mylen() dict
702 return len(self.data)
703 endfunction
704 let l = [0, 1, 2, 3]
705 let mydict = {'data': l}
706 lua d = vim.eval"mydict"
707 lua d.len = vim.funcref"Mylen" -- assign d as 'self'
708 lua res = (d.len() == vim.funcref"len"(vim.eval"l")) and "OK" or "FAIL"
709 call assert_equal("OK", luaeval('res'))
Bram Moolenaar4eefe472019-03-19 21:59:19 +0100710 call assert_equal(function('Mylen', {'data': l, 'len': function('Mylen')}), mydict.len)
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200711
712 lua i1, i2, msg, d, res = nil
Bram Moolenaarca06da92018-07-01 15:12:05 +0200713endfunc
714
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200715" Test vim.type()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100716func Test_lua_type()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200717 " The following values are identical to Lua's type function.
718 call assert_equal('string', luaeval('vim.type("foo")'))
719 call assert_equal('number', luaeval('vim.type(1)'))
720 call assert_equal('number', luaeval('vim.type(1.2)'))
721 call assert_equal('function', luaeval('vim.type(print)'))
722 call assert_equal('table', luaeval('vim.type({})'))
723 call assert_equal('boolean', luaeval('vim.type(true)'))
724 call assert_equal('boolean', luaeval('vim.type(false)'))
725 call assert_equal('nil', luaeval('vim.type(nil)'))
726
727 " The following values are specific to Vim.
728 call assert_equal('window', luaeval('vim.type(vim.window())'))
729 call assert_equal('buffer', luaeval('vim.type(vim.buffer())'))
730 call assert_equal('list', luaeval('vim.type(vim.list())'))
731 call assert_equal('dict', luaeval('vim.type(vim.dict())'))
Bram Moolenaarca06da92018-07-01 15:12:05 +0200732 call assert_equal('funcref', luaeval('vim.type(vim.funcref("Test_type"))'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200733endfunc
734
735" Test vim.open()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100736func Test_lua_open()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200737 call assert_notmatch('XOpen', execute('ls'))
738
739 " Open a buffer XOpen1, but do not jump to it.
740 lua b = vim.open('XOpen1')
741 call assert_equal('XOpen1', luaeval('b.name'))
742 call assert_equal('', bufname('%'))
743
744 call assert_match('XOpen1', execute('ls'))
745 call assert_notequal('XOpen2', bufname('%'))
746
747 " Open a buffer XOpen2 and jump to it.
748 lua b = vim.open('XOpen2')()
749 call assert_equal('XOpen2', luaeval('b.name'))
750 call assert_equal('XOpen2', bufname('%'))
751
752 lua b = nil
753 %bwipe!
754endfunc
755
Bram Moolenaar788fbb42020-05-31 14:08:12 +0200756func Test_update_package_paths()
757 set runtimepath+=./testluaplugin
758 call assert_equal("hello from lua", luaeval("require('testluaplugin').hello()"))
759endfunc
760
Bram Moolenaar801ab062020-06-25 19:27:56 +0200761func Vim_func_call_lua_callback(Concat, Cb)
762 let l:message = a:Concat("hello", "vim")
763 call a:Cb(l:message)
764endfunc
765
766func Test_pass_lua_callback_to_vim_from_lua()
767 lua pass_lua_callback_to_vim_from_lua_result = ""
768 call assert_equal("", luaeval("pass_lua_callback_to_vim_from_lua_result"))
769 lua <<EOF
770 vim.funcref('Vim_func_call_lua_callback')(
771 function(greeting, message)
772 return greeting .. " " .. message
773 end,
774 function(message)
775 pass_lua_callback_to_vim_from_lua_result = message
776 end)
777EOF
778 call assert_equal("hello vim", luaeval("pass_lua_callback_to_vim_from_lua_result"))
779endfunc
780
781func Vim_func_call_metatable_lua_callback(Greet)
782 return a:Greet("world")
783endfunc
784
785func Test_pass_lua_metatable_callback_to_vim_from_lua()
786 let result = luaeval("vim.funcref('Vim_func_call_metatable_lua_callback')(setmetatable({ space = ' '}, { __call = function(tbl, msg) return 'hello' .. tbl.space .. msg end }) )")
787 call assert_equal("hello world", result)
788endfunc
789
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200790" Test vim.line()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100791func Test_lua_line()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200792 new
793 call setline(1, ['first line', 'second line'])
794 1
795 call assert_equal('first line', luaeval('vim.line()'))
796 2
797 call assert_equal('second line', luaeval('vim.line()'))
798 bwipe!
799endfunc
800
801" Test vim.beep()
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100802func Test_lua_beep()
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200803 call assert_beeps('lua vim.beep()')
804endfunc
805
806" Test errors in luaeval()
807func Test_luaeval_error()
808 " Compile error
809 call assert_fails("call luaeval('-nil')",
810 \ '[string "luaeval"]:1: attempt to perform arithmetic on a nil value')
811 call assert_fails("call luaeval(']')",
812 \ "[string \"luaeval\"]:1: unexpected symbol near ']'")
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200813 lua co = coroutine.create(function () print("hi") end)
814 call assert_fails('let i = luaeval("co")', 'luaeval: cannot convert value')
815 lua co = nil
816 call assert_fails('let m = luaeval("{}")', 'luaeval: cannot convert value')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200817endfunc
818
819" Test :luafile foo.lua
820func Test_luafile()
821 call delete('Xlua_file')
Bram Moolenaareb04f082020-05-17 14:32:35 +0200822 call writefile(["str = 'hello'", "num = 123" ], 'Xlua_file')
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200823 call setfperm('Xlua_file', 'r-xr-xr-x')
824
825 luafile Xlua_file
826 call assert_equal('hello', luaeval('str'))
Bram Moolenaareb04f082020-05-17 14:32:35 +0200827 call assert_equal(123, luaeval('num'))
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200828
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200829 lua str, num = nil
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200830 call delete('Xlua_file')
831endfunc
832
833" Test :luafile %
834func Test_luafile_percent()
835 new Xlua_file
836 append
837 str, num = 'foo', 321.0
838 print(string.format('str=%s, num=%d', str, num))
839.
840 w!
841 luafile %
842 let msg = split(execute('message'), "\n")[-1]
843 call assert_equal('str=foo, num=321', msg)
844
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200845 lua str, num = nil
846 call delete('Xlua_file')
847 bwipe!
848endfunc
849
850" Test :luafile with syntax error
851func Test_luafile_error()
852 new Xlua_file
853 call writefile(['nil = 0' ], 'Xlua_file')
854 call setfperm('Xlua_file', 'r-xr-xr-x')
855
856 call assert_fails('luafile Xlua_file', "Xlua_file:1: unexpected symbol near 'nil'")
857
Bram Moolenaar4ff48142018-06-30 21:50:25 +0200858 call delete('Xlua_file')
Bram Moolenaard58f03b2017-01-29 22:48:45 +0100859 bwipe!
860endfunc
Bram Moolenaar53901442018-07-25 22:02:36 +0200861
Bram Moolenaar78e006b2021-07-28 15:07:01 +0200862" Test :luafile printing a long string
863func Test_luafile_print()
864 new Xlua_file
865 let lines =<< trim END
866 local data = ''
867 for i = 1, 130 do
868 data = data .. 'xxxxx asd as as dad sad sad xz cxz czxcxzczxc ad ad asd asd asd asd asd'
869 end
870 print(data)
871 END
872 call setline(1, lines)
873 w
874 luafile %
875
876 call delete('Xlua_file')
877 bwipe!
878endfunc
879
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200880" Test for dealing with strings containing newlines and null character
881func Test_lua_string_with_newline()
Bram Moolenaar2a4bd002021-07-28 21:48:59 +0200882 let x = execute('lua print("Hello\nWorld", 2)')
883 call assert_equal("\nHello\nWorld 2", x)
Bram Moolenaare49b8e82020-07-01 13:52:55 +0200884 new
885 lua k = vim.buffer(vim.eval('bufnr()'))
886 lua k:insert("Hello\0World", 0)
887 call assert_equal(["Hello\nWorld", ''], getline(1, '$'))
888 close!
889endfunc
890
Bram Moolenaar5feabe02020-01-30 18:24:53 +0100891func Test_lua_set_cursor()
Bram Moolenaar53901442018-07-25 22:02:36 +0200892 " Check that setting the cursor position works.
893 new
894 call setline(1, ['first line', 'second line'])
895 normal gg
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200896 lua << trim EOF
897 w = vim.window()
898 w.line = 1
899 w.col = 5
900 EOF
Bram Moolenaar53901442018-07-25 22:02:36 +0200901 call assert_equal([1, 5], [line('.'), col('.')])
902
903 " Check that movement after setting cursor position keeps current column.
904 normal j
905 call assert_equal([2, 5], [line('.'), col('.')])
906endfunc
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200907
908" Test for various heredoc syntax
909func Test_lua_heredoc()
910 lua << END
911vim.command('let s = "A"')
912END
913 lua <<
914vim.command('let s ..= "B"')
915.
916 lua << trim END
917 vim.command('let s ..= "C"')
918 END
919 lua << trim
920 vim.command('let s ..= "D"')
921 .
Bram Moolenaar6ab09532020-05-01 14:10:13 +0200922 lua << trim eof
923 vim.command('let s ..= "E"')
924 eof
925 call assert_equal('ABCDE', s)
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +0200926endfunc
927
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +0200928" Test for adding, accessing and removing global variables using the vim.g
929" Lua table
930func Test_lua_global_var_table()
931 " Access global variables with different types of values
932 let g:Var1 = 10
933 let g:Var2 = 'Hello'
934 let g:Var3 = ['a', 'b']
935 let g:Var4 = #{x: 'edit', y: 'run'}
936 let g:Var5 = function('min')
937 call assert_equal(10, luaeval('vim.g.Var1'))
938 call assert_equal('Hello', luaeval('vim.g.Var2'))
939 call assert_equal(['a', 'b'], luaeval('vim.g.Var3'))
940 call assert_equal(#{x: 'edit', y: 'run'}, luaeval('vim.g.Var4'))
941 call assert_equal(2, luaeval('vim.g.Var5')([5, 9, 2]))
942
943 " Access list of dictionaries and dictionary of lists
944 let g:Var1 = [#{a: 10}, #{b: 20}]
945 let g:Var2 = #{p: [5, 6], q: [1.1, 2.2]}
946 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
947 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
948
949 " Create new global variables with different types of values
950 unlet g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
951 lua << trim END
952 vim.g.Var1 = 34
953 vim.g.Var2 = 'World'
954 vim.g.Var3 = vim.list({'#', '$'})
955 vim.g.Var4 = vim.dict({model='honda', year=2020})
956 vim.g.Var5 = vim.funcref('max')
957 END
958 call assert_equal(34, g:Var1)
959 call assert_equal('World', g:Var2)
960 call assert_equal(['#', '$'], g:Var3)
961 call assert_equal(#{model: 'honda', year: 2020}, g:Var4)
962 call assert_equal(10, g:Var5([5, 10, 9]))
963
964 " Create list of dictionaries and dictionary of lists
965 unlet g:Var1 g:Var2
966 lua << trim END
967 vim.g.Var1 = vim.list({vim.dict({a=10}), vim.dict({b=20})})
968 vim.g.Var2 = vim.dict({p=vim.list({5, 6}), q=vim.list({1.1, 2.2})})
969 END
970 call assert_equal([#{a: 10}, #{b: 20}], luaeval('vim.g.Var1'))
971 call assert_equal(#{p: [5, 6], q: [1.1, 2.2]}, luaeval('vim.g.Var2'))
972
973 " Modify a global variable with a list value or a dictionary value
974 let g:Var1 = [10, 20]
975 let g:Var2 = #{one: 'mercury', two: 'mars'}
976 lua << trim END
977 vim.g.Var1[2] = Nil
978 vim.g.Var1[3] = 15
979 vim.g.Var2['two'] = Nil
980 vim.g.Var2['three'] = 'earth'
981 END
982 call assert_equal([10, 15], g:Var1)
983 call assert_equal(#{one: 'mercury', three: 'earth'}, g:Var2)
984
985 " Remove global variables with different types of values
986 let g:Var1 = 10
987 let g:Var2 = 'Hello'
988 let g:Var3 = ['a', 'b']
989 let g:Var4 = #{x: 'edit', y: 'run'}
990 let g:Var5 = function('min')
991 lua << trim END
992 vim.g.Var1 = Nil
993 vim.g.Var2 = Nil
994 vim.g.Var3 = Nil
995 vim.g.Var4 = Nil
996 vim.g.Var5 = Nil
997 END
998 call assert_false(exists('g:Var1'))
999 call assert_false(exists('g:Var2'))
1000 call assert_false(exists('g:Var3'))
1001 call assert_false(exists('g:Var4'))
1002 call assert_false(exists('g:Var5'))
1003
1004 " Try to modify and remove a locked global variable
1005 let g:Var1 = 10
1006 lockvar g:Var1
1007 call assert_fails('lua vim.g.Var1 = 20', 'variable is locked')
1008 call assert_fails('lua vim.g.Var1 = Nil', 'variable is locked')
1009 unlockvar g:Var1
1010 let g:Var2 = [7, 14]
1011 lockvar 0 g:Var2
1012 lua vim.g.Var2[2] = Nil
1013 lua vim.g.Var2[3] = 21
1014 call assert_fails('lua vim.g.Var2 = Nil', 'variable is locked')
1015 call assert_equal([7, 21], g:Var2)
1016 lockvar 1 g:Var2
1017 call assert_fails('lua vim.g.Var2[2] = Nil', 'list is locked')
1018 call assert_fails('lua vim.g.Var2[3] = 21', 'list is locked')
1019 unlockvar g:Var2
1020
Bram Moolenaar4a011592021-08-05 15:11:08 +02001021 let g:TestFunc = function('len')
1022 call assert_fails('lua vim.g.func = vim.g.TestFunc', ['E704:', 'Couldn''t add to dictionary'])
1023 unlet g:TestFunc
1024
Yegappan Lakshmanan9dc4bef2021-08-04 21:12:52 +02001025 " Attempt to access a non-existing global variable
1026 call assert_equal(v:null, luaeval('vim.g.NonExistingVar'))
1027 lua vim.g.NonExisting = Nil
1028
1029 unlet! g:Var1 g:Var2 g:Var3 g:Var4 g:Var5
1030endfunc
1031
1032" Test for accessing and modifying predefined vim variables using the vim.v
1033" Lua table
1034func Test_lua_predefined_var_table()
1035 call assert_equal(v:progpath, luaeval('vim.v.progpath'))
1036 let v:errmsg = 'SomeError'
1037 call assert_equal('SomeError', luaeval('vim.v.errmsg'))
1038 lua vim.v.errmsg = 'OtherError'
1039 call assert_equal('OtherError', v:errmsg)
1040 call assert_fails('lua vim.v.errmsg = Nil', 'variable is fixed')
1041 let v:oldfiles = ['one', 'two']
1042 call assert_equal(['one', 'two'], luaeval('vim.v.oldfiles'))
1043 lua vim.v.oldfiles = vim.list({})
1044 call assert_equal([], v:oldfiles)
1045 call assert_equal(v:null, luaeval('vim.v.null'))
1046 call assert_fails('lua vim.v.argv[1] = Nil', 'list is locked')
1047 call assert_fails('lua vim.v.newvar = 1', 'Dictionary is locked')
1048endfunc
1049
1050" Test for adding, accessing and modifying window-local variables using the
1051" vim.w Lua table
1052func Test_lua_window_var_table()
1053 " Access window variables with different types of values
1054 new
1055 let w:wvar1 = 10
1056 let w:wvar2 = 'edit'
1057 let w:wvar3 = 3.14
1058 let w:wvar4 = 0zdeadbeef
1059 let w:wvar5 = ['a', 'b']
1060 let w:wvar6 = #{action: 'run'}
1061 call assert_equal(10, luaeval('vim.w.wvar1'))
1062 call assert_equal('edit', luaeval('vim.w.wvar2'))
1063 call assert_equal(3.14, luaeval('vim.w.wvar3'))
1064 call assert_equal(0zdeadbeef, luaeval('vim.w.wvar4'))
1065 call assert_equal(['a', 'b'], luaeval('vim.w.wvar5'))
1066 call assert_equal(#{action: 'run'}, luaeval('vim.w.wvar6'))
1067 call assert_equal(v:null, luaeval('vim.w.NonExisting'))
1068
1069 " modify a window variable
1070 lua vim.w.wvar2 = 'paste'
1071 call assert_equal('paste', w:wvar2)
1072
1073 " change the type stored in a variable
1074 let w:wvar2 = [1, 2]
1075 lua vim.w.wvar2 = vim.dict({a=10, b=20})
1076 call assert_equal(#{a: 10, b: 20}, w:wvar2)
1077
1078 " create a new window variable
1079 lua vim.w.wvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1080 call assert_equal(#{a: [1, 2], b: 20}, w:wvar7)
1081
1082 " delete a window variable
1083 lua vim.w.wvar2 = Nil
1084 call assert_false(exists('w:wvar2'))
1085
1086 new
1087 call assert_equal(v:null, luaeval('vim.w.wvar1'))
1088 call assert_equal(v:null, luaeval('vim.w.wvar2'))
1089 %bw!
1090endfunc
1091
1092" Test for adding, accessing and modifying buffer-local variables using the
1093" vim.b Lua table
1094func Test_lua_buffer_var_table()
1095 " Access buffer variables with different types of values
1096 let b:bvar1 = 10
1097 let b:bvar2 = 'edit'
1098 let b:bvar3 = 3.14
1099 let b:bvar4 = 0zdeadbeef
1100 let b:bvar5 = ['a', 'b']
1101 let b:bvar6 = #{action: 'run'}
1102 call assert_equal(10, luaeval('vim.b.bvar1'))
1103 call assert_equal('edit', luaeval('vim.b.bvar2'))
1104 call assert_equal(3.14, luaeval('vim.b.bvar3'))
1105 call assert_equal(0zdeadbeef, luaeval('vim.b.bvar4'))
1106 call assert_equal(['a', 'b'], luaeval('vim.b.bvar5'))
1107 call assert_equal(#{action: 'run'}, luaeval('vim.b.bvar6'))
1108 call assert_equal(v:null, luaeval('vim.b.NonExisting'))
1109
1110 " modify a buffer variable
1111 lua vim.b.bvar2 = 'paste'
1112 call assert_equal('paste', b:bvar2)
1113
1114 " change the type stored in a variable
1115 let b:bvar2 = [1, 2]
1116 lua vim.b.bvar2 = vim.dict({a=10, b=20})
1117 call assert_equal(#{a: 10, b: 20}, b:bvar2)
1118
1119 " create a new buffer variable
1120 lua vim.b.bvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1121 call assert_equal(#{a: [1, 2], b: 20}, b:bvar7)
1122
1123 " delete a buffer variable
1124 lua vim.b.bvar2 = Nil
1125 call assert_false(exists('b:bvar2'))
1126
1127 new
1128 call assert_equal(v:null, luaeval('vim.b.bvar1'))
1129 call assert_equal(v:null, luaeval('vim.b.bvar2'))
1130 %bw!
1131endfunc
1132
1133" Test for adding, accessing and modifying tabpage-local variables using the
1134" vim.t Lua table
1135func Test_lua_tabpage_var_table()
1136 " Access tabpage variables with different types of values
1137 let t:tvar1 = 10
1138 let t:tvar2 = 'edit'
1139 let t:tvar3 = 3.14
1140 let t:tvar4 = 0zdeadbeef
1141 let t:tvar5 = ['a', 'b']
1142 let t:tvar6 = #{action: 'run'}
1143 call assert_equal(10, luaeval('vim.t.tvar1'))
1144 call assert_equal('edit', luaeval('vim.t.tvar2'))
1145 call assert_equal(3.14, luaeval('vim.t.tvar3'))
1146 call assert_equal(0zdeadbeef, luaeval('vim.t.tvar4'))
1147 call assert_equal(['a', 'b'], luaeval('vim.t.tvar5'))
1148 call assert_equal(#{action: 'run'}, luaeval('vim.t.tvar6'))
1149 call assert_equal(v:null, luaeval('vim.t.NonExisting'))
1150
1151 " modify a tabpage variable
1152 lua vim.t.tvar2 = 'paste'
1153 call assert_equal('paste', t:tvar2)
1154
1155 " change the type stored in a variable
1156 let t:tvar2 = [1, 2]
1157 lua vim.t.tvar2 = vim.dict({a=10, b=20})
1158 call assert_equal(#{a: 10, b: 20}, t:tvar2)
1159
1160 " create a new tabpage variable
1161 lua vim.t.tvar7 = vim.dict({a=vim.list({1, 2}), b=20})
1162 call assert_equal(#{a: [1, 2], b: 20}, t:tvar7)
1163
1164 " delete a tabpage variable
1165 lua vim.t.tvar2 = Nil
1166 call assert_false(exists('t:tvar2'))
1167
1168 tabnew
1169 call assert_equal(v:null, luaeval('vim.t.tvar1'))
1170 call assert_equal(v:null, luaeval('vim.t.tvar2'))
1171 %bw!
1172endfunc
1173
Yegappan Lakshmanan11328bc2021-08-06 21:34:38 +02001174" Test for vim.version()
1175func Test_lua_vim_version()
1176 lua << trim END
1177 vimver = vim.version()
1178 vimver_n = vimver.major * 100 + vimver.minor
1179 END
1180 call assert_equal(v:version, luaeval('vimver_n'))
1181endfunc
1182
1183" Test for running multiple commands using vim.command()
1184func Test_lua_multiple_commands()
1185 lua << trim END
1186 vim.command([[
1187 let Var1 = []
1188 for i in range(3)
1189 let Var1 += [#{name: 'x'}]
1190 endfor
1191 augroup Luagroup
1192 autocmd!
1193 autocmd User Luatest echo 'Hello'
1194 augroup END
1195 ]])
1196 END
1197 call assert_equal([{'name': 'x'}, {'name': 'x'}, {'name': 'x'}], Var1)
1198 call assert_true(exists('#Luagroup'))
1199 call assert_true(exists('#Luagroup#User#Luatest'))
1200 augroup Luagroup
1201 autocmd!
1202 augroup END
1203 augroup! Luagroup
1204endfunc
1205
Dominique Pelleb6643d12022-03-20 11:46:01 +00001206func Test_lua_debug()
1207 CheckRunVimInTerminal
1208
1209 let buf = RunVimInTerminal('', {'rows': 10})
1210 call term_sendkeys(buf, ":lua debug.debug()\n")
1211 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1212
1213 call term_sendkeys(buf, "foo = 42\n")
1214 call WaitForAssert({-> assert_equal('lua_debug> foo = 42', term_getline(buf, 9))})
1215 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1216
1217 call term_sendkeys(buf, "print(foo)\n")
1218 call WaitForAssert({-> assert_equal('lua_debug> print(foo)', term_getline(buf, 8))})
1219 call WaitForAssert({-> assert_equal('42', term_getline(buf, 9))})
1220 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1221
Dominique Pelle81b573d2022-03-22 21:14:55 +00001222 call term_sendkeys(buf, "-\n")
1223 call WaitForAssert({-> assert_equal("(debug command):1: unexpected symbol near '-'",
1224 \ term_getline(buf, 9))})
1225 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1226
Dominique Pelleb6643d12022-03-20 11:46:01 +00001227 call term_sendkeys(buf, "cont\n")
1228 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1229
Dominique Pelle81b573d2022-03-22 21:14:55 +00001230 " Entering an empty line also exits the debugger.
1231 call term_sendkeys(buf, ":lua debug.debug()\n")
1232 call WaitForAssert({-> assert_equal('lua_debug> ', term_getline(buf, 10))})
1233 call term_sendkeys(buf, "\n")
1234 call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))})
1235
Dominique Pelleb6643d12022-03-20 11:46:01 +00001236 call StopVimInTerminal(buf)
Dominique Pelleb6643d12022-03-20 11:46:01 +00001237endfunc
1238
Bram Moolenaar6c2b7b82020-04-14 20:15:49 +02001239" vim: shiftwidth=2 sts=2 expandtab