diff --git a/lua/lazyvim/config/init.lua b/lua/lazyvim/config/init.lua index 3b8092c7..fd9ffcd2 100644 --- a/lua/lazyvim/config/init.lua +++ b/lua/lazyvim/config/init.lua @@ -180,10 +180,7 @@ function M.setup(opts) Util.format.setup() Util.news.setup() - - vim.api.nvim_create_user_command("LazyRoot", function() - Util.root.info() - end, { desc = "LazyVim roots for the current buffer" }) + Util.root.setup() vim.api.nvim_create_user_command("LazyExtras", function() Util.extras.show() diff --git a/lua/lazyvim/util/root.lua b/lua/lazyvim/util/root.lua index a6deb240..29581975 100644 --- a/lua/lazyvim/util/root.lua +++ b/lua/lazyvim/util/root.lua @@ -136,18 +136,38 @@ function M.info() return roots[1] and roots[1].paths[1] or vim.loop.cwd() end +---@type table +M.cache = {} + +function M.setup() + vim.api.nvim_create_user_command("LazyRoot", function() + Util.root.info() + end, { desc = "LazyVim roots for the current buffer" }) + + vim.api.nvim_create_autocmd({ "LspAttach", "BufWritePost" }, { + group = vim.api.nvim_create_augroup("lazyvim_root_cache", { clear = true }), + callback = function(event) + M.cache[event.buf] = nil + end, + }) +end + -- returns the root directory based on: -- * lsp workspace folders -- * lsp root_dir -- * root pattern of filename of the current buffer -- * root pattern of cwd ----@param opts {normalize?:boolean} +---@param opts? {normalize?:boolean} ---@return string function M.get(opts) - opts = opts or {} - local roots = M.detect({ all = false }) - local ret = roots[1] and roots[1].paths[1] or vim.loop.cwd() - if opts.normalize then + local buf = vim.api.nvim_get_current_buf() + local ret = M.cache[buf] + if not ret then + local roots = M.detect({ all = false }) + ret = roots[1] and roots[1].paths[1] or vim.loop.cwd() + M.cache[buf] = ret + end + if opts and opts.normalize then return ret end return Util.is_win() and ret:gsub("/", "\\") or ret