From 75f992c55138d614eba6bb445c4dd630d13a8515 Mon Sep 17 00:00:00 2001 From: Alexander Courtis Date: Sun, 1 Jan 2023 16:36:10 +1100 Subject: [PATCH] fix(#1785): retain focused node following filter toggle --- .../actions/tree-modifiers/toggles.lua | 22 ++++++++++++++----- lua/nvim-tree/lib.lua | 9 ++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/lua/nvim-tree/actions/tree-modifiers/toggles.lua b/lua/nvim-tree/actions/tree-modifiers/toggles.lua index e56d1b37409..8a6a65b893f 100644 --- a/lua/nvim-tree/actions/tree-modifiers/toggles.lua +++ b/lua/nvim-tree/actions/tree-modifiers/toggles.lua @@ -1,3 +1,4 @@ +local lib = require "nvim-tree.lib" local view = require "nvim-tree.view" local filters = require "nvim-tree.explorer.filters" local renderer = require "nvim-tree.renderer" @@ -5,29 +6,40 @@ local reloaders = require "nvim-tree.actions.reloaders.reloaders" local M = {} +--- Reload and attempt to move the cursor to the previously focused node. +local function reload() + local node = lib.get_node_at_cursor() + + reloaders.reload_explorer() + + if node then + lib.place_cursor_at_node(node) + end +end + function M.custom() filters.config.filter_custom = not filters.config.filter_custom - return reloaders.reload_explorer() + reload() end function M.git_ignored() filters.config.filter_git_ignored = not filters.config.filter_git_ignored - return reloaders.reload_explorer() + reload() end function M.git_clean() filters.config.filter_git_clean = not filters.config.filter_git_clean - return reloaders.reload_explorer() + reload() end function M.no_buffer() filters.config.filter_no_buffer = not filters.config.filter_no_buffer - return reloaders.reload_explorer() + reload() end function M.dotfiles() filters.config.filter_dotfiles = not filters.config.filter_dotfiles - return reloaders.reload_explorer() + reload() end function M.help() diff --git a/lua/nvim-tree/lib.lua b/lua/nvim-tree/lib.lua index 82be687c82b..d9ba2cd1b4d 100644 --- a/lua/nvim-tree/lib.lua +++ b/lua/nvim-tree/lib.lua @@ -32,6 +32,15 @@ function M.get_node_at_cursor() return utils.get_nodes_by_line(core.get_explorer().nodes, core.get_nodes_starting_line())[line] end +--- Place the cursor at the node if it is visible or at the top. +--- @param node table +function M.place_cursor_at_node(node) + local _, l = utils.find_node(core.get_explorer().nodes, function(n) + return n == node + end) + view.set_cursor { l + 1, 1 } +end + ---Create a sanitized partial copy of a node, populating children recursively. ---@param node table ---@return table|nil cloned node