From 98db7ec0d287adcd8eaf6a93c4a392f588b5615a Mon Sep 17 00:00:00 2001 From: Folke Lemaitre Date: Mon, 16 Oct 2023 12:42:54 +0200 Subject: [PATCH] perf(root): cache root detection. Fixes #1753 --- lua/lazyvim/config/init.lua | 5 +---- lua/lazyvim/util/root.lua | 30 +++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) 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