Skip to content

Commit 0aaea32

Browse files
authored
feat: support nested (injected) code blocks (#138)
This PR fixes commenting in nested (injected) code blocks. Like in markdown you can have multiple code blocks and those code blocks can also have injected languages for example `markdown -> vue -> css/js` ### Before ```vue <style> body { <!-- color: red; --> } </style> <script> while (true) { <!-- console.log("neovim is awesome!"); --> } </script> ``` ### After ```vue <style> body { /* color: red; */ } </style> <script> while (true) { // console.log("neovim is awesome!"); } </script> ``` --- Closes #137
1 parent 546c487 commit 0aaea32

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

lua/Comment/ft.lua

+19-10
Original file line numberDiff line numberDiff line change
@@ -117,32 +117,41 @@ function ft.lang(lang)
117117
return L[lang]
118118
end
119119

120+
---Get the commenstring by walking the tree recursively
121+
---NOTE: This ignores `comment` parser as this is useless
122+
---@param tree userdata Tree to be walked
123+
---@param range number[] Range to check for
124+
---@return userdata
125+
function ft.contains(tree, range)
126+
for lang, child in pairs(tree:children()) do
127+
if lang ~= 'comment' and child:contains(range) then
128+
return ft.contains(child, range)
129+
end
130+
end
131+
132+
return tree
133+
end
134+
120135
---Calculate commentstring w/ the power of treesitter
121136
---@param ctx Ctx
122137
---@return string
123138
function ft.calculate(ctx)
124139
local buf = A.nvim_get_current_buf()
125-
local ok, langtree = pcall(vim.treesitter.get_parser, buf)
140+
local ok, parser = pcall(vim.treesitter.get_parser, buf)
126141
local default = ft.get(A.nvim_buf_get_option(buf, 'filetype'), ctx.ctype)
127142

128143
if not ok then
129144
return default
130145
end
131146

132-
local range = {
147+
local lang = ft.contains(parser, {
133148
ctx.range.srow - 1,
134149
ctx.range.scol,
135150
ctx.range.erow - 1,
136151
ctx.range.ecol,
137-
}
138-
139-
for lang, tree in pairs(langtree:children()) do
140-
if tree:contains(range) then
141-
return ft.get(lang, ctx.ctype) or default
142-
end
143-
end
152+
}):lang()
144153

145-
return default
154+
return ft.get(lang, ctx.ctype) or default
146155
end
147156

148157
return setmetatable(ft, {

0 commit comments

Comments
 (0)