robin/laufey

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

zeertzjqfix(window): crash when closing new curwin during CTRL-W_x (#41378)2cd4229d01

master
26.6 KiB897 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 = t.describe, t.it, t.before_each
6local assert_visible = n.assert_visible
7local assert_alive = n.assert_alive
8local dedent = t.dedent
9local eq = t.eq
10local neq = t.neq
11local eval = n.eval
12local exec = n.exec
13local feed = n.feed
14local clear = n.clear
15local matches = t.matches
16local api = n.api
17local pcall_err = t.pcall_err
18local fn = n.fn
19local expect = n.expect
20local command = n.command
21local exec_lua = n.exec_lua
22local retry = t.retry
23local source = n.source
24local request = n.request
25
26describe('autocmd', function()
27  before_each(clear)
28
29  it(':tabnew, :split, :close events order, <afile>', function()
30    local expected = {
31      { 'WinLeave', '' },
32      { 'TabLeave', '' },
33      { 'WinEnter', '' },
34      { 'TabNew', 'testfile1' }, -- :tabnew
35      { 'TabEnter', '' },
36      { 'BufLeave', '' },
37      { 'BufEnter', 'testfile1' }, -- :split
38      { 'WinLeave', 'testfile1' },
39      { 'WinEnter', 'testfile1' },
40      { 'WinLeave', 'testfile1' },
41      { 'WinClosed', '1002' }, -- :close, WinClosed <afile> = window-id
42      { 'WinEnter', 'testfile1' },
43      { 'WinLeave', 'testfile1' }, -- :bdelete
44      { 'WinEnter', 'testfile1' },
45      { 'BufLeave', 'testfile1' },
46      { 'BufEnter', 'testfile2' },
47      { 'WinClosed', '1000' },
48    }
49    command('let g:evs = []')
50    command('autocmd BufEnter * :call add(g:evs, ["BufEnter", expand("<afile>")])')
51    command('autocmd BufLeave * :call add(g:evs, ["BufLeave", expand("<afile>")])')
52    command('autocmd TabEnter * :call add(g:evs, ["TabEnter", expand("<afile>")])')
53    command('autocmd TabLeave * :call add(g:evs, ["TabLeave", expand("<afile>")])')
54    command('autocmd TabNew   * :call add(g:evs, ["TabNew", expand("<afile>")])')
55    command('autocmd WinEnter * :call add(g:evs, ["WinEnter", expand("<afile>")])')
56    command('autocmd WinLeave * :call add(g:evs, ["WinLeave", expand("<afile>")])')
57    command('autocmd WinClosed * :call add(g:evs, ["WinClosed", expand("<afile>")])')
58    command('tabnew testfile1')
59    command('split')
60    command('close')
61    command('new testfile2')
62    command('bdelete 1')
63    eq(expected, eval('g:evs'))
64  end)
65
66  it('first edit causes BufUnload on NoName', function()
67    local expected = {
68      { 'BufUnload', '' },
69      { 'BufDelete', '' },
70      { 'BufWipeout', '' },
71      { 'BufEnter', 'testfile1' },
72    }
73    command('let g:evs = []')
74    command('autocmd BufEnter * :call add(g:evs, ["BufEnter", expand("<afile>")])')
75    command('autocmd BufDelete * :call add(g:evs, ["BufDelete", expand("<afile>")])')
76    command('autocmd BufLeave * :call add(g:evs, ["BufLeave", expand("<afile>")])')
77    command('autocmd BufUnload * :call add(g:evs, ["BufUnload", expand("<afile>")])')
78    command('autocmd BufWipeout * :call add(g:evs, ["BufWipeout", expand("<afile>")])')
79    command('edit testfile1')
80    eq(expected, eval('g:evs'))
81  end)
82
83  it('WinClosed is non-recursive', function()
84    command('let g:triggered = 0')
85    command('autocmd WinClosed * :let g:triggered+=1 | :bdelete 2')
86    command('new testfile2')
87    command('new testfile3')
88
89    -- All 3 buffers are visible.
90    assert_visible(1, true)
91    assert_visible(2, true)
92    assert_visible(3, true)
93
94    -- Trigger WinClosed, which also deletes buffer/window 2.
95    command('bdelete 1')
96
97    -- Buffers 1 and 2 were closed but WinClosed was triggered only once.
98    eq(1, eval('g:triggered'))
99    assert_visible(1, false)
100    assert_visible(2, false)
101    assert_visible(3, true)
102  end)
103
104  it('WinClosed from a different tabpage', function()
105    command('let g:evs = []')
106    command('edit tesfile1')
107    command('autocmd WinClosed <buffer> :call add(g:evs, ["WinClosed", expand("<abuf>")])')
108    local buf1 = eval("bufnr('%')")
109    command('new')
110    local buf2 = eval("bufnr('%')")
111    command(
112      'autocmd WinClosed <buffer> :call add(g:evs, ["WinClosed", expand("<abuf>")])'
113        -- Attempt recursion.
114        .. ' | bdelete '
115        .. buf2
116    )
117    command('tabedit testfile2')
118    command('tabedit testfile3')
119    command('bdelete ' .. buf2)
120    -- Non-recursive: only triggered once.
121    eq({
122      { 'WinClosed', '2' },
123    }, eval('g:evs'))
124    command('bdelete ' .. buf1)
125    eq({
126      { 'WinClosed', '2' },
127      { 'WinClosed', '1' },
128    }, eval('g:evs'))
129  end)
130
131  it('WinClosed from root directory', function()
132    command('cd /')
133    command('let g:evs = []')
134    command('autocmd WinClosed * :call add(g:evs, ["WinClosed", expand("<afile>")])')
135    command('new')
136    command('close')
137    eq({
138      { 'WinClosed', '1001' },
139    }, eval('g:evs'))
140  end)
141
142  it('v:vim_did_enter is 1 after VimEnter', function()
143    eq(1, eval('v:vim_did_enter'))
144  end)
145
146  describe('BufLeave autocommand', function()
147    it('can wipe out the buffer created by :edit which triggered autocmd', function()
148      api.nvim_set_option_value('hidden', true, {})
149      api.nvim_buf_set_lines(0, 0, 1, false, {
150        'start of test file xx',
151        'end of test file xx',
152      })
153
154      command('autocmd BufLeave * bwipeout yy')
155      eq(
156        'Vim(edit):E143: Autocommands unexpectedly deleted new buffer yy',
157        pcall_err(command, 'edit yy')
158      )
159
160      expect([[
161        start of test file xx
162        end of test file xx]])
163    end)
164  end)
165
166  it('++once', function() -- :help autocmd-once
167    --
168    -- ":autocmd … ++once" executes its handler once, then removes the handler.
169    --
170    local expected = {
171      'Many1',
172      'Once1',
173      'Once2',
174      'Many2',
175      'Once3',
176      'Many1',
177      'Many2',
178      'Many1',
179      'Many2',
180    }
181    command('let g:foo = []')
182    command('autocmd TabNew * :call add(g:foo, "Many1")')
183    command('autocmd TabNew * ++once :call add(g:foo, "Once1")')
184    command('autocmd TabNew * ++once :call add(g:foo, "Once2")')
185    command('autocmd TabNew * :call add(g:foo, "Many2")')
186    command('autocmd TabNew * ++once :call add(g:foo, "Once3")')
187    eq(
188      dedent([[
189
190       --- Autocommands ---
191       TabNew
192           *         :call add(g:foo, "Many1")
193                     :call add(g:foo, "Once1")
194                     :call add(g:foo, "Once2")
195                     :call add(g:foo, "Many2")
196                     :call add(g:foo, "Once3")]]),
197      fn.execute('autocmd Tabnew')
198    )
199    command('tabnew')
200    command('tabnew')
201    command('tabnew')
202    eq(expected, eval('g:foo'))
203    eq(
204      dedent([[
205
206       --- Autocommands ---
207       TabNew
208           *         :call add(g:foo, "Many1")
209                     :call add(g:foo, "Many2")]]),
210      fn.execute('autocmd Tabnew')
211    )
212
213    --
214    -- ":autocmd … ++once" handlers can be deleted.
215    --
216    expected = {}
217    command('let g:foo = []')
218    command('autocmd TabNew * ++once :call add(g:foo, "Once1")')
219    command('autocmd! TabNew')
220    command('tabnew')
221    eq(expected, eval('g:foo'))
222
223    --
224    -- ":autocmd … <buffer> ++once ++nested"
225    --
226    expected = {
227      'OptionSet-Once',
228      'CursorMoved-Once',
229    }
230    command('let g:foo = []')
231    command('autocmd OptionSet binary ++nested ++once :call add(g:foo, "OptionSet-Once")')
232    command(
233      'autocmd CursorMoved <buffer> ++once ++nested setlocal binary|:call add(g:foo, "CursorMoved-Once")'
234    )
235    command("put ='foo bar baz'")
236    feed('0llhlh')
237    eq(expected, eval('g:foo'))
238
239    --
240    -- :autocmd should not show empty section after ++once handlers expire.
241    --
242    expected = {
243      'Once1',
244      'Once2',
245    }
246    command('let g:foo = []')
247    command('autocmd! TabNew') -- Clear all TabNew handlers.
248    command('autocmd TabNew * ++once :call add(g:foo, "Once1")')
249    command('autocmd TabNew * ++once :call add(g:foo, "Once2")')
250    command('tabnew')
251    eq(expected, eval('g:foo'))
252    eq(
253      dedent([[
254
255       --- Autocommands ---]]),
256      fn.execute('autocmd Tabnew')
257    )
258
259    --
260    -- :autocmd does not recursively call ++once Lua handlers.
261    --
262    exec_lua [[vim.g.count = 0]]
263    eq(0, eval('g:count'))
264    exec_lua [[
265      vim.api.nvim_create_autocmd('User', {
266        once = true,
267        pattern = nil,
268        callback = function()
269          vim.g.count = vim.g.count + 1
270          vim.api.nvim_exec_autocmds('User', { pattern = nil })
271        end,
272      })
273      vim.api.nvim_exec_autocmds('User', { pattern = nil })
274    ]]
275    eq(1, eval('g:count'))
276  end)
277
278  it('internal `aucmd_win` window', function()
279    -- Nvim uses a special internal window `aucmd_win` to execute certain
280    -- actions for an invisible buffer (:help E813).
281    -- Check redrawing (never shown) and API access to this window.
282
283    local screen = Screen.new(50, 10)
284
285    source([[
286      function! Doit()
287        let g:winid = nvim_get_current_win()
288        redraw!
289        echo getchar()
290        " API functions work when aucmd_win is in scope
291        let g:had_value = has_key(w:, "testvar")
292        call nvim_win_set_var(g:winid, "testvar", 7)
293        let g:test = w:testvar
294      endfunction
295      set hidden
296      " add dummy text to not discard the buffer
297      call setline(1,"bb")
298      autocmd User <buffer> call Doit()
299    ]])
300    screen:expect([[
301      ^bb                                                |
302      {1:~                                                 }|*8
303                                                        |
304    ]])
305
306    feed(':enew | doautoall User<cr>')
307    screen:expect([[
308                                                        |
309      {1:~                                                 }|*8
310      :enew | doautoall User                            |
311    ]])
312
313    feed('<cr>')
314    screen:expect([[
315      ^                                                  |
316      {1:~                                                 }|*8
317      13                                                |
318    ]])
319    eq(7, eval('g:test'))
320
321    -- API calls are blocked when aucmd_win is not in scope
322    eq(
323      'Vim(call):E5555: API call: Invalid window id: 1001',
324      pcall_err(command, 'call nvim_set_current_win(g:winid)')
325    )
326
327    -- second time aucmd_win is needed, a different code path is invoked
328    -- to reuse the same window, so check again
329    command('let g:test = v:null')
330    command('let g:had_value = v:null')
331    feed(':doautoall User<cr>')
332    screen:expect([[
333                                                        |
334      {1:~                                                 }|*8
335      :doautoall User                                   |
336    ]])
337
338    feed('<cr>')
339    screen:expect([[
340      ^                                                  |
341      {1:~                                                 }|*8
342      13                                                |
343    ]])
344    -- win vars in aucmd_win should have been reset
345    eq(0, eval('g:had_value'))
346    eq(7, eval('g:test'))
347
348    eq(
349      'Vim(call):E5555: API call: Invalid window id: 1001',
350      pcall_err(command, 'call nvim_set_current_win(g:winid)')
351    )
352  end)
353
354  it('`aucmd_win` cannot be changed into a normal window #13699', function()
355    local screen = Screen.new(50, 10)
356
357    -- Create specific layout and ensure it's left unchanged.
358    -- Use vim._with on a hidden buffer so aucmd_win is used.
359    exec_lua [[
360      vim.cmd "wincmd s | wincmd _"
361      _G.buf = vim.api.nvim_create_buf(true, true)
362      vim._with({buf = _G.buf}, function() vim.cmd "wincmd J" end)
363    ]]
364    screen:expect [[
365      ^                                                  |
366      {1:~                                                 }|*5
367      {3:[No Name]                                         }|
368                                                        |
369      {2:[No Name]                                         }|
370                                                        |
371    ]]
372    -- This used to crash after making aucmd_win a normal window via the above.
373    exec_lua [[
374      vim.cmd "tabnew | tabclose # | wincmd s | wincmd _"
375      vim._with({buf = _G.buf}, function() vim.cmd "wincmd K" end)
376    ]]
377    assert_alive()
378    screen:expect_unchanged()
379
380    -- Also check with win_splitmove().
381    exec_lua [[
382      vim._with({buf = _G.buf}, function()
383        vim.fn.win_splitmove(vim.fn.win_getid(), vim.fn.win_getid(1))
384      end)
385    ]]
386    screen:expect_unchanged()
387
388    -- Also check with nvim_win_set_config().
389    matches(
390      '^Failed to move window %d+ into split$',
391      pcall_err(
392        exec_lua,
393        [[
394          vim._with({buf = _G.buf}, function()
395            vim.api.nvim_win_set_config(0, {
396              vertical = true,
397              win = vim.fn.win_getid(1)
398            })
399          end)
400        ]]
401      )
402    )
403    screen:expect_unchanged()
404
405    -- Ensure splitting still works from inside the aucmd_win.
406    exec_lua [[vim._with({buf = _G.buf}, function() vim.cmd "split" end)]]
407    screen:expect [[
408      ^                                                  |
409      {1:~                                                 }|
410      {3:[No Name]                                         }|
411                                                        |
412      {1:~                                                 }|
413      {2:[Scratch]                                         }|
414                                                        |
415      {1:~                                                 }|
416      {2:[No Name]                                         }|
417                                                        |
418    ]]
419
420    -- After all of our messing around, aucmd_win should still be floating.
421    -- Use :only to ensure _G.buf is hidden again (so the aucmd_win is used).
422    eq(
423      'editor',
424      exec_lua [[
425        vim.cmd "only"
426        vim._with({buf = _G.buf}, function()
427          _G.config = vim.api.nvim_win_get_config(0)
428        end)
429        return _G.config.relative
430      ]]
431    )
432  end)
433
434  it('cannot close `aucmd_win` in non-current tabpage', function()
435    exec([[
436      file Xa
437      tabnew Xb
438      call setline(1, 'foo')
439      tabfirst
440      autocmd BufWriteCmd Xb tablast | bwipe! Xa
441    ]])
442    eq(
443      'BufWriteCmd Autocommands for "Xb": Vim(bwipeout):E813: Cannot close autocmd window',
444      pcall_err(command, 'wall')
445    )
446    -- Sanity check: :bwipe failing to close all windows into Xa should keep it loaded.
447    -- (So there's no risk of it being left unloaded inside a window)
448    eq(1, eval('bufloaded("Xa")'))
449  end)
450
451  describe('closing last non-floating window in tab from `aucmd_win`', function()
452    before_each(function()
453      command('edit Xa.txt')
454      command('tabnew Xb.txt')
455      command('autocmd BufAdd Xa.txt 1close')
456    end)
457
458    it('gives E814 when there are no other floating windows', function()
459      eq(
460        'BufAdd Autocommands for "Xa.txt": Vim(close):E814: Cannot close window, only autocmd window would remain',
461        pcall_err(command, 'doautoall BufAdd')
462      )
463    end)
464
465    it('gives E814 when there are other floating windows', function()
466      api.nvim_open_win(
467        0,
468        true,
469        { width = 10, height = 10, relative = 'editor', row = 10, col = 10 }
470      )
471      eq(
472        'BufAdd Autocommands for "Xa.txt": Vim(close):E814: Cannot close window, only autocmd window would remain',
473        pcall_err(command, 'doautoall BufAdd')
474      )
475    end)
476  end)
477
478  it('closing `aucmd_win` using API gives E813', function()
479    exec_lua([[
480      vim.cmd('tabnew')
481      _G.buf = vim.api.nvim_create_buf(true, true)
482    ]])
483    matches(
484      'Vim:E813: Cannot close autocmd window$',
485      pcall_err(
486        exec_lua,
487        [[
488          vim._with({buf = _G.buf}, function()
489            local win = vim.api.nvim_get_current_win()
490            vim.api.nvim_win_close(win, true)
491          end)
492        ]]
493      )
494    )
495    matches(
496      'Vim:E813: Cannot close autocmd window$',
497      pcall_err(
498        exec_lua,
499        [[
500          vim._with({buf = _G.buf}, function()
501            local win = vim.api.nvim_get_current_win()
502            vim.cmd('tabnext')
503            vim.api.nvim_win_close(win, true)
504          end)
505        ]]
506      )
507    )
508    matches(
509      'Vim:E813: Cannot close autocmd window$',
510      pcall_err(
511        exec_lua,
512        [[
513          vim._with({buf = _G.buf}, function()
514            local win = vim.api.nvim_get_current_win()
515            vim.api.nvim_win_hide(win)
516          end)
517        ]]
518      )
519    )
520    matches(
521      'Vim:E813: Cannot close autocmd window$',
522      pcall_err(
523        exec_lua,
524        [[
525          vim._with({buf = _G.buf}, function()
526            local win = vim.api.nvim_get_current_win()
527            vim.cmd('tabnext')
528            vim.api.nvim_win_hide(win)
529          end)
530        ]]
531      )
532    )
533  end)
534
535  it(':doautocmd does not warn "No matching autocommands" #10689', function()
536    local screen = Screen.new(32, 3)
537
538    feed(':doautocmd User Foo<cr>')
539    screen:expect {
540      grid = [[
541      ^                                |
542      {1:~                               }|
543      :doautocmd User Foo             |
544    ]],
545    }
546    feed(':autocmd! SessionLoadPost<cr>')
547    feed(':doautocmd SessionLoadPost<cr>')
548    screen:expect {
549      grid = [[
550      ^                                |
551      {1:~                               }|
552      :doautocmd SessionLoadPost      |
553    ]],
554    }
555  end)
556
557  describe('v:event is readonly #18063', function()
558    it('during ChanOpen event', function()
559      command('autocmd ChanOpen * let v:event.info.id = 0')
560      fn.jobstart({ 'cat' })
561      retry(nil, nil, function()
562        eq('E46: Cannot change read-only variable "v:event.info"', api.nvim_get_vvar('errmsg'))
563      end)
564    end)
565
566    it('during ChanOpen event', function()
567      command('autocmd ChanInfo * let v:event.info.id = 0')
568      api.nvim_set_client_info('foo', {}, 'remote', {}, {})
569      retry(nil, nil, function()
570        eq('E46: Cannot change read-only variable "v:event.info"', api.nvim_get_vvar('errmsg'))
571      end)
572    end)
573
574    it('during RecordingLeave event', function()
575      command([[autocmd RecordingLeave * let v:event.regname = '']])
576      eq(
577        'RecordingLeave Autocommands for "*": Vim(let):E46: Cannot change read-only variable "v:event.regname"',
578        pcall_err(command, 'normal! qqq')
579      )
580    end)
581
582    it('during TermClose event', function()
583      command('autocmd TermClose * let v:event.status = 0')
584      command('terminal')
585      eq(
586        'TermClose Autocommands for "*": Vim(let):E46: Cannot change read-only variable "v:event.status"',
587        pcall_err(command, 'bdelete!')
588      )
589    end)
590  end)
591
592  describe('old_tests', function()
593    it('vimscript: WinNew ++once', function()
594      source [[
595        " Without ++once WinNew triggers twice
596        let g:did_split = 0
597        augroup Testing
598          au!
599          au WinNew * let g:did_split += 1
600        augroup END
601        split
602        split
603        call assert_equal(2, g:did_split)
604        call assert_true(exists('#WinNew'))
605        close
606        close
607
608        " With ++once WinNew triggers once
609        let g:did_split = 0
610        augroup Testing
611          au!
612          au WinNew * ++once let g:did_split += 1
613        augroup END
614        split
615        split
616        call assert_equal(1, g:did_split)
617        call assert_false(exists('#WinNew'))
618        close
619        close
620
621        call assert_fails('au WinNew * ++once ++once echo bad', 'E983:')
622      ]]
623
624      api.nvim_set_var('did_split', 0)
625
626      source [[
627        augroup Testing
628          au!
629          au WinNew * let g:did_split += 1
630        augroup END
631
632        split
633        split
634      ]]
635
636      eq(2, api.nvim_get_var('did_split'))
637      eq(1, fn.exists('#WinNew'))
638
639      -- Now with once
640      api.nvim_set_var('did_split', 0)
641
642      source [[
643        augroup Testing
644          au!
645          au WinNew * ++once let g:did_split += 1
646        augroup END
647
648        split
649        split
650      ]]
651
652      eq(1, api.nvim_get_var('did_split'))
653      eq(0, fn.exists('#WinNew'))
654
655      -- call assert_fails('au WinNew * ++once ++once echo bad', 'E983:')
656      local ok, msg = pcall(
657        source,
658        [[
659        au WinNew * ++once ++once echo bad
660      ]]
661      )
662
663      eq(false, ok)
664      eq(true, not not string.find(msg, 'E983:'))
665    end)
666
667    it('should have autocmds in filetypedetect group', function()
668      source [[filetype on]]
669      neq({}, api.nvim_get_autocmds { group = 'filetypedetect' })
670    end)
671
672    it('should allow comma-separated patterns', function()
673      source [[
674        augroup TestingPatterns
675          au!
676          autocmd BufReadCmd *.shada,*.shada.tmp.[a-z] echo 'hello'
677          autocmd BufReadCmd *.shada,*.shada.tmp.[a-z] echo 'hello'
678        augroup END
679      ]]
680
681      eq(4, #api.nvim_get_autocmds { event = 'BufReadCmd', group = 'TestingPatterns' })
682    end)
683  end)
684
685  it('no use-after-free when adding autocommands from a callback', function()
686    exec_lua [[
687      vim.cmd "autocmd! TabNew"
688      vim.g.count = 0
689      vim.api.nvim_create_autocmd('TabNew', {
690        callback = function()
691          vim.g.count = vim.g.count + 1
692          for _ = 1, 100 do
693            vim.cmd "autocmd TabNew * let g:count += 1"
694          end
695          return true
696        end,
697      })
698      vim.cmd "tabnew"
699    ]]
700    eq(1, eval('g:count')) -- Added autocommands should not be executed
701  end)
702
703  it('no crash when clearing a group inside a callback #23355', function()
704    exec_lua [[
705      vim.cmd "autocmd! TabNew"
706      local group = vim.api.nvim_create_augroup('Test', {})
707      local id
708      id = vim.api.nvim_create_autocmd('TabNew', {
709        group = group,
710        callback = function()
711          vim.api.nvim_del_autocmd(id)
712          vim.api.nvim_create_augroup('Test', { clear = true })
713        end,
714      })
715      vim.cmd "tabnew"
716    ]]
717  end)
718
719  it('no use-after-free when wiping buffer in Syntax autocommand', function()
720    exec([[
721      new
722      autocmd Syntax * ++once bwipe!
723      setlocal syntax=vim
724    ]])
725    assert_alive()
726  end)
727
728  it('no use-after-free from win_enter autocommands in win_move_after', function()
729    exec [[
730      split foo
731      split bar
732      lcd ..
733      wincmd b
734    ]]
735    eq(fn.winnr('$'), fn.winnr())
736    -- Using DirChanged as Enter/Leave autocmds are blocked by :ball here.
737    exec [[
738      autocmd DirChanged * ++once split flarb | only!
739      ball
740    ]]
741    eq('flarb', fn.bufname())
742  end)
743
744  it('no use-after-free when closing new curwin during CTRL-W_x #41373', function()
745    exec([[
746      tabnew
747      vsplit
748      autocmd WinLeave * ++once bwipe!
749    ]])
750    eq(2, #api.nvim_list_tabpages())
751    feed('<C-W>x')
752    eq(1, #api.nvim_list_tabpages())
753    assert_alive()
754  end)
755
756  it('does not ignore comma-separated patterns after a buffer-local pattern', function()
757    exec [[
758      edit baz  " reuses buffer 1
759      edit bazinga
760      edit bar
761      edit boop
762      edit foo
763      edit floob
764
765      let g:events1 = []
766      autocmd BufEnter <buffer>,<buffer=1>,boop,bar let g:events1 += [expand('<afile>')]
767      let g:events2 = []
768      augroup flobby
769        autocmd BufEnter <buffer=2>,foo let g:events2 += [expand('<afile>')]
770        autocmd BufEnter foo,<buffer=3> let g:events2 += ['flobby ' .. expand('<afile>')]
771      augroup END
772    ]]
773    eq(
774      dedent([=[
775
776      --- Autocommands ---
777      BufEnter
778          <buffer=6>
779                    let g:events1 += [expand('<afile>')]
780          <buffer=1>
781                    let g:events1 += [expand('<afile>')]
782          boop      let g:events1 += [expand('<afile>')]
783          bar       let g:events1 += [expand('<afile>')]
784      flobby  BufEnter
785          <buffer=2>
786                    let g:events2 += [expand('<afile>')]
787          foo       let g:events2 += [expand('<afile>')]
788                    let g:events2 += ['flobby ' .. expand('<afile>')]
789          <buffer=3>
790                    let g:events2 += ['flobby ' .. expand('<afile>')]]=]),
791      fn.execute('autocmd BufEnter')
792    )
793    command('bufdo "')
794    eq({ 'baz', 'bar', 'boop', 'floob' }, eval('g:events1'))
795    eq({ 'bazinga', 'flobby bar', 'foo', 'flobby foo' }, eval('g:events2'))
796
797    -- Also make sure it doesn't repeat the group/event name or pattern for each printed event.
798    -- Do however repeat the pattern if the user specified it multiple times to be printed.
799    -- These conditions aim to make the output consistent with Vim.
800    eq(
801      dedent([=[
802
803      --- Autocommands ---
804      BufEnter
805          <buffer=1>
806                    let g:events1 += [expand('<afile>')]
807          bar       let g:events1 += [expand('<afile>')]
808          bar       let g:events1 += [expand('<afile>')]
809      flobby  BufEnter
810          foo       let g:events2 += [expand('<afile>')]
811                    let g:events2 += ['flobby ' .. expand('<afile>')]
812          foo       let g:events2 += [expand('<afile>')]
813                    let g:events2 += ['flobby ' .. expand('<afile>')]
814      BufEnter
815          <buffer=6>
816                    let g:events1 += [expand('<afile>')]
817          <buffer=6>
818                    let g:events1 += [expand('<afile>')]
819          <buffer=6>
820                    let g:events1 += [expand('<afile>')]]=]),
821      fn.execute('autocmd BufEnter <buffer=1>,bar,bar,foo,foo,<buffer>,<buffer=6>,<buffer>')
822    )
823  end)
824
825  it('parses empty comma-delimited patterns correctly', function()
826    exec [[
827      autocmd User , "
828      autocmd User ,, "
829      autocmd User ,,according,to,,all,known,,,laws,, "
830    ]]
831    api.nvim_create_autocmd('User', { pattern = ',,of,,,aviation,,,,there,,', command = '' })
832    api.nvim_create_autocmd('User', {
833      pattern = { ',,,,is,,no', ',,way,,,', 'a,,bee{,should be, able to,},fly' },
834      command = '',
835    })
836    eq(
837      {
838        'according',
839        'to',
840        'all',
841        'known',
842        'laws',
843        'of',
844        'aviation',
845        'there',
846        'is',
847        'no',
848        'way',
849        'a',
850        'bee{,should be, able to,}',
851        'fly',
852      },
853      exec_lua(function()
854        return vim.tbl_map(function(v)
855          return v.pattern
856        end, vim.api.nvim_get_autocmds({ event = 'User' }))
857      end)
858    )
859    eq(
860      dedent([[
861
862      --- Autocommands ---
863      User
864          there
865          is
866          a
867          fly]]),
868      fn.execute('autocmd User ,,,there,is,,a,fly,,')
869    )
870  end)
871
872  it('normalizes path sep (slashes) in env var `pattern` #39382', function()
873    local path = t.is_os('win') and [[C:\foo\bar]] or 'C:/foo/bar'
874    fn.setenv('FOOBAR', path)
875    exec [[
876      autocmd User ~,$FOOBAR "
877    ]]
878    local cmds = exec_lua(function()
879      return vim.api.nvim_get_autocmds({ event = 'User' })
880    end)
881    eq(vim.fs.normalize('~'), cmds[1].pattern)
882    eq(vim.fs.normalize(path), cmds[2].pattern)
883  end)
884
885  it('exists() consults &fileignorecase', function()
886    command([[autocmd User foo/bar echo]])
887    eq(0, fn.exists([[#User#foo/bar/]]))
888    eq(1, fn.exists([[#User#foo/bar]]))
889    -- Even on Windows, `/` should be used as the path sep
890    eq(0, fn.exists([[#User#foo\bar]]))
891
892    command([[set fileignorecase]])
893    eq(1, fn.exists([[#User#Foo/Bar]]))
894    command([[set nofileignorecase]])
895    eq(0, fn.exists([[#User#Foo/Bar]]))
896  end)
897end)