💤

lazy.nvimでプラグインのディレクトリを再帰的に読み込む

に公開

結論

local specs = {}
local config_path = vim.fn.stdpath("config") .. "/lua"
local subdirs = vim.fn.globpath(config_path, "plugins/**/", true, true)
for _, dir in ipairs(subdirs) do
  local module = dir
      :gsub(config_path, "")
      :gsub("/$", "")
      :gsub("/", ".")
  table.insert(specs, { import = module })
end

require("lazy").setup({
  spec = specs,
})

情報が古い可能性があるので適宜↓も確認してください。

https://github.com/ras0q/dotfiles/blob/main/common/nvim/lua/config/lazy.lua

詳細

lazy.nvimでは指定したディレクトリの下にある*.luaファイルをプラグインのスペックとして読み込むことができます。

しかし、再帰的に読み込むような設定はデフォルトでは用意されておらず、以下のように書くことができます(下記の記事から引用)。

require("lazy").setup({
  spec = {
    { import = "plugins" },
    { import = "plugins.ui" },
    { import = "plugins.lsp" },
  }
})

参考:

自力でglobからスペックを作成することで、再帰的にプラグインを読み込むことができます。

local specs = {}
local config_path = vim.fn.stdpath("config") .. "/lua"
local subdirs = vim.fn.globpath(config_path, "plugins/**/", true, true)
for _, dir in ipairs(subdirs) do
  local module = dir
      :gsub(config_path, "")
      :gsub("/$", "")
      :gsub("/", ".")
  table.insert(specs, { import = module })
end

require("lazy").setup({
  spec = specs,
})

おまけ

ちなみに自分の環境ではGitHubから持ってきたプラグインをlua/plugins/{author}/{repo}.luaに置いて管理しています。

$ tree lua/plugins/
lua/plugins/
├── HakonHarnes
│   └── img-clip.nvim.lua
├── MeanderingProgrammer
│   └── render-markdown.nvim.lua
├── MunifTanjim
│   └── nui.nvim.lua
├── akinsho
│   └── toggleterm.nvim.lua
...

:AddPlugin author/repo でプラグインを追加するコマンドも置いておきます。

vim.api.nvim_create_user_command("AddPlugin", function(opts)
  local spec = opts.fargs[1]
  if not spec or not spec:match("^[^/]+/.+$") then
    return vim.notify("Argument must be in 'author/repo' format", vim.log.levels.ERROR)
  end

  local path = string.format("%s/lua/plugins/%s.lua", vim.fn.stdpath("config"), spec)
  vim.fn.mkdir(vim.fn.fnamemodify(path, ":h"), "p")

  local file = io.open(path, "w")
  if file then
    file:write(string.format('return {\n  "%s",\n}\n', spec))
    file:close()
    vim.notify("Created: " .. vim.fn.fnamemodify(path, ":~"), vim.log.levels.INFO)
  end
end, { nargs = 1 })

Discussion