From bd739b009224fa52f0a3742f7f23c973b1cd189a Mon Sep 17 00:00:00 2001 From: Dreaded_X Date: Wed, 15 Apr 2026 03:31:45 +0200 Subject: [PATCH] Auto start and install treesitter for supported languages --- .../nvim/lua/plugins/treesitter.lua | 61 ++++++++++++++++--- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/nvim/dot-config/nvim/lua/plugins/treesitter.lua b/nvim/dot-config/nvim/lua/plugins/treesitter.lua index 000ce9f..54f1c54 100644 --- a/nvim/dot-config/nvim/lua/plugins/treesitter.lua +++ b/nvim/dot-config/nvim/lua/plugins/treesitter.lua @@ -7,13 +7,10 @@ return { lazy = false, branch = "main", build = ":TSUpdate", - -- main = "nvim-treesitter.configs", - init = function() - vim.wo.foldmethod = "expr" - vim.wo.foldexpr = "v:lua.vim.treesitter.foldexpr()" - vim.bo.indentexpr = "v:lua.require'nvim-treesitter'.indentexpr()" - - require("nvim-treesitter").install({ + -- Taken from kickstart.nvim + config = function() + -- ensure basic parser are installed + local parsers = { "c", "cpp", "go", @@ -32,6 +29,56 @@ return { "cmake", "json", "yaml", + } + require("nvim-treesitter").install(parsers) + + ---@param buf integer + ---@param language string + local function treesitter_try_attach(buf, language) + -- Check if the parser exists + if not vim.treesitter.language.add(language) then + return + end + vim.treesitter.start(buf, language) + + -- TODO: Does this work properly? + local has_fold_query = vim.treesitter.query.get(language, "folds") ~= nil + if has_fold_query then + vim.wo.foldmethod = "expr" + vim.wo.foldexpr = "v:lua.vim.treesitter.foldexpr()" + end + + local has_indent_query = vim.treesitter.query.get(language, "indents") ~= nil + if has_indent_query then + vim.bo.indentexpr = "v:lua.require'nvim-treesitter'.indentexpr()" + end + end + + local available_parsers = require("nvim-treesitter").get_available() + vim.api.nvim_create_autocmd("FileType", { + callback = function(args) + local buf, filetype = args.buf, args.match + + local language = vim.treesitter.language.get_lang(filetype) + if not language then + return + end + + local installed_parsers = require("nvim-treesitter").get_installed("parsers") + + if vim.tbl_contains(installed_parsers, language) then + -- enable the parser if it is installed + treesitter_try_attach(buf, language) + elseif vim.tbl_contains(available_parsers, language) then + -- if a parser is available in `nvim-treesitter` auto install it, and enable it after the installation is done + require("nvim-treesitter").install(language):await(function() + treesitter_try_attach(buf, language) + end) + else + -- try to enable treesitter features in case the parser exists but is not available from `nvim-treesitter` + treesitter_try_attach(buf, language) + end + end, }) end, },