robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
16.6 KiB505 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4
5local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
6local eq = t.eq
7local exec_lua = n.exec_lua
8local clear = n.clear
9local feed = n.feed
10local fn = n.fn
11local assert_log = t.assert_log
12local check_close = n.check_close
13
14local testlog = 'Xtest_lua_ui_event_log'
15
16describe('vim.ui_attach', function()
17  local screen
18  before_each(function()
19    clear()
20    exec_lua [[
21      ns = vim.api.nvim_create_namespace 'testspace'
22      events = {}
23      function on_event(event, ...)
24        events[#events+1] = {event, ...}
25        return true
26      end
27
28      function get_events()
29        local ret_events = events
30        events = {}
31        return ret_events
32      end
33    ]]
34
35    screen = Screen.new(40, 5)
36  end)
37
38  local function expect_events(expected)
39    local evs = exec_lua 'return get_events(...)'
40    eq(expected, evs, vim.inspect(evs))
41  end
42
43  it('can receive popupmenu events', function()
44    exec_lua [[ vim.ui_attach(ns, {ext_popupmenu=true}, on_event) ]]
45    feed('ifo')
46    screen:expect {
47      grid = [[
48      fo^                                      |
49      {1:~                                       }|*3
50      {5:-- INSERT --}                            |
51    ]],
52    }
53
54    fn.complete(1, { 'food', 'foobar', 'foo' })
55    screen:expect {
56      grid = [[
57      food^                                    |
58      {1:~                                       }|*3
59      {5:-- INSERT --}                            |
60    ]],
61    }
62    expect_events {
63      {
64        'popupmenu_show',
65        { { 'food', '', '', '' }, { 'foobar', '', '', '' }, { 'foo', '', '', '' } },
66        0,
67        0,
68        0,
69        1,
70      },
71    }
72
73    feed '<c-n>'
74    screen:expect {
75      grid = [[
76      foobar^                                  |
77      {1:~                                       }|*3
78      {5:-- INSERT --}                            |
79    ]],
80    }
81    expect_events {
82      { 'popupmenu_select', 1 },
83    }
84
85    feed '<c-y>'
86    screen:expect_unchanged()
87    expect_events {
88      { 'popupmenu_hide' },
89    }
90
91    -- vim.ui_detach() stops events, and reenables builtin pum immediately
92    exec_lua [[
93      vim.ui_detach(ns)
94      vim.fn.complete(1, {'food', 'foobar', 'foo'})
95    ]]
96
97    screen:expect {
98      grid = [[
99      food^                                    |
100      {12:food           }{1:                         }|
101      {4:foobar         }{1:                         }|
102      {4:foo            }{1:                         }|
103      {5:-- INSERT --}                            |
104    ]],
105    }
106    expect_events {}
107  end)
108
109  it('does not crash on exit', function()
110    local p = n.spawn_wait(
111      '--cmd',
112      [[ lua ns = vim.api.nvim_create_namespace 'testspace' ]],
113      '--cmd',
114      [[ lua vim.ui_attach(ns, {ext_popupmenu=true}, function() end) ]],
115      '--cmd',
116      'quitall!'
117    )
118    eq(0, p.status)
119  end)
120
121  it('can receive accurate message kinds even if they are history', function()
122    exec_lua([[
123    vim.cmd.echomsg("'message1'")
124    print('message2')
125    vim.ui_attach(ns, { ext_messages = true }, on_event)
126    vim.cmd.echomsg("'message3'")
127    ]])
128    feed(':messages<cr>')
129    feed('<cr>')
130
131    local actual = exec_lua([[
132    return vim.tbl_filter(function (event)
133      return event[1] == "msg_history_show"
134    end, events)
135    ]])
136    eq({
137      {
138        'msg_history_show',
139        {
140          { 'echomsg', { { 0, 'message1', 0 } }, false },
141          { 'lua_print', { { 0, 'message2', 0 } }, false },
142          { 'echomsg', { { 0, 'message3', 0 } }, false },
143        },
144        false,
145      },
146    }, actual, vim.inspect(actual))
147  end)
148
149  it('ui_refresh() activates correct capabilities without remote UI', function()
150    screen:detach()
151    exec_lua('vim.ui_attach(ns, { ext_cmdline = true }, on_event)')
152    eq(1, n.api.nvim_get_option_value('cmdheight', {}))
153    exec_lua('vim.ui_detach(ns)')
154    exec_lua('vim.ui_attach(ns, { ext_messages = true }, on_event)')
155    n.api.nvim_set_option_value('cmdheight', 1, {})
156    screen:attach()
157    eq(1, n.api.nvim_get_option_value('cmdheight', {}))
158  end)
159
160  it("ui_refresh() sets 'cmdheight' for all open tabpages with ext_messages", function()
161    exec_lua('vim.cmd.tabnew()')
162    exec_lua('vim.ui_attach(ns, { ext_messages = true }, on_event)')
163    exec_lua('vim.cmd.tabnext()')
164    eq(0, n.api.nvim_get_option_value('cmdheight', {}))
165  end)
166
167  it("can attach ext_messages without changing 'cmdheight'", function()
168    exec_lua('vim.ui_attach(ns, { ext_messages = true, set_cmdheight = false }, on_event)')
169    eq(1, n.api.nvim_get_option_value('cmdheight', {}))
170  end)
171
172  it('avoids recursive flushing and invalid memory access with :redraw', function()
173    exec_lua([[
174      _G.cmdline = 0
175      vim.ui_attach(ns, { ext_messages = true }, function(ev)
176        if ev == 'msg_show' then
177          vim.schedule(function() vim.cmd.redraw() end)
178        elseif ev:find('cmdline') then
179          _G.cmdline = _G.cmdline + (ev == 'cmdline_show' and 1 or 0)
180          vim.api.nvim_buf_set_lines(0, 0, -1, false, { tostring(_G.cmdline) })
181          vim.cmd('redraw')
182        end
183      end
184    )]])
185    screen:expect([[
186      ^                                        |
187      {1:~                                       }|*4
188    ]])
189    feed(':')
190    screen:expect({
191      grid = [[
192        ^1                                       |
193        {1:~                                       }|*4
194      ]],
195      cmdline = { { content = { { '' } }, firstc = ':', pos = 0 } },
196    })
197    feed('version<CR>')
198    screen:expect({
199      grid = [[
200        ^2                                       |
201        {1:~                                       }|*4
202      ]],
203      condition = function()
204        eq('list_cmd', screen.messages[1].kind)
205        screen.messages = {} -- Ignore the build dependent :version content
206      end,
207    })
208    feed([[v<Esc>:call confirm("Save changes?", "&Yes\n&No\n&Cancel")<CR>]])
209    screen:expect({
210      grid = [[
211        ^4                                       |
212        {1:~                                       }|*4
213      ]],
214      cmdline = {
215        { content = { { '' } }, hl = 'MoreMsg', pos = 0, prompt = '[Y]es, (N)o, (C)ancel: ' },
216      },
217      messages = { { content = { { 'Save changes?', 6, 'MoreMsg' } }, kind = 'confirm' } },
218    })
219    feed('n')
220    screen:expect_unchanged()
221  end)
222
223  it("preserved 'incsearch/command' screen state after :redraw from ext_cmdline", function()
224    exec_lua([[
225      vim.cmd.norm('ifoobar')
226      vim.cmd('1split cmdline')
227      local buf = vim.api.nvim_get_current_buf()
228      vim.cmd.wincmd('p')
229      vim.ui_attach(ns, { ext_cmdline = true }, function(event, ...)
230        if event == 'cmdline_show' then
231          local content = select(1, ...)
232          vim.api.nvim_buf_set_lines(buf, -2, -1, false, {content[1][2]})
233          vim.cmd('redraw')
234        end
235        return true
236      end)
237    ]])
238    -- Updates a cmdline window
239    feed(':cmdline')
240    screen:expect([[
241      cmdline                                 |
242      {2:cmdline [+]                             }|
243      fooba^r                                  |
244      {3:[No Name] [+]                           }|
245                                              |
246    ]])
247    -- Does not clear 'incsearch' highlighting
248    feed('<Esc>/foo')
249    screen:expect([[
250      foo                                     |
251      {2:cmdline [+]                             }|
252      {2:foo}ba^r                                  |
253      {3:[No Name] [+]                           }|
254                                              |
255    ]])
256    -- Shows new cmdline state during 'inccommand'
257    feed('<Esc>:%s/bar/baz')
258    screen:expect([[
259      %s/bar/baz                              |
260      {2:cmdline [+]                             }|
261      foo{10:ba^z}                                  |
262      {3:[No Name] [+]                           }|
263                                              |
264    ]])
265  end)
266
267  it('msg_show in fast context', function()
268    exec_lua([[
269    vim.ui_attach(ns, { ext_messages = true }, function(event, _, content)
270      if event == "msg_show" then
271        vim.api.nvim_get_runtime_file("foo", false)
272        -- non-"fast-api" is not allowed in msg_show callback and should be scheduled
273        local _, err = pcall(vim.api.nvim_buf_set_lines, 0, -2, -1, false, { content[1][2] })
274        pcall(vim.api.nvim__redraw, { flush = true })
275        vim.schedule(function()
276          vim.api.nvim_buf_set_lines(0, -2, -1, false, { content[1][2], err })
277        end)
278      end
279    end)
280    ]])
281    -- "fast-api" does not prevent aborting :function
282    feed(':func Foo()<cr>bar<cr>endf<cr>:func Foo()<cr>')
283    screen:expect({
284      grid = [[
285        ^E122: Function Foo already exists, add !|
286         to replace it                          |
287        E5560: nvim_buf_set_lines must not be ca|
288        lled in a fast event context            |
289        {1:~                                       }|
290      ]],
291      messages = {
292        {
293          content = { { 'E122: Function Foo already exists, add ! to replace it', 9, 'ErrorMsg' } },
294          history = true,
295          kind = 'emsg',
296        },
297      },
298    })
299  end)
300
301  it('ext_cmdline completion popupmenu', function()
302    screen:try_resize(screen._width, 10)
303    screen:add_extra_attr_ids { [100] = { background = Screen.colors.Black } }
304    exec_lua([[
305      vim.o.wildoptions = 'pum'
306      local buf = vim.api.nvim_create_buf(false, true)
307      vim.cmd('call setline(1, range(1, 10))')
308      _G.win = vim.api.nvim_open_win(buf, false, {
309        relative = 'editor',
310        col = 3,
311        row = 3,
312        width = 20,
313        height = 1,
314        style = 'minimal',
315        focusable = false,
316        zindex = 300,
317        _cmdline_offset = 0,
318      })
319      vim.ui_attach(ns, { ext_cmdline = true }, function(event, content, _, firstc)
320        if event == 'cmdline_show' then
321          local prompt = vim.api.nvim_win_get_config(_G.win)._cmdline_offset == 0
322          prompt = (prompt and firstc or 'Excommand:') .. content[1][2]
323          vim.api.nvim_buf_set_lines(buf, -2, -1, false, { prompt })
324          vim.api.nvim_win_set_cursor(_G.win, { 1, #prompt })
325          vim.api.nvim__redraw({ win = _G.win, cursor = true, flush = true })
326        end
327        return true
328      end)
329      vim.api.nvim_set_hl(0, 'Pmenu', {})
330    ]])
331    feed(':call buf<tab>')
332    screen:expect([[
333      1                                       |
334      2                                       |
335      3                                       |
336      4  :call bufadd^(                        |
337      5       {12: bufadd(        }{100: }               |
338      6        bufexists(     {100: }               |
339      7        buffer_exists( {12: }               |
340      8        buffer_name(   {12: }               |
341      9        buffer_number( {12: }               |
342                                              |
343    ]])
344    exec_lua([[
345      vim.api.nvim_win_set_config(_G.win, {
346        relative = 'editor',
347        col = 0,
348        row = 1000,
349        width = 1000,
350        height = 1,
351      })
352      vim.api.nvim__redraw({flush = true})
353    ]])
354    screen:expect([[
355      1                                       |
356      2                                       |
357      3                                       |
358      4                                       |
359      5       {12: bufadd(        }{100: }               |
360      6        bufexists(     {100: }               |
361      7        buffer_exists( {12: }               |
362      8        buffer_name(   {12: }               |
363      9        buffer_number( {12: }               |
364      :call bufadd^(                           |
365    ]])
366    feed('<tab>')
367    screen:expect([[
368      1     bufadd(        {100: }                  |
369      2    {12: bufexists(     }{100: }                  |
370      3     buffer_exists( {100: }                  |
371      4     buffer_name(   {100: }                  |
372      5     buffer_number( {100: }                  |
373      6     buflisted(     {100: }                  |
374      7     bufload(       {12: }                  |
375      8     bufloaded(     {12: }                  |
376      9     bufname(       {12: }                  |
377      :call bufexists^(                        |
378    ]])
379    -- Test different offset (e.g. for custom prompt)
380    exec_lua('vim.api.nvim_win_set_config(_G.win, { _cmdline_offset = 9 })')
381    feed('<Esc>:call buf<Tab>')
382    screen:expect([[
383      1             {12: bufadd(        }{100: }         |
384      2              bufexists(     {100: }         |
385      3              buffer_exists( {100: }         |
386      4              buffer_name(   {100: }         |
387      5              buffer_number( {100: }         |
388      6              buflisted(     {100: }         |
389      7              bufload(       {12: }         |
390      8              bufloaded(     {12: }         |
391      9              bufname(       {12: }         |
392      Excommand:call bufadd^(                  |
393    ]])
394    -- _cmdline_offset remains set after being turned into a split.
395    exec_lua(function()
396      vim.fn.win_execute(_G.win, 'wincmd J')
397    end)
398    feed('<Tab>') -- Was a signed int overflow; offset was INT_MAX despite cmdline_win being set.
399    eq(9, exec_lua('return vim.api.nvim_win_get_config(_G.win)._cmdline_offset'))
400    -- No crash after _cmdline_offset window is closed #35584.
401    exec_lua(function()
402      vim.ui_detach(_G.ns)
403      vim.api.nvim_win_close(_G.win, true)
404    end)
405    feed('<Esc>:<Tab>')
406    n.assert_alive()
407  end)
408
409  it("does not crash with :norm 'showcmd' from shell message callback #38233", function()
410    exec_lua(function()
411      vim.ui_attach(vim.api.nvim_create_namespace(''), { ext_messages = true }, function(event)
412        if event == 'msg_show' then
413          vim.api.nvim_command('norm! G')
414        end
415      end)
416    end)
417    n.command('set showcmd | !echo "foo"')
418    n.assert_alive()
419  end)
420end)
421
422describe('vim.ui_attach', function()
423  before_each(function()
424    clear({ env = { NVIM_LOG_FILE = testlog } })
425  end)
426
427  after_each(function()
428    check_close()
429    os.remove(testlog)
430  end)
431
432  it('callback error is logged', function()
433    exec_lua([[
434      local ns = vim.api.nvim_create_namespace('test')
435      vim.ui_attach(ns, { ext_popupmenu = true }, function() error(42) end)
436    ]])
437    feed('ifoo<CR>foobar<CR>fo<C-X><C-N>')
438    assert_log(
439      'Error in "popupmenu_show" UI event handler %(ns=test%):[\r\n\t ]+Lua: .*: 42',
440      testlog,
441      100
442    )
443  end)
444
445  it('detaches after excessive errors', function()
446    local screen = Screen.new(66, 10)
447    screen:add_extra_attr_ids({ [100] = { bold = true, foreground = Screen.colors.SeaGreen } })
448    exec_lua([[
449      vim.ui_attach(vim.api.nvim_create_namespace(''), { ext_messages = true }, function(ev)
450        if ev == 'msg_show' then
451          error('foo')
452        end
453      end)
454    ]])
455    feed('@@')
456    screen:expect({
457      grid = [[
458                                                                          |
459        {1:~                                                                 }|*2
460        {3:                                                                  }|
461        {9:Error in "msg_show" UI event handler (ns=(UNKNOWN PLUGIN)):}       |
462        {9:Lua: [string "<nvim>"]:3: foo}                                     |
463        {9:stack traceback:}                                                  |
464        {9:        [C]: in function 'error'}                                  |
465        {9:        [string "<nvim>"]:3: in function <[string "<nvim>"]:1>}    |
466        {100:Press ENTER or type command to continue}^                           |
467      ]],
468      condition = function()
469        screen.messages = {}
470      end,
471    })
472    feed('<Esc>')
473
474    -- Also when scheduled
475    exec_lua([[
476      vim.ui_attach(vim.api.nvim_create_namespace(''), { ext_messages = true }, function(ev)
477        if ev == 'msg_show' then
478          vim.schedule(function() error('foo') end)
479        end
480      end)
481    ]])
482    feed('@@')
483    screen:expect({
484      grid = [[
485                                                                          |
486        {1:~                                                                 }|*6
487        {3:                                                                  }|
488        {9:Excessive errors in vim.ui_attach() callback (ns=(UNKNOWN PLUGIN))}|
489        {100:Press ENTER or type command to continue}^                           |
490      ]],
491      condition = function()
492        screen.messages = {}
493      end,
494    })
495  end)
496
497  it('sourcing invalid file does not crash #32166', function()
498    exec_lua([[
499      local ns = vim.api.nvim_create_namespace("")
500      vim.ui_attach(ns, { ext_messages = true }, function() end)
501    ]])
502    feed((':luafile %s<CR>'):format(testlog))
503    n.assert_alive()
504  end)
505end)