fix(treesitter): run FileType autocmds in the context of <abuf>

Problem: many FileType autocommands assume curbuf is the same as the target
buffer; this can cause &syntax to be restored for the wrong buffer in some cases
when TSHighlighter:destroy is called.

Solution: run nvim_exec_autocmds in the context of the target buffer via
nvim_buf_call.
This commit is contained in:
Sean Dewar
2025-08-19 16:14:10 +01:00
parent 701258921e
commit 3ec63cdab8
2 changed files with 16 additions and 4 deletions

View File

@@ -191,10 +191,13 @@ function TSHighlighter:destroy()
vim.b[self.bufnr].ts_highlight = nil
api.nvim_buf_clear_namespace(self.bufnr, ns, 0, -1)
if vim.g.syntax_on == 1 then
api.nvim_exec_autocmds(
'FileType',
{ group = 'syntaxset', buffer = self.bufnr, modeline = false }
)
-- FileType autocmds commonly assume curbuf is the target buffer, so nvim_buf_call.
api.nvim_buf_call(self.bufnr, function()
api.nvim_exec_autocmds(
'FileType',
{ group = 'syntaxset', buffer = self.bufnr, modeline = false }
)
end)
end
end
end

View File

@@ -5,6 +5,7 @@ local Screen = require('test.functional.ui.screen')
local clear = n.clear
local insert = n.insert
local exec_lua = n.exec_lua
local eval = n.eval
local feed = n.feed
local command = n.command
local api = n.api
@@ -197,6 +198,14 @@ describe('treesitter highlighting (C)', function()
end)
-- legacy syntax highlighting is used
screen:expect(hl_grid_legacy_c)
exec_lua(function()
vim.cmd 'new | wincmd p'
vim.treesitter.start()
vim.cmd 'bdelete!'
end)
-- Does not change &syntax of the other, unrelated buffer.
eq('', eval('&syntax'))
end)
it('is updated with edits', function()