robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
91.6 KiB3217 linesraw
1-- Test suite for testing interactions with API bindings
2local t = require('test.testutil')
3local n = require('test.functional.testnvim')()
4local Screen = require('test.functional.ui.screen')
5
6local describe, it, before_each = t.describe, t.it, t.before_each
7local nvim_prog = n.nvim_prog
8local fn = n.fn
9local api = n.api
10local command = n.command
11local dedent = t.dedent
12local insert = n.insert
13local clear = n.clear
14local eq = t.eq
15local neq = t.neq
16local ok = t.ok
17local pesc = vim.pesc
18local eval = n.eval
19local feed = n.feed
20local pcall_err = t.pcall_err
21local exec_lua = n.exec_lua
22local matches = t.matches
23local exec = n.exec
24local NIL = vim.NIL
25local retry = t.retry
26local next_msg = n.next_msg
27local remove_trace = t.remove_trace
28local poke_eventloop = n.poke_eventloop
29local assert_alive = n.assert_alive
30local expect = n.expect
31
32describe('lua stdlib', function()
33  before_each(clear)
34  -- İ: `tolower("İ")` is `i` which has length 1 while `İ` itself has
35  --    length 2 (in bytes).
36  -- Ⱥ: `tolower("Ⱥ")` is `ⱥ` which has length 2 while `Ⱥ` itself has
37  --    length 3 (in bytes).
38  --
39  -- Note: 'i' !=? 'İ' and 'ⱥ' !=? 'Ⱥ' on some systems.
40  -- Note: Built-in Nvim comparison (on systems lacking `strcasecmp`) works
41  --       only on ASCII characters.
42  it('vim.stricmp', function()
43    eq(0, fn.luaeval('vim.stricmp("a", "A")'))
44    eq(0, fn.luaeval('vim.stricmp("A", "a")'))
45    eq(0, fn.luaeval('vim.stricmp("a", "a")'))
46    eq(0, fn.luaeval('vim.stricmp("A", "A")'))
47
48    eq(0, fn.luaeval('vim.stricmp("", "")'))
49    eq(0, fn.luaeval('vim.stricmp("\\0", "\\0")'))
50    eq(0, fn.luaeval('vim.stricmp("\\0\\0", "\\0\\0")'))
51    eq(0, fn.luaeval('vim.stricmp("\\0\\0\\0", "\\0\\0\\0")'))
52    eq(0, fn.luaeval('vim.stricmp("\\0\\0\\0A", "\\0\\0\\0a")'))
53    eq(0, fn.luaeval('vim.stricmp("\\0\\0\\0a", "\\0\\0\\0A")'))
54    eq(0, fn.luaeval('vim.stricmp("\\0\\0\\0a", "\\0\\0\\0a")'))
55
56    eq(0, fn.luaeval('vim.stricmp("a\\0", "A\\0")'))
57    eq(0, fn.luaeval('vim.stricmp("A\\0", "a\\0")'))
58    eq(0, fn.luaeval('vim.stricmp("a\\0", "a\\0")'))
59    eq(0, fn.luaeval('vim.stricmp("A\\0", "A\\0")'))
60
61    eq(0, fn.luaeval('vim.stricmp("\\0a", "\\0A")'))
62    eq(0, fn.luaeval('vim.stricmp("\\0A", "\\0a")'))
63    eq(0, fn.luaeval('vim.stricmp("\\0a", "\\0a")'))
64    eq(0, fn.luaeval('vim.stricmp("\\0A", "\\0A")'))
65
66    eq(0, fn.luaeval('vim.stricmp("\\0a\\0", "\\0A\\0")'))
67    eq(0, fn.luaeval('vim.stricmp("\\0A\\0", "\\0a\\0")'))
68    eq(0, fn.luaeval('vim.stricmp("\\0a\\0", "\\0a\\0")'))
69    eq(0, fn.luaeval('vim.stricmp("\\0A\\0", "\\0A\\0")'))
70
71    eq(-1, fn.luaeval('vim.stricmp("a", "B")'))
72    eq(-1, fn.luaeval('vim.stricmp("A", "b")'))
73    eq(-1, fn.luaeval('vim.stricmp("a", "b")'))
74    eq(-1, fn.luaeval('vim.stricmp("A", "B")'))
75
76    eq(-1, fn.luaeval('vim.stricmp("", "\\0")'))
77    eq(-1, fn.luaeval('vim.stricmp("\\0", "\\0\\0")'))
78    eq(-1, fn.luaeval('vim.stricmp("\\0\\0", "\\0\\0\\0")'))
79    eq(-1, fn.luaeval('vim.stricmp("\\0\\0\\0A", "\\0\\0\\0b")'))
80    eq(-1, fn.luaeval('vim.stricmp("\\0\\0\\0a", "\\0\\0\\0B")'))
81    eq(-1, fn.luaeval('vim.stricmp("\\0\\0\\0a", "\\0\\0\\0b")'))
82
83    eq(-1, fn.luaeval('vim.stricmp("a\\0", "B\\0")'))
84    eq(-1, fn.luaeval('vim.stricmp("A\\0", "b\\0")'))
85    eq(-1, fn.luaeval('vim.stricmp("a\\0", "b\\0")'))
86    eq(-1, fn.luaeval('vim.stricmp("A\\0", "B\\0")'))
87
88    eq(-1, fn.luaeval('vim.stricmp("\\0a", "\\0B")'))
89    eq(-1, fn.luaeval('vim.stricmp("\\0A", "\\0b")'))
90    eq(-1, fn.luaeval('vim.stricmp("\\0a", "\\0b")'))
91    eq(-1, fn.luaeval('vim.stricmp("\\0A", "\\0B")'))
92
93    eq(-1, fn.luaeval('vim.stricmp("\\0a\\0", "\\0B\\0")'))
94    eq(-1, fn.luaeval('vim.stricmp("\\0A\\0", "\\0b\\0")'))
95    eq(-1, fn.luaeval('vim.stricmp("\\0a\\0", "\\0b\\0")'))
96    eq(-1, fn.luaeval('vim.stricmp("\\0A\\0", "\\0B\\0")'))
97
98    eq(1, fn.luaeval('vim.stricmp("c", "B")'))
99    eq(1, fn.luaeval('vim.stricmp("C", "b")'))
100    eq(1, fn.luaeval('vim.stricmp("c", "b")'))
101    eq(1, fn.luaeval('vim.stricmp("C", "B")'))
102
103    eq(1, fn.luaeval('vim.stricmp("\\0", "")'))
104    eq(1, fn.luaeval('vim.stricmp("\\0\\0", "\\0")'))
105    eq(1, fn.luaeval('vim.stricmp("\\0\\0\\0", "\\0\\0")'))
106    eq(1, fn.luaeval('vim.stricmp("\\0\\0\\0\\0", "\\0\\0\\0")'))
107    eq(1, fn.luaeval('vim.stricmp("\\0\\0\\0C", "\\0\\0\\0b")'))
108    eq(1, fn.luaeval('vim.stricmp("\\0\\0\\0c", "\\0\\0\\0B")'))
109    eq(1, fn.luaeval('vim.stricmp("\\0\\0\\0c", "\\0\\0\\0b")'))
110
111    eq(1, fn.luaeval('vim.stricmp("c\\0", "B\\0")'))
112    eq(1, fn.luaeval('vim.stricmp("C\\0", "b\\0")'))
113    eq(1, fn.luaeval('vim.stricmp("c\\0", "b\\0")'))
114    eq(1, fn.luaeval('vim.stricmp("C\\0", "B\\0")'))
115
116    eq(1, fn.luaeval('vim.stricmp("c\\0", "B")'))
117    eq(1, fn.luaeval('vim.stricmp("C\\0", "b")'))
118    eq(1, fn.luaeval('vim.stricmp("c\\0", "b")'))
119    eq(1, fn.luaeval('vim.stricmp("C\\0", "B")'))
120
121    eq(1, fn.luaeval('vim.stricmp("\\0c", "\\0B")'))
122    eq(1, fn.luaeval('vim.stricmp("\\0C", "\\0b")'))
123    eq(1, fn.luaeval('vim.stricmp("\\0c", "\\0b")'))
124    eq(1, fn.luaeval('vim.stricmp("\\0C", "\\0B")'))
125
126    eq(1, fn.luaeval('vim.stricmp("\\0c\\0", "\\0B\\0")'))
127    eq(1, fn.luaeval('vim.stricmp("\\0C\\0", "\\0b\\0")'))
128    eq(1, fn.luaeval('vim.stricmp("\\0c\\0", "\\0b\\0")'))
129    eq(1, fn.luaeval('vim.stricmp("\\0C\\0", "\\0B\\0")'))
130  end)
131
132  --- @param prerel string | nil
133  local function test_vim_deprecate(prerel)
134    -- vim.deprecate(name, alternative, version, plugin, backtrace)
135    -- See MAINTAIN.md for the soft/hard deprecation policy
136
137    describe(('vim.deprecate prerel=%s,'):format(prerel or 'nil'), function()
138      local curver --- @type {major:number, minor:number}
139      local curstr --- @type string
140      local nextver --- @type string
141
142      before_each(function()
143        curver = exec_lua('return vim.version()')
144        -- "0.10" or "0.10-dev+xxx"
145        curstr = ('%s.%s%s'):format(curver.major, curver.minor, prerel or '')
146        -- "0.10" or "0.11"
147        nextver = ('%s.%s'):format(curver.major, curver.minor + (prerel and 0 or 1))
148      end)
149
150      it('plugin=nil, same message skipped', function()
151        eq(
152          [[foo.bar() is deprecated. Run ":checkhealth vim.deprecated" for more information]],
153          exec_lua('return vim.deprecate(...)', 'foo.bar()', 'zub.wooo{ok=yay}', curstr)
154        )
155        -- Same message as above; skipped this time.
156        eq(vim.NIL, exec_lua('return vim.deprecate(...)', 'foo.bar()', 'zub.wooo{ok=yay}', curstr))
157      end)
158
159      it('plugin=nil, no error if soft-deprecated', function()
160        eq(vim.NIL, exec_lua [[return vim.deprecate('old1', 'new1', '0.99.0')]])
161        -- Major version > current Nvim major is always "soft-deprecated".
162        -- XXX: This is also a reminder to update the hardcoded `nvim_major`, when Nvim reaches 1.0.
163        eq(vim.NIL, exec_lua [[return vim.deprecate('old2', 'new2', '1.0.0')]])
164      end)
165
166      it('plugin=nil, show error if hard-deprecated', function()
167        eq(
168          [[foo.hard_dep() is deprecated. Run ":checkhealth vim.deprecated" for more information]],
169          exec_lua('return vim.deprecate(...)', 'foo.hard_dep()', 'vim.new_api()', nextver)
170        )
171      end)
172
173      it('plugin=nil, message is only truncated in display #38841', function()
174        local screen = Screen.new(50, 10)
175        exec_lua('vim.deprecate(...)', 'foo.bar()', 'zub.wooo{ok=yay}', curstr)
176        screen:expect([[
177          ^                                                  |
178          {1:~                                                 }|*8
179          {19:foo.bar() is deprecated. Run ":checkhealth vim.dep}|
180        ]])
181        eq(
182          [[foo.bar() is deprecated. Run ":checkhealth vim.deprecated" for more information]],
183          n.exec_capture('messages')
184        )
185      end)
186
187      it('plugin specified', function()
188        -- When `plugin` is specified, don't show ":help deprecated". #22235
189        eq(
190          dedent [[
191            foo.bar() is deprecated, use zub.wooo{ok=yay} instead.
192            Feature will be removed in my-plugin.nvim 0.3.0]],
193          exec_lua(
194            'return vim.deprecate(...)',
195            'foo.bar()',
196            'zub.wooo{ok=yay}',
197            '0.3.0',
198            'my-plugin.nvim',
199            false
200          )
201        )
202
203        -- plugins: no soft deprecation period
204        eq(
205          dedent [[
206            foo.bar() is deprecated, use zub.wooo{ok=yay} instead.
207            Feature will be removed in my-plugin.nvim 0.11.0]],
208          exec_lua(
209            'return vim.deprecate(...)',
210            'foo.bar()',
211            'zub.wooo{ok=yay}',
212            '0.11.0',
213            'my-plugin.nvim',
214            false
215          )
216        )
217      end)
218    end)
219  end
220
221  test_vim_deprecate()
222  test_vim_deprecate('-dev+g0000000')
223
224  it('vim.startswith', function()
225    eq(true, fn.luaeval('vim.startswith("123", "1")'))
226    eq(true, fn.luaeval('vim.startswith("123", "")'))
227    eq(true, fn.luaeval('vim.startswith("123", "123")'))
228    eq(true, fn.luaeval('vim.startswith("", "")'))
229
230    eq(false, fn.luaeval('vim.startswith("123", " ")'))
231    eq(false, fn.luaeval('vim.startswith("123", "2")'))
232    eq(false, fn.luaeval('vim.startswith("123", "1234")'))
233
234    matches(
235      'prefix: expected string, got nil',
236      pcall_err(exec_lua, 'return vim.startswith("123", nil)')
237    )
238    matches('s: expected string, got nil', pcall_err(exec_lua, 'return vim.startswith(nil, "123")'))
239  end)
240
241  it('vim.endswith', function()
242    eq(true, fn.luaeval('vim.endswith("123", "3")'))
243    eq(true, fn.luaeval('vim.endswith("123", "")'))
244    eq(true, fn.luaeval('vim.endswith("123", "123")'))
245    eq(true, fn.luaeval('vim.endswith("", "")'))
246
247    eq(false, fn.luaeval('vim.endswith("123", " ")'))
248    eq(false, fn.luaeval('vim.endswith("123", "2")'))
249    eq(false, fn.luaeval('vim.endswith("123", "1234")'))
250
251    matches(
252      'suffix: expected string, got nil',
253      pcall_err(exec_lua, 'return vim.endswith("123", nil)')
254    )
255    matches('s: expected string, got nil', pcall_err(exec_lua, 'return vim.endswith(nil, "123")'))
256  end)
257
258  it('vim.str_utfindex/str_byteindex', function()
259    exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ\000ъ"]])
260    local indices32 = {
261      [0] = 0,
262      1,
263      2,
264      3,
265      5,
266      7,
267      9,
268      10,
269      12,
270      13,
271      16,
272      19,
273      20,
274      23,
275      24,
276      28,
277      29,
278      33,
279      34,
280      35,
281      37,
282      38,
283      40,
284      42,
285      44,
286      46,
287      48,
288      49,
289      51,
290    }
291    local indices16 = {
292      [0] = 0,
293      1,
294      2,
295      3,
296      5,
297      7,
298      9,
299      10,
300      12,
301      13,
302      16,
303      19,
304      20,
305      23,
306      24,
307      28,
308      28,
309      29,
310      33,
311      33,
312      34,
313      35,
314      37,
315      38,
316      40,
317      42,
318      44,
319      46,
320      48,
321      49,
322      51,
323    }
324    local indices8 = {
325      [0] = 0,
326      1,
327      2,
328      3,
329      4,
330      5,
331      6,
332      7,
333      8,
334      9,
335      10,
336      11,
337      12,
338      13,
339      14,
340      15,
341      16,
342      17,
343      18,
344      19,
345      20,
346      21,
347      22,
348      23,
349      24,
350      25,
351      26,
352      27,
353      28,
354      29,
355      30,
356      31,
357      32,
358      33,
359      34,
360      35,
361      36,
362      37,
363      38,
364      39,
365      40,
366      41,
367      42,
368      43,
369      44,
370      45,
371      46,
372      47,
373      48,
374      49,
375      50,
376      51,
377    }
378    for i, k in pairs(indices32) do
379      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, ...)', i), i)
380      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, ..., false)', i), i)
381      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, "utf-32", ...)', i), i)
382    end
383    for i, k in pairs(indices16) do
384      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, ..., true)', i), i)
385      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, "utf-16", ...)', i), i)
386    end
387    for i, k in pairs(indices8) do
388      eq(k, exec_lua('return vim.str_byteindex(_G.test_text, "utf-8", ...)', i), i)
389    end
390    matches(
391      'index out of range',
392      pcall_err(exec_lua, 'return vim.str_byteindex(_G.test_text, ...)', #indices32 + 1)
393    )
394    matches(
395      'index out of range',
396      pcall_err(exec_lua, 'return vim.str_byteindex(_G.test_text, ..., true)', #indices16 + 1)
397    )
398    matches(
399      'index out of range',
400      pcall_err(exec_lua, 'return vim.str_byteindex(_G.test_text, "utf-16", ...)', #indices16 + 1)
401    )
402    matches(
403      'index out of range',
404      pcall_err(exec_lua, 'return vim.str_byteindex(_G.test_text, "utf-32", ...)', #indices32 + 1)
405    )
406    matches(
407      'invalid encoding',
408      pcall_err(exec_lua, 'return vim.str_byteindex("hello", "madeupencoding", 1)')
409    )
410    eq(
411      indices32[#indices32],
412      exec_lua('return vim.str_byteindex(_G.test_text, "utf-32", 99999, false)')
413    )
414    eq(
415      indices16[#indices16],
416      exec_lua('return vim.str_byteindex(_G.test_text, "utf-16", 99999, false)')
417    )
418    eq(
419      indices8[#indices8],
420      exec_lua('return vim.str_byteindex(_G.test_text, "utf-8", 99999, false)')
421    )
422    eq(2, exec_lua('return vim.str_byteindex("é", "utf-16", 2, false)'))
423    local i32, i16, i8 = 0, 0, 0
424    local len = 51
425    for k = 0, len do
426      if indices32[i32] < k then
427        i32 = i32 + 1
428      end
429      if indices16[i16] < k then
430        i16 = i16 + 1
431        if indices16[i16 + 1] == indices16[i16] then
432          i16 = i16 + 1
433        end
434      end
435      if indices8[i8] < k then
436        i8 = i8 + 1
437      end
438      eq({ i32, i16 }, exec_lua('return {vim.str_utfindex(_G.test_text, ...)}', k), k)
439      eq({ i32 }, exec_lua('return {vim.str_utfindex(_G.test_text, "utf-32", ...)}', k), k)
440      eq({ i16 }, exec_lua('return {vim.str_utfindex(_G.test_text, "utf-16", ...)}', k), k)
441      eq({ i8 }, exec_lua('return {vim.str_utfindex(_G.test_text, "utf-8", ...)}', k), k)
442    end
443
444    eq({ #indices32, #indices16 }, exec_lua('return {vim.str_utfindex(_G.test_text)}'))
445
446    eq(#indices32, exec_lua('return vim.str_utfindex(_G.test_text, "utf-32", math.huge, false)'))
447    eq(#indices16, exec_lua('return vim.str_utfindex(_G.test_text, "utf-16", math.huge, false)'))
448    eq(#indices8, exec_lua('return vim.str_utfindex(_G.test_text, "utf-8", math.huge, false)'))
449
450    eq(#indices32, exec_lua('return vim.str_utfindex(_G.test_text, "utf-32")'))
451    eq(#indices16, exec_lua('return vim.str_utfindex(_G.test_text, "utf-16")'))
452    eq(#indices8, exec_lua('return vim.str_utfindex(_G.test_text, "utf-8")'))
453    matches(
454      'invalid encoding',
455      pcall_err(exec_lua, 'return vim.str_utfindex(_G.test_text, "madeupencoding", ...)', 1)
456    )
457    matches(
458      'index out of range',
459      pcall_err(exec_lua, 'return vim.str_utfindex(_G.test_text, ...)', len + 1)
460    )
461  end)
462
463  it('vim.str_byteindex stays within the string for truncated sequences', function()
464    for _, s in ipairs({ '\xc3', '\xe4\xb8', '\xf0\x9f', '\xf0\x9f\x98', 'abc\xc3' }) do
465      for _, encoding in ipairs({ 'utf-8', 'utf-16', 'utf-32' }) do
466        for index = 0, #s + 2 do
467          local byteindex = exec_lua('return vim.str_byteindex(...)', s, encoding, index, false)
468          ok(
469            byteindex <= #s,
470            ('at most %d'):format(#s),
471            ('%d (encoding=%s, index=%d)'):format(byteindex, encoding, index)
472          )
473        end
474      end
475    end
476  end)
477
478  it('vim.str_utf_start', function()
479    exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]])
480    local expected_positions = {
481      0,
482      0,
483      0,
484      0,
485      -1,
486      0,
487      -1,
488      0,
489      -1,
490      0,
491      0,
492      -1,
493      0,
494      0,
495      -1,
496      -2,
497      0,
498      -1,
499      -2,
500      0,
501      0,
502      -1,
503      -2,
504      0,
505      0,
506      -1,
507      -2,
508      -3,
509      0,
510      0,
511      -1,
512      -2,
513      -3,
514      0,
515      0,
516      0,
517      -1,
518      0,
519      0,
520      -1,
521      0,
522      -1,
523      0,
524      -1,
525      0,
526      -1,
527      0,
528      -1,
529    }
530    eq(
531      expected_positions,
532      exec_lua([[
533      local start_codepoint_positions = {}
534      for idx = 1, #_G.test_text do
535        table.insert(start_codepoint_positions, vim.str_utf_start(_G.test_text, idx))
536      end
537      return start_codepoint_positions
538    ]])
539    )
540  end)
541
542  it('vim.str_utf_end', function()
543    exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]])
544    local expected_positions = {
545      0,
546      0,
547      0,
548      1,
549      0,
550      1,
551      0,
552      1,
553      0,
554      0,
555      1,
556      0,
557      0,
558      2,
559      1,
560      0,
561      2,
562      1,
563      0,
564      0,
565      2,
566      1,
567      0,
568      0,
569      3,
570      2,
571      1,
572      0,
573      0,
574      3,
575      2,
576      1,
577      0,
578      0,
579      0,
580      1,
581      0,
582      0,
583      1,
584      0,
585      1,
586      0,
587      1,
588      0,
589      1,
590      0,
591      1,
592      0,
593    }
594    eq(
595      expected_positions,
596      exec_lua([[
597      local end_codepoint_positions = {}
598      for idx = 1, #_G.test_text do
599        table.insert(end_codepoint_positions, vim.str_utf_end(_G.test_text, idx))
600      end
601      return end_codepoint_positions
602    ]])
603    )
604  end)
605
606  it('vim.str_utf_pos', function()
607    exec_lua([[_G.test_text = "xy åäö ɧ 汉语 ↥ 🤦x🦄 å بِيَّ"]])
608    local expected_positions = {
609      1,
610      2,
611      3,
612      4,
613      6,
614      8,
615      10,
616      11,
617      13,
618      14,
619      17,
620      20,
621      21,
622      24,
623      25,
624      29,
625      30,
626      34,
627      35,
628      36,
629      38,
630      39,
631      41,
632      43,
633      45,
634      47,
635    }
636    eq(expected_positions, exec_lua('return vim.str_utf_pos(_G.test_text)'))
637  end)
638
639  it('vim.schedule', function()
640    exec_lua([[
641      test_table = {}
642      vim.schedule(function()
643        table.insert(test_table, "xx")
644      end)
645      table.insert(test_table, "yy")
646    ]])
647    eq({ 'yy', 'xx' }, exec_lua('return test_table'))
648
649    -- Validates args.
650    matches('vim.schedule: expected function', pcall_err(exec_lua, "vim.schedule('stringly')"))
651    matches('vim.schedule: expected function', pcall_err(exec_lua, 'vim.schedule()'))
652
653    exec_lua([[
654      vim.schedule(function()
655        error("big failure\nvery async")
656      end)
657    ]])
658
659    feed('<cr>')
660    matches('big failure\nvery async', remove_trace(eval('v:errmsg')))
661
662    local screen = Screen.new(60, 5)
663    screen:expect {
664      grid = [[
665      ^                                                            |
666      {1:~                                                           }|*3
667                                                                  |
668    ]],
669    }
670
671    -- nvim_command causes a Vimscript exception, check that it is properly caught
672    -- and propagated as an error message in async contexts.. #10809
673    exec_lua([[
674      vim.schedule(function()
675        vim.api.nvim_command(":echo 'err")
676      end)
677    ]])
678    screen:expect {
679      grid = [[
680      {9:stack traceback:}                                            |
681      {9:        [C]: in function 'nvim_command'}                     |
682      {9:        [string "<nvim>"]:2: in function <[string "<nvim>"]:}|
683      {9:1>}                                                          |
684      {6:Press ENTER or type command to continue}^                     |
685    ]],
686    }
687  end)
688
689  it('vim.gsplit, vim.split', function()
690    local tests = {
691      --                            plain  trimempty
692      { 'a,b', ',', false, false, { 'a', 'b' } },
693      { ':aa::::bb:', ':', false, false, { '', 'aa', '', '', '', 'bb', '' } },
694      { ':aa::::bb:', ':', false, true, { 'aa', '', '', '', 'bb' } },
695      { 'aa::::bb:', ':', false, true, { 'aa', '', '', '', 'bb' } },
696      { ':aa::bb:', ':', false, true, { 'aa', '', 'bb' } },
697      { '/a/b:/b/\n', '[:\n]', false, true, { '/a/b', '/b/' } },
698      { '::ee::ff:', ':', false, false, { '', '', 'ee', '', 'ff', '' } },
699      { '::ee::ff::', ':', false, true, { 'ee', '', 'ff' } },
700      { 'ab', '.', false, false, { '', '', '' } },
701      { 'a1b2c', '[0-9]', false, false, { 'a', 'b', 'c' } },
702      { 'xy', '', false, false, { 'x', 'y' } },
703      { 'here be dragons', ' ', false, false, { 'here', 'be', 'dragons' } },
704      { 'axaby', 'ab?', false, false, { '', 'x', 'y' } },
705      { 'f v2v v3v w2w ', '([vw])2%1', false, false, { 'f ', ' v3v ', ' ' } },
706      { '', '', false, false, {} },
707      { '', '', false, true, {} },
708      { '\n', '[:\n]', false, true, {} },
709      { '', 'a', false, false, { '' } },
710      { 'x*yz*oo*l', '*', true, false, { 'x', 'yz', 'oo', 'l' } },
711    }
712
713    for _, q in ipairs(tests) do
714      eq(q[5], vim.split(q[1], q[2], { plain = q[3], trimempty = q[4] }), q[1])
715    end
716
717    -- Test old signature
718    eq({ 'x', 'yz', 'oo', 'l' }, vim.split('x*yz*oo*l', '*', true))
719
720    local loops = {
721      { 'abc', '.-' },
722    }
723
724    for _, q in ipairs(loops) do
725      matches('Infinite loop detected', pcall_err(vim.split, q[1], q[2]))
726    end
727
728    -- Validates args.
729    eq(true, pcall(vim.split, 'string', 'string'))
730    matches('s: expected string, got number', pcall_err(vim.split, 1, 'string'))
731    matches('sep: expected string, got number', pcall_err(vim.split, 'string', 1))
732    matches('opts: expected table, got number', pcall_err(vim.split, 'string', 'string', 1))
733  end)
734
735  it('vim.trim', function()
736    local trim = function(s)
737      return exec_lua('return vim.trim(...)', s)
738    end
739
740    local trims = {
741      { '   a', 'a' },
742      { ' b  ', 'b' },
743      { '\tc', 'c' },
744      { 'r\n', 'r' },
745      { '', '' },
746      { ' \t \n', '' },
747    }
748
749    for _, q in ipairs(trims) do
750      eq(q[2], trim(q[1]))
751    end
752
753    -- Validates args.
754    matches('s: expected string, got number', pcall_err(trim, 2))
755  end)
756
757  it('vim.inspect', function()
758    -- just make sure it basically works, it has its own test suite
759    local inspect = function(q, opts)
760      return exec_lua('return vim.inspect(...)', q, opts)
761    end
762
763    eq('2', inspect(2))
764    eq('{+a = {+b = 1+}+}', inspect({ a = { b = 1 } }, { newline = '+', indent = '' }))
765
766    -- special value vim.inspect.KEY works
767    eq(
768      '{  KEY_a = "x",  KEY_b = "y"}',
769      exec_lua([[
770      return vim.inspect({a="x", b="y"}, {newline = '', process = function(item, path)
771        if path[#path] == vim.inspect.KEY then
772          return 'KEY_'..item
773        end
774        return item
775      end})
776    ]])
777    )
778  end)
779
780  it('vim.deepcopy', function()
781    ok(exec_lua([[
782      local a = { x = { 1, 2 }, y = 5}
783      local b = vim.deepcopy(a)
784
785      return b.x[1] == 1 and b.x[2] == 2 and b.y == 5 and vim.tbl_count(b) == 2
786             and tostring(a) ~= tostring(b)
787    ]]))
788
789    ok(exec_lua([[
790      local a = {}
791      local b = vim.deepcopy(a)
792
793      return vim.islist(b) and vim.tbl_count(b) == 0 and tostring(a) ~= tostring(b)
794    ]]))
795
796    ok(exec_lua([[
797      local a = vim.empty_dict()
798      local b = vim.deepcopy(a)
799
800      return not vim.islist(b) and vim.tbl_count(b) == 0
801    ]]))
802
803    ok(exec_lua([[
804      local a = {x = vim.empty_dict(), y = {}}
805      local b = vim.deepcopy(a)
806
807      return not vim.islist(b.x) and vim.islist(b.y)
808        and vim.tbl_count(b) == 2
809        and tostring(a) ~= tostring(b)
810    ]]))
811
812    ok(exec_lua([[
813      local f1 = function() return 1 end
814      local f2 = function() return 2 end
815      local t1 = {f = f1}
816      local t2 = vim.deepcopy(t1)
817      t1.f = f2
818      return t1.f() ~= t2.f()
819    ]]))
820
821    ok(exec_lua([[
822      local t1 = {a = 5}
823      t1.self = t1
824      local t2 = vim.deepcopy(t1)
825      return t2.self == t2 and t2.self ~= t1
826    ]]))
827
828    ok(exec_lua([[
829      local mt = {mt=true}
830      local t1 = setmetatable({a = 5}, mt)
831      local t2 = vim.deepcopy(t1)
832      return getmetatable(t2) == mt
833    ]]))
834
835    ok(exec_lua([[
836      local t1 = {a = vim.NIL}
837      local t2 = vim.deepcopy(t1)
838      return t2.a == vim.NIL
839    ]]))
840
841    matches(
842      'Cannot deepcopy object of type thread',
843      pcall_err(
844        exec_lua,
845        [[
846        local thread = coroutine.create(function () return 0 end)
847        local t = {thr = thread}
848        vim.deepcopy(t)
849      ]]
850      )
851    )
852  end)
853
854  it('vim._copy', function()
855    ok(exec_lua([[
856      local inner = { x = 1 }
857      local mt = { tag = true }
858      local a = setmetatable({ inner = inner }, mt)
859      local b = vim._copy(a)
860
861      local c = vim.empty_dict()
862      c.inner = inner
863      local d = vim._copy(c)
864
865      return b ~= a
866        and b.inner == inner
867        and getmetatable(b) == mt
868        and d ~= c
869        and d.inner == inner
870        and not vim.islist(d)
871    ]]))
872  end)
873
874  it('vim.pesc', function()
875    eq('foo%-bar', exec_lua([[return vim.pesc('foo-bar')]]))
876    eq('foo%%%-bar', exec_lua([[return vim.pesc(vim.pesc('foo-bar'))]]))
877    -- pesc() returns one result. #20751
878    eq({ 'x' }, exec_lua([[return {vim.pesc('x')}]]))
879
880    -- Validates args.
881    matches('s: expected string, got number', pcall_err(exec_lua, [[return vim.pesc(2)]]))
882  end)
883
884  it('vim.list_contains', function()
885    eq(true, exec_lua("return vim.list_contains({'a','b','c'}, 'c')"))
886    eq(false, exec_lua("return vim.list_contains({'a','b','c'}, 'd')"))
887  end)
888
889  it('vim.tbl_contains', function()
890    eq(true, exec_lua("return vim.tbl_contains({'a','b','c'}, 'c')"))
891    eq(false, exec_lua("return vim.tbl_contains({'a','b','c'}, 'd')"))
892    eq(true, exec_lua("return vim.tbl_contains({[2]='a',foo='b',[5] = 'c'}, 'c')"))
893    eq(
894      true,
895      exec_lua([[
896        return vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
897          return vim.deep_equal(v, { 'b', 'c' })
898        end, { predicate = true })
899    ]])
900    )
901  end)
902
903  it('vim.tbl_keys', function()
904    eq({}, exec_lua('return vim.tbl_keys({})'))
905    for _, v in pairs(exec_lua("return vim.tbl_keys({'a', 'b', 'c'})")) do
906      eq(true, exec_lua('return vim.tbl_contains({ 1, 2, 3 }, ...)', v))
907    end
908    for _, v in pairs(exec_lua('return vim.tbl_keys({a=1, b=2, c=3})')) do
909      eq(true, exec_lua("return vim.tbl_contains({ 'a', 'b', 'c' }, ...)", v))
910    end
911  end)
912
913  it('vim.tbl_values', function()
914    eq({}, exec_lua('return vim.tbl_values({})'))
915    for _, v in pairs(exec_lua("return vim.tbl_values({'a', 'b', 'c'})")) do
916      eq(true, exec_lua("return vim.tbl_contains({ 'a', 'b', 'c' }, ...)", v))
917    end
918    for _, v in pairs(exec_lua('return vim.tbl_values({a=1, b=2, c=3})')) do
919      eq(true, exec_lua('return vim.tbl_contains({ 1, 2, 3 }, ...)', v))
920    end
921  end)
922
923  it('vim.tbl_map', function()
924    eq(
925      {},
926      exec_lua([[
927      return vim.tbl_map(function(v) return v * 2 end, {})
928    ]])
929    )
930    eq(
931      { 2, 4, 6 },
932      exec_lua([[
933      return vim.tbl_map(function(v) return v * 2 end, {1, 2, 3})
934    ]])
935    )
936    eq(
937      { { i = 2 }, { i = 4 }, { i = 6 } },
938      exec_lua([[
939      return vim.tbl_map(function(v) return { i = v.i * 2 } end, {{i=1}, {i=2}, {i=3}})
940    ]])
941    )
942  end)
943
944  it('vim.tbl_filter', function()
945    eq(
946      {},
947      exec_lua([[
948      return vim.tbl_filter(function(v) return (v % 2) == 0 end, {})
949    ]])
950    )
951    eq(
952      { 2 },
953      exec_lua([[
954      return vim.tbl_filter(function(v) return (v % 2) == 0 end, {1, 2, 3})
955    ]])
956    )
957    eq(
958      { { i = 2 } },
959      exec_lua([[
960      return vim.tbl_filter(function(v) return (v.i % 2) == 0 end, {{i=1}, {i=2}, {i=3}})
961    ]])
962    )
963  end)
964
965  it('vim.isarray', function()
966    eq(true, exec_lua('return vim.isarray({})'))
967    eq(false, exec_lua('return vim.isarray(vim.empty_dict())'))
968    eq(true, exec_lua("return vim.isarray({'a', 'b', 'c'})"))
969    eq(false, exec_lua("return vim.isarray({'a', '32', a='hello', b='baz'})"))
970    eq(false, exec_lua("return vim.isarray({1, a='hello', b='baz'})"))
971    eq(false, exec_lua("return vim.isarray({a='hello', b='baz', 1})"))
972    eq(false, exec_lua("return vim.isarray({1, 2, nil, a='hello'})"))
973    eq(true, exec_lua('return vim.isarray({1, 2, nil, 4})'))
974    eq(true, exec_lua('return vim.isarray({nil, 2, 3, 4})'))
975    eq(false, exec_lua('return vim.isarray({1, [1.5]=2, [3]=3})'))
976  end)
977
978  it('vim.islist', function()
979    eq(true, exec_lua('return vim.islist({})'))
980    eq(false, exec_lua('return vim.islist(vim.empty_dict())'))
981    eq(true, exec_lua("return vim.islist({'a', 'b', 'c'})"))
982    eq(false, exec_lua("return vim.islist({'a', '32', a='hello', b='baz'})"))
983    eq(false, exec_lua("return vim.islist({1, a='hello', b='baz'})"))
984    eq(false, exec_lua("return vim.islist({a='hello', b='baz', 1})"))
985    eq(false, exec_lua("return vim.islist({1, 2, nil, a='hello'})"))
986    eq(false, exec_lua('return vim.islist({1, 2, nil, 4})'))
987    eq(false, exec_lua('return vim.islist({nil, 2, 3, 4})'))
988    eq(false, exec_lua('return vim.islist({1, [1.5]=2, [3]=3})'))
989    eq(
990      false,
991      exec_lua([[
992        local t = setmetatable({ 1, [3] = 3 }, {
993          __index = function()
994            return 2
995          end,
996        })
997        return vim.islist(t)
998      ]])
999    )
1000  end)
1001
1002  it('vim.isnil', function()
1003    eq(true, exec_lua('return vim.isnil(nil)'))
1004    eq(true, exec_lua('return vim.isnil(vim.NIL)'))
1005    eq(false, exec_lua('return vim.isnil(true)'))
1006    eq(false, exec_lua('return vim.isnil(false)'))
1007    eq(false, exec_lua('return vim.isnil({})'))
1008  end)
1009
1010  it('vim.tbl_isempty', function()
1011    eq(true, exec_lua('return vim.tbl_isempty({})'))
1012    eq(false, exec_lua('return vim.tbl_isempty({ 1, 2, 3 })'))
1013    eq(false, exec_lua('return vim.tbl_isempty({a=1, b=2, c=3})'))
1014  end)
1015
1016  it('vim.tbl_get', function()
1017    eq(
1018      true,
1019      exec_lua("return vim.tbl_get({ test = { nested_test = true }}, 'test', 'nested_test')")
1020    )
1021    eq(NIL, exec_lua("return vim.tbl_get({ unindexable = true }, 'unindexable', 'missing_key')"))
1022    eq(NIL, exec_lua("return vim.tbl_get({ unindexable = 1 }, 'unindexable', 'missing_key')"))
1023    eq(
1024      NIL,
1025      exec_lua(
1026        "return vim.tbl_get({ unindexable = coroutine.create(function () end) }, 'unindexable', 'missing_key')"
1027      )
1028    )
1029    eq(
1030      NIL,
1031      exec_lua(
1032        "return vim.tbl_get({ unindexable = function () end }, 'unindexable', 'missing_key')"
1033      )
1034    )
1035    eq(NIL, exec_lua("return vim.tbl_get({}, 'missing_key')"))
1036    eq(NIL, exec_lua('return vim.tbl_get({})'))
1037    eq(NIL, exec_lua("return vim.tbl_get({}, nil, 'key')"))
1038    eq(1, exec_lua("return select('#', vim.tbl_get({}))"))
1039    eq(1, exec_lua("return select('#', vim.tbl_get({ nested = {} }, 'nested', 'missing_key'))"))
1040  end)
1041
1042  it('vim.tbl_extend', function()
1043    ok(exec_lua([[
1044      local a = {x = 1}
1045      local b = {y = 2}
1046      local c = vim.tbl_extend("keep", a, b)
1047
1048      return c.x == 1 and b.y == 2 and vim.tbl_count(c) == 2
1049    ]]))
1050
1051    ok(exec_lua([[
1052      local a = {x = 1}
1053      local b = {y = 2}
1054      local c = {z = 3}
1055      local d = vim.tbl_extend("keep", a, b, c)
1056
1057      return d.x == 1 and d.y == 2 and d.z == 3 and vim.tbl_count(d) == 3
1058    ]]))
1059
1060    ok(exec_lua([[
1061      local a = {x = 1}
1062      local b = {x = 3}
1063      local c = vim.tbl_extend("keep", a, b)
1064
1065      return c.x == 1 and vim.tbl_count(c) == 1
1066    ]]))
1067
1068    ok(exec_lua([[
1069      local a = {x = 1}
1070      local b = {x = 3}
1071      local c = vim.tbl_extend("force", a, b)
1072
1073      return c.x == 3 and vim.tbl_count(c) == 1
1074    ]]))
1075
1076    ok(exec_lua([[
1077      local a = vim.empty_dict()
1078      local b = {}
1079      local c = vim.tbl_extend("keep", a, b)
1080
1081      return not vim.islist(c) and vim.tbl_count(c) == 0
1082    ]]))
1083
1084    ok(exec_lua([[
1085      local a = {}
1086      local b = vim.empty_dict()
1087      local c = vim.tbl_extend("keep", a, b)
1088
1089      return vim.islist(c) and vim.tbl_count(c) == 0
1090    ]]))
1091
1092    ok(exec_lua([[
1093      local a = {x = {a = 1, b = 2}}
1094      local b = {x = {a = 2, c = {y = 3}}}
1095      local c = vim.tbl_extend("keep", a, b)
1096
1097      local count = 0
1098      for _ in pairs(c) do count = count + 1 end
1099
1100      return c.x.a == 1 and c.x.b == 2 and c.x.c == nil and count == 1
1101    ]]))
1102
1103    ok(exec_lua([[
1104      local a = { a = 1, b = 2, c = 1 }
1105      local b = { a = -1, b = 5, c = 3, d = 4 }
1106      -- Return the maximum value for each key.
1107      local c = vim.tbl_extend(function(k, prev_v, v)
1108        if prev_v then
1109          return v > prev_v and v or prev_v
1110        else
1111          return v
1112        end
1113      end, a, b)
1114      return vim.deep_equal(c, { a = 1, b = 5, c = 3, d = 4 })
1115    ]]))
1116
1117    matches(
1118      'invalid "behavior": nil',
1119      pcall_err(
1120        exec_lua,
1121        [[
1122        return vim.tbl_extend()
1123      ]]
1124      )
1125    )
1126
1127    matches(
1128      'wrong number of arguments %(given 1, expected at least 3%)',
1129      pcall_err(
1130        exec_lua,
1131        [[
1132        return vim.tbl_extend("keep")
1133      ]]
1134      )
1135    )
1136
1137    matches(
1138      'wrong number of arguments %(given 2, expected at least 3%)',
1139      pcall_err(
1140        exec_lua,
1141        [[
1142        return vim.tbl_extend("keep", {})
1143      ]]
1144      )
1145    )
1146  end)
1147
1148  it('vim.tbl_deep_extend', function()
1149    ok(exec_lua([[
1150      local a = {x = {a = 1, b = 2}}
1151      local b = {x = {a = 2, c = {y = 3}}}
1152      local c = vim.tbl_deep_extend("keep", a, b)
1153
1154      local count = 0
1155      for _ in pairs(c) do count = count + 1 end
1156
1157      return c.x.a == 1 and c.x.b == 2 and c.x.c.y == 3 and count == 1
1158    ]]))
1159
1160    ok(exec_lua([[
1161      local a = {x = {a = 1, b = 2}}
1162      local b = {x = {a = 2, c = {y = 3}}}
1163      local c = vim.tbl_deep_extend("force", a, b)
1164
1165      local count = 0
1166      for _ in pairs(c) do count = count + 1 end
1167
1168      return c.x.a == 2 and c.x.b == 2 and c.x.c.y == 3 and count == 1
1169    ]]))
1170
1171    ok(exec_lua([[
1172      local a = {x = {a = 1, b = 2}}
1173      local b = {x = {a = 2, c = {y = 3}}}
1174      local c = {x = {c = 4, d = {y = 4}}}
1175      local d = vim.tbl_deep_extend("keep", a, b, c)
1176
1177      local count = 0
1178      for _ in pairs(c) do count = count + 1 end
1179
1180      return d.x.a == 1 and d.x.b == 2 and d.x.c.y == 3 and d.x.d.y == 4 and count == 1
1181    ]]))
1182
1183    ok(exec_lua([[
1184      local a = {x = {a = 1, b = 2}}
1185      local b = {x = {a = 2, c = {y = 3}}}
1186      local c = {x = {c = 4, d = {y = 4}}}
1187      local d = vim.tbl_deep_extend("force", a, b, c)
1188
1189      local count = 0
1190      for _ in pairs(c) do count = count + 1 end
1191
1192      return d.x.a == 2 and d.x.b == 2 and d.x.c == 4 and d.x.d.y == 4 and count == 1
1193    ]]))
1194
1195    ok(exec_lua([[
1196      local a = vim.empty_dict()
1197      local b = {}
1198      local c = vim.tbl_deep_extend("keep", a, b)
1199
1200      local count = 0
1201      for _ in pairs(c) do count = count + 1 end
1202
1203      return not vim.islist(c) and count == 0
1204    ]]))
1205
1206    ok(exec_lua([[
1207      local a = {}
1208      local b = vim.empty_dict()
1209      local c = vim.tbl_deep_extend("keep", a, b)
1210
1211      local count = 0
1212      for _ in pairs(c) do count = count + 1 end
1213
1214      return vim.islist(c) and count == 0
1215    ]]))
1216
1217    eq(
1218      { a = { b = 1 } },
1219      exec_lua([[
1220      local a = { a = { b = 1 } }
1221      local b = { a = {} }
1222      return vim.tbl_deep_extend("force", a, b)
1223    ]])
1224    )
1225
1226    eq(
1227      { a = { b = 1 } },
1228      exec_lua([[
1229      local a = { a = 123 }
1230      local b = { a = { b = 1} }
1231      return vim.tbl_deep_extend("force", a, b)
1232    ]])
1233    )
1234
1235    ok(exec_lua([[
1236      local a = { a = {[2] = 3} }
1237      local b = { a = {[3] = 3} }
1238      local c = vim.tbl_deep_extend("force", a, b)
1239      return vim.deep_equal(c, {a = {[2] = 3, [3] = 3}})
1240    ]]))
1241
1242    eq(
1243      { a = 123 },
1244      exec_lua([[
1245      local a = { a = { b = 1} }
1246      local b = { a = 123 }
1247      return vim.tbl_deep_extend("force", a, b)
1248    ]])
1249    )
1250
1251    ok(exec_lua([[
1252      local a = { sub = { 'a', 'b' } }
1253      local b = { sub = { 'b', 'c' } }
1254      local c = vim.tbl_deep_extend('force', a, b)
1255      return vim.deep_equal(c, { sub = { 'b', 'c' } })
1256    ]]))
1257
1258    ok(exec_lua([[
1259      local a = { a = 1, b = 2, c = { d = 1, e = -2} }
1260      local b = { a = -1, b = 5, c = { d = 6 } }
1261      -- Return the maximum value for each key.
1262      local c = vim.tbl_deep_extend(function(k, prev_v, v)
1263        if prev_v then
1264          return v > prev_v and v or prev_v
1265        else
1266          return v
1267        end
1268      end, a, b)
1269      return vim.deep_equal(c, { a = 1, b = 5, c = { d = 6, e = -2 } })
1270    ]]))
1271
1272    matches('invalid "behavior": nil', pcall_err(exec_lua, [[return vim.tbl_deep_extend()]]))
1273
1274    matches(
1275      'wrong number of arguments %(given 1, expected at least 3%)',
1276      pcall_err(exec_lua, [[return vim.tbl_deep_extend("keep")]])
1277    )
1278
1279    matches(
1280      'wrong number of arguments %(given 2, expected at least 3%)',
1281      pcall_err(exec_lua, [[return vim.tbl_deep_extend("keep", {})]])
1282    )
1283
1284    matches(
1285      'after the second argument%: expected table, got number',
1286      pcall_err(exec_lua, [[return vim.tbl_deep_extend("keep", {}, 42)]])
1287    )
1288  end)
1289
1290  it('vim.tbl_count', function()
1291    eq(0, exec_lua [[ return vim.tbl_count({}) ]])
1292    eq(0, exec_lua [[ return vim.tbl_count(vim.empty_dict()) ]])
1293    eq(0, exec_lua [[ return vim.tbl_count({nil}) ]])
1294    eq(0, exec_lua [[ return vim.tbl_count({a=nil}) ]])
1295    eq(1, exec_lua [[ return vim.tbl_count({1}) ]])
1296    eq(2, exec_lua [[ return vim.tbl_count({1, 2}) ]])
1297    eq(2, exec_lua [[ return vim.tbl_count({1, nil, 3}) ]])
1298    eq(1, exec_lua [[ return vim.tbl_count({a=1}) ]])
1299    eq(2, exec_lua [[ return vim.tbl_count({a=1, b=2}) ]])
1300    eq(2, exec_lua [[ return vim.tbl_count({a=1, b=nil, c=3}) ]])
1301  end)
1302
1303  it('vim.deep_equal', function()
1304    eq(true, exec_lua [[ return vim.deep_equal({a=1}, {a=1}) ]])
1305    eq(true, exec_lua [[ return vim.deep_equal({a={b=1}}, {a={b=1}}) ]])
1306    eq(true, exec_lua [[ return vim.deep_equal({a={b={nil}}}, {a={b={}}}) ]])
1307    eq(true, exec_lua [[ return vim.deep_equal({a=1, [5]=5}, {nil,nil,nil,nil,5,a=1}) ]])
1308    eq(
1309      true,
1310      exec_lua [[ local shared = {}; return vim.deep_equal({ 1, shared, 1, shared }, { 1, {}, 1, {} }) ]]
1311    )
1312    -- cyclic table
1313    eq(true, exec_lua [[ local a,b={},{}; a[1]=a; b[1]=b; return vim.deep_equal(a, b) ]])
1314    eq(false, exec_lua [[ return vim.deep_equal(1, {nil,nil,nil,nil,5,a=1}) ]])
1315    eq(false, exec_lua [[ return vim.deep_equal(1, 3) ]])
1316    eq(false, exec_lua [[ return vim.deep_equal(nil, 3) ]])
1317    eq(false, exec_lua [[ return vim.deep_equal({a=1}, {a=2}) ]])
1318    eq(false, exec_lua [[ local a,b={},{}; a[1]=a; b[1]={}; return vim.deep_equal(a, b) ]])
1319  end)
1320
1321  it('vim.list_extend', function()
1322    eq({ 1, 2, 3 }, exec_lua [[ return vim.list_extend({1}, {2,3}) ]])
1323    matches(
1324      'src: expected table, got nil',
1325      pcall_err(exec_lua, [[ return vim.list_extend({1}, nil) ]])
1326    )
1327    eq({ 1, 2 }, exec_lua [[ return vim.list_extend({1}, {2;a=1}) ]])
1328    eq(true, exec_lua [[ local a = {1} return vim.list_extend(a, {2;a=1}) == a ]])
1329    eq({ 2 }, exec_lua [[ return vim.list_extend({}, {2;a=1}, 1) ]])
1330    eq({}, exec_lua [[ return vim.list_extend({}, {2;a=1}, 2) ]])
1331    eq({}, exec_lua [[ return vim.list_extend({}, {2;a=1}, 1, -1) ]])
1332    eq({ 2 }, exec_lua [[ return vim.list_extend({}, {2;a=1}, -1, 2) ]])
1333  end)
1334
1335  it('vim.spairs', function()
1336    local res = ''
1337    local table = {
1338      ccc = 1,
1339      bbb = 2,
1340      ddd = 3,
1341      aaa = 4,
1342    }
1343    for key, _ in vim.spairs(table) do
1344      res = res .. key
1345    end
1346    matches('aaabbbcccddd', res)
1347  end)
1348
1349  it('vim.call, vim.fn', function()
1350    eq(true, exec_lua([[return vim.call('sin', 0.0) == 0.0 ]]))
1351    eq(true, exec_lua([[return vim.fn.sin(0.0) == 0.0 ]]))
1352    -- compat: nvim_call_function uses "special" value for Vimscript float
1353    eq(false, exec_lua([[return vim.api.nvim_call_function('sin', {0.0}) == 0.0 ]]))
1354
1355    exec([[
1356      func! FooFunc(test)
1357        let g:test = a:test
1358        return {}
1359      endfunc
1360      func! VarArg(...)
1361        return a:000
1362      endfunc
1363      func! Nilly()
1364        return [v:null, v:null]
1365      endfunc
1366    ]])
1367    eq(true, exec_lua([[return next(vim.fn.FooFunc(3)) == nil ]]))
1368    eq(3, eval('g:test'))
1369    eq(true, exec_lua([[return vim.tbl_isempty(vim.api.nvim_call_function("FooFunc", {5}))]]))
1370    eq(5, eval('g:test'))
1371
1372    eq({ 2, 'foo', true }, exec_lua([[return vim.fn.VarArg(2, "foo", true)]]))
1373
1374    eq(
1375      true,
1376      exec_lua([[
1377      local x = vim.fn.Nilly()
1378      return #x == 2 and x[1] == vim.NIL and x[2] == vim.NIL
1379    ]])
1380    )
1381    eq({ NIL, NIL }, exec_lua([[return vim.fn.Nilly()]]))
1382
1383    -- error handling
1384    eq(
1385      { false, 'Vim:E897: List or Blob required' },
1386      exec_lua([[return {pcall(vim.fn.add, "aa", "bb")}]])
1387    )
1388
1389    -- conversion between LuaRef and Vim Funcref
1390    eq(
1391      true,
1392      exec_lua([[
1393      local x = vim.fn.VarArg(function() return 'foo' end, function() return 'bar' end)
1394      return #x == 2 and x[1]() == 'foo' and x[2]() == 'bar'
1395    ]])
1396    )
1397
1398    -- Test for #20211
1399    eq(
1400      'a (b) c',
1401      exec_lua([[
1402      return vim.fn.substitute('a b c', 'b', function(m) return '(' .. m[1] .. ')' end, 'g')
1403    ]])
1404    )
1405  end)
1406
1407  it('vim.fn `func_lua` (fast path for Lua-implemented builtins)', function()
1408    -- hostname() is implemented via func_lua, calling Lua directly when invoked from Lua.
1409    local lua_result = exec_lua([[return vim.fn.hostname()]])
1410    eq('string', type(lua_result))
1411    assert(#lua_result > 0, 'hostname() should return a non-empty string')
1412    -- VimScript path (lua_wrapper) should return the same result.
1413    eq(lua_result, eval('hostname()'))
1414  end)
1415
1416  it('vim.call fails in fast context', function()
1417    local screen = Screen.new(120, 10)
1418    exec_lua([[
1419      local timer = vim.uv.new_timer()
1420      timer:start(0, 0, function()
1421        timer:close()
1422        vim.call('sin', 0.0)
1423      end)
1424    ]])
1425    screen:expect({
1426      any = pesc('E5560: Vimscript function "sin" must not be called in a fast event context'),
1427    })
1428    feed('<CR>')
1429    assert_alive()
1430  end)
1431
1432  it('vim.fn errors when calling API function', function()
1433    matches(
1434      'Tried to call API function with vim.fn: use vim.api.nvim_get_current_line instead',
1435      pcall_err(exec_lua, 'vim.fn.nvim_get_current_line()')
1436    )
1437  end)
1438
1439  it('vim.fn is allowed in "fast" context by some functions #18306', function()
1440    exec_lua([[
1441      local timer = vim.uv.new_timer()
1442      timer:start(0, 0, function()
1443        timer:close()
1444        assert(vim.in_fast_event())
1445        vim.g.fnres = vim.fn.iconv('hello', 'utf-8', 'utf-8')
1446      end)
1447    ]])
1448
1449    poke_eventloop()
1450    eq('hello', exec_lua [[return vim.g.fnres]])
1451  end)
1452
1453  it('vim.rpcrequest and vim.rpcnotify', function()
1454    exec_lua([[
1455      chan = vim.fn.jobstart({'cat'}, {rpc=true})
1456      vim.rpcrequest(chan, 'nvim_set_current_line', 'meow')
1457    ]])
1458    eq('meow', api.nvim_get_current_line())
1459    command("let x = [3, 'aa', v:true, v:null]")
1460    eq(
1461      true,
1462      exec_lua([[
1463      ret = vim.rpcrequest(chan, 'nvim_get_var', 'x')
1464      return #ret == 4 and ret[1] == 3 and ret[2] == 'aa' and ret[3] == true and ret[4] == vim.NIL
1465    ]])
1466    )
1467    eq({ 3, 'aa', true, NIL }, exec_lua([[return ret]]))
1468
1469    eq(
1470      { {}, {}, false, true },
1471      exec_lua([[
1472      vim.rpcrequest(chan, 'nvim_exec', 'let xx = {}\nlet yy = []', false)
1473      local dict = vim.rpcrequest(chan, 'nvim_eval', 'xx')
1474      local list = vim.rpcrequest(chan, 'nvim_eval', 'yy')
1475      return {dict, list, vim.islist(dict), vim.islist(list)}
1476     ]])
1477    )
1478
1479    exec_lua([[
1480       vim.rpcrequest(chan, 'nvim_set_var', 'aa', {})
1481       vim.rpcrequest(chan, 'nvim_set_var', 'bb', vim.empty_dict())
1482     ]])
1483    eq({ 1, 1 }, eval('[type(g:aa) == type([]), type(g:bb) == type({})]'))
1484
1485    -- error handling
1486    eq({ false, 'Invalid channel: 23' }, exec_lua([[return {pcall(vim.rpcrequest, 23, 'foo')}]]))
1487    eq({ false, 'Invalid channel: 23' }, exec_lua([[return {pcall(vim.rpcnotify, 23, 'foo')}]]))
1488
1489    eq(
1490      { false, 'Vim:E121: Undefined variable: foobar' },
1491      exec_lua([[return {pcall(vim.rpcrequest, chan, 'nvim_eval', "foobar")}]])
1492    )
1493
1494    -- rpcnotify doesn't wait on request
1495    eq(
1496      'meow',
1497      exec_lua([[
1498      vim.rpcnotify(chan, 'nvim_set_current_line', 'foo')
1499      return vim.api.nvim_get_current_line()
1500    ]])
1501    )
1502    retry(10, nil, function()
1503      eq('foo', api.nvim_get_current_line())
1504    end)
1505
1506    local screen = Screen.new(50, 7)
1507    exec_lua([[
1508      timer = vim.uv.new_timer()
1509      timer:start(20, 0, function ()
1510        -- notify ok (executed later when safe)
1511        vim.rpcnotify(chan, 'nvim_set_var', 'yy', {3, vim.NIL})
1512        -- rpcrequest an error
1513        vim.rpcrequest(chan, 'nvim_set_current_line', 'bork')
1514      end)
1515    ]])
1516    screen:expect {
1517      grid = [[
1518      {9:[string "<nvim>"]:6: E5560: rpcrequest must not be}|
1519      {9: called in a fast event context}                   |
1520      {9:stack traceback:}                                  |
1521      {9:        [C]: in function 'rpcrequest'}             |
1522      {9:        [string "<nvim>"]:6: in function <[string }|
1523      {9:"<nvim>"]:2>}                                      |
1524      {6:Press ENTER or type command to continue}^           |
1525    ]],
1526    }
1527    feed('<cr>')
1528    retry(10, nil, function()
1529      eq({ 3, NIL }, api.nvim_get_var('yy'))
1530    end)
1531
1532    exec_lua([[timer:close()]])
1533  end)
1534
1535  it('vim.empty_dict()', function()
1536    eq(
1537      { true, false, true, true },
1538      exec_lua([[
1539      vim.api.nvim_set_var('listy', {})
1540      vim.api.nvim_set_var('dicty', vim.empty_dict())
1541      local listy = vim.fn.eval("listy")
1542      local dicty = vim.fn.eval("dicty")
1543      return {vim.islist(listy), vim.islist(dicty), next(listy) == nil, next(dicty) == nil}
1544    ]])
1545    )
1546
1547    -- vim.empty_dict() gives new value each time
1548    -- equality is not overridden (still by ref)
1549    -- non-empty table uses the usual heuristics (ignores the tag)
1550    eq(
1551      { false, { 'foo' }, { namey = 'bar' } },
1552      exec_lua([[
1553      local aa = vim.empty_dict()
1554      local bb = vim.empty_dict()
1555      local equally = (aa == bb)
1556      aa[1] = "foo"
1557      bb["namey"] = "bar"
1558      return {equally, aa, bb}
1559    ]])
1560    )
1561
1562    eq('{ {}, vim.empty_dict() }', exec_lua('return vim.inspect({{}, vim.empty_dict()})'))
1563    eq('{}', exec_lua([[ return vim.fn.json_encode(vim.empty_dict()) ]]))
1564    eq('{"a": {}, "b": []}', exec_lua([[ return vim.fn.json_encode({a=vim.empty_dict(), b={}}) ]]))
1565  end)
1566
1567  it('vim.validate (fast form)', function()
1568    exec_lua("vim.validate('arg1', {}, 'table')")
1569    exec_lua("vim.validate('arg1', nil, 'table', true)")
1570    exec_lua("vim.validate('arg1', { foo='foo' }, 'table')")
1571    exec_lua("vim.validate('arg1', { 'foo' }, 'table')")
1572    exec_lua("vim.validate('arg1', 'foo', 'string')")
1573    exec_lua("vim.validate('arg1', nil, 'string', true)")
1574    exec_lua("vim.validate('arg1', 1, 'number')")
1575    exec_lua("vim.validate('arg1', 0, 'number')")
1576    exec_lua("vim.validate('arg1', 0.1, 'number')")
1577    exec_lua("vim.validate('arg1', nil, 'number', true)")
1578    exec_lua("vim.validate('arg1', true, 'boolean')")
1579    exec_lua("vim.validate('arg1', false, 'boolean')")
1580    exec_lua("vim.validate('arg1', nil, 'boolean', true)")
1581    exec_lua("vim.validate('arg1', function()end, 'function')")
1582    exec_lua("vim.validate('arg1', nil, 'function', true)")
1583    exec_lua("vim.validate('arg1', nil, 'nil')")
1584    exec_lua("vim.validate('arg1', nil, 'nil', true)")
1585    exec_lua("vim.validate('arg1', coroutine.create(function()end), 'thread')")
1586    exec_lua("vim.validate('arg1', nil, 'thread', true)")
1587    exec_lua("vim.validate('arg1', 2, function(a) return (a % 2) == 0  end, 'even number')")
1588    exec_lua("vim.validate('arg1', 5, {'number', 'string'})")
1589    exec_lua("vim.validate('arg2', 'foo', {'number', 'string'})")
1590
1591    matches('arg1: expected number, got nil', pcall_err(vim.validate, 'arg1', nil, 'number'))
1592    matches('arg1: expected string, got nil', pcall_err(vim.validate, 'arg1', nil, 'string'))
1593    matches('arg1: expected table, got nil', pcall_err(vim.validate, 'arg1', nil, 'table'))
1594    matches('arg1: expected function, got nil', pcall_err(vim.validate, 'arg1', nil, 'function'))
1595    matches('arg1: expected string, got number', pcall_err(vim.validate, 'arg1', 5, 'string'))
1596    matches('arg1: expected table, got number', pcall_err(vim.validate, 'arg1', 5, 'table'))
1597    matches('arg1: expected function, got number', pcall_err(vim.validate, 'arg1', 5, 'function'))
1598    matches('arg1: expected number, got string', pcall_err(vim.validate, 'arg1', '5', 'number'))
1599    matches('arg1: expected x, got number', pcall_err(exec_lua, "vim.validate('arg1', 1, 'x')"))
1600    matches('invalid validator: 1', pcall_err(exec_lua, "vim.validate('arg1', 1, 1)"))
1601    matches('invalid arguments', pcall_err(exec_lua, "vim.validate('arg1', { 1 })"))
1602
1603    -- Validated parameters are required by default.
1604    matches(
1605      'arg1: expected string, got nil',
1606      pcall_err(exec_lua, "vim.validate('arg1',  nil, 'string')")
1607    )
1608    -- Explicitly required.
1609    matches(
1610      'arg1: expected string, got nil',
1611      pcall_err(exec_lua, "vim.validate('arg1', nil, 'string', false)")
1612    )
1613
1614    matches(
1615      'arg1: expected table, got number',
1616      pcall_err(exec_lua, "vim.validate('arg1', 1, 'table')")
1617    )
1618
1619    matches(
1620      'arg1: expected even number, got 3',
1621      pcall_err(exec_lua, "vim.validate('arg1', 3, function(a) return a == 1 end, 'even number')")
1622    )
1623    matches(
1624      'arg1: expected %?, got 3',
1625      pcall_err(exec_lua, "vim.validate('arg1', 3, function(a) return a == 1 end)")
1626    )
1627    matches(
1628      'arg1: expected number|string, got nil',
1629      pcall_err(exec_lua, "vim.validate('arg1', nil, {'number', 'string'})")
1630    )
1631
1632    -- Validator func can return an extra "Info" message.
1633    matches(
1634      'arg1: expected %?, got 3. Info: TEST_MSG',
1635      pcall_err(exec_lua, "vim.validate('arg1', 3, function(a) return a == 1, 'TEST_MSG' end)")
1636    )
1637    -- Caller can override the "expected" message.
1638    eq(
1639      'arg1: expected TEST_MSG, got nil',
1640      pcall_err(exec_lua, "vim.validate('arg1', nil, 'table', 'TEST_MSG')")
1641    )
1642  end)
1643
1644  it('vim.validate (spec form)', function()
1645    exec_lua("vim.validate{arg1={{}, 'table' }}")
1646    exec_lua("vim.validate{arg1={{}, 't' }}")
1647    exec_lua("vim.validate{arg1={nil, 't', true }}")
1648    exec_lua("vim.validate{arg1={{ foo='foo' }, 't' }}")
1649    exec_lua("vim.validate{arg1={{ 'foo' }, 't' }}")
1650    exec_lua("vim.validate{arg1={'foo', 'string' }}")
1651    exec_lua("vim.validate{arg1={'foo', 's' }}")
1652    exec_lua("vim.validate{arg1={'', 's' }}")
1653    exec_lua("vim.validate{arg1={nil, 's', true }}")
1654    exec_lua("vim.validate{arg1={1, 'number' }}")
1655    exec_lua("vim.validate{arg1={1, 'n' }}")
1656    exec_lua("vim.validate{arg1={0, 'n' }}")
1657    exec_lua("vim.validate{arg1={0.1, 'n' }}")
1658    exec_lua("vim.validate{arg1={nil, 'n', true }}")
1659    exec_lua("vim.validate{arg1={true, 'boolean' }}")
1660    exec_lua("vim.validate{arg1={true, 'b' }}")
1661    exec_lua("vim.validate{arg1={false, 'b' }}")
1662    exec_lua("vim.validate{arg1={nil, 'b', true }}")
1663    exec_lua("vim.validate{arg1={function()end, 'function' }}")
1664    exec_lua("vim.validate{arg1={function()end, 'f' }}")
1665    exec_lua("vim.validate{arg1={nil, 'f', true }}")
1666    exec_lua("vim.validate{arg1={nil, 'nil' }}")
1667    exec_lua("vim.validate{arg1={nil, 'nil', true }}")
1668    exec_lua("vim.validate{arg1={coroutine.create(function()end), 'thread' }}")
1669    exec_lua("vim.validate{arg1={nil, 'thread', true }}")
1670    exec_lua("vim.validate{arg1={{}, 't' }, arg2={ 'foo', 's' }}")
1671    exec_lua("vim.validate{arg1={2, function(a) return (a % 2) == 0  end, 'even number' }}")
1672    exec_lua("vim.validate{arg1={5, {'n', 's'} }, arg2={ 'foo', {'n', 's'} }}")
1673
1674    matches('expected table, got number', pcall_err(exec_lua, "vim.validate{ 1, 'x' }"))
1675    matches('arg1: expected x, got number', pcall_err(exec_lua, "vim.validate{ arg1={ 1, 'x' }}"))
1676    matches('invalid validator: 1', pcall_err(exec_lua, 'vim.validate{ arg1={ 1, 1 }}'))
1677    matches('invalid validator: nil', pcall_err(exec_lua, 'vim.validate{ arg1={ 1 }}'))
1678
1679    -- Validated parameters are required by default.
1680    matches(
1681      'arg1: expected string, got nil',
1682      pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's' }}")
1683    )
1684    -- Explicitly required.
1685    matches(
1686      'arg1: expected string, got nil',
1687      pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's', false }}")
1688    )
1689
1690    matches('arg1: expected table, got number', pcall_err(exec_lua, "vim.validate{arg1={1, 't'}}"))
1691    matches(
1692      'arg2: expected string, got number',
1693      pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={1, 's'}}")
1694    )
1695    matches(
1696      'arg2: expected string, got nil',
1697      pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}")
1698    )
1699    matches(
1700      'arg2: expected string, got nil',
1701      pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}")
1702    )
1703    matches(
1704      'arg1: expected even number, got 3',
1705      pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1 end, 'even number'}}")
1706    )
1707    matches(
1708      'arg1: expected %?, got 3',
1709      pcall_err(exec_lua, 'vim.validate{arg1={3, function(a) return a == 1 end}}')
1710    )
1711    matches(
1712      'arg1: expected number|string, got nil',
1713      pcall_err(exec_lua, "vim.validate{ arg1={ nil, {'n', 's'} }}")
1714    )
1715
1716    -- Pass an additional message back.
1717    matches(
1718      'arg1: expected %?, got 3. Info: TEST_MSG',
1719      pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1, 'TEST_MSG' end}}")
1720    )
1721  end)
1722
1723  it('vim.is_callable', function()
1724    eq(true, exec_lua('return vim.is_callable(function()end)'))
1725    eq(
1726      true,
1727      exec_lua([[
1728      local meta = { __call = function()end }
1729      local function new_callable()
1730        return setmetatable({}, meta)
1731      end
1732      local callable = new_callable()
1733      return vim.is_callable(callable)
1734    ]])
1735    )
1736
1737    eq(
1738      { false, false },
1739      exec_lua([[
1740      local meta = { __call = {} }
1741      assert(meta.__call)
1742      local function new()
1743        return setmetatable({}, meta)
1744      end
1745      local not_callable = new()
1746      return { pcall(function() not_callable() end), vim.is_callable(not_callable) }
1747    ]])
1748    )
1749    eq(
1750      { false, false },
1751      exec_lua([[
1752      local function new()
1753        return { __call = function()end }
1754      end
1755      local not_callable = new()
1756      assert(not_callable.__call)
1757      return { pcall(function() not_callable() end), vim.is_callable(not_callable) }
1758    ]])
1759    )
1760    eq(
1761      { false, false },
1762      exec_lua([[
1763      local meta = setmetatable(
1764        { __index = { __call = function() end } },
1765        { __index = { __call = function() end } }
1766      )
1767      assert(meta.__call)
1768      local not_callable = setmetatable({}, meta)
1769      assert(not_callable.__call)
1770      return { pcall(function() not_callable() end), vim.is_callable(not_callable) }
1771    ]])
1772    )
1773    eq(
1774      { false, false },
1775      exec_lua([[
1776      local meta = setmetatable({
1777        __index = function()
1778          return function() end
1779        end,
1780      }, {
1781        __index = function()
1782          return function() end
1783        end,
1784      })
1785      assert(meta.__call)
1786      local not_callable = setmetatable({}, meta)
1787      assert(not_callable.__call)
1788      return { pcall(function() not_callable() end), vim.is_callable(not_callable) }
1789    ]])
1790    )
1791    eq(false, exec_lua('return vim.is_callable(1)'))
1792    eq(false, exec_lua("return vim.is_callable('foo')"))
1793    eq(false, exec_lua('return vim.is_callable({})'))
1794  end)
1795
1796  it('vim.cmd', function()
1797    exec_lua [[
1798    vim.cmd "autocmd BufNew * ++once lua BUF = vim.fn.expand('<abuf>')"
1799    vim.cmd "new"
1800    ]]
1801    eq('2', fn.luaeval 'BUF')
1802    eq(2, fn.luaeval '#vim.api.nvim_list_bufs()')
1803
1804    -- vim.cmd can be indexed with a command name
1805    exec_lua [[
1806      vim.cmd.let 'g:var = 2'
1807    ]]
1808
1809    eq(2, fn.luaeval 'vim.g.var')
1810
1811    -- Passing many arguments to indexed vim.cmd (#41314)
1812    local props = exec_lua [[
1813      local props = {}
1814      for i = 1, 300 do
1815        props[i] = ('custom_property_%03d'):format(i)
1816      end
1817      vim.cmd.syntax { 'keyword', 'editorconfigProperty', unpack(props) }
1818      return props
1819    ]]
1820
1821    local output = n.exec_capture('syntax list editorconfigProperty')
1822    output = output:match('^%-%-%- Syntax items %-%-%-\neditorconfigProperty xxx (.*)')
1823    local output_list = vim.split(output, ' ')
1824    table.sort(output_list)
1825    eq(props, output_list)
1826  end)
1827
1828  it('vim.regex', function()
1829    exec_lua [[
1830      re1 = vim.regex"ab\\+c"
1831      vim.cmd "set nomagic ignorecase"
1832      re2 = vim.regex"xYz"
1833    ]]
1834    eq({}, exec_lua [[return {re1:match_str("x ac")}]])
1835    eq({ 3, 7 }, exec_lua [[return {re1:match_str("ac abbc")}]])
1836
1837    api.nvim_buf_set_lines(0, 0, -1, true, { 'yy', 'abc abbc' })
1838    eq({}, exec_lua [[return {re1:match_line(0, 0)}]])
1839    eq({ 0, 3 }, exec_lua [[return {re1:match_line(0, 1)}]])
1840    eq({ 3, 7 }, exec_lua [[return {re1:match_line(0, 1, 1)}]])
1841    eq({ 3, 7 }, exec_lua [[return {re1:match_line(0, 1, 1, 8)}]])
1842    eq({}, exec_lua [[return {re1:match_line(0, 1, 1, 7)}]])
1843    eq({ 0, 3 }, exec_lua [[return {re1:match_line(0, 1, 0, 7)}]])
1844
1845    -- vim.regex() error inside :silent! should not crash. #20546
1846    command([[silent! lua vim.regex('\\z')]])
1847    assert_alive()
1848
1849    -- match_str() in a fast (luv) callback does not abort. #18111
1850    eq(
1851      { true, true },
1852      exec_lua(function()
1853        local re = vim.regex('^.*\\.go$')
1854        local res
1855        local timer = assert(vim.uv.new_timer())
1856        timer:start(10, 0, function()
1857          -- Enough matches to reach BREAKCHECK_SKIP, which would abort (reentrant event loop).
1858          local ok = true
1859          for _ = 1, 3000 do
1860            ok = ok and re:match_str('internal/config/config.go') ~= nil
1861          end
1862          res = { ok, vim.in_fast_event() }
1863          timer:close()
1864        end)
1865        vim.wait(1000, function()
1866          return res ~= nil
1867        end)
1868        return res
1869      end)
1870    )
1871  end)
1872
1873  it('vim.defer_fn', function()
1874    eq(
1875      false,
1876      exec_lua [[
1877      vim.g.test = false
1878      vim.defer_fn(function() vim.g.test = true end, 150)
1879      return vim.g.test
1880    ]]
1881    )
1882    exec_lua [[vim.wait(1000, function() return vim.g.test end)]]
1883    eq(true, exec_lua [[return vim.g.test]])
1884  end)
1885
1886  it('nested vim.defer_fn does not leak handles on exit #19727', function()
1887    n.expect_exit(exec_lua, function()
1888      vim.defer_fn(function()
1889        vim.defer_fn(function()
1890          vim.defer_fn(function() end, 0)
1891        end, 0)
1892      end, 0)
1893      vim.cmd('qall')
1894    end)
1895  end)
1896
1897  it('vim.defer_fn with timeout does not leak handles on exit', function()
1898    n.expect_exit(exec_lua, function()
1899      vim.defer_fn(function() end, 50)
1900      vim.cmd('qall')
1901    end)
1902  end)
1903
1904  describe('vim.region', function()
1905    it('charwise', function()
1906      insert(dedent([[
1907      text tααt tααt text
1908      text tαxt txtα tex
1909      text tαxt tαxt
1910      ]]))
1911      eq({ 5, 13 }, exec_lua [[ return vim.region(0,{0,5},{0,13},'v',false)[0] ]])
1912      eq({ 5, 15 }, exec_lua [[ return vim.region(0,{0,5},{0,13},'v',true)[0] ]])
1913      eq({ 5, 15 }, exec_lua [[ return vim.region(0,{0,5},{0,14},'v',true)[0] ]])
1914      eq({ 5, 15 }, exec_lua [[ return vim.region(0,{0,5},{0,15},'v',false)[0] ]])
1915      eq({ 5, 17 }, exec_lua [[ return vim.region(0,{0,5},{0,15},'v',true)[0] ]])
1916      eq({ 5, 17 }, exec_lua [[ return vim.region(0,{0,5},{0,16},'v',true)[0] ]])
1917      eq({ 5, 17 }, exec_lua [[ return vim.region(0,{0,5},{0,17},'v',false)[0] ]])
1918      eq({ 5, 18 }, exec_lua [[ return vim.region(0,{0,5},{0,17},'v',true)[0] ]])
1919    end)
1920    it('blockwise', function()
1921      insert([[αα]])
1922      eq({ 0, 5 }, exec_lua [[ return vim.region(0,{0,0},{0,4},'3',true)[0] ]])
1923    end)
1924    it('linewise', function()
1925      insert(dedent([[
1926      text tααt tααt text
1927      text tαxt txtα tex
1928      text tαxt tαxt
1929      ]]))
1930      eq({ 0, -1 }, exec_lua [[ return vim.region(0,{1,5},{1,14},'V',true)[1] ]])
1931    end)
1932    it('getpos() input', function()
1933      insert('getpos')
1934      eq({ 0, 6 }, exec_lua [[ return vim.region(0,{0,0},'.','v',true)[0] ]])
1935    end)
1936  end)
1937
1938  describe('vim.on_key', function()
1939    it('tracks Unicode input', function()
1940      insert([[hello world ]])
1941
1942      exec_lua [[
1943        keys = {}
1944        typed = {}
1945
1946        vim.on_key(function(buf, typed_buf)
1947          if buf:byte() == 27 then
1948            buf = "<ESC>"
1949          end
1950          if typed_buf:byte() == 27 then
1951            typed_buf = "<ESC>"
1952          end
1953
1954          table.insert(keys, buf)
1955          table.insert(typed, typed_buf)
1956        end)
1957      ]]
1958
1959      insert([[next 🤦 lines å …]])
1960
1961      -- It has escape in the keys pressed
1962      eq('inext 🤦 lines å …<ESC>', exec_lua [[return table.concat(keys, '')]])
1963      eq('inext 🤦 lines å …<ESC>', exec_lua [[return table.concat(typed, '')]])
1964    end)
1965
1966    it('tracks input with modifiers', function()
1967      exec_lua [[
1968        keys = {}
1969        typed = {}
1970
1971        vim.on_key(function(buf, typed_buf)
1972          table.insert(keys, vim.fn.keytrans(buf))
1973          table.insert(typed, vim.fn.keytrans(typed_buf))
1974        end)
1975      ]]
1976
1977      feed([[i<C-V><C-;><C-V><C-…><Esc>]])
1978
1979      eq('i<C-V><C-;><C-V><C-…><Esc>', exec_lua [[return table.concat(keys, '')]])
1980      eq('i<C-V><C-;><C-V><C-…><Esc>', exec_lua [[return table.concat(typed, '')]])
1981    end)
1982
1983    it('works with character find and Select mode', function()
1984      insert('12345')
1985
1986      exec_lua [[
1987        typed = {}
1988
1989        vim.cmd('snoremap # @')
1990
1991        vim.on_key(function(buf, typed_buf)
1992          table.insert(typed, vim.fn.keytrans(typed_buf))
1993        end)
1994      ]]
1995
1996      feed('F3gHβγδεζ<Esc>gH…<Esc>gH#$%^')
1997      eq('F3gHβγδεζ<Esc>gH…<Esc>gH#$%^', exec_lua [[return table.concat(typed, '')]])
1998    end)
1999
2000    it('allows removing on_key listeners', function()
2001      -- Create some unused namespaces
2002      api.nvim_create_namespace('unused1')
2003      api.nvim_create_namespace('unused2')
2004      api.nvim_create_namespace('unused3')
2005      api.nvim_create_namespace('unused4')
2006
2007      insert([[hello world]])
2008
2009      exec_lua [[
2010        keys = {}
2011
2012        return vim.on_key(function(buf)
2013          if buf:byte() == 27 then
2014            buf = "<ESC>"
2015          end
2016
2017          table.insert(keys, buf)
2018        end, vim.api.nvim_create_namespace("logger"))
2019      ]]
2020
2021      insert([[next lines]])
2022
2023      eq(1, exec_lua('return vim.on_key()'))
2024      exec_lua("vim.on_key(nil, vim.api.nvim_create_namespace('logger'))")
2025      eq(0, exec_lua('return vim.on_key()'))
2026
2027      insert([[more lines]])
2028
2029      -- It has escape in the keys pressed
2030      eq('inext lines<ESC>', exec_lua [[return table.concat(keys, '')]])
2031    end)
2032
2033    it('skips any function that caused an error and shows stacktrace', function()
2034      insert([[hello world]])
2035
2036      exec_lua [[
2037        local function ErrF2()
2038          error("Dumb Error")
2039        end
2040        local function ErrF1()
2041          ErrF2()
2042        end
2043
2044        keys = {}
2045
2046        return vim.on_key(function(buf)
2047          if buf:byte() == 27 then
2048            buf = "<ESC>"
2049          end
2050
2051          table.insert(keys, buf)
2052
2053          if buf == 'l' then
2054            ErrF1()
2055          end
2056        end)
2057      ]]
2058
2059      insert([[next lines]])
2060      insert([[more lines]])
2061
2062      -- Only the first letter gets added. After that we remove the callback
2063      eq('inext l', exec_lua [[ return table.concat(keys, '') ]])
2064
2065      local errmsg = api.nvim_get_vvar('errmsg')
2066      matches(
2067        t.dedent [[
2068          ^vim%.on%_key%(%) callbacks:.*
2069          With ns%_id %d+: .*: Dumb Error
2070          stack traceback:
2071          .*: in function 'error'
2072          .*: in function 'ErrF2'
2073          .*: in function 'ErrF1'
2074          .*]],
2075        errmsg
2076      )
2077    end)
2078
2079    it('argument 1 is keys after mapping, argument 2 is typed keys', function()
2080      exec_lua [[
2081        keys = {}
2082        typed = {}
2083
2084        vim.cmd("inoremap hello world")
2085
2086        vim.on_key(function(buf, typed_buf)
2087          if buf:byte() == 27 then
2088            buf = "<ESC>"
2089          end
2090          if typed_buf:byte() == 27 then
2091            typed_buf = "<ESC>"
2092          end
2093
2094          table.insert(keys, buf)
2095          table.insert(typed, typed_buf)
2096        end)
2097      ]]
2098      insert('hello')
2099
2100      eq('iworld<ESC>', exec_lua [[return table.concat(keys, '')]])
2101      eq('ihello<ESC>', exec_lua [[return table.concat(typed, '')]])
2102    end)
2103
2104    it('can call vim.fn functions on Ctrl-C #17273', function()
2105      exec_lua([[
2106        _G.ctrl_c_cmdtype = ''
2107
2108        vim.on_key(function(c)
2109          if c == '\3' then
2110            _G.ctrl_c_cmdtype = vim.fn.getcmdtype()
2111          end
2112        end)
2113      ]])
2114      feed('/')
2115      poke_eventloop() -- This is needed because Ctrl-C flushes input
2116      feed('<C-C>')
2117      eq('/', exec_lua([[return _G.ctrl_c_cmdtype]]))
2118    end)
2119
2120    it('not invoked recursively #30752', function()
2121      local screen = Screen.new(60, 10)
2122      exec_lua([[
2123        vim.on_key(function(key, typed)
2124          vim.api.nvim_echo({
2125            { 'key_cb\n' },
2126            { ("KEYCB: key '%s', typed '%s'\n"):format(key, typed) },
2127          }, false, {})
2128        end)
2129      ]])
2130      feed('^')
2131      screen:expect([[
2132                                                                    |
2133        {1:~                                                           }|*5
2134        {3:                                                            }|
2135        key_cb                                                      |
2136        KEYCB: key '^', typed '^'                                   |
2137        {6:Press ENTER or type command to continue}^                     |
2138      ]])
2139      feed('<C-C>')
2140      screen:expect([[
2141                                                                    |
2142        {1:~                                                           }|*3
2143        {3:                                                            }|
2144        key_cb                                                      |
2145        KEYCB: key '^', typed '^'                                   |
2146        key_cb                                                      |
2147        KEYCB: key '{18:^C}', typed '{18:^C}'                                 |
2148        {6:Press ENTER or type command to continue}^                     |
2149      ]])
2150      feed('<C-C>')
2151      screen:expect([[
2152        ^                                                            |
2153        {1:~                                                           }|*8
2154                                                                    |
2155      ]])
2156    end)
2157
2158    it('not invoked for keys consumed by getchar() #40010', function()
2159      exec_lua(function()
2160        _G.typed = {}
2161        vim.on_key(function(_, typed)
2162          table.insert(_G.typed, vim.fn.keytrans(typed))
2163        end)
2164        vim.keymap.set('n', '<M-m>', function()
2165          _G.got = vim.fn.getchar()
2166        end)
2167      end)
2168      feed('<M-m><CR>')
2169      eq(13, exec_lua('return _G.got'))
2170      eq({ '<M-m>' }, exec_lua('return _G.typed'))
2171    end)
2172
2173    it('can discard input', function()
2174      -- discard the first key produced by every other 'x' key typed
2175      exec_lua [[
2176        n_key = 0
2177
2178        vim.on_key(function(buf, typed_buf)
2179          if typed_buf == 'x' then
2180            n_key = n_key + 1
2181            return (n_key % 2 == 0) and '' or nil
2182          end
2183        end)
2184      ]]
2185
2186      api.nvim_buf_set_lines(0, 0, -1, true, { '54321' })
2187
2188      feed('x') -- 'x' not discarded
2189      expect('4321')
2190      feed('x') -- 'x' discarded
2191      expect('4321')
2192      feed('x') -- 'x' not discarded
2193      expect('321')
2194      feed('x') -- 'x' discarded
2195      expect('321')
2196
2197      api.nvim_buf_set_lines(0, 0, -1, true, { '54321' })
2198
2199      -- only the first key from the mapping is discarded
2200      command('nnoremap x $x')
2201      feed('0x') -- '$' not discarded
2202      expect('5432')
2203      feed('0x') -- '$' discarded
2204      expect('432')
2205      feed('0x') -- '$' not discarded
2206      expect('43')
2207      feed('0x') -- '$' discarded
2208      expect('3')
2209
2210      feed('i')
2211      -- when discarding <Cmd>, the following command is also discarded.
2212      command([[inoremap x <Cmd>call append('$', 'foo')<CR>]])
2213      feed('x') -- not discarded
2214      expect('3\nfoo')
2215      feed('x') -- discarded
2216      expect('3\nfoo')
2217      feed('x') -- not discarded
2218      expect('3\nfoo\nfoo')
2219      feed('x') -- discarded
2220      expect('3\nfoo\nfoo')
2221
2222      -- K_LUA is handled similarly to <Cmd>
2223      exec_lua([[vim.keymap.set('i', 'x', function() vim.fn.append('$', 'bar') end)]])
2224      feed('x') -- not discarded
2225      expect('3\nfoo\nfoo\nbar')
2226      feed('x') -- discarded
2227      expect('3\nfoo\nfoo\nbar')
2228      feed('x') -- not discarded
2229      expect('3\nfoo\nfoo\nbar\nbar')
2230      feed('x') -- discarded
2231      expect('3\nfoo\nfoo\nbar\nbar')
2232    end)
2233
2234    it('behaves consistently with <Cmd>, K_LUA, nvim_paste', function()
2235      exec_lua([[
2236        vim.keymap.set('i', '<F2>', "<Cmd>call append('$', 'FOO')<CR>")
2237        vim.keymap.set('i', '<F3>', function() vim.fn.append('$', 'BAR') end)
2238      ]])
2239
2240      feed('qrafoo<F2><F3>')
2241      api.nvim_paste('bar', false, -1)
2242      feed('<Esc>q')
2243      expect('foobar\nFOO\nBAR')
2244
2245      exec_lua([[
2246        keys = {}
2247        typed = {}
2248
2249        vim.on_key(function(buf, typed_buf)
2250          table.insert(keys, buf)
2251          table.insert(typed, typed_buf)
2252        end)
2253      ]])
2254
2255      feed('@r')
2256      local keys = exec_lua('return keys')
2257      eq('@r', exec_lua([[return table.concat(typed, '')]]))
2258      expect('foobarfoobar\nFOO\nBAR\nFOO\nBAR')
2259
2260      -- Add a new callback that discards most special keys as well as 'f'.
2261      -- The old callback is still active.
2262      exec_lua([[
2263        vim.on_key(function(buf, _)
2264          if not buf:find('^[@rao\27]$') then
2265            return ''
2266          end
2267        end)
2268
2269        keys = {}
2270        typed = {}
2271      ]])
2272
2273      feed('@r')
2274      eq(keys, exec_lua('return keys'))
2275      eq('@r', exec_lua([[return table.concat(typed, '')]]))
2276      -- The "bar" paste is discarded as a whole.
2277      expect('foobarfoobaroo\nFOO\nBAR\nFOO\nBAR')
2278    end)
2279
2280    it('callback invalid return', function()
2281      -- second key produces an error which removes the callback
2282      exec_lua [[
2283        n_call = 0
2284
2285        vim.on_key(function(buf, typed_buf)
2286          if typed_buf == 'x' then
2287            n_call = n_call + 1
2288          end
2289          return n_call >= 2 and '!' or nil
2290        end)
2291      ]]
2292
2293      api.nvim_buf_set_lines(0, 0, -1, true, { '54321' })
2294
2295      feed('x')
2296      eq(1, exec_lua [[ return n_call ]])
2297      eq(1, exec_lua [[ return vim.on_key(nil, nil) ]])
2298      eq('', eval('v:errmsg'))
2299      feed('x')
2300      eq(2, exec_lua [[ return n_call ]])
2301      matches('return string must be empty', eval('v:errmsg'))
2302      command('let v:errmsg = ""')
2303
2304      eq(0, exec_lua [[ return vim.on_key(nil, nil) ]])
2305
2306      feed('x')
2307      eq(2, exec_lua [[ return n_call ]])
2308      expect('21')
2309      eq('', eval('v:errmsg'))
2310    end)
2311  end)
2312
2313  describe('vim.wait', function()
2314    before_each(function()
2315      exec_lua [[
2316        -- high precision timer
2317        get_time = function()
2318          return vim.fn.reltimefloat(vim.fn.reltime())
2319        end
2320      ]]
2321    end)
2322
2323    it('runs from lua', function()
2324      exec_lua [[vim.wait(100, function() return true end)]]
2325    end)
2326
2327    it('returns all (multiple) callback results', function()
2328      eq({ true, false }, exec_lua [[return { vim.wait(200, function() return true, false end) }]])
2329      eq(
2330        { true, 'a', 42, { ok = { 'yes' } } },
2331        exec_lua [[
2332          local ok, rv1, rv2, rv3 = vim.wait(200, function()
2333            return true, 'a', 42, { ok = { 'yes' } }
2334          end)
2335
2336          return { ok, rv1, rv2, rv3 }
2337        ]]
2338      )
2339    end)
2340
2341    it('does not return callback results on timeout', function()
2342      eq(
2343        { false, -1 },
2344        exec_lua [[
2345          return { vim.wait(1, function()
2346            return false, 'a', 42, { ok = { 'yes' } }
2347          end) }
2348        ]]
2349      )
2350    end)
2351
2352    it('waits the expected time if false', function()
2353      eq(
2354        { time = true, wait_result = { false, -1 } },
2355        exec_lua [[
2356        start_time = get_time()
2357        wait_succeed, wait_fail_val = vim.wait(200, function() return false end)
2358
2359        return {
2360          -- 150ms waiting or more results in true. Flaky tests are bad.
2361          time = (start_time + 0.15) < get_time(),
2362          wait_result = {wait_succeed, wait_fail_val}
2363        }
2364      ]]
2365      )
2366    end)
2367
2368    it('does not block other events', function()
2369      eq(
2370        { time = true, wait_result = true },
2371        exec_lua [[
2372        start_time = get_time()
2373
2374        vim.g.timer_result = false
2375        timer = vim.uv.new_timer()
2376        timer:start(100, 0, vim.schedule_wrap(function()
2377          vim.g.timer_result = true
2378        end))
2379
2380        -- Would wait ten seconds if results blocked.
2381        wait_result = vim.wait(10000, function() return vim.g.timer_result end)
2382
2383        timer:close()
2384
2385        return {
2386          time = (start_time + 5) > get_time(),
2387          wait_result = wait_result,
2388        }
2389      ]]
2390      )
2391    end)
2392
2393    it('does not process non-fast events when commanded', function()
2394      eq(
2395        { wait_result = false },
2396        exec_lua [[
2397        start_time = get_time()
2398
2399        vim.g.timer_result = false
2400        timer = vim.uv.new_timer()
2401        timer:start(100, 0, vim.schedule_wrap(function()
2402          vim.g.timer_result = true
2403        end))
2404
2405        wait_result = vim.wait(300, function() return vim.g.timer_result end, nil, true)
2406
2407        timer:close()
2408
2409        return {
2410          wait_result = wait_result,
2411        }
2412      ]]
2413      )
2414    end)
2415
2416    it('works with vim.defer_fn', function()
2417      eq(
2418        { time = true, wait_result = true },
2419        exec_lua [[
2420        start_time = get_time()
2421
2422        vim.defer_fn(function() vim.g.timer_result = true end, 100)
2423        wait_result = vim.wait(10000, function() return vim.g.timer_result end)
2424
2425        return {
2426          time = (start_time + 5) > get_time(),
2427          wait_result = wait_result,
2428        }
2429      ]]
2430      )
2431    end)
2432
2433    it('does not crash when callback errors', function()
2434      local result = exec_lua [[
2435        return {pcall(function() vim.wait(1000, function() error("As Expected") end) end)}
2436      ]]
2437      eq({ false, '[string "<nvim>"]:1: As Expected' }, { result[1], remove_trace(result[2]) })
2438    end)
2439
2440    it('callback must be a function', function()
2441      local result = exec_lua [[return {pcall(function() vim.wait(1000, 13) end)}]]
2442      eq(false, result[1])
2443      matches('callback: expected callable, got number$', remove_trace(result[2]))
2444    end)
2445
2446    it('waits if callback arg is nil', function()
2447      eq(
2448        true,
2449        exec_lua [[
2450        local start_time = vim.uv.hrtime()
2451        vim.wait(50.1, nil) -- select('#', ...) == 1
2452        return vim.uv.hrtime() - start_time > 25000
2453      ]]
2454      )
2455    end)
2456
2457    it('waits if callback arg is omitted', function()
2458      eq(
2459        true,
2460        exec_lua [[
2461        local start_time = vim.uv.hrtime()
2462        vim.wait(50) -- select('#', ...) == 0
2463        return vim.uv.hrtime() - start_time > 25000
2464      ]]
2465      )
2466    end)
2467
2468    it('invokes callback exactly once if it returns true immediately', function()
2469      eq(
2470        true,
2471        exec_lua [[
2472        vim.g.wait_count = 0
2473        vim.wait(1000, function()
2474          vim.g.wait_count = vim.g.wait_count + 1
2475          return true
2476        end, 20)
2477        return vim.g.wait_count == 1
2478      ]]
2479      )
2480    end)
2481
2482    it('calls callbacks few times with large `interval`', function()
2483      eq(
2484        true,
2485        exec_lua [[
2486        vim.g.wait_count = 0
2487        vim.wait(50, function() vim.g.wait_count = vim.g.wait_count + 1 end, 200)
2488        return vim.g.wait_count < 5
2489      ]]
2490      )
2491    end)
2492
2493    it('does not leak when Nvim exits while waiting', function()
2494      n.expect_exit(500, exec_lua, function()
2495        vim.defer_fn(function()
2496          vim.cmd('qall!')
2497        end, 10)
2498        vim.wait(10000)
2499      end)
2500    end)
2501
2502    it('plays nice with `not` when fails', function()
2503      eq(
2504        true,
2505        exec_lua [[
2506        if not vim.wait(50, function() end) then
2507          return true
2508        end
2509
2510        return false
2511      ]]
2512      )
2513    end)
2514
2515    it('plays nice with `if` when success', function()
2516      eq(
2517        true,
2518        exec_lua [[
2519        if vim.wait(50, function() return true end) then
2520          return true
2521        end
2522
2523        return false
2524      ]]
2525      )
2526    end)
2527
2528    it('returns immediately with false if timeout is 0', function()
2529      eq(
2530        { false, -1 },
2531        exec_lua [[
2532        return {
2533          vim.wait(0, function() return false end)
2534        }
2535      ]]
2536      )
2537    end)
2538
2539    it('works with tables with __call', function()
2540      eq(
2541        true,
2542        exec_lua [[
2543        local t = setmetatable({}, {__call = function(...) return true end})
2544        return vim.wait(100, t, 10)
2545      ]]
2546      )
2547    end)
2548
2549    it('works with tables with __call that change', function()
2550      eq(
2551        true,
2552        exec_lua [[
2553        local t = {count = 0}
2554        setmetatable(t, {
2555          __call = function()
2556            t.count = t.count + 1
2557            return t.count > 3
2558          end
2559        })
2560
2561        return vim.wait(1000, t, 10)
2562      ]]
2563      )
2564    end)
2565
2566    it('fails with negative intervals', function()
2567      local pcall_result = exec_lua [[
2568        return pcall(function() vim.wait(1000, function() return false end, -1) end)
2569      ]]
2570
2571      eq(false, pcall_result)
2572    end)
2573
2574    it('fails with weird intervals', function()
2575      local pcall_result = exec_lua [[
2576        return pcall(function() vim.wait(1000, function() return false end, 'a string value') end)
2577      ]]
2578
2579      eq(false, pcall_result)
2580    end)
2581
2582    describe('returns -2 when interrupted', function()
2583      before_each(function()
2584        local channel = api.nvim_get_chan_info(0).id
2585        api.nvim_set_var('channel', channel)
2586      end)
2587
2588      it('without callback', function()
2589        exec_lua([[
2590          function _G.Wait()
2591            vim.rpcnotify(vim.g.channel, 'ready')
2592            -- handles math.huge #36854
2593            local _, interrupted = vim.wait(math.huge)
2594            vim.rpcnotify(vim.g.channel, 'wait', interrupted)
2595          end
2596        ]])
2597        feed(':lua _G.Wait()<CR>')
2598        eq({ 'notification', 'ready', {} }, next_msg(500))
2599        feed('<C-C>')
2600        eq({ 'notification', 'wait', { -2 } }, next_msg(500))
2601      end)
2602
2603      it('with callback', function()
2604        exec_lua([[
2605          function _G.Wait()
2606            vim.rpcnotify(vim.g.channel, 'ready')
2607            local _, interrupted = vim.wait(math.huge, function() end)
2608            vim.rpcnotify(vim.g.channel, 'wait', interrupted)
2609          end
2610        ]])
2611        feed(':lua _G.Wait()<CR>')
2612        eq({ 'notification', 'ready', {} }, next_msg(500))
2613        feed('<C-C>')
2614        eq({ 'notification', 'wait', { -2 } }, next_msg(500))
2615      end)
2616    end)
2617
2618    it('lets CTRL-C interrupt a Lua loop', function()
2619      api.nvim_set_var('channel', api.nvim_get_chan_info(0).id)
2620      exec_lua([[
2621        function _G.Loop()
2622          vim.rpcnotify(vim.g.channel, 'ready')
2623          while true do
2624            local _, code = vim.wait(0, nil, 0)
2625            if code == -2 then
2626              vim.rpcnotify(vim.g.channel, 'wait', code)
2627              return
2628            end
2629          end
2630        end
2631      ]])
2632      feed(':lua _G.Loop()<CR>')
2633      eq({ 'notification', 'ready', {} }, next_msg(500))
2634      feed('<C-C>')
2635      eq({ 'notification', 'wait', { -2 } }, next_msg(500))
2636    end)
2637
2638    it('fails in fast callbacks #26122', function()
2639      local screen = Screen.new(80, 10)
2640      exec_lua([[
2641        local timer = vim.uv.new_timer()
2642        timer:start(0, 0, function()
2643          timer:close()
2644          vim.wait(100, function() end)
2645        end)
2646      ]])
2647      screen:expect({
2648        any = pesc('E5560: vim.wait must not be called in a fast event context'),
2649      })
2650      feed('<CR>')
2651      assert_alive()
2652    end)
2653  end)
2654
2655  it('vim.notify_once', function()
2656    local screen = Screen.new(60, 5)
2657    screen:expect {
2658      grid = [[
2659      ^                                                            |
2660      {1:~                                                           }|*3
2661                                                                  |
2662    ]],
2663    }
2664    exec_lua [[vim.notify_once("I'll only tell you this once...", vim.log.levels.WARN)]]
2665    screen:expect {
2666      grid = [[
2667      ^                                                            |
2668      {1:~                                                           }|*3
2669      {19:I'll only tell you this once...}                             |
2670    ]],
2671    }
2672    feed('<C-l>')
2673    screen:expect {
2674      grid = [[
2675      ^                                                            |
2676      {1:~                                                           }|*3
2677                                                                  |
2678    ]],
2679    }
2680    exec_lua [[vim.notify_once("I'll only tell you this once...")]]
2681    screen:expect_unchanged()
2682  end)
2683
2684  describe('vim.schedule_wrap', function()
2685    it('preserves argument lists', function()
2686      exec_lua [[
2687        local fun = vim.schedule_wrap(function(kling, klang, klonk)
2688          vim.rpcnotify(1, 'mayday_mayday', {a=kling, b=klang, c=klonk})
2689        end)
2690        fun("BOB", nil, "MIKE")
2691      ]]
2692      eq({ 'notification', 'mayday_mayday', { { a = 'BOB', c = 'MIKE' } } }, next_msg())
2693
2694      -- let's gooooo
2695      exec_lua [[
2696        vim.schedule_wrap(function(...) vim.rpcnotify(1, 'boogalo', select('#', ...)) end)(nil,nil,nil,nil)
2697      ]]
2698      eq({ 'notification', 'boogalo', { 4 } }, next_msg())
2699    end)
2700  end)
2701
2702  describe('vim.iconv', function()
2703    it('can convert strings', function()
2704      eq(
2705        'hello',
2706        exec_lua [[
2707        return vim.iconv('hello', 'latin1', 'utf-8')
2708      ]]
2709      )
2710    end)
2711
2712    it('can validate arguments', function()
2713      eq(
2714        { false, 'Expected at least 3 arguments' },
2715        exec_lua [[
2716        return {pcall(vim.iconv, 'hello')}
2717      ]]
2718      )
2719
2720      eq(
2721        { false, "bad argument #3 to '?' (expected string)" },
2722        exec_lua [[
2723        return {pcall(vim.iconv, 'hello', 'utf-8', true)}
2724      ]]
2725      )
2726    end)
2727
2728    it('can handle bad encodings', function()
2729      eq(
2730        NIL,
2731        exec_lua [[
2732        return vim.iconv('hello', 'foo', 'bar')
2733      ]]
2734      )
2735    end)
2736
2737    it('can handle strings with NUL bytes', function()
2738      eq(
2739        7,
2740        exec_lua [[
2741        local a = string.char(97, 98, 99, 0, 100, 101, 102) -- abc\0def
2742        return string.len(vim.iconv(a, 'latin1', 'utf-8'))
2743      ]]
2744      )
2745    end)
2746
2747    it('utf-16le should not be equal to utf-16be', function()
2748      neq(
2749        exec_lua [[
2750        return vim.iconv('hello', 'utf-8', 'utf-16le')
2751      ]],
2752        exec_lua [[
2753        return vim.iconv('hello', 'utf-8', 'utf-16be')
2754      ]]
2755      )
2756    end)
2757  end)
2758
2759  describe('vim.defaulttable', function()
2760    it('creates nested table by default', function()
2761      eq(
2762        { b = { c = 1 } },
2763        exec_lua [[
2764        local a = vim.defaulttable()
2765        a.b.c = 1
2766        return a
2767      ]]
2768      )
2769    end)
2770
2771    it('allows to create default objects', function()
2772      eq(
2773        { b = 1 },
2774        exec_lua [[
2775        local a = vim.defaulttable(function() return 0 end)
2776        a.b = a.b + 1
2777        return a
2778      ]]
2779      )
2780    end)
2781
2782    it('accepts the key name', function()
2783      eq(
2784        { b = 'b', c = 'c' },
2785        exec_lua [[
2786        local a = vim.defaulttable(function(k) return k end)
2787        local _ = a.b
2788        local _ = a.c
2789        return a
2790      ]]
2791      )
2792    end)
2793  end)
2794
2795  it('vim.lua_omnifunc', function()
2796    local screen = Screen.new(60, 5)
2797    command [[ set omnifunc=v:lua.vim.lua_omnifunc ]]
2798
2799    -- Note: the implementation is shared with lua command line completion.
2800    -- More tests for completion in lua/command_line_completion_spec.lua
2801    feed [[ivim.insp<c-x><c-o>]]
2802    screen:expect {
2803      grid = [[
2804      vim.inspect^                                                 |
2805      {1:~  }{12: inspect        }{1:                                         }|
2806      {1:~  }{4: inspect_pos    }{1:                                         }|
2807      {1:~                                                           }|
2808      {5:-- Omni completion (^O^N^P) }{6:match 1 of 2}                    |
2809    ]],
2810    }
2811  end)
2812
2813  it('vim.print', function()
2814    -- vim.print() returns its args.
2815    eq(
2816      { 42, 'abc', { a = { b = 77 } } },
2817      exec_lua [[return {vim.print(42, 'abc', { a = { b = 77 }})}]]
2818    )
2819
2820    -- vim.print() pretty-prints the args.
2821    eq(
2822      dedent [[
2823
2824      42
2825      abc
2826      {
2827        a = {
2828          b = 77
2829        }
2830      }]],
2831      eval [[execute('lua vim.print(42, "abc", { a = { b = 77 }})')]]
2832    )
2833  end)
2834
2835  it('vim.nonnil', function()
2836    local function nonnil(...)
2837      return exec_lua(
2838        [[
2839        local args = {...}
2840        local nargs = select('#', ...)
2841        for i = 1, nargs do
2842          if args[i] == vim.NIL then
2843            args[i] = nil
2844          end
2845        end
2846        return vim.nonnil(unpack(args, 1, nargs))
2847      ]],
2848        ...
2849      )
2850    end
2851
2852    local a = NIL
2853    local b = NIL
2854    local c = 42
2855    local d = false
2856    eq(42, nonnil(a, c))
2857    eq(false, nonnil(d, b))
2858    eq(42, nonnil(a, b, c, d))
2859    eq(false, nonnil(d))
2860    eq(false, nonnil(d, c))
2861    eq(NIL, nonnil(a))
2862  end)
2863
2864  it('vim.npcall', function()
2865    -- No error
2866    eq(
2867      { '123', 'test' },
2868      exec_lua(function()
2869        local function swap_args(a, b)
2870          return b, a
2871        end
2872        return { vim.npcall(swap_args, 'test', '123') }
2873      end)
2874    )
2875
2876    -- Error
2877    eq(
2878      nil,
2879      exec_lua(function()
2880        return vim.npcall(error, 'error')
2881      end)
2882    )
2883  end)
2884
2885  it('lpeg', function()
2886    eq(
2887      5,
2888      exec_lua [[
2889      local m = vim.lpeg
2890      return m.match(m.R'09'^1, '4504ab')
2891    ]]
2892    )
2893
2894    eq(4, exec_lua [[ return vim.re.match("abcde", '[a-c]+') ]])
2895  end)
2896
2897  it('vim.ringbuf', function()
2898    local results = exec_lua([[
2899      local ringbuf = vim.ringbuf(3)
2900      ringbuf:push("a") -- idx: 0
2901      local peeka1 = ringbuf:peek()
2902      local peeka2 = ringbuf:peek()
2903      local popa = ringbuf:pop()
2904      local popnil = ringbuf:pop()
2905      ringbuf:push("a") -- idx: 1
2906      ringbuf:push("b") -- idx: 2
2907
2908      -- doesn't read last added item, but uses separate read index
2909      local pop_after_add_b = ringbuf:pop()
2910
2911      ringbuf:push("c") -- idx: 3 wraps around, overrides idx: 0 "a"
2912      ringbuf:push("d") -- idx: 4 wraps around, overrides idx: 1 "a"
2913      return {
2914        peeka1 = peeka1,
2915        peeka2 = peeka2,
2916        pop1 = popa,
2917        pop2 = popnil,
2918        pop3 = ringbuf:pop(),
2919        pop4 = ringbuf:pop(),
2920        pop5 = ringbuf:pop(),
2921        pop_after_add_b = pop_after_add_b,
2922      }
2923    ]])
2924    local expected = {
2925      peeka1 = 'a',
2926      peeka2 = 'a',
2927      pop1 = 'a',
2928      pop2 = nil,
2929      pop3 = 'b',
2930      pop4 = 'c',
2931      pop5 = 'd',
2932      pop_after_add_b = 'a',
2933    }
2934    eq(expected, results)
2935  end)
2936end)
2937
2938describe('lua: builtin modules', function()
2939  local function do_tests()
2940    eq(2, exec_lua [[return vim.tbl_count {x=1,y=2}]])
2941    eq('{ 10, "spam" }', exec_lua [[return vim.inspect {10, 'spam'}]])
2942  end
2943
2944  it('works', function()
2945    clear()
2946    do_tests()
2947  end)
2948
2949  it('works when disabled', function()
2950    clear('--luamod-dev')
2951    do_tests()
2952  end)
2953
2954  it('works without runtime', function()
2955    clear { env = { VIMRUNTIME = 'fixtures/a' } }
2956    do_tests()
2957  end)
2958
2959  it('fails when disabled without runtime', function()
2960    clear()
2961    command("let $VIMRUNTIME='fixtures/a'")
2962    -- Use system([nvim,…]) instead of clear() to avoid stderr noise. #21844
2963    local out = fn.system({
2964      nvim_prog,
2965      '--clean',
2966      '--luamod-dev',
2967      [[+call nvim_exec_lua('return vim.tbl_count {x=1,y=2}')]],
2968      '+qa!',
2969    }):gsub('\r\n', '\n')
2970    eq(1, eval('v:shell_error'))
2971    matches("'vim%._core.shared' not found", out)
2972  end)
2973end)
2974
2975describe('lua: require("mod") from packages', function()
2976  before_each(function()
2977    clear('--cmd', 'set rtp+=test/functional/fixtures pp+=test/functional/fixtures')
2978  end)
2979
2980  it('propagates syntax error', function()
2981    local syntax_error_msg = exec_lua [[
2982      local _, err = pcall(require, "syntax_error")
2983      return err
2984    ]]
2985
2986    matches('unexpected symbol', syntax_error_msg)
2987  end)
2988
2989  it('uses the right order of mod.lua vs mod/init.lua', function()
2990    -- lua/fancy_x.lua takes precedence over lua/fancy_x/init.lua
2991    eq('I am fancy_x.lua', exec_lua [[ return require'fancy_x' ]])
2992    -- but lua/fancy_y/init.lua takes precedence over after/lua/fancy_y.lua
2993    eq('I am init.lua of fancy_y!', exec_lua [[ return require'fancy_y' ]])
2994    -- safety check: after/lua/fancy_z.lua is still loaded
2995    eq('I am fancy_z.lua', exec_lua [[ return require'fancy_z' ]])
2996  end)
2997end)
2998
2999describe('vim.keymap', function()
3000  before_each(clear)
3001
3002  it('validates', function()
3003    matches(
3004      'modes: expected string|table, got number',
3005      pcall_err(exec_lua, [[vim.keymap.set(42, 'x', print)]])
3006    )
3007
3008    matches(
3009      'rhs: expected string|function, got nil',
3010      pcall_err(exec_lua, [[vim.keymap.set('n', 'x')]])
3011    )
3012
3013    matches(
3014      'lhs: expected string|table, got number',
3015      pcall_err(exec_lua, [[vim.keymap.set('n', 5, print)]])
3016    )
3017
3018    matches(
3019      'rhs: expected string|function, got number',
3020      pcall_err(exec_lua, [[vim.keymap.set({}, 'x', 42, function() end)]])
3021    )
3022
3023    matches(
3024      'opts: expected table, got function',
3025      pcall_err(exec_lua, [[vim.keymap.set({}, 'x', 'x', function() end)]])
3026    )
3027
3028    matches(
3029      'rhs: expected string|function, got number',
3030      pcall_err(exec_lua, [[vim.keymap.set('z', 'x', 42)]])
3031    )
3032
3033    matches('Invalid mode shortname: "z"', pcall_err(exec_lua, [[vim.keymap.set('z', 'x', 'y')]]))
3034  end)
3035
3036  it('mapping', function()
3037    eq(
3038      0,
3039      exec_lua [[
3040      GlobalCount = 0
3041      vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end)
3042      vim.keymap.set('n', { 'ghjk', 'qwer' }, function() GlobalCount = GlobalCount + 1 end)
3043      return GlobalCount
3044    ]]
3045    )
3046
3047    feed('asdf\n')
3048    eq(1, exec_lua [[return GlobalCount]])
3049
3050    feed('ghjk\nqwer\n')
3051    eq(3, exec_lua [[return GlobalCount]])
3052  end)
3053
3054  it('expr mapping', function()
3055    exec_lua [[
3056      vim.keymap.set('n', 'aa', function() return '<Insert>π<C-V><M-π>foo<lt><Esc>' end, {expr = true})
3057    ]]
3058
3059    feed('aa')
3060
3061    eq({ 'π<M-π>foo<' }, api.nvim_buf_get_lines(0, 0, -1, false))
3062  end)
3063
3064  it('overwrite a mapping', function()
3065    eq(
3066      0,
3067      exec_lua [[
3068      GlobalCount = 0
3069      vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end)
3070      return GlobalCount
3071    ]]
3072    )
3073
3074    feed('asdf\n')
3075
3076    eq(1, exec_lua [[return GlobalCount]])
3077
3078    exec_lua [[
3079      vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount - 1 end)
3080    ]]
3081
3082    feed('asdf\n')
3083
3084    eq(0, exec_lua [[return GlobalCount]])
3085  end)
3086
3087  it('unmap', function()
3088    eq(
3089      0,
3090      exec_lua [[
3091      GlobalCount = 0
3092      vim.keymap.set('n', { 'asdf', 'ghjk', 'qwer' }, function() GlobalCount = GlobalCount + 1 end)
3093      return GlobalCount
3094    ]]
3095    )
3096
3097    feed('asdf\n')
3098
3099    eq(1, exec_lua [[return GlobalCount]])
3100
3101    exec_lua [[
3102      vim.keymap.del('n', 'asdf')
3103    ]]
3104
3105    feed('asdf\n')
3106
3107    eq(1, exec_lua [[return GlobalCount]])
3108    eq('\nNo mapping found', n.exec_capture('nmap asdf'))
3109
3110    exec_lua [[
3111      vim.keymap.del('n', { 'ghjk', 'qwer' })
3112    ]]
3113
3114    feed('ghjk\nqwer\n')
3115
3116    eq(1, exec_lua [[return GlobalCount]])
3117    eq('\nNo mapping found', n.exec_capture('nmap ghjk'))
3118    eq('\nNo mapping found', n.exec_capture('nmap qwer'))
3119  end)
3120
3121  it('unmap with lhs option', function()
3122    eq(
3123      'q',
3124      exec_lua [[
3125      vim.keymap.set('n', 'ge', 'q')
3126      local ok, err = pcall(vim.keymap.del, 'n', 'q', { lhs = true })
3127      assert(not ok and err:match('E31: No such mapping'), err)
3128      return vim.fn.maparg('ge', 'n')
3129    ]]
3130    )
3131
3132    exec_lua [[
3133      vim.keymap.del('n', 'ge', { lhs = true })
3134    ]]
3135    eq('\nNo mapping found', n.exec_capture('nmap ge'))
3136  end)
3137
3138  it('buffer-local mappings', function()
3139    eq(
3140      0,
3141      exec_lua [[
3142      GlobalCount = 0
3143      vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end, {buf=0})
3144      return GlobalCount
3145    ]]
3146    )
3147
3148    feed('asdf\n')
3149
3150    eq(1, exec_lua [[return GlobalCount]])
3151
3152    exec_lua [[
3153      vim.keymap.del('n', 'asdf', {buf=0})
3154    ]]
3155
3156    feed('asdf\n')
3157
3158    eq(1, exec_lua [[return GlobalCount]])
3159    eq('\nNo mapping found', n.exec_capture('nmap asdf'))
3160  end)
3161
3162  it('does not mutate the opts parameter', function()
3163    eq(
3164      0,
3165      exec_lua [[
3166      opts = {buf=0}
3167      vim.keymap.set('n', 'asdf', function() end, opts)
3168      return opts.buf
3169    ]]
3170    )
3171    eq(
3172      0,
3173      exec_lua [[
3174      vim.keymap.del('n', 'asdf', opts)
3175      return opts.buf
3176    ]]
3177    )
3178  end)
3179
3180  it('<Plug> mappings', function()
3181    eq(
3182      0,
3183      exec_lua [[
3184      GlobalCount = 0
3185      vim.keymap.set('n', '<plug>(asdf)', function() GlobalCount = GlobalCount + 1 end)
3186      vim.keymap.set('n', 'ww', '<plug>(asdf)')
3187      return GlobalCount
3188    ]]
3189    )
3190
3191    feed('ww\n')
3192
3193    eq(1, exec_lua [[return GlobalCount]])
3194  end)
3195end)
3196
3197describe('vim.fn.exists()', function()
3198  it('can check a Lua function', function()
3199    eq(
3200      1,
3201      exec_lua [[
3202      _G.test = function() print("hello") end
3203      return vim.fn.exists('*v:lua.test')
3204    ]]
3205    )
3206
3207    eq(1, fn.exists('*v:lua.require("mpack").decode'))
3208    eq(1, fn.exists("*v:lua.require('mpack').decode"))
3209    eq(1, fn.exists('*v:lua.require"mpack".decode'))
3210    eq(1, fn.exists("*v:lua.require'mpack'.decode"))
3211    eq(1, fn.exists("*v:lua.require('vim.lsp').start"))
3212    eq(1, fn.exists('*v:lua.require"vim.lsp".start'))
3213    eq(1, fn.exists("*v:lua.require'vim.lsp'.start"))
3214    eq(0, fn.exists("*v:lua.require'vim.lsp'.unknown"))
3215    eq(0, fn.exists('*v:lua.?'))
3216  end)
3217end)