Skip to content

Commit

Permalink
feat(buf): added support for ---@module "foobar". Fixes #4
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Jun 2, 2024
1 parent 62c8bbf commit 6d0aaae
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
23 changes: 6 additions & 17 deletions lua/lazydev/buf.lua
Original file line number Diff line number Diff line change
Expand Up @@ -92,24 +92,13 @@ end
---@param first number
---@param last number
function M.on_lines(buf, first, last)
if -- fast exit when no line contains "require" in the range
#vim.tbl_filter(function(line)
return line:find("require", 1, true)
end, vim.api.nvim_buf_get_lines(buf, first, last, false)) == 0
then
return
end

-- Find require calls in the range
local parser = vim.treesitter.get_parser(buf)
local changes = {} ---@type string[]
for id, node in M.query:iter_captures(parser:trees()[1]:root(), buf, first, last) do
local capture = M.query.captures[id]
if capture == "modname" then
local text = vim.treesitter.get_node_text(node, buf)
if M.modules[text] == nil then
changes[#changes + 1] = text
end

local lines = vim.api.nvim_buf_get_lines(buf, first, last, false)
for _, line in ipairs(lines) do
local module = Pkg.get_module(line)
if module then
changes[#changes + 1] = module
end
end

Expand Down
28 changes: 28 additions & 0 deletions lua/lazydev/pkg.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
---@class lazydev.Pkg
local M = {}

M.PAT_MODULE_BASE = "%-%-%-%s*@module%s*[\"']([%w%.%-_]+)"
M.PAT_REQUIRE_BASE = "require%s*%(?%s*['\"]([%w%.%-_]+)"
M.PAT_MODULE_BEFORE = M.PAT_MODULE_BASE .. "$"
M.PAT_REQUIRE_BEFORE = M.PAT_REQUIRE_BASE .. "$"
M.PAT_MODULE = M.PAT_MODULE_BASE .. "[\"']"
M.PAT_REQUIRE = M.PAT_REQUIRE_BASE .. "[\"']"

local is_lazy = type(package.loaded.lazy) == "table"

---@param modname string
Expand Down Expand Up @@ -38,4 +45,25 @@ end

M.get_unloaded = is_lazy and M.lazy_unloaded or M.pack_unloaded

--- Get the module name from a line,
--- either `---@module "modname"` or `require "modname"`
---@param line string
---@param opts? {before?:boolean}
---@return string?
function M.get_module(line, opts)
local patterns = opts and opts.before and {
M.PAT_MODULE_BEFORE,
M.PAT_REQUIRE_BEFORE,
} or {
M.PAT_MODULE,
M.PAT_REQUIRE,
}
for _, pat in ipairs(patterns) do
local match = line:match(pat)
if match then
return match
end
end
end

return M

0 comments on commit 6d0aaae

Please sign in to comment.