robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
64.6 KiB2136 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each, pending = t.describe, t.it, t.before_each, t.pending
5local clear = n.clear
6local command = n.command
7local eq = t.eq
8local neq = t.neq
9local exec_lua = n.exec_lua
10local matches = t.matches
11local api = n.api
12local source = n.source
13local pcall_err = t.pcall_err
14
15before_each(clear)
16
17describe('autocmd api', function()
18  describe('nvim_create_autocmd', function()
19    it('validation', function()
20      eq(
21        "Conflict: 'callback' not allowed with 'command'",
22        pcall_err(api.nvim_create_autocmd, 'BufReadPost', {
23          pattern = '*.py,*.pyi',
24          command = "echo 'Should Have Errored",
25          callback = 'NotAllowed',
26        })
27      )
28      eq(
29        "Conflict: 'pattern' not allowed with 'buf'",
30        pcall_err(api.nvim_create_autocmd, 'FileType', {
31          command = 'let g:called = g:called + 1',
32          buf = 0,
33          pattern = '*.py',
34        })
35      )
36      -- Deprecated `buffer` key still triggers the same conflict.
37      eq(
38        "Conflict: 'pattern' not allowed with 'buf'",
39        pcall_err(api.nvim_create_autocmd, 'FileType', {
40          command = 'let g:called = g:called + 1',
41          buffer = 0,
42          pattern = '*.py',
43        })
44      )
45      -- Passing both `buf` and `buffer` is rejected.
46      eq(
47        "Conflict: 'buf' not allowed with 'buffer'",
48        pcall_err(api.nvim_create_autocmd, 'FileType', {
49          command = 'ls',
50          buf = 0,
51          buffer = 1,
52        })
53      )
54      eq(
55        "Required: 'event'",
56        pcall_err(api.nvim_create_autocmd, {}, {
57          command = 'ls',
58        })
59      )
60      matches(
61        "Invalid 'event': expected Array or String, got nil$",
62        pcall_err(exec_lua, function()
63          vim.api.nvim_create_autocmd(nil, {})
64        end)
65      )
66      eq("Required: 'command' or 'callback'", pcall_err(api.nvim_create_autocmd, 'FileType', {}))
67      eq(
68        "Invalid 'desc': expected String, got Integer",
69        pcall_err(api.nvim_create_autocmd, 'FileType', {
70          command = 'ls',
71          desc = 42,
72        })
73      )
74      eq(
75        "Invalid 'callback': expected Lua function or Vim function name, got Integer",
76        pcall_err(api.nvim_create_autocmd, 'FileType', {
77          callback = 0,
78        })
79      )
80      eq(
81        "Invalid 'event' item: expected String, got Array",
82        pcall_err(api.nvim_create_autocmd, { 'FileType', {} }, {})
83      )
84      eq(
85        "Invalid 'group': 0",
86        pcall_err(api.nvim_create_autocmd, 'FileType', {
87          group = 0,
88          command = 'ls',
89        })
90      )
91
92      eq("Invalid 'event': 'foo'", pcall_err(api.nvim_create_autocmd, 'foo', { command = '' }))
93      eq(
94        "Invalid 'event': 'VimEnter '",
95        pcall_err(api.nvim_create_autocmd, 'VimEnter ', { command = '' })
96      )
97      eq(
98        "Invalid 'event': 'VimEnter foo'",
99        pcall_err(api.nvim_create_autocmd, 'VimEnter foo', { command = '' })
100      )
101      eq(
102        "Invalid 'event': 'BufAdd,BufDelete'",
103        pcall_err(api.nvim_create_autocmd, 'BufAdd,BufDelete', { command = '' })
104      )
105
106      eq(
107        'No non-empty patterns specified',
108        pcall_err(api.nvim_create_autocmd, 'VimEnter', { pattern = '', command = '' })
109      )
110      eq(
111        'No non-empty patterns specified',
112        pcall_err(api.nvim_create_autocmd, 'VimEnter', { pattern = ',', command = '' })
113      )
114      eq(
115        'No non-empty patterns specified',
116        pcall_err(api.nvim_create_autocmd, 'VimEnter', { pattern = {}, command = '' })
117      )
118      eq(
119        'No non-empty patterns specified',
120        pcall_err(api.nvim_create_autocmd, 'VimEnter', { pattern = { '' }, command = '' })
121      )
122      eq(
123        'No non-empty patterns specified',
124        pcall_err(api.nvim_create_autocmd, 'VimEnter', { pattern = { ',,' }, command = '' })
125      )
126      -- OK when at least one non-empty pattern is given.
127      api.nvim_create_autocmd('VimEnter', { pattern = 'hi,,', command = '' })
128      api.nvim_create_autocmd('VimEnter', { pattern = { ',', 'bye' }, command = '' })
129      eq(
130        { 'hi', 'bye' },
131        exec_lua(function()
132          return vim
133            .iter(vim.api.nvim_get_autocmds({ event = 'VimEnter' }))
134            :map(function(ev)
135              return ev.pattern
136            end)
137            :totable()
138        end)
139      )
140    end)
141
142    it('doesnt leak when you use ++once', function()
143      eq(
144        1,
145        exec_lua(
146          [[
147        local count = 0
148
149        vim.api.nvim_create_autocmd("FileType", {
150          pattern = "*",
151          callback = function() count = count + 1 end,
152          once = true
153        })
154
155        vim.cmd "set filetype=txt"
156        vim.cmd "set filetype=python"
157
158        return count
159      ]],
160          {}
161        )
162      )
163    end)
164
165    it('allows passing buf by key', function()
166      for _, buf_key in ipairs({
167        'buf',
168        'buffer', -- deprecated name
169      }) do
170        api.nvim_set_var('called', 0)
171
172        api.nvim_create_autocmd('FileType', {
173          command = 'let g:called = g:called + 1',
174          [buf_key] = 0,
175        })
176
177        command 'set filetype=txt'
178        eq(1, api.nvim_get_var('called'))
179
180        -- switch to a new buffer
181        command 'new'
182        command 'set filetype=python'
183
184        eq(1, api.nvim_get_var('called'))
185      end
186    end)
187
188    it('does not allow passing invalid buffers', function()
189      local ok, msg = pcall(api.nvim_create_autocmd, 'FileType', {
190        command = 'let g:called = g:called + 1',
191        buf = -1,
192      })
193
194      eq(false, ok)
195      matches('Invalid buffer id', msg)
196    end)
197
198    it('errors on non-functions for cb', function()
199      eq(
200        false,
201        pcall(
202          exec_lua,
203          [[
204        vim.api.nvim_create_autocmd("BufReadPost", {
205          pattern = "*.py,*.pyi",
206          callback = 5,
207        })
208      ]]
209        )
210      )
211    end)
212
213    it('allow passing pattern and <buffer> in same pattern', function()
214      local ok = pcall(api.nvim_create_autocmd, 'BufReadPost', {
215        pattern = '*.py,<buffer>',
216        command = "echo 'Should Not Error'",
217      })
218
219      eq(true, ok)
220    end)
221
222    it('should handle multiple values as comma separated list', function()
223      api.nvim_create_autocmd('BufReadPost', {
224        pattern = '*.py,*.pyi',
225        command = "echo 'Should Not Have Errored'",
226      })
227
228      -- We should have one autocmd for *.py and one for *.pyi
229      eq(2, #api.nvim_get_autocmds { event = 'BufReadPost' })
230    end)
231
232    it('should handle multiple values as array', function()
233      api.nvim_create_autocmd('BufReadPost', {
234        pattern = { '*.py', '*.pyi' },
235        command = "echo 'Should Not Have Errored'",
236      })
237
238      -- We should have one autocmd for *.py and one for *.pyi
239      eq(2, #api.nvim_get_autocmds { event = 'BufReadPost' })
240    end)
241
242    describe('desc', function()
243      it('can add description to one autocmd', function()
244        local cmd = "echo 'Should Not Have Errored'"
245        local desc = 'Can show description'
246        api.nvim_create_autocmd('BufReadPost', {
247          pattern = '*.py',
248          command = cmd,
249          desc = desc,
250        })
251
252        eq(desc, api.nvim_get_autocmds { event = 'BufReadPost' }[1].desc)
253        eq(cmd, api.nvim_get_autocmds { event = 'BufReadPost' }[1].command)
254      end)
255
256      it('can add description to one autocmd that uses a callback', function()
257        local desc = 'Can show description'
258        api.nvim_set_var('desc', desc)
259
260        local result = exec_lua([[
261          local callback = function() print 'Should Not Have Errored' end
262          vim.api.nvim_create_autocmd("BufReadPost", {
263            pattern = "*.py",
264            callback = callback,
265            desc = vim.g.desc,
266          })
267          local aus = vim.api.nvim_get_autocmds({ event = 'BufReadPost' })
268          local first = aus[1]
269          return {
270            desc = first.desc,
271            cbtype = type(first.callback)
272          }
273        ]])
274
275        eq({ desc = desc, cbtype = 'function' }, result)
276      end)
277
278      it('will not add a description unless it was provided', function()
279        exec_lua([[
280          local callback = function() print 'Should Not Have Errored' end
281          vim.api.nvim_create_autocmd("BufReadPost", {
282            pattern = "*.py",
283            callback = callback,
284          })
285        ]])
286
287        eq(nil, api.nvim_get_autocmds({ event = 'BufReadPost' })[1].desc)
288      end)
289
290      it('can add description to multiple autocmd', function()
291        api.nvim_create_autocmd('BufReadPost', {
292          pattern = { '*.py', '*.pyi' },
293          command = "echo 'Should Not Have Errored'",
294          desc = 'Can show description',
295        })
296
297        local aus = api.nvim_get_autocmds { event = 'BufReadPost' }
298        eq(2, #aus)
299        eq('Can show description', aus[1].desc)
300        eq('Can show description', aus[2].desc)
301      end)
302    end)
303
304    pending('script and verbose settings', function()
305      it('marks API client', function()
306        api.nvim_create_autocmd('BufReadPost', {
307          pattern = '*.py',
308          command = "echo 'Should Not Have Errored'",
309          desc = 'Can show description',
310        })
311
312        local aus = api.nvim_get_autocmds { event = 'BufReadPost' }
313        eq(1, #aus, aus)
314      end)
315    end)
316
317    it('removes an autocommand if the callback returns true', function()
318      api.nvim_set_var('some_condition', false)
319
320      exec_lua [[
321      vim.api.nvim_create_autocmd("User", {
322        pattern = "Test",
323        desc = "A test autocommand",
324        callback = function()
325          return vim.g.some_condition
326        end,
327      })
328      ]]
329
330      api.nvim_exec_autocmds('User', { pattern = 'Test' })
331
332      local aus = api.nvim_get_autocmds({ event = 'User', pattern = 'Test' })
333      local first = aus[1]
334      eq(true, first.id > 0)
335
336      api.nvim_set_var('some_condition', true)
337      api.nvim_exec_autocmds('User', { pattern = 'Test' })
338      eq({}, api.nvim_get_autocmds({ event = 'User', pattern = 'Test' }))
339    end)
340
341    local function test_autocmd_args(event)
342      local function get_amatch(pat)
343        return event == 'User' and pat or vim.fs.normalize(n.fn.fnamemodify(pat, ':p'))
344      end
345
346      local group_id = api.nvim_create_augroup('TestGroup', {})
347      -- Having an existing autocmd calling expand("<afile>") shouldn't change args #18964
348      api.nvim_create_autocmd(event, {
349        group = 'TestGroup',
350        pattern = 'Te*',
351        command = 'call expand("<afile>")',
352      })
353
354      local autocmd_id = exec_lua(([[
355        return vim.api.nvim_create_autocmd(%q, {
356          group = "TestGroup",
357          pattern = "Te*",
358          callback = function(args)
359            vim.g.autocmd_args = args
360          end,
361        })
362      ]]):format(event))
363
364      local exec_pat = 'Test pattern'
365      local amatch = get_amatch(exec_pat)
366      api.nvim_exec_autocmds(event, { pattern = exec_pat })
367      eq({
368        id = autocmd_id,
369        group = group_id,
370        event = event,
371        match = amatch,
372        file = exec_pat,
373        win = api.nvim_get_current_win(),
374        buf = 1,
375      }, api.nvim_get_var('autocmd_args'))
376
377      -- Test without a group
378      autocmd_id = exec_lua(([[
379        return vim.api.nvim_create_autocmd(%q, {
380          pattern = "*",
381          callback = function(args)
382            vim.g.autocmd_args = args
383          end,
384        })
385      ]]):format(event))
386
387      exec_pat = 'some_pat'
388      amatch = get_amatch(exec_pat)
389      api.nvim_exec_autocmds(event, { pattern = exec_pat })
390      eq({
391        id = autocmd_id,
392        group = nil,
393        event = event,
394        match = amatch,
395        file = exec_pat,
396        win = api.nvim_get_current_win(),
397        buf = 1,
398      }, api.nvim_get_var('autocmd_args'))
399    end
400
401    describe('receives correct args table', function()
402      it('for event that takes non-file pattern', function()
403        test_autocmd_args('User')
404      end)
405
406      it('for event that takes file pattern', function()
407        test_autocmd_args('BufEnter')
408      end)
409    end)
410
411    describe('ev.win #25844', function()
412      it('is the current window for events that are not about a window', function()
413        local win = api.nvim_get_current_win()
414        exec_lua(function()
415          vim.api.nvim_create_autocmd('BufAdd', {
416            callback = function(ev)
417              vim.g.ev_win = ev.win
418            end,
419          })
420        end)
421        command('badd some_file')
422        eq(win, api.nvim_get_var('ev_win'))
423      end)
424
425      it('WinClosed reports the closed window', function()
426        command('split')
427        local closed_win = api.nvim_get_current_win()
428        exec_lua(function()
429          vim.api.nvim_create_autocmd('WinClosed', {
430            callback = function(ev)
431              vim.g.ev_win = ev.win
432              vim.g.ev_match = ev.match
433            end,
434          })
435        end)
436        command('quit')
437        eq(closed_win, api.nvim_get_var('ev_win'))
438        eq(tostring(closed_win), api.nvim_get_var('ev_match'))
439      end)
440
441      it('WinNew reports the new window, not the focused one', function()
442        local origin_win = api.nvim_get_current_win()
443        local buf = api.nvim_create_buf(false, true)
444        exec_lua(function()
445          vim.api.nvim_create_autocmd('WinNew', {
446            callback = function(ev)
447              vim.g.ev_win = ev.win
448            end,
449          })
450        end)
451        local new_win = api.nvim_open_win(buf, false, {
452          relative = 'editor',
453          row = 0,
454          col = 0,
455          width = 10,
456          height = 5,
457        })
458        eq(origin_win, api.nvim_get_current_win())
459        eq(new_win, api.nvim_get_var('ev_win'))
460      end)
461
462      it('WinResized reports the resized window, not curwin', function()
463        local top_win = api.nvim_get_current_win()
464        command('botright split')
465        local bot_win = api.nvim_get_current_win()
466        neq(top_win, bot_win)
467        command('redraw') -- flush the WinResized caused by the split itself
468        exec_lua(function()
469          vim.api.nvim_create_autocmd('WinResized', {
470            callback = function(ev)
471              vim.g.ev_win = ev.win
472              vim.g.ev_match = ev.match
473              vim.g.ev_curwin = vim.api.nvim_get_current_win()
474            end,
475          })
476        end)
477        command('resize 3')
478        command('redraw')
479        -- ev.win is the first window whose size changed, matching <amatch>.
480        eq(top_win, api.nvim_get_var('ev_win'))
481        eq(tostring(top_win), api.nvim_get_var('ev_match'))
482        eq(bot_win, api.nvim_get_var('ev_curwin'))
483      end)
484
485      it('WinScrolled reports the scrolled window, not curwin', function()
486        command('split')
487        local scrolled = api.nvim_get_current_win()
488        exec_lua(function()
489          local lines = {}
490          for i = 1, 30 do
491            lines[i] = 'line ' .. i
492          end
493          vim.api.nvim_buf_set_lines(0, 0, -1, false, lines)
494        end)
495        command('wincmd w')
496        neq(scrolled, api.nvim_get_current_win())
497        command('redraw')
498        exec_lua(function(scroll_win)
499          vim.api.nvim_create_autocmd('WinScrolled', {
500            callback = function(ev)
501              vim.g.ev_win = ev.win
502              vim.g.ev_match = ev.match
503              vim.g.ev_curwin = vim.api.nvim_get_current_win()
504            end,
505          })
506          vim.api.nvim_win_call(scroll_win, function()
507            vim.cmd('normal! G')
508          end)
509        end, scrolled)
510        command('redraw')
511        eq(scrolled, api.nvim_get_var('ev_win'))
512        eq(tostring(scrolled), api.nvim_get_var('ev_match'))
513        neq(scrolled, api.nvim_get_var('ev_curwin'))
514      end)
515
516      it('is restored after a nested autocmd', function()
517        command('edit a')
518        command('rightbelow vsplit b')
519        command('wincmd w')
520        local trigger_win = api.nvim_get_current_win()
521        exec_lua(function()
522          -- Fires BufLeave/WinLeave/WinEnter/BufEnter, each with its own ev.win.
523          vim.api.nvim_create_autocmd('ColorScheme', {
524            callback = function()
525              vim.cmd('wincmd w')
526            end,
527          })
528          vim.api.nvim_create_autocmd('ColorScheme', {
529            callback = function(ev)
530              vim.g.ev_win = ev.win
531            end,
532          })
533        end)
534        command('colorscheme blue')
535        eq(trigger_win, api.nvim_get_var('ev_win'))
536      end)
537    end)
538
539    it('can receive arbitrary data', function()
540      local function test(data)
541        eq(
542          data,
543          exec_lua(
544            [[
545          local input = ...
546          local output
547          vim.api.nvim_create_autocmd("User", {
548            pattern = "Test",
549            callback = function(ev)
550              output = ev.data
551            end,
552          })
553
554          vim.api.nvim_exec_autocmds("User", {
555            pattern = "Test",
556            data = input,
557          })
558
559          return output
560        ]],
561            data
562          )
563        )
564      end
565
566      test('Hello')
567      test(42)
568      test(true)
569      test({ 'list' })
570      test({ foo = 'bar' })
571    end)
572
573    it('function in arbitrary data is passed to all autocmds #28353', function()
574      eq(
575        1303,
576        exec_lua([[
577          local res = 1
578
579          local fun = function(m, x)
580            res = res * m + x
581          end
582
583          local group = vim.api.nvim_create_augroup('MyTest', { clear = false })
584
585          vim.api.nvim_create_autocmd('User', {
586            group = group,
587            callback = function(payload)
588              payload.data.fun(10, payload.data.x)
589            end,
590            pattern = 'MyEvent',
591          })
592          vim.api.nvim_create_autocmd('User', {
593            group = group,
594            callback = function(payload)
595              payload.data.fun(100, payload.data.x)
596            end,
597            pattern = 'MyEvent',
598          })
599
600          vim.api.nvim_exec_autocmds('User', {
601            group = group,
602            pattern = 'MyEvent',
603            data = { x = 3, fun = fun },
604          })
605
606          return res
607        ]])
608      )
609    end)
610  end)
611
612  describe('nvim_get_autocmds', function()
613    it('validation', function()
614      eq(
615        "Invalid 'group': 9997999",
616        pcall_err(api.nvim_get_autocmds, {
617          group = 9997999,
618        })
619      )
620      eq(
621        "Invalid 'group': 'bogus'",
622        pcall_err(api.nvim_get_autocmds, {
623          group = 'bogus',
624        })
625      )
626      eq(
627        "Invalid 'group': 0",
628        pcall_err(api.nvim_get_autocmds, {
629          group = 0,
630        })
631      )
632      eq(
633        "Invalid 'group': expected String or Integer, got Array",
634        pcall_err(api.nvim_get_autocmds, {
635          group = {},
636        })
637      )
638      eq(
639        "Invalid 'buffer': expected Integer or Array, got Boolean",
640        pcall_err(api.nvim_get_autocmds, {
641          buf = true,
642        })
643      )
644      -- Deprecated `buffer` key still validated.
645      eq(
646        "Invalid 'buffer': expected Integer or Array, got Boolean",
647        pcall_err(api.nvim_get_autocmds, {
648          buffer = true,
649        })
650      )
651      -- Passing both `buf` and `buffer` is rejected.
652      eq(
653        "Conflict: 'buf' not allowed with 'buffer'",
654        pcall_err(api.nvim_get_autocmds, {
655          buf = 0,
656          buffer = 1,
657        })
658      )
659      eq(
660        "Invalid 'event': expected String or Array",
661        pcall_err(api.nvim_get_autocmds, {
662          event = true,
663        })
664      )
665      eq(
666        "Invalid 'pattern': expected String or Array, got Boolean",
667        pcall_err(api.nvim_get_autocmds, {
668          pattern = true,
669        })
670      )
671    end)
672
673    describe('events', function()
674      it('returns one autocmd when there is only one for an event', function()
675        command [[au! InsertEnter]]
676        command [[au InsertEnter * :echo "1"]]
677
678        local aus = api.nvim_get_autocmds { event = 'InsertEnter' }
679        eq(1, #aus)
680      end)
681
682      it('returns two autocmds when there are two for an event', function()
683        command [[au! InsertEnter]]
684        command [[au InsertEnter * :echo "1"]]
685        command [[au InsertEnter * :echo "2"]]
686
687        local aus = api.nvim_get_autocmds { event = 'InsertEnter' }
688        eq(2, #aus)
689      end)
690
691      it('returns the same thing if you use string or list', function()
692        command [[au! InsertEnter]]
693        command [[au InsertEnter * :echo "1"]]
694        command [[au InsertEnter * :echo "2"]]
695
696        local string_aus = api.nvim_get_autocmds { event = 'InsertEnter' }
697        local array_aus = api.nvim_get_autocmds { event = { 'InsertEnter' } }
698        eq(string_aus, array_aus)
699      end)
700
701      it('returns two autocmds when there are two for an event', function()
702        command [[au! InsertEnter]]
703        command [[au! InsertLeave]]
704        command [[au InsertEnter * :echo "1"]]
705        command [[au InsertEnter * :echo "2"]]
706
707        local aus = api.nvim_get_autocmds { event = { 'InsertEnter', 'InsertLeave' } }
708        eq(2, #aus)
709      end)
710
711      it('returns different IDs for different autocmds', function()
712        command [[au! InsertEnter]]
713        command [[au! InsertLeave]]
714        command [[au InsertEnter * :echo "1"]]
715        source [[
716          call nvim_create_autocmd("InsertLeave", #{
717            \ command: ":echo 2",
718            \ })
719        ]]
720
721        local aus = api.nvim_get_autocmds { event = { 'InsertEnter', 'InsertLeave' } }
722        local first = aus[1]
723        eq(nil, first.id)
724
725        -- TODO: Maybe don't have this number, just assert it's not nil
726        local second = aus[2]
727        neq(nil, second.id)
728
729        api.nvim_del_autocmd(second.id)
730        local new_aus = api.nvim_get_autocmds { event = { 'InsertEnter', 'InsertLeave' } }
731        eq(1, #new_aus)
732        eq(first, new_aus[1])
733      end)
734
735      it('returns event name', function()
736        command [[au! InsertEnter]]
737        command [[au InsertEnter * :echo "1"]]
738
739        local aus = api.nvim_get_autocmds { event = 'InsertEnter' }
740        eq({
741          {
742            buflocal = false,
743            command = ':echo "1"',
744            event = 'InsertEnter',
745            once = false,
746            pattern = '*',
747          },
748        }, aus)
749      end)
750
751      it('works with buffer numbers', function()
752        command [[new]]
753        command [[au! InsertEnter]]
754        command [[au InsertEnter <buffer=1> :echo "1"]]
755        command [[au InsertEnter <buffer=2> :echo "2"]]
756
757        local aus = api.nvim_get_autocmds { event = 'InsertEnter', buf = 0 }
758        eq({
759          {
760            buf = 2,
761            buffer = 2, -- deprecated
762            buflocal = true,
763            command = ':echo "2"',
764            event = 'InsertEnter',
765            once = false,
766            pattern = '<buffer=2>',
767          },
768        }, aus)
769
770        aus = api.nvim_get_autocmds { event = 'InsertEnter', buf = 1 }
771        eq({
772          {
773            buf = 1,
774            buffer = 1, -- deprecated
775            buflocal = true,
776            command = ':echo "1"',
777            event = 'InsertEnter',
778            once = false,
779            pattern = '<buffer=1>',
780          },
781        }, aus)
782
783        aus = api.nvim_get_autocmds { event = 'InsertEnter', buf = { 1, 2 } }
784        eq({
785          {
786            buf = 1,
787            buffer = 1, -- deprecated
788            buflocal = true,
789            command = ':echo "1"',
790            event = 'InsertEnter',
791            once = false,
792            pattern = '<buffer=1>',
793          },
794          {
795            buf = 2,
796            buffer = 2, -- deprecated
797            buflocal = true,
798            command = ':echo "2"',
799            event = 'InsertEnter',
800            once = false,
801            pattern = '<buffer=2>',
802          },
803        }, aus)
804
805        -- Deprecated `buffer` key still works.
806        eq(
807          api.nvim_get_autocmds { event = 'InsertEnter', buf = { 1, 2 } },
808          api.nvim_get_autocmds { event = 'InsertEnter', buffer = { 1, 2 } }
809        )
810
811        eq(
812          "Invalid 'buffer': expected Integer or Array, got String",
813          pcall_err(api.nvim_get_autocmds, { event = 'InsertEnter', buf = 'foo' })
814        )
815        eq(
816          "Invalid 'buffer': expected Integer, got String",
817          pcall_err(api.nvim_get_autocmds, { event = 'InsertEnter', buf = { 'foo', 42 } })
818        )
819        eq(
820          'Invalid buffer id: 42',
821          pcall_err(api.nvim_get_autocmds, { event = 'InsertEnter', buf = { 42 } })
822        )
823
824        local bufs = {}
825        for _ = 1, 257 do
826          table.insert(bufs, api.nvim_create_buf(true, false))
827        end
828
829        eq(
830          'Too many buffers (maximum of 256)',
831          pcall_err(api.nvim_get_autocmds, { event = 'InsertEnter', buf = bufs })
832        )
833      end)
834
835      it('returns autocmds when group is specified by id', function()
836        local auid = api.nvim_create_augroup('nvim_test_augroup', { clear = true })
837        api.nvim_create_autocmd('FileType', { group = auid, command = 'echo "1"' })
838        api.nvim_create_autocmd('FileType', { group = auid, command = 'echo "2"' })
839
840        local aus = api.nvim_get_autocmds { group = auid }
841        eq(2, #aus)
842
843        local aus2 = api.nvim_get_autocmds { group = auid, event = 'InsertEnter' }
844        eq(0, #aus2)
845      end)
846
847      it('returns autocmds when group is specified by name', function()
848        local auname = 'nvim_test_augroup'
849        api.nvim_create_augroup(auname, { clear = true })
850        api.nvim_create_autocmd('FileType', { group = auname, command = 'echo "1"' })
851        api.nvim_create_autocmd('FileType', { group = auname, command = 'echo "2"' })
852
853        local aus = api.nvim_get_autocmds { group = auname }
854        eq(2, #aus)
855
856        local aus2 = api.nvim_get_autocmds { group = auname, event = 'InsertEnter' }
857        eq(0, #aus2)
858      end)
859
860      it('should respect nested', function()
861        local bufs = exec_lua [[
862          local count = 0
863          vim.api.nvim_create_autocmd("BufNew", {
864            once = false,
865            nested = true,
866            callback = function()
867              count = count + 1
868              if count > 5 then
869                return true
870              end
871
872              vim.cmd(string.format("new README_%s.md", count))
873            end
874          })
875
876          vim.cmd "new First.md"
877
878          return vim.api.nvim_list_bufs()
879        ]]
880
881        -- 1 for the first buffer
882        -- 2 for First.md
883        -- 3-7 for the 5 we make in the autocmd
884        eq({ 1, 2, 3, 4, 5, 6, 7 }, bufs)
885      end)
886
887      it('can retrieve a callback from an autocmd', function()
888        local content = 'I Am A Callback'
889        api.nvim_set_var('content', content)
890        exec_lua([[
891          local cb = function() return vim.g.content end
892          vim.api.nvim_create_autocmd("User", {
893            pattern = "TestTrigger",
894            desc = "A test autocommand with a callback",
895            callback = cb,
896          })
897        ]])
898
899        local result = exec_lua([[
900          local aus = vim.api.nvim_get_autocmds({ event = 'User', pattern = 'TestTrigger' })
901          local first = aus[1]
902          return {
903            cb = {
904              type = type(first.callback),
905              can_retrieve = first.callback() == vim.g.content
906            }
907          }
908        ]])
909        eq({ cb = { type = 'function', can_retrieve = true } }, result)
910
911        -- Also test with Vimscript
912        source([[
913          let s:aus = nvim_get_autocmds({'event': 'User', 'pattern': 'TestTrigger'})
914          let g:result = s:aus[0].callback()
915        ]])
916        eq(content, api.nvim_get_var('result'))
917      end)
918
919      it(
920        'will return an empty string as the command for an autocmd that uses a callback',
921        function()
922          local result = exec_lua([[
923          local callback = function() print 'I Am A Callback' end
924          vim.api.nvim_create_autocmd("BufWritePost", {
925            pattern = "*.py",
926            callback = callback,
927          })
928          local aus = vim.api.nvim_get_autocmds({ event = 'BufWritePost' })
929          local first = aus[1]
930          return {
931            command = first.command,
932            cbtype = type(first.callback)
933          }
934        ]])
935
936          eq({ command = '', cbtype = 'function' }, result)
937        end
938      )
939    end)
940
941    describe('groups', function()
942      before_each(function()
943        command [[au! InsertEnter]]
944
945        command [[au InsertEnter * :echo "No Group"]]
946
947        command [[augroup GroupOne]]
948        command [[  au InsertEnter * :echo "GroupOne:1"]]
949        command [[augroup END]]
950
951        command [[augroup GroupTwo]]
952        command [[  au InsertEnter * :echo "GroupTwo:2"]]
953        command [[  au InsertEnter * :echo "GroupTwo:3"]]
954        command [[augroup END]]
955      end)
956
957      it('returns all groups if no group is specified', function()
958        local aus = api.nvim_get_autocmds { event = 'InsertEnter' }
959        if #aus ~= 4 then
960          eq({}, aus)
961        end
962
963        eq(4, #aus)
964      end)
965
966      it('returns only the group specified', function()
967        local aus = api.nvim_get_autocmds {
968          event = 'InsertEnter',
969          group = 'GroupOne',
970        }
971
972        eq(1, #aus)
973        eq([[:echo "GroupOne:1"]], aus[1].command)
974        eq('GroupOne', aus[1].group_name)
975      end)
976
977      it('returns only the group specified, multiple values', function()
978        local aus = api.nvim_get_autocmds {
979          event = 'InsertEnter',
980          group = 'GroupTwo',
981        }
982
983        eq(2, #aus)
984        eq([[:echo "GroupTwo:2"]], aus[1].command)
985        eq('GroupTwo', aus[1].group_name)
986        eq([[:echo "GroupTwo:3"]], aus[2].command)
987        eq('GroupTwo', aus[2].group_name)
988      end)
989    end)
990
991    describe('groups: 2', function()
992      it('raises error for undefined augroup name', function()
993        local success, code = unpack(api.nvim_exec_lua(
994          [[
995          return {pcall(function()
996            vim.api.nvim_create_autocmd("FileType", {
997              pattern = "*",
998              group = "NotDefined",
999              command = "echo 'hello'",
1000            })
1001          end)}
1002        ]],
1003          {}
1004        ))
1005
1006        eq(false, success)
1007        matches("Invalid 'group': 'NotDefined'", code)
1008      end)
1009
1010      it('raises error for undefined augroup id', function()
1011        local success, code = unpack(api.nvim_exec_lua(
1012          [[
1013          return {pcall(function()
1014            -- Make sure the augroup is deleted
1015            vim.api.nvim_del_augroup_by_id(1)
1016
1017            vim.api.nvim_create_autocmd("FileType", {
1018              pattern = "*",
1019              group = 1,
1020              command = "echo 'hello'",
1021            })
1022          end)}
1023        ]],
1024          {}
1025        ))
1026
1027        eq(false, success)
1028        matches("Invalid 'group': 1", code)
1029      end)
1030
1031      it('raises error for invalid group type', function()
1032        local success, code = unpack(api.nvim_exec_lua(
1033          [[
1034          return {pcall(function()
1035            vim.api.nvim_create_autocmd("FileType", {
1036              pattern = "*",
1037              group = true,
1038              command = "echo 'hello'",
1039            })
1040          end)}
1041        ]],
1042          {}
1043        ))
1044
1045        eq(false, success)
1046        matches("Invalid 'group': expected String or Integer, got Boolean", code)
1047      end)
1048
1049      it('raises error for invalid pattern array', function()
1050        local success, code = unpack(api.nvim_exec_lua(
1051          [[
1052          return {pcall(function()
1053            vim.api.nvim_create_autocmd("FileType", {
1054              pattern = {{}},
1055              command = "echo 'hello'",
1056            })
1057          end)}
1058        ]],
1059          {}
1060        ))
1061
1062        eq(false, success)
1063        matches("Invalid 'pattern' item: expected String, got Array", code)
1064      end)
1065    end)
1066
1067    describe('patterns', function()
1068      before_each(function()
1069        command [[au! InsertEnter]]
1070
1071        command [[au InsertEnter *        :echo "No Group"]]
1072        command [[au InsertEnter *.one    :echo "GroupOne:1"]]
1073        command [[au InsertEnter *.two    :echo "GroupTwo:2"]]
1074        command [[au InsertEnter *.two    :echo "GroupTwo:3"]]
1075        command [[au InsertEnter <buffer> :echo "Buffer"]]
1076      end)
1077
1078      it('returns for literal match', function()
1079        local aus = api.nvim_get_autocmds {
1080          event = 'InsertEnter',
1081          pattern = '*',
1082        }
1083
1084        eq(1, #aus)
1085        eq([[:echo "No Group"]], aus[1].command)
1086      end)
1087
1088      it('returns for multiple matches', function()
1089        -- vim.api.nvim_get_autocmds
1090        local aus = api.nvim_get_autocmds {
1091          event = 'InsertEnter',
1092          pattern = { '*.one', '*.two' },
1093        }
1094
1095        eq(3, #aus)
1096        eq([[:echo "GroupOne:1"]], aus[1].command)
1097        eq([[:echo "GroupTwo:2"]], aus[2].command)
1098        eq([[:echo "GroupTwo:3"]], aus[3].command)
1099      end)
1100
1101      it('should work for buffer autocmds', function()
1102        local normalized_aus = api.nvim_get_autocmds {
1103          event = 'InsertEnter',
1104          pattern = '<buffer=1>',
1105        }
1106
1107        local raw_aus = api.nvim_get_autocmds {
1108          event = 'InsertEnter',
1109          pattern = '<buffer>',
1110        }
1111
1112        local zero_aus = api.nvim_get_autocmds {
1113          event = 'InsertEnter',
1114          pattern = '<buffer=0>',
1115        }
1116
1117        eq(normalized_aus, raw_aus)
1118        eq(normalized_aus, zero_aus)
1119        eq([[:echo "Buffer"]], normalized_aus[1].command)
1120      end)
1121    end)
1122
1123    describe('id', function()
1124      it('gets events by ID', function()
1125        local id = api.nvim_create_autocmd('BufEnter', {
1126          command = 'echo "hello"',
1127        })
1128        eq({
1129          {
1130            buflocal = false,
1131            command = 'echo "hello"',
1132            event = 'BufEnter',
1133            id = id,
1134            once = false,
1135            pattern = '*',
1136          },
1137        }, api.nvim_get_autocmds({ id = id }))
1138      end)
1139
1140      it('gets events by ID by other filters', function()
1141        local group_name = 'NVIM_GET_AUTOCMDS_ID'
1142        local group = api.nvim_create_augroup(group_name, { clear = true })
1143        local id = api.nvim_create_autocmd('BufEnter', {
1144          command = 'set number',
1145          group = group,
1146        })
1147        api.nvim_create_autocmd('WinEnter', {
1148          group = group,
1149          command = 'set cot&',
1150        })
1151        eq({
1152          {
1153            buflocal = false,
1154            command = 'set number',
1155            event = 'BufEnter',
1156            group = group,
1157            group_name = group_name,
1158            id = id,
1159            once = false,
1160            pattern = '*',
1161          },
1162        }, api.nvim_get_autocmds({ id = id, group = group }))
1163      end)
1164
1165      it('gets events by ID and a specific event', function()
1166        local id = api.nvim_create_autocmd('InsertEnter', { command = 'set number' })
1167        api.nvim_create_autocmd('InsertEnter', { command = 'set wrap' })
1168        eq({
1169          {
1170            buflocal = false,
1171            command = 'set number',
1172            event = 'InsertEnter',
1173            id = id,
1174            once = false,
1175            pattern = '*',
1176          },
1177        }, api.nvim_get_autocmds({ id = id, event = 'InsertEnter' }))
1178      end)
1179
1180      it('gets events by ID and a specific pattern', function()
1181        local id = api.nvim_create_autocmd('InsertEnter', {
1182          pattern = '*.c',
1183          command = 'set number',
1184        })
1185        api.nvim_create_autocmd('InsertEnter', {
1186          pattern = '*.c',
1187          command = 'set wrap',
1188        })
1189        eq({
1190          {
1191            buflocal = false,
1192            command = 'set number',
1193            event = 'InsertEnter',
1194            id = id,
1195            once = false,
1196            pattern = '*.c',
1197          },
1198        }, api.nvim_get_autocmds({ id = id, pattern = '*.c' }))
1199      end)
1200
1201      it('empty result when id does not found', function()
1202        eq({}, api.nvim_get_autocmds({ id = 255 }))
1203      end)
1204    end)
1205  end)
1206
1207  describe('nvim_exec_autocmds', function()
1208    it('validation', function()
1209      eq(
1210        "Invalid 'group': 9997999",
1211        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1212          group = 9997999,
1213        })
1214      )
1215      eq(
1216        "Invalid 'group': 'bogus'",
1217        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1218          group = 'bogus',
1219        })
1220      )
1221      eq(
1222        "Invalid 'group': expected String or Integer, got Array",
1223        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1224          group = {},
1225        })
1226      )
1227      eq(
1228        "Invalid 'group': 0",
1229        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1230          group = 0,
1231        })
1232      )
1233      eq(
1234        "Invalid 'buf': expected Buffer, got Array",
1235        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1236          buf = {},
1237        })
1238      )
1239      -- Deprecated `buffer` key still validated.
1240      eq(
1241        "Invalid 'buffer': expected Buffer, got Array",
1242        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1243          buffer = {},
1244        })
1245      )
1246      -- Passing both `buf` and `buffer` is rejected.
1247      eq(
1248        "Conflict: 'buf' not allowed with 'buffer'",
1249        pcall_err(api.nvim_exec_autocmds, 'FileType', {
1250          buf = 0,
1251          buffer = 1,
1252        })
1253      )
1254      eq(
1255        "Invalid 'event' item: expected String, got Array",
1256        pcall_err(api.nvim_exec_autocmds, { 'FileType', {} }, {})
1257      )
1258      matches(
1259        "Invalid 'event': expected Array or String, got nil$",
1260        pcall_err(exec_lua, function()
1261          vim.api.nvim_exec_autocmds(nil, {})
1262        end)
1263      )
1264    end)
1265
1266    it('can trigger builtin autocmds', function()
1267      api.nvim_set_var('autocmd_executed', false)
1268
1269      api.nvim_create_autocmd('BufReadPost', {
1270        pattern = '*',
1271        command = 'let g:autocmd_executed = v:true',
1272      })
1273
1274      eq(false, api.nvim_get_var('autocmd_executed'))
1275      api.nvim_exec_autocmds('BufReadPost', {})
1276      eq(true, api.nvim_get_var('autocmd_executed'))
1277    end)
1278
1279    it('can trigger multiple patterns', function()
1280      api.nvim_set_var('autocmd_executed', 0)
1281
1282      api.nvim_create_autocmd('BufReadPost', {
1283        pattern = '*',
1284        command = 'let g:autocmd_executed += 1',
1285      })
1286
1287      api.nvim_exec_autocmds('BufReadPost', { pattern = { '*.lua', '*.vim' } })
1288      eq(2, api.nvim_get_var('autocmd_executed'))
1289
1290      api.nvim_create_autocmd('BufReadPre', {
1291        pattern = { 'bar', 'foo' },
1292        command = 'let g:autocmd_executed += 10',
1293      })
1294
1295      api.nvim_exec_autocmds('BufReadPre', { pattern = { 'foo', 'bar', 'baz', 'frederick' } })
1296      eq(22, api.nvim_get_var('autocmd_executed'))
1297
1298      eq('', api.nvim_buf_get_name(0))
1299      api.nvim_exec_autocmds({ 'BufReadPre', 'BufReadPost' }, {})
1300      eq(23, api.nvim_get_var('autocmd_executed'))
1301
1302      api.nvim_buf_set_name(0, 'bar')
1303      api.nvim_exec_autocmds({ 'BufReadPre', 'BufReadPost' }, {})
1304      eq(34, api.nvim_get_var('autocmd_executed'))
1305
1306      -- Empty event array matches (and executes) nothing.
1307      api.nvim_exec_autocmds({}, {})
1308      eq(34, api.nvim_get_var('autocmd_executed'))
1309
1310      -- Non-nil, fully-empty patterns execute nothing.
1311      api.nvim_exec_autocmds('BufReadPre', { pattern = '' })
1312      api.nvim_exec_autocmds('BufReadPre', { pattern = ',,,,' })
1313      api.nvim_exec_autocmds('BufReadPre', { pattern = {} })
1314      api.nvim_exec_autocmds('BufReadPre', { pattern = { ',', '' } })
1315      eq(34, api.nvim_get_var('autocmd_executed'))
1316    end)
1317
1318    it('can pass the buffer', function()
1319      api.nvim_set_var('buffer_executed', -1)
1320      eq(-1, api.nvim_get_var('buffer_executed'))
1321
1322      api.nvim_create_autocmd('BufLeave', {
1323        pattern = '*',
1324        command = 'let g:buffer_executed = +expand("<abuf>")',
1325      })
1326
1327      -- Doesn't execute for other non-matching events
1328      api.nvim_exec_autocmds('CursorHold', { buf = 1 })
1329      eq(-1, api.nvim_get_var('buffer_executed'))
1330
1331      -- Deprecated `buffer` key still works.
1332      api.nvim_exec_autocmds('BufLeave', { buf = 1 })
1333      eq(1, api.nvim_get_var('buffer_executed'))
1334      api.nvim_set_var('buffer_executed', -1)
1335      api.nvim_exec_autocmds('BufLeave', { buffer = 1 })
1336      eq(1, api.nvim_get_var('buffer_executed'))
1337    end)
1338
1339    it('executes in target buf context for one visible window', function()
1340      local caller = api.nvim_get_current_buf()
1341      local caller_win = api.nvim_get_current_win()
1342      command('split')
1343      local target = api.nvim_create_buf(true, false)
1344      api.nvim_set_current_buf(target)
1345      local target_win = api.nvim_get_current_win()
1346      api.nvim_set_current_win(caller_win)
1347
1348      api.nvim_create_autocmd('CursorHold', {
1349        buffer = target,
1350        command = 'let [g:abuf, g:cur, g:win] = [str2nr(expand("<abuf>")), bufnr("%"), win_getid()]',
1351      })
1352      api.nvim_exec_autocmds('CursorHold', { buf = target })
1353
1354      eq(target, api.nvim_get_var('abuf'))
1355      eq(target, api.nvim_get_var('cur'))
1356      eq(target_win, api.nvim_get_var('win'))
1357      eq(caller, api.nvim_get_current_buf())
1358      eq(caller_win, api.nvim_get_current_win())
1359    end)
1360
1361    it('executes in target buf context for a hidden buffer', function()
1362      local caller = api.nvim_get_current_buf()
1363      local caller_win = api.nvim_get_current_win()
1364      local target = api.nvim_create_buf(true, false)
1365
1366      api.nvim_create_autocmd('User', {
1367        buffer = target,
1368        command = 'let [g:abuf, g:cur] = [str2nr(expand("<abuf>")), bufnr("%")]',
1369      })
1370      api.nvim_exec_autocmds('User', { buf = target })
1371
1372      eq(target, api.nvim_get_var('abuf'))
1373      eq(target, api.nvim_get_var('cur'))
1374      eq(caller, api.nvim_get_current_buf())
1375      eq(caller_win, api.nvim_get_current_win())
1376    end)
1377
1378    it('ignores modelines when executing for a passed buffer', function()
1379      local caller = api.nvim_get_current_buf()
1380      local target = api.nvim_create_buf(true, false)
1381      api.nvim_buf_set_lines(caller, 0, -1, false, { 'x', '/* vim: set textwidth=23: */' })
1382      api.nvim_buf_set_lines(target, 0, -1, false, { 'x', '/* vim: set textwidth=17: */' })
1383      api.nvim_set_option_value('textwidth', 0, { buf = caller })
1384      api.nvim_set_option_value('textwidth', 0, { buf = target })
1385
1386      api.nvim_create_autocmd('User', { buffer = target, command = '' })
1387      api.nvim_exec_autocmds('User', { buf = target, modeline = true })
1388
1389      eq(0, api.nvim_get_option_value('textwidth', { buf = caller }))
1390      eq(0, api.nvim_get_option_value('textwidth', { buf = target }))
1391    end)
1392
1393    it('restores caller if target buffer is wiped during execution', function()
1394      local caller = api.nvim_get_current_buf()
1395      local caller_win = api.nvim_get_current_win()
1396      local target = api.nvim_create_buf(true, false)
1397
1398      api.nvim_create_autocmd('User', {
1399        buffer = target,
1400        command = 'let g:seen = bufnr("%") | execute "bwipeout!" expand("<abuf>")',
1401      })
1402      api.nvim_exec_autocmds('User', { buf = target })
1403
1404      eq(target, api.nvim_get_var('seen'))
1405      eq(false, api.nvim_buf_is_valid(target))
1406      eq(caller, api.nvim_get_current_buf())
1407      eq(caller_win, api.nvim_get_current_win())
1408    end)
1409
1410    it('restores caller if callback changes current buffer', function()
1411      local caller = api.nvim_get_current_buf()
1412      local caller_win = api.nvim_get_current_win()
1413      local target = api.nvim_create_buf(true, false)
1414      local other = api.nvim_create_buf(true, false)
1415      command('split')
1416      api.nvim_set_current_buf(target)
1417      local target_win = api.nvim_get_current_win()
1418      api.nvim_set_current_win(caller_win)
1419
1420      api.nvim_create_autocmd('User', {
1421        buffer = target,
1422        command = string.format(
1423          'let g:seen = bufnr("%%") | buffer %d | let g:changed = bufnr("%%")',
1424          other
1425        ),
1426      })
1427      api.nvim_exec_autocmds('User', { buf = target })
1428
1429      eq(target, api.nvim_get_var('seen'))
1430      eq(other, api.nvim_get_var('changed'))
1431      eq(caller, api.nvim_get_current_buf())
1432      eq(caller_win, api.nvim_get_current_win())
1433      eq(target, api.nvim_win_get_buf(target_win))
1434    end)
1435
1436    it('restores nested target buffer contexts', function()
1437      local caller = api.nvim_get_current_buf()
1438      local caller_win = api.nvim_get_current_win()
1439      local target = api.nvim_create_buf(true, false)
1440      local other = api.nvim_create_buf(true, false)
1441
1442      api.nvim_create_autocmd('User', {
1443        buffer = other,
1444        command = 'let g:inner = bufnr("%")',
1445      })
1446      api.nvim_create_autocmd('User', {
1447        buffer = target,
1448        nested = true,
1449        command = string.format(
1450          'let g:outer = bufnr("%%")'
1451            .. ' | call nvim_exec_autocmds("User", #{buf: %d})'
1452            .. ' | let g:outer_after = bufnr("%%")',
1453          other
1454        ),
1455      })
1456      api.nvim_exec_autocmds('User', { buf = target })
1457
1458      eq(target, api.nvim_get_var('outer'))
1459      eq(other, api.nvim_get_var('inner'))
1460      eq(target, api.nvim_get_var('outer_after'))
1461      eq(caller, api.nvim_get_current_buf())
1462      eq(caller_win, api.nvim_get_current_win())
1463    end)
1464
1465    it('respects eventignorewin across multiple windows', function()
1466      local caller_win = api.nvim_get_current_win()
1467      local target = api.nvim_create_buf(false, false)
1468      command('split')
1469      local w_allows = api.nvim_get_current_win()
1470      api.nvim_win_set_buf(w_allows, target)
1471      command('vsplit')
1472      local w_ignores = api.nvim_get_current_win()
1473      api.nvim_win_set_buf(w_ignores, target)
1474      api.nvim_set_current_win(caller_win)
1475
1476      api.nvim_create_autocmd('CursorHold', {
1477        buffer = target,
1478        command = 'let g:fired += 1',
1479      })
1480      api.nvim_set_option_value('eventignorewin', '', { win = w_allows })
1481      api.nvim_set_option_value('eventignorewin', 'CursorHold', { win = w_ignores })
1482
1483      api.nvim_set_var('fired', 0)
1484      api.nvim_exec_autocmds('CursorHold', { buf = target })
1485      eq(1, api.nvim_get_var('fired'))
1486
1487      api.nvim_set_option_value('eventignorewin', 'CursorHold', { win = w_allows })
1488      api.nvim_set_var('fired', 0)
1489      api.nvim_exec_autocmds('CursorHold', { buf = target })
1490      eq(0, api.nvim_get_var('fired'))
1491      eq(caller_win, api.nvim_get_current_win())
1492    end)
1493
1494    it('can pass the filename, pattern match', function()
1495      api.nvim_set_var('filename_executed', 'none')
1496      eq('none', api.nvim_get_var('filename_executed'))
1497
1498      api.nvim_create_autocmd('BufEnter', {
1499        pattern = '*.py',
1500        command = 'let g:filename_executed = expand("<afile>")',
1501      })
1502
1503      -- Doesn't execute for other non-matching events
1504      api.nvim_exec_autocmds('CursorHold', { buf = 1 })
1505      eq('none', api.nvim_get_var('filename_executed'))
1506
1507      command('edit __init__.py')
1508      eq('__init__.py', api.nvim_get_var('filename_executed'))
1509    end)
1510
1511    it('cannot pass buf and fname', function()
1512      local ok = pcall(
1513        api.nvim_exec_autocmds,
1514        'BufReadPre',
1515        { pattern = 'literally_cannot_error.rs', buf = 1 }
1516      )
1517      eq(false, ok)
1518
1519      -- Same conflict via deprecated `buffer` key.
1520      ok = pcall(
1521        api.nvim_exec_autocmds,
1522        'BufReadPre',
1523        { pattern = 'literally_cannot_error.rs', buffer = 1 }
1524      )
1525      eq(false, ok)
1526    end)
1527
1528    it('can pass the filename, exact match', function()
1529      api.nvim_set_var('filename_executed', 'none')
1530      eq('none', api.nvim_get_var('filename_executed'))
1531
1532      command('edit other_file.txt')
1533      command('edit __init__.py')
1534      eq('none', api.nvim_get_var('filename_executed'))
1535
1536      api.nvim_create_autocmd('CursorHoldI', {
1537        pattern = '__init__.py',
1538        command = 'let g:filename_executed = expand("<afile>")',
1539      })
1540
1541      -- Doesn't execute for other non-matching events
1542      api.nvim_exec_autocmds('CursorHoldI', { buf = 1 })
1543      eq('none', api.nvim_get_var('filename_executed'))
1544
1545      api.nvim_exec_autocmds('CursorHoldI', { buf = api.nvim_get_current_buf() })
1546      eq('__init__.py', api.nvim_get_var('filename_executed'))
1547
1548      -- Reset filename
1549      api.nvim_set_var('filename_executed', 'none')
1550
1551      api.nvim_exec_autocmds('CursorHoldI', { pattern = '__init__.py' })
1552      eq('__init__.py', api.nvim_get_var('filename_executed'))
1553    end)
1554
1555    it('works with user autocmds', function()
1556      api.nvim_set_var('matched', 'none')
1557
1558      api.nvim_create_autocmd('User', {
1559        pattern = 'TestCommand',
1560        command = 'let g:matched = "matched"',
1561      })
1562
1563      api.nvim_exec_autocmds('User', { pattern = 'OtherCommand' })
1564      eq('none', api.nvim_get_var('matched'))
1565      api.nvim_exec_autocmds('User', { pattern = 'TestCommand' })
1566      eq('matched', api.nvim_get_var('matched'))
1567    end)
1568
1569    it('can pass group by id', function()
1570      api.nvim_set_var('group_executed', false)
1571
1572      local auid = api.nvim_create_augroup('nvim_test_augroup', { clear = true })
1573      api.nvim_create_autocmd('FileType', {
1574        group = auid,
1575        command = 'let g:group_executed = v:true',
1576      })
1577
1578      eq(false, api.nvim_get_var('group_executed'))
1579      api.nvim_exec_autocmds('FileType', { group = auid })
1580      eq(true, api.nvim_get_var('group_executed'))
1581    end)
1582
1583    it('can pass group by name', function()
1584      api.nvim_set_var('group_executed', false)
1585
1586      local auname = 'nvim_test_augroup'
1587      api.nvim_create_augroup(auname, { clear = true })
1588      api.nvim_create_autocmd('FileType', {
1589        group = auname,
1590        command = 'let g:group_executed = v:true',
1591      })
1592
1593      eq(false, api.nvim_get_var('group_executed'))
1594      api.nvim_exec_autocmds('FileType', { group = auname })
1595      eq(true, api.nvim_get_var('group_executed'))
1596    end)
1597
1598    it('redraw restores curwin temporarily without clearing aucmd_win', function()
1599      local win = api.nvim_get_current_win()
1600      local buf = api.nvim_create_buf(true, true)
1601      exec_lua([[
1602        vim.api.nvim_set_decoration_provider(vim.api.nvim_create_namespace(''), {
1603          on_start = function()
1604            _G.win = vim.api.nvim_get_current_win()
1605          end
1606        })
1607      ]])
1608      api.nvim_create_autocmd('User', { command = 'let w:x=1|redraw!|let g:x=w:x' })
1609      api.nvim_exec_autocmds('User', { buf = buf })
1610      eq(1000, exec_lua('return _G.win'))
1611      eq(1, n.eval('g:x'))
1612    end)
1613  end)
1614
1615  describe('nvim_create_augroup', function()
1616    before_each(function()
1617      api.nvim_set_var('executed', 0)
1618    end)
1619
1620    local make_counting_autocmd = function(opts)
1621      opts = opts or {}
1622
1623      local resulting = {
1624        pattern = '*',
1625        command = 'let g:executed = g:executed + 1',
1626      }
1627
1628      resulting.group = opts.group
1629      resulting.once = opts.once
1630
1631      api.nvim_create_autocmd('FileType', resulting)
1632    end
1633
1634    local set_ft = function(ft)
1635      ft = ft or 'txt'
1636      source(string.format('set filetype=%s', ft))
1637    end
1638
1639    local get_executed_count = function()
1640      return api.nvim_get_var('executed')
1641    end
1642
1643    it('can be added in a group', function()
1644      local augroup = 'TestGroup'
1645      api.nvim_create_augroup(augroup, { clear = true })
1646      make_counting_autocmd { group = augroup }
1647
1648      set_ft('txt')
1649      set_ft('python')
1650
1651      eq(2, get_executed_count())
1652    end)
1653
1654    it('works getting called multiple times', function()
1655      make_counting_autocmd()
1656      set_ft()
1657      set_ft()
1658      set_ft()
1659
1660      eq(3, get_executed_count())
1661    end)
1662
1663    it('handles ++once', function()
1664      make_counting_autocmd { once = true }
1665      set_ft('txt')
1666      set_ft('help')
1667      set_ft('txt')
1668      set_ft('help')
1669
1670      eq(1, get_executed_count())
1671    end)
1672
1673    it('errors on unexpected keys', function()
1674      local success, code = pcall(api.nvim_create_autocmd, 'FileType', {
1675        pattern = '*',
1676        not_a_valid_key = 'NotDefined',
1677      })
1678
1679      eq(false, success)
1680      matches('not_a_valid_key', code)
1681    end)
1682
1683    it('can execute simple callback', function()
1684      exec_lua(
1685        [[
1686        vim.g.executed = false
1687
1688        vim.api.nvim_create_autocmd("FileType", {
1689          pattern = "*",
1690          callback = function() vim.g.executed = true end,
1691        })
1692      ]],
1693        {}
1694      )
1695
1696      eq(
1697        true,
1698        exec_lua(
1699          [[
1700        vim.cmd "set filetype=txt"
1701        return vim.g.executed
1702      ]],
1703          {}
1704        )
1705      )
1706    end)
1707
1708    it('calls multiple lua callbacks for the same autocmd execution', function()
1709      eq(
1710        4,
1711        exec_lua(
1712          [[
1713        local count = 0
1714        local counter = function()
1715          count = count + 1
1716        end
1717
1718        vim.api.nvim_create_autocmd("FileType", {
1719          pattern = "*",
1720          callback = counter,
1721        })
1722
1723        vim.api.nvim_create_autocmd("FileType", {
1724          pattern = "*",
1725          callback = counter,
1726        })
1727
1728        vim.cmd "set filetype=txt"
1729        vim.cmd "set filetype=txt"
1730
1731        return count
1732      ]],
1733          {}
1734        )
1735      )
1736    end)
1737
1738    it('properly releases functions with ++once', function()
1739      exec_lua([[
1740        WeakTable = setmetatable({}, { __mode = "k" })
1741
1742        OnceCount = 0
1743
1744        MyVal = {}
1745        WeakTable[MyVal] = true
1746
1747        vim.api.nvim_create_autocmd("FileType", {
1748          pattern = "*",
1749          callback = function()
1750            OnceCount = OnceCount + 1
1751            MyVal = {}
1752          end,
1753          once = true
1754        })
1755      ]])
1756
1757      command [[set filetype=txt]]
1758      eq(1, exec_lua([[return OnceCount]], {}))
1759
1760      exec_lua([[collectgarbage()]], {})
1761
1762      command [[set filetype=txt]]
1763      eq(1, exec_lua([[return OnceCount]], {}))
1764
1765      eq(
1766        0,
1767        exec_lua([[
1768        local count = 0
1769        for _ in pairs(WeakTable) do
1770          count = count + 1
1771        end
1772
1773        return count
1774      ]]),
1775        'Should have no keys remaining'
1776      )
1777    end)
1778
1779    it('groups can be cleared', function()
1780      local augroup = 'TestGroup'
1781      api.nvim_create_augroup(augroup, { clear = true })
1782      api.nvim_create_autocmd('FileType', {
1783        group = augroup,
1784        command = 'let g:executed = g:executed + 1',
1785      })
1786
1787      set_ft('txt')
1788      set_ft('txt')
1789      eq(2, get_executed_count(), 'should only count twice')
1790
1791      api.nvim_create_augroup(augroup, { clear = true })
1792      eq({}, api.nvim_get_autocmds { group = augroup })
1793
1794      set_ft('txt')
1795      set_ft('txt')
1796      eq(2, get_executed_count(), 'No additional counts')
1797    end)
1798
1799    it('can delete non-existent groups with pcall', function()
1800      eq(false, exec_lua [[return pcall(vim.api.nvim_del_augroup_by_name, 'noexist')]])
1801      eq('Vim:E367: No such group: "noexist"', pcall_err(api.nvim_del_augroup_by_name, 'noexist'))
1802
1803      eq(false, exec_lua [[return pcall(vim.api.nvim_del_augroup_by_id, -12342)]])
1804      eq('Vim:E367: No such group id: -12312', pcall_err(api.nvim_del_augroup_by_id, -12312))
1805
1806      eq(false, exec_lua [[return pcall(vim.api.nvim_del_augroup_by_id, 0)]])
1807      eq('Vim:E367: No such group id: 0', pcall_err(api.nvim_del_augroup_by_id, 0))
1808
1809      eq(false, exec_lua [[return pcall(vim.api.nvim_del_augroup_by_id, 12342)]])
1810      eq('Vim:E367: No such group id: 12312', pcall_err(api.nvim_del_augroup_by_id, 12312))
1811    end)
1812
1813    it('groups work with once', function()
1814      local augroup = 'TestGroup'
1815
1816      api.nvim_create_augroup(augroup, { clear = true })
1817      make_counting_autocmd { group = augroup, once = true }
1818
1819      set_ft('txt')
1820      set_ft('python')
1821
1822      eq(1, get_executed_count())
1823    end)
1824
1825    it('autocmds can be registered multiple times.', function()
1826      local augroup = 'TestGroup'
1827
1828      api.nvim_create_augroup(augroup, { clear = true })
1829      make_counting_autocmd { group = augroup, once = false }
1830      make_counting_autocmd { group = augroup, once = false }
1831      make_counting_autocmd { group = augroup, once = false }
1832
1833      set_ft('txt')
1834      set_ft('python')
1835
1836      eq(3 * 2, get_executed_count())
1837    end)
1838
1839    it('can be deleted', function()
1840      local augroup = 'WillBeDeleted'
1841
1842      api.nvim_create_augroup(augroup, { clear = true })
1843      api.nvim_create_autocmd({ 'FileType' }, {
1844        pattern = '*',
1845        command = "echo 'does not matter'",
1846      })
1847
1848      -- Clears the augroup from before, which erases the autocmd
1849      api.nvim_create_augroup(augroup, { clear = true })
1850
1851      local result = #api.nvim_get_autocmds { group = augroup }
1852
1853      eq(0, result)
1854    end)
1855
1856    it('can be used for buffer local autocmds', function()
1857      local augroup = 'WillBeDeleted'
1858
1859      api.nvim_set_var('value_set', false)
1860
1861      api.nvim_create_augroup(augroup, { clear = true })
1862      api.nvim_create_autocmd('FileType', {
1863        pattern = '<buffer>',
1864        command = 'let g:value_set = v:true',
1865      })
1866
1867      command 'new'
1868      command 'set filetype=python'
1869
1870      eq(false, api.nvim_get_var('value_set'))
1871    end)
1872
1873    it('can accept vimscript functions', function()
1874      source [[
1875        let g:vimscript_executed = 0
1876
1877        function! MyVimscriptFunction() abort
1878          let g:vimscript_executed = g:vimscript_executed + 1
1879        endfunction
1880
1881        call nvim_create_autocmd("FileType", #{
1882          \ pattern: ["python", "javascript"],
1883          \ callback: "MyVimscriptFunction",
1884          \ })
1885
1886        set filetype=txt
1887        set filetype=python
1888        set filetype=txt
1889        set filetype=javascript
1890        set filetype=txt
1891      ]]
1892
1893      eq(2, api.nvim_get_var('vimscript_executed'))
1894    end)
1895  end)
1896
1897  describe('augroup!', function()
1898    it('legacy: should clear and not return any autocmds for delete groups', function()
1899      command('augroup TEMP_A')
1900      command('    autocmd! BufReadPost *.py :echo "Hello"')
1901      command('augroup END')
1902
1903      command('augroup! TEMP_A')
1904
1905      eq(false, pcall(api.nvim_get_autocmds, { group = 'TEMP_A' }))
1906
1907      -- For some reason, augroup! doesn't clear the autocmds themselves, which is just wild
1908      -- but we managed to keep this behavior.
1909      eq(1, #api.nvim_get_autocmds { event = 'BufReadPost' })
1910    end)
1911
1912    it('legacy: remove augroups that have no autocmds', function()
1913      command('augroup TEMP_AB')
1914      command('augroup END')
1915
1916      command('augroup! TEMP_AB')
1917
1918      eq(false, pcall(api.nvim_get_autocmds, { group = 'TEMP_AB' }))
1919      eq(0, #api.nvim_get_autocmds { event = 'BufReadPost' })
1920    end)
1921
1922    it('legacy: multiple remove and add augroup', function()
1923      command('augroup TEMP_ABC')
1924      command('    au!')
1925      command('    autocmd BufReadPost *.py echo "Hello"')
1926      command('augroup END')
1927
1928      command('augroup! TEMP_ABC')
1929
1930      -- Should still have one autocmd :'(
1931      local aus = api.nvim_get_autocmds { event = 'BufReadPost' }
1932      eq(1, #aus, aus)
1933
1934      command('augroup TEMP_ABC')
1935      command('    au!')
1936      command('    autocmd BufReadPost *.py echo "Hello"')
1937      command('augroup END')
1938
1939      -- Should now have two autocmds :'(
1940      aus = api.nvim_get_autocmds { event = 'BufReadPost' }
1941      eq(2, #aus, aus)
1942
1943      command('augroup! TEMP_ABC')
1944
1945      eq(false, pcall(api.nvim_get_autocmds, { group = 'TEMP_ABC' }))
1946      eq(2, #api.nvim_get_autocmds { event = 'BufReadPost' })
1947    end)
1948
1949    it('api: should clear and not return any autocmds for delete groups by id', function()
1950      command('augroup TEMP_ABCD')
1951      command('autocmd! BufReadPost *.py :echo "Hello"')
1952      command('augroup END')
1953
1954      local augroup_id = api.nvim_create_augroup('TEMP_ABCD', { clear = false })
1955      api.nvim_del_augroup_by_id(augroup_id)
1956
1957      -- For good reason, we kill all the autocmds from del_augroup,
1958      -- so now this works as expected
1959      eq(false, pcall(api.nvim_get_autocmds, { group = 'TEMP_ABCD' }))
1960      eq(0, #api.nvim_get_autocmds { event = 'BufReadPost' })
1961
1962      -- deleting an already deleted group gives NICE error message:
1963      -- exact value of augroup_id here depends on defaults.lua and bullshit, splice it in!
1964      eq(
1965        'Vim:E367: No such group id: ' .. augroup_id .. ' "--Deleted--"',
1966        pcall_err(api.nvim_del_augroup_by_id, augroup_id)
1967      )
1968    end)
1969
1970    it('api: should clear and not return any autocmds for delete groups by name', function()
1971      command('augroup TEMP_ABCDE')
1972      command('autocmd! BufReadPost *.py :echo "Hello"')
1973      command('augroup END')
1974
1975      api.nvim_del_augroup_by_name('TEMP_ABCDE')
1976
1977      -- For good reason, we kill all the autocmds from del_augroup,
1978      -- so now this works as expected
1979      eq(false, pcall(api.nvim_get_autocmds, { group = 'TEMP_ABCDE' }))
1980      eq(0, #api.nvim_get_autocmds { event = 'BufReadPost' })
1981    end)
1982  end)
1983
1984  describe('nvim_clear_autocmds', function()
1985    it('validation', function()
1986      eq(
1987        "Conflict: 'pattern' not allowed with 'buf'",
1988        pcall_err(api.nvim_clear_autocmds, {
1989          pattern = '*',
1990          buf = 42,
1991        })
1992      )
1993      -- Deprecated `buffer` key still triggers the same conflict.
1994      eq(
1995        "Conflict: 'pattern' not allowed with 'buf'",
1996        pcall_err(api.nvim_clear_autocmds, {
1997          pattern = '*',
1998          buffer = 42,
1999        })
2000      )
2001      -- Passing both `buf` and `buffer` is rejected.
2002      eq(
2003        "Conflict: 'buf' not allowed with 'buffer'",
2004        pcall_err(api.nvim_clear_autocmds, {
2005          buf = 0,
2006          buffer = 1,
2007        })
2008      )
2009      eq(
2010        "Invalid 'event' item: expected String, got Array",
2011        pcall_err(api.nvim_clear_autocmds, {
2012          event = { 'FileType', {} },
2013        })
2014      )
2015      eq(
2016        "Invalid 'event': expected Array or String, got Integer",
2017        pcall_err(api.nvim_clear_autocmds, { event = 1337 })
2018      )
2019      matches(
2020        "Invalid 'event': expected Array or String, got Function$",
2021        pcall_err(exec_lua, function()
2022          vim.api.nvim_clear_autocmds({ event = function() end })
2023        end)
2024      )
2025      eq("Invalid 'group': 0", pcall_err(api.nvim_clear_autocmds, { group = 0 }))
2026    end)
2027
2028    it('should clear based on event + pattern', function()
2029      command('autocmd InsertEnter *.py  :echo "Python can be cool sometimes"')
2030      command('autocmd InsertEnter *.txt :echo "Text Files Are Cool"')
2031
2032      local search = { event = 'InsertEnter', pattern = '*.txt' }
2033      local before_delete = api.nvim_get_autocmds(search)
2034      eq(1, #before_delete)
2035
2036      local before_delete_all = api.nvim_get_autocmds { event = search.event }
2037      eq(2, #before_delete_all)
2038
2039      api.nvim_clear_autocmds(search)
2040      local after_delete = api.nvim_get_autocmds(search)
2041      eq(0, #after_delete)
2042
2043      local after_delete_all = api.nvim_get_autocmds { event = search.event }
2044      eq(1, #after_delete_all)
2045    end)
2046
2047    it('should clear based on event', function()
2048      command('autocmd InsertEnter *.py  :echo "Python can be cool sometimes"')
2049      command('autocmd InsertEnter *.txt :echo "Text Files Are Cool"')
2050
2051      local search = { event = 'InsertEnter' }
2052      local before_delete = api.nvim_get_autocmds(search)
2053      eq(2, #before_delete)
2054
2055      -- Like nvim_exec_autocmds(), empty event array matches (and clears) nothing.
2056      api.nvim_clear_autocmds({ event = {} })
2057      eq(2, #api.nvim_get_autocmds(search))
2058
2059      api.nvim_clear_autocmds(search)
2060      local after_delete = api.nvim_get_autocmds(search)
2061      eq(0, #after_delete)
2062    end)
2063
2064    it('should clear based on pattern', function()
2065      command('autocmd InsertEnter *.TestPat1 :echo "Enter 1"')
2066      command('autocmd InsertLeave *.TestPat1 :echo "Leave 1"')
2067      command('autocmd InsertEnter *.TestPat2 :echo "Enter 2"')
2068      command('autocmd InsertLeave *.TestPat2 :echo "Leave 2"')
2069
2070      local search = { pattern = '*.TestPat1' }
2071      local before_delete = api.nvim_get_autocmds(search)
2072      eq(2, #before_delete)
2073      local before_delete_events =
2074        api.nvim_get_autocmds { event = { 'InsertEnter', 'InsertLeave' } }
2075      eq(4, #before_delete_events)
2076
2077      api.nvim_clear_autocmds(search)
2078      local after_delete = api.nvim_get_autocmds(search)
2079      eq(0, #after_delete)
2080
2081      local after_delete_events = api.nvim_get_autocmds { event = { 'InsertEnter', 'InsertLeave' } }
2082      eq(2, #after_delete_events)
2083
2084      -- Non-nil, fully-empty patterns clear nothing.
2085      local event_count = #api.nvim_get_autocmds {}
2086      api.nvim_clear_autocmds({ pattern = '' })
2087      api.nvim_clear_autocmds({ pattern = ',,,' })
2088      api.nvim_clear_autocmds({ pattern = {} })
2089      api.nvim_clear_autocmds({ pattern = { '', '' } })
2090      api.nvim_clear_autocmds({ pattern = { ',', ',,' } })
2091      eq(event_count, #api.nvim_get_autocmds {})
2092    end)
2093
2094    it('should allow clearing by buf', function()
2095      for _, buf_key in ipairs({
2096        'buf',
2097        'buffer', -- deprecated name
2098      }) do
2099        command('autocmd! InsertEnter')
2100        command('autocmd InsertEnter <buffer> :echo "Enter Buffer"')
2101        command('autocmd InsertEnter *.TestPat1 :echo "Enter Pattern"')
2102
2103        local search = { event = 'InsertEnter' }
2104        local before_delete = api.nvim_get_autocmds(search)
2105        eq(2, #before_delete)
2106
2107        api.nvim_clear_autocmds { [buf_key] = 0 }
2108        local after_delete = api.nvim_get_autocmds(search)
2109        eq(1, #after_delete)
2110        eq('*.TestPat1', after_delete[1].pattern)
2111      end
2112    end)
2113
2114    it('should allow clearing by buf and group', function()
2115      command('augroup TestNvimClearAutocmds')
2116      command('  au!')
2117      command('  autocmd InsertEnter <buffer> :echo "Enter Buffer"')
2118      command('  autocmd InsertEnter *.TestPat1 :echo "Enter Pattern"')
2119      command('augroup END')
2120
2121      local search = { event = 'InsertEnter', group = 'TestNvimClearAutocmds' }
2122      local before_delete = api.nvim_get_autocmds(search)
2123      eq(2, #before_delete)
2124
2125      -- Doesn't clear without passing group.
2126      api.nvim_clear_autocmds { buf = 0 }
2127      local without_group = api.nvim_get_autocmds(search)
2128      eq(2, #without_group)
2129
2130      -- Doesn't clear with passing group.
2131      api.nvim_clear_autocmds { buf = 0, group = search.group }
2132      local with_group = api.nvim_get_autocmds(search)
2133      eq(1, #with_group)
2134    end)
2135  end)
2136end)