nvim-treesitterのmainブランチ対応 #
新規インストールした環境でtreesitterがエラーを吐いてしまい,原因を探ったらデフォルトブランチが破壊的変更の入ったものに変わっていた.
これまでensure_installやauto_installに頼りきりでもうやめられないので,同等の機能を再現した.
https://github.com/Nanamiiiii/dotfiles/blob/3d0de5061be313181d9ba5f30fe2568c241415b4/config/nvim/lua/plugins/treesitter.lua
再現にあたり,自分のやりたいことを概ね実現してくれていた以下を参考にした. https://github.com/atusy/dotfiles/blob/9884146c26cb76692723758306f2f191cd6d47e4/dot_config/nvim/lua/plugins/nvim-treesitter.lua https://blog.atusy.net/2025/08/10/nvim-treesitter-main-branch/
プラグインマネージャはlazy.nvim
{
"nvim-treesitter/nvim-treesitter",
lazy = true,
branch = "main",
build = ":TSUpdate",
config = function()
local treesitter = require("nvim-treesitter")
treesitter.setup({
install_dir = vim.fs.joinpath(vim.fn.stdpath("data"), "/nvim-treesitter"),
})
-- refs: https://github.com/atusy/dotfiles/blob/9884146c26cb76692723758306f2f191cd6d47e4/dot_config/nvim/lua/plugins/nvim-treesitter.lua
local ok, err = pcall(function()
local installed = treesitter.get_installed()
local ensure_installed = {
"c",
"rust",
"go",
"lua",
"python",
"cpp",
"yaml",
"json",
"bash",
"dockerfile",
"vim",
"vimdoc",
"make",
"cmake",
"bash",
"diff",
"html",
"javascript",
"jsdoc",
"jsonc",
"lua",
"luadoc",
"luap",
"markdown",
"markdown_inline",
"query",
"regex",
"toml",
"tsx",
"typescript",
"xml",
}
local missing = vim.tbl_filter(function(lang)
return not vim.tbl_contains(installed, lang)
end, ensure_installed)
treesitter.install(missing)
end)
if not ok then
vim.notify(err or "failed to install required parsers", vim.log.levels.ERROR,
{ title = "nvim-treesitter" })
end
end,
init = function(plugin)
require("lazy.core.loader").add_to_rtp(plugin)
-- refs: https://github.com/atusy/dotfiles/blob/9884146c26cb76692723758306f2f191cd6d47e4/dot_config/nvim/lua/plugins/nvim-treesitter.lua
vim.api.nvim_create_autocmd("FileType", {
group = augroup,
callback = function(ctx)
local filetype = ctx.match
local treesitter = require("nvim-treesitter")
local ok = pcall(vim.treesitter.start, ctx.buf)
if ok then
return
end
local lang = vim.treesitter.language.get_lang(filetype)
treesitter.install({ lang }):await(function(err)
if err then
vim.notify(err, vim.log.levels.ERROR, { title = "nvim-treesitter" })
end
pcall(vim.treesitter.start, ctx.buf)
end)
end,
})
end,
}- 参考実装ではプラグインのインストール・更新時に利用可能なものを全てインストールする動作だったが,
configに入れてロード時に毎回チェックされるようにした- 処理的には多少重くなる可能性はあるが,インストール時や更新時Onlyだと中断されたときに中途半端になってしまうため
- 利用可能なもの全てではなく,リストアップしたものだけを入れたかったので,気にならない程度のオーバーヘッドだろうと
- FileTypeによりインストールする部分はそのまま