feat(util): small ts parse wrapper that parses async when available

This commit is contained in:
Folke Lemaitre 2025-03-01 07:53:55 +01:00
parent 0e50e80189
commit 9f0aa20489
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040
2 changed files with 20 additions and 11 deletions

View file

@ -106,9 +106,6 @@ local defaults = {
},
}
---@diagnostic disable-next-line: invisible
M.TS_ASYNC = (vim.treesitter.languagetree or {})._async_parse ~= nil
local id = 0
---@alias snacks.scope.scope {buf: number, from: number, to: number, indent?: number}
@ -399,12 +396,7 @@ function TSScope:init(cb, opts)
if not parser then
return cb()
end
if M.TS_ASYNC then
parser:parse(opts.treesitter.injections, cb)
else
parser:parse(opts.treesitter.injections)
cb()
end
Snacks.util.parse(parser, opts.treesitter.injections, cb)
end
---@param opts snacks.scope.Opts

View file

@ -315,7 +315,8 @@ end
---@param opts? {ms?:number}
---@return T
function M.throttle(fn, opts)
local timer, trailing, ms = assert(uv.new_timer()), false, opts and opts.ms or 20
local timer = assert(uv.new_timer())
local trailing, ms = false, opts and opts.ms or 20
local running = false
local function run()
running = true
@ -343,7 +344,8 @@ end
---@param opts? {ms?:number}
---@return T
function M.debounce(fn, opts)
local timer, ms = assert(uv.new_timer()), opts and opts.ms or 20
local timer = assert(uv.new_timer())
local ms = opts and opts.ms or 20
return function()
timer:start(ms, 0, vim.schedule_wrap(fn))
end
@ -441,4 +443,19 @@ M.base64 = vim.base64 and vim.base64.encode
return b64
end
--- Parse async when available.
---@param parser vim.treesitter.LanguageTree
---@param range boolean|Range|nil: Parse this range in the parser's source.
---@param on_parse fun(err?: string, trees?: table<integer, TSTree>) Function invoked when parsing completes.
function M.parse(parser, range, on_parse)
---@diagnostic disable-next-line: invisible
local have_async = (vim.treesitter.languagetree or {})._async_parse ~= nil
if have_async then
parser:parse(range, on_parse)
else
parser:parse(range)
on_parse(nil, parser:trees())
end
end
return M