Skip to content

Commit 617fee0

Browse files
authored
fix: Compatibility issue with Neovim <v0.11. (#407)
The `vim.treesitter.language.get_lang` function was added in Neovim v0.11[1], so we should not assume it to exist. The implementation is pretty short/simple so we just copy it into our codebase. [1]: https://neovim.io/doc/user/news-0.11.html
1 parent 5cfaad2 commit 617fee0

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

lua/nvim-surround/queries.lua

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,35 @@ local M = {}
33
-- Some compatibility shims over the builtin `vim.treesitter` functions
44
local get_query = vim.treesitter.get_query or vim.treesitter.query.get
55

6+
--- Returns the language name to be used when loading a parser for {filetype}.
7+
---
8+
--- If no language has been explicitly registered via |vim.treesitter.language.register()|,
9+
--- default to {filetype}. For composite filetypes like `html.glimmer`, only the main filetype is
10+
--- returned.
11+
---
12+
--- NOTE: This is a copy-pasted implementation from the Neovim v0.11 source code; it is to avoid nil-dereferencing
13+
--- issues on older versions of Neovim.
14+
--- @param filetype string
15+
--- @return string|nil
16+
local get_lang = function(filetype)
17+
if filetype == "" then
18+
return nil
19+
end
20+
21+
---@type table<string,string>
22+
local ft_to_lang = {
23+
help = "vimdoc",
24+
checkhealth = "vimdoc",
25+
}
26+
27+
if ft_to_lang[filetype] then
28+
return ft_to_lang[filetype]
29+
end
30+
-- for subfiletypes like html.glimmer use only "main" filetype
31+
filetype = vim.split(filetype, ".", { plain = true })[1]
32+
return ft_to_lang[filetype] or filetype
33+
end
34+
635
-- Retrieves the node that corresponds exactly to a given selection.
736
---@param selection selection The given selection.
837
---@return TSNode|nil @The corresponding node.
@@ -42,9 +71,13 @@ M.get_selection = function(capture, type)
4271
local treesitter = require("nvim-surround.treesitter")
4372

4473
local root = treesitter.get_root()
45-
local language = vim.treesitter.language.get_lang(vim.bo.filetype) or vim.bo.filetype
74+
local language = get_lang(vim.bo.filetype)
75+
if root == nil or language == nil then
76+
return nil
77+
end
78+
4679
local query = get_query(language, type)
47-
if root == nil or query == nil then
80+
if query == nil then
4881
return nil
4982
end
5083

0 commit comments

Comments
 (0)