From 5306fd8a81fb0a91e5c3699ba21e6bc94bf86586 Mon Sep 17 00:00:00 2001 From: Y <24789671+yangfree@users.noreply.github.com> Date: Mon, 25 May 2026 22:48:30 +0800 Subject: [PATCH] fix: add nil safety checks in ft.contains and ft.calculate - Add nil guard in ft.contains() to prevent 'attempt to index nil' error when treesitter tree is not yet parsed - Add nil check for lang in ft.calculate() to fall back to filetype-based commentstring when treesitter parsing fails - Fix error handler in utils.lua to use tostring(err) instead of err.msg, since Lua errors are strings not objects --- lua/Comment/ft.lua | 22 ++++++++++++++++++---- lua/Comment/utils.lua | 2 +- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lua/Comment/ft.lua b/lua/Comment/ft.lua index 34afffaf..21706452 100644 --- a/lua/Comment/ft.lua +++ b/lua/Comment/ft.lua @@ -277,7 +277,14 @@ end ---print('Lang:', tree:lang()) ---@usage ]] function ft.contains(tree, range) - for lang, child in pairs(tree:children()) do + if not tree then + return nil + end + local ok, children = pcall(tree.children, tree) + if not ok or not children then + return tree + end + for lang, child in pairs(children) do if lang ~= 'comment' and child:contains(range) then return ft.contains(child, range) end @@ -297,14 +304,21 @@ function ft.calculate(ctx) return ft.get(vim.bo.filetype, ctx.ctype) --[[ @as string ]] end - local lang = ft.contains(parser, { + local tree = ft.contains(parser, { ctx.range.srow - 1, ctx.range.scol, ctx.range.erow - 1, ctx.range.ecol, - }):lang() + }) + local lang = tree and tree:lang() - return ft.get(lang, ctx.ctype) or ft.get(vim.bo.filetype, ctx.ctype) --[[ @as string ]] + if lang then + local result = ft.get(lang, ctx.ctype) + if result then + return result + end + end + return ft.get(vim.bo.filetype, ctx.ctype) --[[ @as string ]] end ---@export ft diff --git a/lua/Comment/utils.lua b/lua/Comment/utils.lua index e95ee2c3..d78322b4 100644 --- a/lua/Comment/utils.lua +++ b/lua/Comment/utils.lua @@ -369,7 +369,7 @@ end ---@param ... unknown function U.catch(fn, ...) xpcall(fn, function(err) - vim.notify(string.format('[Comment.nvim] %s', err.msg), vim.log.levels.WARN) + vim.notify(string.format('[Comment.nvim] %s', tostring(err)), vim.log.levels.WARN) end, ...) end