xref: /vim-8.2.3635/src/testdir/test_lua.vim (revision e3f915d1)
1" Tests for Lua.
2
3source check.vim
4CheckFeature lua
5CheckFeature float
6
7let s:luaver = split(split(luaeval('_VERSION'), ' ')[1], '\.')
8let s:major = str2nr(s:luaver[0])
9let s:minor = str2nr(s:luaver[1])
10if s:major < 5 || (s:major == 5 && s:minor < 3)
11  let s:lua_53_or_later = 0
12else
13  let s:lua_53_or_later = 1
14endif
15
16func TearDown()
17  " Run garbage collection after each test to exercise luaV_setref().
18  call test_garbagecollect_now()
19endfunc
20
21" Check that switching to another buffer does not trigger ml_get error.
22func Test_lua_command_new_no_ml_get_error()
23  new
24  let wincount = winnr('$')
25  call setline(1, ['one', 'two', 'three'])
26  luado vim.command("new")
27  call assert_equal(wincount + 1, winnr('$'))
28  %bwipe!
29endfunc
30
31" Test vim.command()
32func Test_lua_command()
33  new
34  call setline(1, ['one', 'two', 'three'])
35  luado vim.command("1,2d_")
36  call assert_equal(['three'], getline(1, '$'))
37  bwipe!
38endfunc
39
40func Test_lua_luado()
41  new
42  call setline(1, ['one', 'two'])
43  luado return(linenr)
44  call assert_equal(['1', '2'], getline(1, '$'))
45  close!
46
47  " Error cases
48  call assert_fails('luado string.format()',
49        \ "[string \"vim chunk\"]:1: bad argument #1 to 'format' (string expected, got no value)")
50  call assert_fails('luado func()',
51        \ s:lua_53_or_later
52        \ ? "[string \"vim chunk\"]:1: attempt to call a nil value (global 'func')"
53        \ : "[string \"vim chunk\"]:1: attempt to call global 'func' (a nil value)")
54  call assert_fails('luado error("failed")', "[string \"vim chunk\"]:1: failed")
55endfunc
56
57" Test vim.eval()
58func Test_lua_eval()
59  " lua.eval with a number
60  lua v = vim.eval('123')
61  call assert_equal('number', luaeval('vim.type(v)'))
62  call assert_equal(123, luaeval('v'))
63
64  " lua.eval with a string
65  lua v = vim.eval('"abc"')
66  call assert_equal('string', 'vim.type(v)'->luaeval())
67  call assert_equal('abc', luaeval('v'))
68
69  " lua.eval with a list
70  lua v = vim.eval("['a']")
71  call assert_equal('list', luaeval('vim.type(v)'))
72  call assert_equal(['a'], luaeval('v'))
73
74  " lua.eval with a dict
75  lua v = vim.eval("{'a':'b'}")
76  call assert_equal('dict', luaeval('vim.type(v)'))
77  call assert_equal({'a':'b'}, luaeval('v'))
78
79  " lua.eval with a blob
80  lua v = vim.eval("0z00112233.deadbeef")
81  call assert_equal('blob', luaeval('vim.type(v)'))
82  call assert_equal(0z00112233.deadbeef, luaeval('v'))
83
84  " lua.eval with a float
85  lua v = vim.eval('3.14')
86  call assert_equal('number', luaeval('vim.type(v)'))
87  call assert_equal(3.14, luaeval('v'))
88
89  " lua.eval with a bool
90  lua v = vim.eval('v:true')
91  call assert_equal('number', luaeval('vim.type(v)'))
92  call assert_equal(1, luaeval('v'))
93  lua v = vim.eval('v:false')
94  call assert_equal('number', luaeval('vim.type(v)'))
95  call assert_equal(0, luaeval('v'))
96
97  " lua.eval with a null
98  lua v = vim.eval('v:null')
99  call assert_equal('nil', luaeval('vim.type(v)'))
100  call assert_equal(v:null, luaeval('v'))
101
102  call assert_fails('lua v = vim.eval(nil)',
103        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got nil)")
104  call assert_fails('lua v = vim.eval(true)',
105        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got boolean)")
106  call assert_fails('lua v = vim.eval({})',
107        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got table)")
108  call assert_fails('lua v = vim.eval(print)',
109        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got function)")
110  call assert_fails('lua v = vim.eval(vim.buffer())',
111        \ "[string \"vim chunk\"]:1: bad argument #1 to 'eval' (string expected, got userdata)")
112
113  lua v = nil
114endfunc
115
116" Test vim.window()
117func Test_lua_window()
118  e Xfoo2
119  new Xfoo1
120
121  " Window 1 (top window) contains Xfoo1
122  " Window 2 (bottom window) contains Xfoo2
123  call assert_equal('Xfoo1', luaeval('vim.window(1):buffer().name'))
124  call assert_equal('Xfoo2', luaeval('vim.window(2):buffer().name'))
125
126  " Window 3 does not exist so vim.window(3) should return nil
127  call assert_equal('nil', luaeval('tostring(vim.window(3))'))
128
129  call assert_fails("let n = luaeval('vim.window().xyz()')",
130        \ s:lua_53_or_later
131        \ ? "[string \"luaeval\"]:1: attempt to call a nil value (field 'xyz')"
132        \ : "[string \"luaeval\"]:1: attempt to call field 'xyz' (a nil value)")
133  call assert_fails('lua vim.window().xyz = 1',
134        \ "[string \"vim chunk\"]:1: invalid window property: `xyz'")
135
136  %bwipe!
137endfunc
138
139" Test vim.window().height
140func Test_lua_window_height()
141  new
142  lua vim.window().height = 2
143  call assert_equal(2, winheight(0))
144  lua vim.window().height = vim.window().height + 1
145  call assert_equal(3, winheight(0))
146  bwipe!
147endfunc
148
149" Test vim.window().width
150func Test_lua_window_width()
151  vert new
152  lua vim.window().width = 2
153  call assert_equal(2, winwidth(0))
154  lua vim.window().width = vim.window().width + 1
155  call assert_equal(3, winwidth(0))
156  bwipe!
157endfunc
158
159" Test vim.window().line and vim.window.col
160func Test_lua_window_line_col()
161  new
162  call setline(1, ['line1', 'line2', 'line3'])
163  lua vim.window().line = 2
164  lua vim.window().col = 4
165  call assert_equal([0, 2, 4, 0], getpos('.'))
166  lua vim.window().line = vim.window().line + 1
167  lua vim.window().col = vim.window().col - 1
168  call assert_equal([0, 3, 3, 0], getpos('.'))
169
170  call assert_fails('lua vim.window().line = 10',
171        \           '[string "vim chunk"]:1: line out of range')
172  bwipe!
173endfunc
174
175" Test vim.call
176func Test_lua_call()
177  call assert_equal(has('lua'), luaeval('vim.call("has", "lua")'))
178  call assert_equal(printf("Hello %s", "vim"), luaeval('vim.call("printf", "Hello %s", "vim")'))
179
180  " Error cases
181  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)')",
182        \ s:lua_53_or_later
183        \ ? '[string "luaeval"]:1: Function called with too many arguments'
184        \ : 'Function called with too many arguments')
185  lua co = coroutine.create(function () print("hi") end)
186  call assert_fails("call luaeval('vim.call(\"type\", co)')",
187        \ s:lua_53_or_later
188        \ ? '[string "luaeval"]:1: lua: cannot convert value'
189        \ : 'lua: cannot convert value')
190  lua co = nil
191  call assert_fails("call luaeval('vim.call(\"abc\")')",
192        \ ['E117:', s:lua_53_or_later ? '\[string "luaeval"]:1: lua: call_vim_function failed'
193        \                             : 'lua: call_vim_function failed'])
194endfunc
195
196" Test vim.fn.*
197func Test_lua_fn()
198  call assert_equal(has('lua'), luaeval('vim.fn.has("lua")'))
199  call assert_equal(printf("Hello %s", "vim"), luaeval('vim.fn.printf("Hello %s", "vim")'))
200endfunc
201
202" Test setting the current window
203func Test_lua_window_set_current()
204  new Xfoo1
205  lua w1 = vim.window()
206  new Xfoo2
207  lua w2 = vim.window()
208
209  call assert_equal('Xfoo2', bufname('%'))
210  lua w1()
211  call assert_equal('Xfoo1', bufname('%'))
212  lua w2()
213  call assert_equal('Xfoo2', bufname('%'))
214
215  lua w1, w2 = nil
216  %bwipe!
217endfunc
218
219" Test vim.window().buffer
220func Test_lua_window_buffer()
221  new Xfoo1
222  lua w1 = vim.window()
223  lua b1 = w1.buffer()
224  new Xfoo2
225  lua w2 = vim.window()
226  lua b2 = w2.buffer()
227
228  lua b1()
229  call assert_equal('Xfoo1', bufname('%'))
230  lua b2()
231  call assert_equal('Xfoo2', bufname('%'))
232
233  lua b1, b2, w1, w2 = nil
234  %bwipe!
235endfunc
236
237" Test vim.window():previous() and vim.window():next()
238func Test_lua_window_next_previous()
239  new Xfoo1
240  new Xfoo2
241  new Xfoo3
242  wincmd j
243
244  call assert_equal('Xfoo2', luaeval('vim.window().buffer().name'))
245  call assert_equal('Xfoo1', luaeval('vim.window():next():buffer().name'))
246  call assert_equal('Xfoo3', luaeval('vim.window():previous():buffer().name'))
247
248  %bwipe!
249endfunc
250
251" Test vim.window():isvalid()
252func Test_lua_window_isvalid()
253  new Xfoo
254  lua w = vim.window()
255  call assert_true(luaeval('w:isvalid()'))
256
257  " FIXME: how to test the case when isvalid() returns v:false?
258  " isvalid() gives errors when the window is deleted. Is it a bug?
259
260  lua w = nil
261  bwipe!
262endfunc
263
264" Test vim.buffer() with and without argument
265func Test_lua_buffer()
266  new Xfoo1
267  let bn1 = bufnr('%')
268  new Xfoo2
269  let bn2 = bufnr('%')
270
271  " Test vim.buffer() without argument.
272  call assert_equal('Xfoo2', luaeval("vim.buffer().name"))
273
274  " Test vim.buffer() with string argument.
275  call assert_equal('Xfoo1', luaeval("vim.buffer('Xfoo1').name"))
276  call assert_equal('Xfoo2', luaeval("vim.buffer('Xfoo2').name"))
277
278  " Test vim.buffer() with integer argument.
279  call assert_equal('Xfoo1', luaeval("vim.buffer(" . bn1 . ").name"))
280  call assert_equal('Xfoo2', luaeval("vim.buffer(" . bn2 . ").name"))
281
282  lua bn1, bn2 = nil
283  %bwipe!
284endfunc
285
286" Test vim.buffer().name and vim.buffer().fname
287func Test_lua_buffer_name()
288  new
289  call assert_equal('', luaeval('vim.buffer().name'))
290  call assert_equal('', luaeval('vim.buffer().fname'))
291  bwipe!
292
293  new Xfoo
294  call assert_equal('Xfoo', luaeval('vim.buffer().name'))
295  call assert_equal(expand('%:p'), luaeval('vim.buffer().fname'))
296  bwipe!
297endfunc
298
299" Test vim.buffer().number
300func Test_lua_buffer_number()
301  " All numbers in Lua are floating points number (no integers).
302  call assert_equal(bufnr('%'), float2nr(luaeval('vim.buffer().number')))
303endfunc
304
305" Test inserting lines in buffer.
306func Test_lua_buffer_insert()
307  new
308  lua vim.buffer()[1] = '3'
309  lua vim.buffer():insert('1', 0)
310  lua vim.buffer():insert('2', 1)
311  lua vim.buffer():insert('4', 10)
312
313  call assert_equal(['1', '2', '3', '4'], getline(1, '$'))
314  call assert_equal('4', luaeval('vim.buffer()[4]'))
315  call assert_equal(v:null, luaeval('vim.buffer()[5]'))
316  call assert_equal(v:null, luaeval('vim.buffer()[{}]'))
317  call assert_fails('lua vim.buffer():xyz()',
318        \ s:lua_53_or_later
319        \ ? "[string \"vim chunk\"]:1: attempt to call a nil value (method 'xyz')"
320        \ : "[string \"vim chunk\"]:1: attempt to call method 'xyz' (a nil value)")
321  call assert_fails('lua vim.buffer()[1] = {}',
322        \ '[string "vim chunk"]:1: wrong argument to change')
323  bwipe!
324endfunc
325
326" Test deleting line in buffer
327func Test_lua_buffer_delete()
328  new
329  call setline(1, ['1', '2', '3'])
330  call cursor(3, 1)
331  lua vim.buffer()[2] = nil
332  call assert_equal(['1', '3'], getline(1, '$'))
333
334  call assert_fails('lua vim.buffer()[3] = nil',
335        \           '[string "vim chunk"]:1: invalid line number')
336  bwipe!
337endfunc
338
339" Test #vim.buffer() i.e. number of lines in buffer
340func Test_lua_buffer_number_lines()
341  new
342  call setline(1, ['a', 'b', 'c'])
343  call assert_equal(3, luaeval('#vim.buffer()'))
344  bwipe!
345endfunc
346
347" Test vim.buffer():next() and vim.buffer():previous()
348" Note that these functions get the next or previous buffers
349" but do not switch buffer.
350func Test_lua_buffer_next_previous()
351  new Xfoo1
352  new Xfoo2
353  new Xfoo3
354  b Xfoo2
355
356  lua bn = vim.buffer():next()
357  lua bp = vim.buffer():previous()
358
359  call assert_equal('Xfoo2', luaeval('vim.buffer().name'))
360  call assert_equal('Xfoo1', luaeval('bp.name'))
361  call assert_equal('Xfoo3', luaeval('bn.name'))
362
363  call assert_equal('Xfoo2', bufname('%'))
364
365  lua bn()
366  call assert_equal('Xfoo3', luaeval('vim.buffer().name'))
367  call assert_equal('Xfoo3', bufname('%'))
368
369  lua bp()
370  call assert_equal('Xfoo1', luaeval('vim.buffer().name'))
371  call assert_equal('Xfoo1', bufname('%'))
372
373  lua bn, bp = nil
374  %bwipe!
375endfunc
376
377" Test vim.buffer():isvalid()
378func Test_lua_buffer_isvalid()
379  new Xfoo
380  lua b = vim.buffer()
381  call assert_true(luaeval('b:isvalid()'))
382
383  " FIXME: how to test the case when isvalid() returns v:false?
384  " isvalid() gives errors when the buffer is wiped. Is it a bug?
385
386  lua b = nil
387  bwipe!
388endfunc
389
390func Test_lua_list()
391  call assert_equal([], luaeval('vim.list()'))
392
393  let l = []
394  lua l = vim.eval('l')
395  lua l:add(123)
396  lua l:add('abc')
397  lua l:add(true)
398  lua l:add(false)
399  lua l:add(nil)
400  lua l:add(vim.eval("[1, 2, 3]"))
401  lua l:add(vim.eval("{'a':1, 'b':2, 'c':3}"))
402  call assert_equal([123, 'abc', v:true, v:false, v:null, [1, 2, 3], {'a': 1, 'b': 2, 'c': 3}], l)
403  call assert_equal(7, luaeval('#l'))
404  call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
405
406  lua l[1] = 124
407  lua l[6] = nil
408  lua l:insert('first')
409  lua l:insert('xx', 3)
410  call assert_fails('lua l:insert("xx", -20)',
411        \ '[string "vim chunk"]:1: invalid position')
412  call assert_equal(['first', 124, 'abc', 'xx', v:true, v:false, v:null, {'a': 1, 'b': 2, 'c': 3}], l)
413
414  lockvar 1 l
415  call assert_fails('lua l:add("x")', '[string "vim chunk"]:1: list is locked')
416  call assert_fails('lua l:insert(2)', '[string "vim chunk"]:1: list is locked')
417  call assert_fails('lua l[9] = 1', '[string "vim chunk"]:1: list is locked')
418
419  unlockvar l
420  let l = [1, 2]
421  lua ll = vim.eval('l')
422  let x = luaeval("ll[3]")
423  call assert_equal(v:null, x)
424  call assert_fails('let x = luaeval("ll:xyz(3)")',
425        \ s:lua_53_or_later
426        \ ? "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
427        \ : "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)")
428  let y = luaeval("ll[{}]")
429  call assert_equal(v:null, y)
430
431  lua l = nil
432endfunc
433
434func Test_lua_list_table()
435  " See :help lua-vim
436  " Non-numeric keys should not be used to initialize the list
437  " so say = 'hi' should be ignored.
438  lua t = {3.14, 'hello', false, true, say = 'hi'}
439  call assert_equal([3.14, 'hello', v:false, v:true], luaeval('vim.list(t)'))
440  lua t = nil
441
442  call assert_fails('lua vim.list(1)', '[string "vim chunk"]:1: table expected, got number')
443  call assert_fails('lua vim.list("x")', '[string "vim chunk"]:1: table expected, got string')
444  call assert_fails('lua vim.list(print)', '[string "vim chunk"]:1: table expected, got function')
445  call assert_fails('lua vim.list(true)', '[string "vim chunk"]:1: table expected, got boolean')
446endfunc
447
448func Test_lua_list_table_insert_remove()
449  if !s:lua_53_or_later
450    throw 'Skipped: Lua version < 5.3'
451  endif
452
453  let l = [1, 2]
454  lua t = vim.eval('l')
455  lua table.insert(t, 10)
456  lua t[#t + 1] = 20
457  lua table.insert(t, 2, 30)
458  call assert_equal(l, [1, 30, 2, 10, 20])
459  lua table.remove(t, 2)
460  call assert_equal(l, [1, 2, 10, 20])
461  lua t[3] = nil
462  call assert_equal(l, [1, 2, 20])
463  lua removed_value = table.remove(t, 3)
464  call assert_equal(luaeval('removed_value'), 20)
465  lua t = nil
466  lua removed_value = nil
467  unlet l
468endfunc
469
470" Test l() i.e. iterator on list
471func Test_lua_list_iter()
472  lua l = vim.list():add('foo'):add('bar')
473  lua str = ''
474  lua for v in l() do str = str .. v end
475  call assert_equal('foobar', luaeval('str'))
476
477  lua str, l = nil
478endfunc
479
480func Test_lua_recursive_list()
481  lua l = vim.list():add(1):add(2)
482  lua l = l:add(l)
483
484  call assert_equal(1, luaeval('l[1]'))
485  call assert_equal(2, luaeval('l[2]'))
486
487  call assert_equal(1, luaeval('l[3][1]'))
488  call assert_equal(2, luaeval('l[3][2]'))
489
490  call assert_equal(1, luaeval('l[3][3][1]'))
491  call assert_equal(2, luaeval('l[3][3][2]'))
492
493  call assert_equal('[1, 2, [...]]', string(luaeval('l')))
494
495  call assert_match('^list: \%(0x\)\?\x\+$', luaeval('tostring(l)'))
496  call assert_equal(luaeval('tostring(l)'), luaeval('tostring(l[3])'))
497
498  call assert_equal(luaeval('l'), luaeval('l[3]'))
499  call assert_equal(luaeval('l'), luaeval('l[3][3]'))
500
501  lua l = nil
502endfunc
503
504func Test_lua_dict()
505  call assert_equal({}, luaeval('vim.dict()'))
506
507  let d = {}
508  lua d = vim.eval('d')
509  lua d[0] = 123
510  lua d[1] = "abc"
511  lua d[2] = true
512  lua d[3] = false
513  lua d[4] = vim.eval("[1, 2, 3]")
514  lua d[5] = vim.eval("{'a':1, 'b':2, 'c':3}")
515  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)
516  call assert_equal(6, luaeval('#d'))
517  call assert_match('^dict: \%(0x\)\?\x\+$', luaeval('tostring(d)'))
518
519  call assert_equal('abc', luaeval('d[1]'))
520  call assert_equal(v:null, luaeval('d[22]'))
521
522  lua d[0] = 124
523  lua d[4] = nil
524  call assert_equal({'0':124, '1':'abc', '2':v:true, '3':v:false, '5': {'a':1, 'b':2, 'c':3}}, d)
525
526  lockvar 1 d
527  call assert_fails('lua d[6] = 1', '[string "vim chunk"]:1: dict is locked')
528  unlockvar d
529
530  " Error case
531  lua d = {}
532  lua d[''] = 10
533  call assert_fails("let t = luaeval('vim.dict(d)')",
534        \ s:lua_53_or_later
535        \ ? '[string "luaeval"]:1: table has empty key'
536        \ : 'table has empty key')
537  let d = {}
538  lua x = vim.eval('d')
539  call assert_fails("lua x[''] = 10", '[string "vim chunk"]:1: empty key')
540  lua x['a'] = nil
541  call assert_equal({}, d)
542
543  " cannot assign funcrefs in the global scope
544  lua x = vim.eval('g:')
545  call assert_fails("lua x['min'] = vim.funcref('max')",
546        \ '[string "vim chunk"]:1: cannot assign funcref to builtin scope')
547
548  lua d = nil
549endfunc
550
551func Test_lua_dict_table()
552  lua t = {key1 = 'x', key2 = 3.14, key3 = true, key4 = false}
553  call assert_equal({'key1': 'x', 'key2': 3.14, 'key3': v:true, 'key4': v:false},
554        \           luaeval('vim.dict(t)'))
555
556  " Same example as in :help lua-vim.
557  lua t = {math.pi, false, say = 'hi'}
558  " FIXME: commented out as it currently does not work as documented:
559  " Expected {'say': 'hi'}
560  " but got {'1': 3.141593, '2': v:false, 'say': 'hi'}
561  " Is the documentation or the code wrong?
562  "call assert_equal({'say' : 'hi'}, luaeval('vim.dict(t)'))
563  lua t = nil
564
565  call assert_fails('lua vim.dict(1)', '[string "vim chunk"]:1: table expected, got number')
566  call assert_fails('lua vim.dict("x")', '[string "vim chunk"]:1: table expected, got string')
567  call assert_fails('lua vim.dict(print)', '[string "vim chunk"]:1: table expected, got function')
568  call assert_fails('lua vim.dict(true)', '[string "vim chunk"]:1: table expected, got boolean')
569endfunc
570
571" Test d() i.e. iterator on dictionary
572func Test_lua_dict_iter()
573  let d = {'a': 1, 'b':2}
574  lua d = vim.eval('d')
575  lua str = ''
576  lua for k,v in d() do str = str .. k ..':' .. v .. ',' end
577  call assert_equal('a:1,b:2,', luaeval('str'))
578
579  lua str, d = nil
580endfunc
581
582func Test_lua_blob()
583  call assert_equal(0z, luaeval('vim.blob("")'))
584  call assert_equal(0z31326162, luaeval('vim.blob("12ab")'))
585  call assert_equal(0z00010203, luaeval('vim.blob("\x00\x01\x02\x03")'))
586  call assert_equal(0z8081FEFF, luaeval('vim.blob("\x80\x81\xfe\xff")'))
587
588  lua b = vim.blob("\x00\x00\x00\x00")
589  call assert_equal(0z00000000, luaeval('b'))
590  call assert_equal(4, luaeval('#b'))
591  lua b[0], b[1], b[2], b[3] = 1, 32, 256, 0xff
592  call assert_equal(0z012000ff, luaeval('b'))
593  lua b[4] = string.byte("z", 1)
594  call assert_equal(0z012000ff.7a, luaeval('b'))
595  call assert_equal(5, luaeval('#b'))
596  call assert_fails('lua b[#b+1] = 0x80', '[string "vim chunk"]:1: index out of range')
597  lua b:add("12ab")
598  call assert_equal(0z012000ff.7a313261.62, luaeval('b'))
599  call assert_equal(9, luaeval('#b'))
600  call assert_fails('lua b:add(nil)', '[string "vim chunk"]:1: string expected, got nil')
601  call assert_fails('lua b:add(true)', '[string "vim chunk"]:1: string expected, got boolean')
602  call assert_fails('lua b:add({})', '[string "vim chunk"]:1: string expected, got table')
603  lua b = nil
604
605  let b = 0z0102
606  lua lb = vim.eval('b')
607  let n = luaeval('lb[1]')
608  call assert_equal(2, n)
609  let n = luaeval('lb[6]')
610  call assert_equal(v:null, n)
611  call assert_fails('let x = luaeval("lb:xyz(3)")',
612        \ s:lua_53_or_later
613        \ ? "[string \"luaeval\"]:1: attempt to call a nil value (method 'xyz')"
614        \ : "[string \"luaeval\"]:1: attempt to call method 'xyz' (a nil value)")
615  let y = luaeval("lb[{}]")
616  call assert_equal(v:null, y)
617
618  lockvar b
619  call assert_fails('lua lb[1] = 2', '[string "vim chunk"]:1: blob is locked')
620  call assert_fails('lua lb:add("12")', '[string "vim chunk"]:1: blob is locked')
621
622  " Error cases
623  lua t = {}
624  call assert_fails('lua b = vim.blob(t)',
625        \ '[string "vim chunk"]:1: string expected, got table')
626endfunc
627
628func Test_lua_funcref()
629  function I(x)
630    return a:x
631  endfunction
632  let R = function('I')
633  lua i1 = vim.funcref"I"
634  lua i2 = vim.eval"R"
635  lua msg = "funcref|test|" .. (#i2(i1) == #i1(i2) and "OK" or "FAIL")
636  lua msg = vim.funcref"tr"(msg, "|", " ")
637  call assert_equal("funcref test OK", luaeval('msg'))
638
639  " Error cases
640  call assert_fails('lua f1 = vim.funcref("")',
641        \ '[string "vim chunk"]:1: invalid function name: ')
642  call assert_fails('lua f1 = vim.funcref("10")',
643        \ '[string "vim chunk"]:1: invalid function name: 10')
644  let fname = test_null_string()
645  call assert_fails('lua f1 = vim.funcref(fname)',
646        \ "[string \"vim chunk\"]:1: bad argument #1 to 'funcref' (string expected, got nil)")
647  call assert_fails('lua vim.funcref("abc")()',
648        \ ['E117:', '\[string "vim chunk"]:1: cannot call funcref'])
649
650  " dict funcref
651  function Mylen() dict
652    return len(self.data)
653  endfunction
654  let l = [0, 1, 2, 3]
655  let mydict = {'data': l}
656  lua d = vim.eval"mydict"
657  lua d.len = vim.funcref"Mylen" -- assign d as 'self'
658  lua res = (d.len() == vim.funcref"len"(vim.eval"l")) and "OK" or "FAIL"
659  call assert_equal("OK", luaeval('res'))
660  call assert_equal(function('Mylen', {'data': l, 'len': function('Mylen')}), mydict.len)
661
662  lua i1, i2, msg, d, res = nil
663endfunc
664
665" Test vim.type()
666func Test_lua_type()
667  " The following values are identical to Lua's type function.
668  call assert_equal('string',   luaeval('vim.type("foo")'))
669  call assert_equal('number',   luaeval('vim.type(1)'))
670  call assert_equal('number',   luaeval('vim.type(1.2)'))
671  call assert_equal('function', luaeval('vim.type(print)'))
672  call assert_equal('table',    luaeval('vim.type({})'))
673  call assert_equal('boolean',  luaeval('vim.type(true)'))
674  call assert_equal('boolean',  luaeval('vim.type(false)'))
675  call assert_equal('nil',      luaeval('vim.type(nil)'))
676
677  " The following values are specific to Vim.
678  call assert_equal('window',   luaeval('vim.type(vim.window())'))
679  call assert_equal('buffer',   luaeval('vim.type(vim.buffer())'))
680  call assert_equal('list',     luaeval('vim.type(vim.list())'))
681  call assert_equal('dict',     luaeval('vim.type(vim.dict())'))
682  call assert_equal('funcref',  luaeval('vim.type(vim.funcref("Test_type"))'))
683endfunc
684
685" Test vim.open()
686func Test_lua_open()
687  call assert_notmatch('XOpen', execute('ls'))
688
689  " Open a buffer XOpen1, but do not jump to it.
690  lua b = vim.open('XOpen1')
691  call assert_equal('XOpen1', luaeval('b.name'))
692  call assert_equal('', bufname('%'))
693
694  call assert_match('XOpen1', execute('ls'))
695  call assert_notequal('XOpen2', bufname('%'))
696
697  " Open a buffer XOpen2 and jump to it.
698  lua b = vim.open('XOpen2')()
699  call assert_equal('XOpen2', luaeval('b.name'))
700  call assert_equal('XOpen2', bufname('%'))
701
702  lua b = nil
703  %bwipe!
704endfunc
705
706func Test_update_package_paths()
707  set runtimepath+=./testluaplugin
708  call assert_equal("hello from lua", luaeval("require('testluaplugin').hello()"))
709endfunc
710
711func Vim_func_call_lua_callback(Concat, Cb)
712  let l:message = a:Concat("hello", "vim")
713  call a:Cb(l:message)
714endfunc
715
716func Test_pass_lua_callback_to_vim_from_lua()
717  lua pass_lua_callback_to_vim_from_lua_result = ""
718  call assert_equal("", luaeval("pass_lua_callback_to_vim_from_lua_result"))
719  lua <<EOF
720  vim.funcref('Vim_func_call_lua_callback')(
721    function(greeting, message)
722      return greeting .. " " .. message
723    end,
724    function(message)
725      pass_lua_callback_to_vim_from_lua_result = message
726    end)
727EOF
728  call assert_equal("hello vim", luaeval("pass_lua_callback_to_vim_from_lua_result"))
729endfunc
730
731func Vim_func_call_metatable_lua_callback(Greet)
732  return a:Greet("world")
733endfunc
734
735func Test_pass_lua_metatable_callback_to_vim_from_lua()
736  let result = luaeval("vim.funcref('Vim_func_call_metatable_lua_callback')(setmetatable({ space = ' '}, { __call = function(tbl, msg) return 'hello' .. tbl.space .. msg  end }) )")
737  call assert_equal("hello world", result)
738endfunc
739
740" Test vim.line()
741func Test_lua_line()
742  new
743  call setline(1, ['first line', 'second line'])
744  1
745  call assert_equal('first line', luaeval('vim.line()'))
746  2
747  call assert_equal('second line', luaeval('vim.line()'))
748  bwipe!
749endfunc
750
751" Test vim.beep()
752func Test_lua_beep()
753  call assert_beeps('lua vim.beep()')
754endfunc
755
756" Test errors in luaeval()
757func Test_luaeval_error()
758  " Compile error
759  call assert_fails("call luaeval('-nil')",
760  \ '[string "luaeval"]:1: attempt to perform arithmetic on a nil value')
761  call assert_fails("call luaeval(']')",
762  \ "[string \"luaeval\"]:1: unexpected symbol near ']'")
763  lua co = coroutine.create(function () print("hi") end)
764  call assert_fails('let i = luaeval("co")', 'luaeval: cannot convert value')
765  lua co = nil
766  call assert_fails('let m = luaeval("{}")', 'luaeval: cannot convert value')
767endfunc
768
769" Test :luafile foo.lua
770func Test_luafile()
771  call delete('Xlua_file')
772  call writefile(["str = 'hello'", "num = 123" ], 'Xlua_file')
773  call setfperm('Xlua_file', 'r-xr-xr-x')
774
775  luafile Xlua_file
776  call assert_equal('hello', luaeval('str'))
777  call assert_equal(123, luaeval('num'))
778
779  lua str, num = nil
780  call delete('Xlua_file')
781endfunc
782
783" Test :luafile %
784func Test_luafile_percent()
785  new Xlua_file
786  append
787    str, num = 'foo', 321.0
788    print(string.format('str=%s, num=%d', str, num))
789.
790  w!
791  luafile %
792  let msg = split(execute('message'), "\n")[-1]
793  call assert_equal('str=foo, num=321', msg)
794
795  lua str, num = nil
796  call delete('Xlua_file')
797  bwipe!
798endfunc
799
800" Test :luafile with syntax error
801func Test_luafile_error()
802  new Xlua_file
803  call writefile(['nil = 0' ], 'Xlua_file')
804  call setfperm('Xlua_file', 'r-xr-xr-x')
805
806  call assert_fails('luafile Xlua_file', "Xlua_file:1: unexpected symbol near 'nil'")
807
808  call delete('Xlua_file')
809  bwipe!
810endfunc
811
812" Test for dealing with strings containing newlines and null character
813func Test_lua_string_with_newline()
814  let x = execute('lua print("Hello\nWorld")')
815  call assert_equal("\nHello\nWorld", x)
816  new
817  lua k = vim.buffer(vim.eval('bufnr()'))
818  lua k:insert("Hello\0World", 0)
819  call assert_equal(["Hello\nWorld", ''], getline(1, '$'))
820  close!
821endfunc
822
823func Test_lua_set_cursor()
824  " Check that setting the cursor position works.
825  new
826  call setline(1, ['first line', 'second line'])
827  normal gg
828  lua << trim EOF
829    w = vim.window()
830    w.line = 1
831    w.col = 5
832  EOF
833  call assert_equal([1, 5], [line('.'), col('.')])
834
835  " Check that movement after setting cursor position keeps current column.
836  normal j
837  call assert_equal([2, 5], [line('.'), col('.')])
838endfunc
839
840" Test for various heredoc syntax
841func Test_lua_heredoc()
842  lua << END
843vim.command('let s = "A"')
844END
845  lua <<
846vim.command('let s ..= "B"')
847.
848  lua << trim END
849    vim.command('let s ..= "C"')
850  END
851  lua << trim
852    vim.command('let s ..= "D"')
853  .
854  lua << trim eof
855    vim.command('let s ..= "E"')
856  eof
857  call assert_equal('ABCDE', s)
858endfunc
859
860" vim: shiftwidth=2 sts=2 expandtab
861