xref: /vim-8.2.3635/src/testdir/test_lua.vim (revision 01a6c216)
1" Tests for Lua.
2
3if !has('lua')
4  finish
5endif
6
7" Check that switching to another buffer does not trigger ml_get error.
8func Test_command_new_no_ml_get_error()
9  new
10  let wincount = winnr('$')
11  call setline(1, ['one', 'two', 'three'])
12  luado vim.command("new")
13  call assert_equal(wincount + 1, winnr('$'))
14  %bwipe!
15endfunc
16
17" Test vim.command()
18func Test_command()
19  new
20  call setline(1, ['one', 'two', 'three'])
21  luado vim.command("1,2d_")
22  call assert_equal(['three'], getline(1, '$'))
23  bwipe!
24endfunc
25
26" Test vim.eval()
27func Test_eval()
28  " lua.eval with a number
29  lua v = vim.eval('123')
30  call assert_equal('number', luaeval('vim.type(v)'))
31  call assert_equal(123.0, luaeval('v'))
32
33  " lua.eval with a string
34  lua v = vim.eval('"abc"')
35  call assert_equal('string', luaeval('vim.type(v)'))
36  call assert_equal('abc', luaeval('v'))
37
38  " lua.eval with a list
39  lua v = vim.eval("['a']")
40  call assert_equal('list', luaeval('vim.type(v)'))
41  call assert_equal(['a'], luaeval('v'))
42
43  " lua.eval with a dict
44  lua v = vim.eval("{'a':'b'}")
45  call assert_equal('dict', luaeval('vim.type(v)'))
46  call assert_equal({'a':'b'}, luaeval('v'))
47
48  call assert_fails('lua v = vim.eval(nil)',
49        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got nil)")
50  call assert_fails('lua v = vim.eval(true)',
51        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got boolean)")
52  call assert_fails('lua v = vim.eval({})',
53        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got table)")
54  call assert_fails('lua v = vim.eval(print)',
55        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got function)")
56  call assert_fails('lua v = vim.eval(vim.buffer())',
57        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got userdata)")
58
59  lua v = nil
60endfunc
61
62" Test vim.window()
63func Test_window()
64  e Xfoo2
65  new Xfoo1
66
67  " Window 1 (top window) contains Xfoo1
68  " Window 2 (bottom window) contains Xfoo2
69  call assert_equal('Xfoo1', luaeval('vim.window(1):buffer().name'))
70  call assert_equal('Xfoo2', luaeval('vim.window(2):buffer().name'))
71
72  " Window 3 does not exist so vim.window(3) should return nil
73  call assert_equal('nil', luaeval('tostring(vim.window(3))'))
74
75  %bwipe!
76endfunc
77
78" Test vim.window().height
79func Test_window_height()
80  new
81  lua vim.window().height = 2
82  call assert_equal(2, winheight(0))
83  lua vim.window().height = vim.window().height + 1
84  call assert_equal(3, winheight(0))
85  bwipe!
86endfunc
87
88" Test vim.window().width
89func Test_window_width()
90  vert new
91  lua vim.window().width = 2
92  call assert_equal(2, winwidth(0))
93  lua vim.window().width = vim.window().width + 1
94  call assert_equal(3, winwidth(0))
95  bwipe!
96endfunc
97
98" Test vim.window().line and vim.window.col
99func Test_window_line_col()
100  new
101  call setline(1, ['line1', 'line2', 'line3'])
102  lua vim.window().line = 2
103  lua vim.window().col = 4
104  call assert_equal([0, 2, 4, 0], getpos('.'))
105  lua vim.window().line = vim.window().line + 1
106  lua vim.window().col = vim.window().col - 1
107  call assert_equal([0, 3, 3, 0], getpos('.'))
108
109  call assert_fails('lua vim.window().line = 10',
110        \           '[string "vim chunk"]:1: line out of range')
111  bwipe!
112endfunc
113
114" Test setting the current window
115func Test_window_set_current()
116  new Xfoo1
117  lua w1 = vim.window()
118  new Xfoo2
119  lua w2 = vim.window()
120
121  call assert_equal('Xfoo2', bufname('%'))
122  lua w1()
123  call assert_equal('Xfoo1', bufname('%'))
124  lua w2()
125  call assert_equal('Xfoo2', bufname('%'))
126
127  lua w1, w2 = nil
128  %bwipe!
129endfunc
130
131" Test vim.window().buffer
132func Test_window_buffer()
133  new Xfoo1
134  lua w1 = vim.window()
135  lua b1 = w1.buffer()
136  new Xfoo2
137  lua w2 = vim.window()
138  lua b2 = w2.buffer()
139
140  lua b1()
141  call assert_equal('Xfoo1', bufname('%'))
142  lua b2()
143  call assert_equal('Xfoo2', bufname('%'))
144
145  lua b1, b2, w1, w2 = nil
146  %bwipe!
147endfunc
148
149" Test vim.window():previous() and vim.window():next()
150func Test_window_next_previous()
151  new Xfoo1
152  new Xfoo2
153  new Xfoo3
154  wincmd j
155
156  call assert_equal('Xfoo2', luaeval('vim.window().buffer().name'))
157  call assert_equal('Xfoo1', luaeval('vim.window():next():buffer().name'))
158  call assert_equal('Xfoo3', luaeval('vim.window():previous():buffer().name'))
159
160  %bwipe!
161endfunc
162
163" Test vim.window():isvalid()
164func Test_window_isvalid()
165  new Xfoo
166  lua w = vim.window()
167  call assert_true(luaeval('w:isvalid()'))
168
169  " FIXME: how to test the case when isvalid() returns v:false?
170  " isvalid() gives errors when the window is deleted. Is it a bug?
171
172  lua w = nil
173  bwipe!
174endfunc
175
176" Test vim.buffer() with and without argument
177func Test_buffer()
178  new Xfoo1
179  let bn1 = bufnr('%')
180  new Xfoo2
181  let bn2 = bufnr('%')
182
183  " Test vim.buffer() without argument.
184  call assert_equal('Xfoo2', luaeval("vim.buffer().name"))
185
186  " Test vim.buffer() with string argument.
187  call assert_equal('Xfoo1', luaeval("vim.buffer('Xfoo1').name"))
188  call assert_equal('Xfoo2', luaeval("vim.buffer('Xfoo2').name"))
189
190  " Test vim.buffer() with integer argument.
191  call assert_equal('Xfoo1', luaeval("vim.buffer(" . bn1 . ").name"))
192  call assert_equal('Xfoo2', luaeval("vim.buffer(" . bn2 . ").name"))
193
194  lua bn1, bn2 = nil
195  %bwipe!
196endfunc
197
198" Test vim.buffer().name and vim.buffer().fname
199func Test_buffer_name()
200  new
201  call assert_equal('', luaeval('vim.buffer().name'))
202  call assert_equal('', luaeval('vim.buffer().fname'))
203  bwipe!
204
205  new Xfoo
206  call assert_equal('Xfoo', luaeval('vim.buffer().name'))
207  call assert_equal(expand('%:p'), luaeval('vim.buffer().fname'))
208  bwipe!
209endfunc
210
211" Test vim.buffer().number
212func Test_buffer_number()
213  " All numbers in Lua are floating points number (no integers).
214  call assert_equal(bufnr('%'), float2nr(luaeval('vim.buffer().number')))
215endfunc
216
217" Test inserting lines in buffer.
218func Test_buffer_insert()
219  new
220  lua vim.buffer()[1] = '3'
221  lua vim.buffer():insert('1', 0)
222  lua vim.buffer():insert('2', 1)
223  lua vim.buffer():insert('4', 10)
224
225  call assert_equal(['1', '2', '3', '4'], getline(1, '$'))
226  bwipe!
227endfunc
228
229" Test deleting line in buffer
230func Test_buffer_delete()
231  new
232  call setline(1, ['1', '2', '3'])
233  lua vim.buffer()[2] = nil
234  call assert_equal(['1', '3'], getline(1, '$'))
235
236  call assert_fails('lua vim.buffer()[3] = nil',
237        \           '[string "vim chunk"]:1: invalid line number')
238  bwipe!
239endfunc
240
241" Test #vim.buffer() i.e. number of lines in buffer
242func Test_buffer_number_lines()
243  new
244  call setline(1, ['a', 'b', 'c'])
245  call assert_equal(3.0, luaeval('#vim.buffer()'))
246  bwipe!
247endfunc
248
249" Test vim.buffer():next() and vim.buffer():previous()
250" Note that these functions get the next or previous buffers
251" but do not switch buffer.
252func Test_buffer_next_previous()
253  new Xfoo1
254  new Xfoo2
255  new Xfoo3
256  b Xfoo2
257
258  lua bn = vim.buffer():next()
259  lua bp = vim.buffer():previous()
260
261  call assert_equal('Xfoo2', luaeval('vim.buffer().name'))
262  call assert_equal('Xfoo1', luaeval('bp.name'))
263  call assert_equal('Xfoo3', luaeval('bn.name'))
264
265  call assert_equal('Xfoo2', bufname('%'))
266
267  lua bn()
268  call assert_equal('Xfoo3', luaeval('vim.buffer().name'))
269  call assert_equal('Xfoo3', bufname('%'))
270
271  lua bp()
272  call assert_equal('Xfoo1', luaeval('vim.buffer().name'))
273  call assert_equal('Xfoo1', bufname('%'))
274
275  lua bn, bp = nil
276  %bwipe!
277endfunc
278
279" Test vim.buffer():isvalid()
280func Test_buffer_isvalid()
281  new Xfoo
282  lua b = vim.buffer()
283  call assert_true(luaeval('b:isvalid()'))
284
285  " FIXME: how to test the case when isvalid() returns v:false?
286  " isvalid() gives errors when the buffer is wiped. Is it a bug?
287
288  lua b = nil
289  bwipe!
290endfunc
291
292func Test_list()
293  call assert_equal([], luaeval('vim.list()'))
294
295  let l = []
296  lua l = vim.eval('l')
297  lua l:add(123)
298  lua l:add('abc')
299  lua l:add(true)
300  lua l:add(false)
301  lua l:add(nil)
302  lua l:add(vim.eval("[1, 2, 3]"))
303  lua l:add(vim.eval("{'a':1, 'b':2, 'c':3}"))
304  call assert_equal([123.0, 'abc', v:true, v:false, v:null, [1, 2, 3], {'a': 1, 'b': 2, 'c': 3}], l)
305  call assert_equal(7.0, luaeval('#l'))
306  call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
307
308  lua l[0] = 124
309  lua l[5] = nil
310  lua l:insert('first')
311  lua l:insert('xx', 3)
312  call assert_equal(['first', 124.0, 'abc', 'xx', v:true, v:false, v:null, {'a': 1, 'b': 2, 'c': 3}], l)
313
314  lockvar 1 l
315  call assert_fails('lua l:add("x")', '[string "vim chunk"]:1: list is locked')
316
317  lua l = nil
318endfunc
319
320func Test_list_table()
321  " See :help lua-vim
322  " Non-numeric keys should not be used to initialize the list
323  " so say = 'hi' should be ignored.
324  lua t = {3.14, 'hello', false, true, say = 'hi'}
325  call assert_equal([3.14, 'hello', v:false, v:true], luaeval('vim.list(t)'))
326  lua t = nil
327
328  call assert_fails('lua vim.list(1)', '[string "vim chunk"]:1: table expected, got number')
329  call assert_fails('lua vim.list("x")', '[string "vim chunk"]:1: table expected, got string')
330  call assert_fails('lua vim.list(print)', '[string "vim chunk"]:1: table expected, got function')
331  call assert_fails('lua vim.list(true)', '[string "vim chunk"]:1: table expected, got boolean')
332endfunc
333
334" Test l() i.e. iterator on list
335func Test_list_iter()
336  lua l = vim.list():add('foo'):add('bar')
337  lua str = ''
338  lua for v in l() do str = str .. v end
339  call assert_equal('foobar', luaeval('str'))
340
341  lua str, l = nil
342endfunc
343
344func Test_recursive_list()
345  lua l = vim.list():add(1):add(2)
346  lua l = l:add(l)
347
348  call assert_equal(1.0, luaeval('l[0]'))
349  call assert_equal(2.0, luaeval('l[1]'))
350
351  call assert_equal(1.0, luaeval('l[2][0]'))
352  call assert_equal(2.0, luaeval('l[2][1]'))
353
354  call assert_equal(1.0, luaeval('l[2][2][0]'))
355  call assert_equal(2.0, luaeval('l[2][2][1]'))
356
357  call assert_equal('[1.0, 2.0, [...]]', string(luaeval('l')))
358
359  call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
360  call assert_equal(luaeval('tostring(l)'), luaeval('tostring(l[2])'))
361
362  call assert_equal(luaeval('l'), luaeval('l[2]'))
363  call assert_equal(luaeval('l'), luaeval('l[2][2]'))
364
365  lua l = nil
366endfunc
367
368func Test_dict()
369  call assert_equal({}, luaeval('vim.dict()'))
370
371  let d = {}
372  lua d = vim.eval('d')
373  lua d[0] = 123
374  lua d[1] = "abc"
375  lua d[2] = true
376  lua d[3] = false
377  lua d[4] = vim.eval("[1, 2, 3]")
378  lua d[5] = vim.eval("{'a':1, 'b':2, 'c':3}")
379  call assert_equal({'0':123.0, '1':'abc', '2':v:true, '3':v:false, '4': [1, 2, 3], '5': {'a':1, 'b':2, 'c':3}}, d)
380  call assert_equal(6.0, luaeval('#d'))
381  call assert_match('^dict: \%(0x\)\?\x\+$', luaeval('tostring(d)'))
382
383  call assert_equal('abc', luaeval('d[1]'))
384
385  lua d[0] = 124
386  lua d[4] = nil
387  call assert_equal({'0':124.0, '1':'abc', '2':v:true, '3':v:false, '5': {'a':1, 'b':2, 'c':3}}, d)
388
389  lockvar 1 d
390  call assert_fails('lua d[6] = 1', '[string "vim chunk"]:1: dict is locked')
391
392  lua d = nil
393endfunc
394
395func Test_dict_table()
396  lua t = {key1 = 'x', key2 = 3.14, key3 = true, key4 = false}
397  call assert_equal({'key1': 'x', 'key2': 3.14, 'key3': v:true, 'key4': v:false},
398        \           luaeval('vim.dict(t)'))
399
400  " Same example as in :help lua-vim.
401  lua t = {math.pi, false, say = 'hi'}
402  " FIXME: commented out as it currently does not work as documented:
403  " Expected {'say': 'hi'}
404  " but got {'1': 3.141593, '2': v:false, 'say': 'hi'}
405  " Is the documentation or the code wrong?
406  "call assert_equal({'say' : 'hi'}, luaeval('vim.dict(t)'))
407  lua t = nil
408
409  call assert_fails('lua vim.dict(1)', '[string "vim chunk"]:1: table expected, got number')
410  call assert_fails('lua vim.dict("x")', '[string "vim chunk"]:1: table expected, got string')
411  call assert_fails('lua vim.dict(print)', '[string "vim chunk"]:1: table expected, got function')
412  call assert_fails('lua vim.dict(true)', '[string "vim chunk"]:1: table expected, got boolean')
413endfunc
414
415" Test d() i.e. iterator on dictionary
416func Test_dict_iter()
417  let d = {'a': 1, 'b':2}
418  lua d = vim.eval('d')
419  lua str = ''
420  lua for k,v in d() do str = str .. k ..':' .. v .. ',' end
421  call assert_equal('a:1,b:2,', luaeval('str'))
422
423  lua str, d = nil
424endfunc
425
426func Test_funcref()
427  function I(x)
428    return a:x
429  endfunction
430  let R = function('I')
431  lua i1 = vim.funcref"I"
432  lua i2 = vim.eval"R"
433  lua msg = "funcref|test|" .. (#i2(i1) == #i1(i2) and "OK" or "FAIL")
434  lua msg = vim.funcref"tr"(msg, "|", " ")
435  call assert_equal("funcref test OK", luaeval('msg'))
436
437  " dict funcref
438  function Mylen() dict
439    return len(self.data)
440  endfunction
441  let l = [0, 1, 2, 3]
442  let mydict = {'data': l}
443  lua d = vim.eval"mydict"
444  lua d.len = vim.funcref"Mylen" -- assign d as 'self'
445  lua res = (d.len() == vim.funcref"len"(vim.eval"l")) and "OK" or "FAIL"
446  call assert_equal("OK", luaeval('res'))
447
448  lua i1, i2, msg, d, res = nil
449endfunc
450
451" Test vim.type()
452func Test_type()
453  " The following values are identical to Lua's type function.
454  call assert_equal('string',   luaeval('vim.type("foo")'))
455  call assert_equal('number',   luaeval('vim.type(1)'))
456  call assert_equal('number',   luaeval('vim.type(1.2)'))
457  call assert_equal('function', luaeval('vim.type(print)'))
458  call assert_equal('table',    luaeval('vim.type({})'))
459  call assert_equal('boolean',  luaeval('vim.type(true)'))
460  call assert_equal('boolean',  luaeval('vim.type(false)'))
461  call assert_equal('nil',      luaeval('vim.type(nil)'))
462
463  " The following values are specific to Vim.
464  call assert_equal('window',   luaeval('vim.type(vim.window())'))
465  call assert_equal('buffer',   luaeval('vim.type(vim.buffer())'))
466  call assert_equal('list',     luaeval('vim.type(vim.list())'))
467  call assert_equal('dict',     luaeval('vim.type(vim.dict())'))
468  call assert_equal('funcref',  luaeval('vim.type(vim.funcref("Test_type"))'))
469endfunc
470
471" Test vim.open()
472func Test_open()
473  call assert_notmatch('XOpen', execute('ls'))
474
475  " Open a buffer XOpen1, but do not jump to it.
476  lua b = vim.open('XOpen1')
477  call assert_equal('XOpen1', luaeval('b.name'))
478  call assert_equal('', bufname('%'))
479
480  call assert_match('XOpen1', execute('ls'))
481  call assert_notequal('XOpen2', bufname('%'))
482
483  " Open a buffer XOpen2 and jump to it.
484  lua b = vim.open('XOpen2')()
485  call assert_equal('XOpen2', luaeval('b.name'))
486  call assert_equal('XOpen2', bufname('%'))
487
488  lua b = nil
489  %bwipe!
490endfunc
491
492" Test vim.line()
493func Test_line()
494  new
495  call setline(1, ['first line', 'second line'])
496  1
497  call assert_equal('first line', luaeval('vim.line()'))
498  2
499  call assert_equal('second line', luaeval('vim.line()'))
500  bwipe!
501endfunc
502
503" Test vim.beep()
504func Test_beep()
505  call assert_beeps('lua vim.beep()')
506endfunc
507
508" Test errors in luaeval()
509func Test_luaeval_error()
510  " Compile error
511  call assert_fails("call luaeval('-nil')",
512  \ '[string "luaeval"]:1: attempt to perform arithmetic on a nil value')
513  call assert_fails("call luaeval(']')",
514  \ "[string \"luaeval\"]:1: unexpected symbol near ']'")
515endfunc
516
517" Test :luafile foo.lua
518func Test_luafile()
519  call delete('Xlua_file')
520  call writefile(["str = 'hello'", "num = 123.0" ], 'Xlua_file')
521  call setfperm('Xlua_file', 'r-xr-xr-x')
522
523  luafile Xlua_file
524  call assert_equal('hello', luaeval('str'))
525  call assert_equal(123.0, luaeval('num'))
526
527  lua str, num = nil
528  call delete('Xlua_file')
529endfunc
530
531" Test :luafile %
532func Test_luafile_percent()
533  new Xlua_file
534  append
535    str, num = 'foo', 321.0
536    print(string.format('str=%s, num=%d', str, num))
537.
538  w!
539  luafile %
540  let msg = split(execute('message'), "\n")[-1]
541  call assert_equal('str=foo, num=321', msg)
542
543  lua str, num = nil
544  call delete('Xlua_file')
545  bwipe!
546endfunc
547
548" Test :luafile with syntax error
549func Test_luafile_error()
550  new Xlua_file
551  call writefile(['nil = 0' ], 'Xlua_file')
552  call setfperm('Xlua_file', 'r-xr-xr-x')
553
554  call assert_fails('luafile Xlua_file', "Xlua_file:1: unexpected symbol near 'nil'")
555
556  call delete('Xlua_file')
557  bwipe!
558endfunc
559
560func Test_set_cursor()
561  " Check that setting the cursor position works.
562  new
563  call setline(1, ['first line', 'second line'])
564  normal gg
565  lua << EOF
566w = vim.window()
567w.line = 1
568w.col = 5
569EOF
570  call assert_equal([1, 5], [line('.'), col('.')])
571
572  " Check that movement after setting cursor position keeps current column.
573  normal j
574  call assert_equal([2, 5], [line('.'), col('.')])
575endfunc
576