Skip to content

Commit f7e2ad7

Browse files
[Backport release-0.7] fix(treesitter): create new parser if language is not the same as cached parser (neovim#18220)
* fix(treesitter): create new parser if language is not the same as cached parser Fixes neovim#18148 (cherry picked from commit 8e35894) * test: create new parser in vim.treesitter.get_parser() when filetype changes (cherry picked from commit 30e7b3f) Co-authored-by: Chinmay Dalal <[email protected]>
1 parent 7f8faac commit f7e2ad7

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

runtime/lua/vim/treesitter.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ function M.get_parser(bufnr, lang, opts)
9090
lang = a.nvim_buf_get_option(bufnr, "filetype")
9191
end
9292

93-
if parsers[bufnr] == nil then
93+
if parsers[bufnr] == nil or parsers[bufnr]:lang() ~= lang then
9494
parsers[bufnr] = M._create_parser(bufnr, lang, opts)
9595
end
9696

test/functional/treesitter/language_spec.lua

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ local helpers = require('test.functional.helpers')(after_each)
22

33
local clear = helpers.clear
44
local eq = helpers.eq
5+
local command = helpers.command
56
local exec_lua = helpers.exec_lua
67
local pcall_err = helpers.pcall_err
78
local matches = helpers.matches
@@ -67,5 +68,15 @@ describe('treesitter API', function()
6768
end
6869
eq({true,true}, {has_named,has_anonymous})
6970
end)
71+
72+
it('checks if vim.treesitter.get_parser tries to create a new parser on filetype change', function ()
73+
command("set filetype=c")
74+
-- Should not throw an error when filetype is c
75+
eq('c', exec_lua("return vim.treesitter.get_parser(0):lang()"))
76+
command("set filetype=borklang")
77+
-- Should throw an error when filetype changes to borklang
78+
eq("Error executing lua: .../language.lua:0: no parser for 'borklang' language, see :help treesitter-parsers",
79+
pcall_err(exec_lua, "new_parser = vim.treesitter.get_parser(0)"))
80+
end)
7081
end)
7182

0 commit comments

Comments
 (0)