Compare commits

..

27 Commits

Author SHA1 Message Date
Alexander Courtis
996219335c refactor(#2826): default lifecycle log off 2025-06-17 17:07:03 +10:00
Alexander Courtis
b1a5cb55b0 Merge remote-tracking branch 'origin/master' into 2826-multi-instance-view-amc 2025-06-17 17:01:20 +10:00
Alexander Courtis
1fe6ed858d refactor(#2826): add lib.target_win_id to tabline 2025-06-17 16:38:47 +10:00
Alexander Courtis
0d975b4cb4 refactor(#2826): add View.tab_line for debugging 2025-06-17 16:22:33 +10:00
Alexander Courtis
c7779d93a7 refactor(#2826): better enumerate_options function 2025-06-17 13:11:04 +10:00
Alexander Courtis
d24f959bf1 refactor(#2826): remove unnecessary view setup and members 2025-06-16 16:18:49 +10:00
Alexander Courtis
8b9c9c107f refactor(#2826): split global View and instance Window 2025-06-16 16:11:06 +10:00
Alexander Courtis
54439447f1 refactor(#2826): add lifecycle logging to all Explorer members 2025-06-16 13:55:35 +10:00
Alexander Courtis
fc81249d4f refactor(#2826): rename View to Window 2025-06-16 13:42:56 +10:00
Alexander Courtis
5377a3fd69 refactor(#2826): move all winhl to appearance constants 2025-06-16 13:00:33 +10:00
Alexander Courtis
76186fa64b Merge remote-tracking branch 'origin/master' into 2826-multi-instance-view-amc 2025-06-16 12:59:49 +10:00
Alexander Courtis
e0759880db refactor(#2826): retain necessary view globals 2025-05-03 08:04:06 +10:00
Alexander Courtis
6218f9c2f6
Merge branch 'master' into 2826-multi-instance-view-amc 2025-05-03 07:22:27 +10:00
Alexander Courtis
21d532fdce refactor(#2826): move View into Explorer package 2025-04-21 14:23:52 +10:00
Alexander Courtis
b5e7406df4
Merge branch 'master' into 2826-multi-instance-view-amc 2025-04-21 14:13:37 +10:00
Alexander Courtis
9594528a8a refactor(#2826): API uses Explorer's View 2025-04-21 14:12:12 +10:00
Alexander Courtis
3a82885cc3 refactor(#2826): move autocmds to Explorer 2025-04-21 12:17:21 +10:00
Alexander Courtis
44cb3d2f0a refactor(#2826): View is an Explorer member 2025-04-21 12:02:19 +10:00
Alexander Courtis
0eb21f66f7 Merge remote-tracking branch 'origin/master' into 2826-multi-instance-view-amc 2025-04-21 09:25:27 +10:00
Alexander Courtis
f309ca21e9 refactor(#2826): singleton View class 2025-04-20 14:47:43 +10:00
Alexander Courtis
f098195667 refactor(#2826): singleton View class, WIP 2025-04-20 14:28:44 +10:00
Alexander Courtis
0a04e435b1 refactor(#2826): singleton View class, WIP 2025-04-20 14:07:02 +10:00
Alexander Courtis
b95b873626 refactor(#2826): singleton View class, WIP 2025-04-20 13:57:12 +10:00
Alexander Courtis
9d3d0d220f refactor(#2826): singleton View class, WIP 2025-04-20 13:54:37 +10:00
Alexander Courtis
a3fe0c9007 refactor(#2826): singleton View class, WIP 2025-04-20 13:20:41 +10:00
Alexander Courtis
3c024975fd refactor(#2826): singleton View class, WIP 2025-04-20 12:48:22 +10:00
Alexander Courtis
fa64574f16 refactor(#2826): singleton View class, WIP 2025-04-20 12:45:22 +10:00
48 changed files with 1234 additions and 1198 deletions

View File

@ -24,15 +24,15 @@ jobs:
steps:
- name: checkout
uses: actions/checkout@v5
uses: actions/checkout@v4
- name: install lua ${{ matrix.lua_version }}
uses: leafo/gh-actions-lua@v12
uses: leafo/gh-actions-lua@v11
with:
luaVersion: ${{ matrix.lua_version }}
- name: install luarocks
uses: leafo/gh-actions-luarocks@v6
uses: leafo/gh-actions-luarocks@v5
- name: install luacheck ${{ matrix.luacheck_version }}
run: luarocks install luacheck ${{ matrix.luacheck_version }}
@ -49,14 +49,14 @@ jobs:
strategy:
matrix:
nvim_version: [ stable, nightly ]
luals_version: [ 3.15.0 ]
luals_version: [ 3.13.9 ]
env:
VIMRUNTIME: /home/runner/nvim-${{ matrix.nvim_version }}/share/nvim/runtime
steps:
- name: checkout
uses: actions/checkout@v5
uses: actions/checkout@v4
- name: install nvim ${{ matrix.nvim_version }}
uses: rhysd/action-setup-vim@v1

View File

@ -10,7 +10,7 @@ jobs:
luarocks-upload:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: LuaRocks Upload
uses: nvim-neorocks/luarocks-tag-release@v7
env:

View File

@ -16,7 +16,7 @@ jobs:
steps:
- uses: google-github-actions/release-please-action@v4
id: release
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: tag major and minor versions
if: ${{ steps.release.outputs.release_created }}
run: |

View File

@ -14,6 +14,6 @@ jobs:
semantic-pr-subject:
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v6.1.1
- uses: amannn/action-semantic-pull-request@v5.5.3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,3 +1,3 @@
{
".": "1.14.0"
".": "1.13.0"
}

View File

@ -1,37 +1,5 @@
# Changelog
## [1.14.0](https://github.com/nvim-tree/nvim-tree.lua/compare/nvim-tree-v1.13.0...nvim-tree-v1.14.0) (2025-08-12)
### Features
* **#2685:** highlight git new tracked with NvimTreeGitFileNewHL ([#3176](https://github.com/nvim-tree/nvim-tree.lua/issues/3176)) ([0a52012](https://github.com/nvim-tree/nvim-tree.lua/commit/0a52012d611f3c1492b8d2aba363fabf734de91d))
* **#2789:** add optional function expand_until to api.tree.expand_all and api.node.expand ([#3166](https://github.com/nvim-tree/nvim-tree.lua/issues/3166)) ([1b876db](https://github.com/nvim-tree/nvim-tree.lua/commit/1b876db04903b93c78c97fd3f3dd85d59eeef5ff))
* **#2826:** allow only one window with nvim-tree buffer per tab ([#3174](https://github.com/nvim-tree/nvim-tree.lua/issues/3174)) ([dd2364d](https://github.com/nvim-tree/nvim-tree.lua/commit/dd2364d6802f7f57a98acb8b545ed484c6697626))
* **#3157:** add view.cursorlineopt ([#3158](https://github.com/nvim-tree/nvim-tree.lua/issues/3158)) ([8eb5e0b](https://github.com/nvim-tree/nvim-tree.lua/commit/8eb5e0bfd1c4da6efc03ab0c1ccf463dbaae831e))
### Bug Fixes
* **#3077:** deleting a directory containing symlinked directory will delete the contents of the linked directory ([#3168](https://github.com/nvim-tree/nvim-tree.lua/issues/3168)) ([10db694](https://github.com/nvim-tree/nvim-tree.lua/commit/10db6943cb40625941a35235eeb385ffdfbf827a))
* **#3157:** add view.cursorlineopt ([8eb5e0b](https://github.com/nvim-tree/nvim-tree.lua/commit/8eb5e0bfd1c4da6efc03ab0c1ccf463dbaae831e))
* **#3172:** live filter exception ([#3173](https://github.com/nvim-tree/nvim-tree.lua/issues/3173)) ([0a7fcdf](https://github.com/nvim-tree/nvim-tree.lua/commit/0a7fcdf3f8ba208f4260988a198c77ec11748339))
* invalid window id for popup info window ([#3147](https://github.com/nvim-tree/nvim-tree.lua/issues/3147)) ([d54a187](https://github.com/nvim-tree/nvim-tree.lua/commit/d54a1875a91e1a705795ea26074795210b92ce7f))
* **picker:** exclude full_name window id from the choice ([#3165](https://github.com/nvim-tree/nvim-tree.lua/issues/3165)) ([543ed3c](https://github.com/nvim-tree/nvim-tree.lua/commit/543ed3cac212dc3993ef9f042f6c0812e34ddd43))
* window picker ignore hidden window ([#3145](https://github.com/nvim-tree/nvim-tree.lua/issues/3145)) ([d87b41c](https://github.com/nvim-tree/nvim-tree.lua/commit/d87b41ca537e2131622d48a6c25ccf2fbe0e5d62))
### Performance Improvements
* **#3171:** cache toplevel for untracked ([#3185](https://github.com/nvim-tree/nvim-tree.lua/issues/3185)) ([4425136](https://github.com/nvim-tree/nvim-tree.lua/commit/442513648c6936e754c3308a1c58591a399493e5))
* **#3171:** use vim.system() instead of vim.fn.system() to execute git toplevel ([#3175](https://github.com/nvim-tree/nvim-tree.lua/issues/3175)) ([9a05b9e](https://github.com/nvim-tree/nvim-tree.lua/commit/9a05b9e9f928856ca23dbf876fab372003180c3f))
### Reverts
* **#3180, #3177:** invalid group or tabpage ([#3181](https://github.com/nvim-tree/nvim-tree.lua/issues/3181)) ([9b289ab](https://github.com/nvim-tree/nvim-tree.lua/commit/9b289abd6998e30fd24cbc9919e0b0cbed6364ce))
* **#3180, #3177:** resolve live filter failures ([#3183](https://github.com/nvim-tree/nvim-tree.lua/issues/3183)) ([a4699c0](https://github.com/nvim-tree/nvim-tree.lua/commit/a4699c0904103e7767334f6da05f5c2ea5514845))
## [1.13.0](https://github.com/nvim-tree/nvim-tree.lua/compare/nvim-tree-v1.12.0...nvim-tree-v1.13.0) (2025-06-14)

View File

@ -4,30 +4,6 @@ Thank you for contributing.
See [wiki: Development](https://github.com/nvim-tree/nvim-tree.lua/wiki/Development) for environment setup, tips and tools.
<!--
https://github.com/jonschlinkert/markdown-toc
markdown-toc --maxdepth=2 -i CONTRIBUTING.md
-->
<!-- toc -->
- [Tools](#tools)
- [Quality](#quality)
* [lint](#lint)
* [style](#style)
* [check](#check)
- [Diagnostics](#diagnostics)
- [Backwards Compatibility](#backwards-compatibility)
- [Adding New Actions](#adding-new-actions)
- [Documentation](#documentation)
* [Opts](#opts)
* [API](#api)
- [Windows](#windows)
- [Pull Request](#pull-request)
* [Subject](#subject)
<!-- tocstop -->
# Tools
Following are used during CI and strongly recommended during local development.
@ -96,30 +72,6 @@ curl -L "https://github.com/LuaLS/lua-language-server/releases/download/3.9.1/lu
PATH="luals/bin:${PATH}" make check
```
# Diagnostics
Diagnostics issues may not be suppressed. See [luals](https://luals.github.io) documentation for details on how to structure the code and comments.
Suppressions are permitted only in the following cases:
- Backwards compatibility shims
- neovim API metadata incorrect, awaiting upstream fix
- classic class framework
# Backwards Compatibility
Whenever new neovim API is introduced, please ensure that it is available in older versions. See `:help deprecated.txt` and `$VIMRUNTIME/lua/vim/_meta/api.lua`
See `nvim-tree.setup` for the oldest supported version of neovim. If the API is not availble in that version, a backwards compatibility shim must be used e.g.
```lua
if vim.fn.has("nvim-0.10") == 1 then
modified = vim.api.nvim_get_option_value("modified", { buf = target_bufid })
else
modified = vim.api.nvim_buf_get_option(target_bufid, "modified") ---@diagnostic disable-line: deprecated
end
```
# Adding New Actions
To add a new action, add a file in `actions/name-of-the-action.lua`. You should export a `setup` function if some configuration is needed.

View File

@ -398,7 +398,6 @@ Following is the default configuration. See |nvim-tree-opts| for details. >lua
view = {
centralize_selection = false,
cursorline = true,
cursorlineopt = "both",
debounce_delay = 15,
side = "left",
preserve_window_proportions = false,
@ -545,7 +544,6 @@ Following is the default configuration. See |nvim-tree-opts| for details. >lua
warning = "",
error = "",
},
diagnostic_opts = false,
},
modified = {
enable = false,
@ -651,6 +649,7 @@ Following is the default configuration. See |nvim-tree-opts| for details. >lua
dev = false,
diagnostics = false,
git = false,
lifecycle = false,
profile = false,
watcher = false,
},
@ -772,10 +771,6 @@ initially centralized, see |zz|.
Enable |cursorline| in the tree window.
Type: `boolean`, Default: `true`
*nvim-tree.view.cursorlineopt*
Set |cursorlineopt| in the tree window.
Type: `string`, Default: `"both"`
*nvim-tree.view.debounce_delay*
Idle milliseconds before some reload / refresh operations.
Increase if you experience performance issues around screen refresh.
@ -1330,10 +1325,6 @@ Icons for diagnostic severity.
error = ""
}
<
*nvim-tree.diagnostics.diagnostic_opts*
|vim.diagnostic.Opts| overrides |nvim-tree.diagnostics.severity| and
|nvim-tree.diagnostics.icons|
Type: `boolean`, Default: `false`
==============================================================================
5.9 OPTS: MODIFIED *nvim-tree-opts-modified*
@ -1524,6 +1515,11 @@ Configuration options for opening a file from nvim-tree.
Resizes the tree when opening a file.
Type: `boolean`, Default: `true`
*nvim-tree.experimental.actions.open_file.relative_path*
Buffers opened by nvim-tree will use with relative paths instead of
absolute.
Type: `boolean`, Default: `true`
*nvim-tree.actions.open_file.window_picker*
Window picker configuration.
@ -1846,17 +1842,11 @@ tree.collapse_all({opts}) *nvim-tree-api.tree.collapse_all()*
Options: ~
• {keep_buffers} (boolean) do not collapse nodes with open buffers.
tree.expand_all({node}, {opts}) *nvim-tree-api.tree.expand_all()*
tree.expand_all({node}) *nvim-tree-api.tree.expand_all()*
Recursively expand all nodes under the tree root or specified folder.
Parameters: ~
• {node} (Node|nil) folder
• {opts} (ApiTreeExpandOpts) optional parameters
Options: ~
• {expand_until} ((fun(expansion_count: integer, node: Node?): boolean)?)
Return true if {node} should be expanded.
{expansion_count} is the total number of folders expanded.
*nvim-tree-api.tree.toggle_enable_filters()*
tree.toggle_enable_filters()
@ -2290,18 +2280,12 @@ node.buffer.wipe({node}, {opts}) *nvim-tree-api.node.buffer.wipe()*
Options: ~
• {force} (boolean) wipe even if buffer is modified, default false
node.expand({node}, {opts}) *nvim-tree-api.node.expand()*
node.expand({node}) *nvim-tree-api.node.expand()*
Recursively expand all nodes under a directory or a file's parent
directory.
Parameters: ~
• {node} (Node|nil) file or folder
• {opts} (ApiTreeExpandOpts) optional parameters
Options: ~
• {expand_until} ((fun(expansion_count: integer, node: Node?): boolean)?)
Return true if {node} should be expanded.
{expansion_count} is the total number of folders expanded.
node.collapse({node}, {opts}) *nvim-tree-api.node.collapse()*
Collapse the tree under a directory or a file's parent directory.
@ -2339,7 +2323,6 @@ events.Event *nvim-tree-api.events.Event*
live_filter.start() *nvim-tree-api.live_filter.start()*
Enter |nvim-tree.live_filter| mode.
Opens an input window with |filetype| `"NvimTreeFilter"`
live_filter.clear() *nvim-tree-api.live_filter.clear()*
Exit |nvim-tree.live_filter| mode.
@ -2946,71 +2929,43 @@ Decorators may:
- Set highlight group for the name or icons
- Override node icon
Create a `nvim_tree.api.decorator.UserDecorator` class and register it with
precedence via |nvim-tree.renderer.decorators|
See |nvim-tree-decorator-example|
See `nvim-tree/_meta/api_decorator.lua` for full class documentation.
Specify decorators and their precedence via |nvim-tree.renderer.decorators|
e.g. defaults with a user decorator class being overridden only by Cut: >lua
{
"Git",
"Open",
"Hidden",
"Modified",
"Bookmark",
"Diagnostics",
"Copied",
MyDecorator,
"Cut",
}
See `nvim-tree/_meta/api_decorator.lua` for full
`nvim_tree.api.decorator.UserDecorator` class documentation.
<
==============================================================================
11.1. DECORATOR EXAMPLE *nvim-tree-decorator-example*
A decorator class for nodes named "example", overridind all builtin decorators
except for Cut.
- Highlights node name with `IncSearch`
- Creates two icons `"1"` and `"2"` placed after the node name, highlighted with
`DiffAdd` and `DiffText`
- Replaces the node icon with `"N"`, highlighted with `Error `
Create a class file `~/.config/nvim/lua/my-decorator.lua`
Require and register it during |nvim-tree-setup|:
>lua
local MyDecorator = require("my-decorator")
require("nvim-tree").setup({
renderer = {
decorators = {
"Git",
"Open",
"Hidden",
"Modified",
"Bookmark",
"Diagnostics",
"Copied",
MyDecorator,
"Cut",
},
},
})
<
Contents of `my-decorator.lua`:
>lua
---Create your decorator class
---@class (exact) MyDecorator: nvim_tree.api.decorator.UserDecorator
---@field private my_icon1 nvim_tree.api.HighlightedString
---@field private my_icon2 nvim_tree.api.HighlightedString
---@field private my_icon_node nvim_tree.api.HighlightedString
---@field private my_highlight_group string
---@field private my_icon nvim_tree.api.HighlightedString
local MyDecorator = require("nvim-tree.api").decorator.UserDecorator:extend()
---Mandatory constructor :new() will be called once per tree render, with no arguments.
function MyDecorator:new()
self.enabled = true
self.highlight_range = "name"
self.icon_placement = "after"
self.enabled = true
self.highlight_range = "all"
self.icon_placement = "signcolumn"
-- create your icons and highlights once, applied to every node
self.my_icon1 = { str = "1", hl = { "DiffAdd" } }
self.my_icon2 = { str = "2", hl = { "DiffText" } }
self.my_icon_node = { str = "N", hl = { "Error" } }
self.my_highlight_group = "IncSearch"
-- create your icon once, for convenience
self.my_icon = { str = "I", hl = { "MyIcon" } }
-- Define the icon signs only once
-- Define the icon sign only once
-- Only needed if you are using icon_placement = "signcolumn"
-- self:define_sign(self.my_icon1)
-- self:define_sign(self.my_icon2)
self:define_sign(self.my_icon)
end
---Override node icon
@ -3018,35 +2973,33 @@ Contents of `my-decorator.lua`:
---@return nvim_tree.api.HighlightedString? icon_node
function MyDecorator:icon_node(node)
if node.name == "example" then
return self.my_icon_node
return self.my_icon
else
return nil
end
end
---Return two icons for DecoratorIconPlacement "after"
---Return one icon for DecoratorIconPlacement
---@param node nvim_tree.api.Node
---@return nvim_tree.api.HighlightedString[]? icons
function MyDecorator:icons(node)
if node.name == "example" then
return { self.my_icon1, self.my_icon2, }
return { self.my_icon }
else
return nil
end
end
---Exactly one highlight group for DecoratorHighlightRange "name"
---Exactly one highlight group for DecoratorHighlightRange
---@param node nvim_tree.api.Node
---@return string? highlight_group
function MyDecorator:highlight_group(node)
if node.name == "example" then
return self.my_highlight_group
return "MyHighlight"
else
return nil
end
end
return MyDecorator
<
==============================================================================
12. OS SPECIFIC RESTRICTIONS *nvim-tree-os-specific*
@ -3056,6 +3009,9 @@ Windows WSL and PowerShell
- Executable file detection is disabled as this is non-performant and can
freeze nvim
- Some filesystem watcher error related to permissions will not be reported
- Some users have reported unspecified issues with
|nvim-tree.experimental.actions.open_file.relative_path|. Please report any
issues or disable this feature.
==============================================================================
13. NETRW *nvim-tree-netrw*
@ -3181,7 +3137,6 @@ highlight group is not, hard linking as follows: >
|nvim-tree.actions.use_system_clipboard|
|nvim-tree.auto_reload_on_write|
|nvim-tree.diagnostics.debounce_delay|
|nvim-tree.diagnostics.diagnostic_opts|
|nvim-tree.diagnostics.enable|
|nvim-tree.diagnostics.icons|
|nvim-tree.diagnostics.severity|
@ -3191,6 +3146,7 @@ highlight group is not, hard linking as follows: >
|nvim-tree.diagnostics.show_on_open_dirs|
|nvim-tree.disable_netrw|
|nvim-tree.experimental|
|nvim-tree.experimental.actions.open_file.relative_path|
|nvim-tree.filesystem_watchers.debounce_delay|
|nvim-tree.filesystem_watchers.enable|
|nvim-tree.filesystem_watchers.ignore_dirs|
@ -3311,7 +3267,6 @@ highlight group is not, hard linking as follows: >
|nvim-tree.update_focused_file.update_root.ignore_list|
|nvim-tree.view.centralize_selection|
|nvim-tree.view.cursorline|
|nvim-tree.view.cursorlineopt|
|nvim-tree.view.debounce_delay|
|nvim-tree.view.float|
|nvim-tree.view.float.enable|

View File

@ -89,10 +89,10 @@ function M.tab_enter()
return
end
end
view.open({ focus_tree = false })
local explorer = core.get_explorer()
if explorer then
explorer.window:open({ focus_tree = false })
explorer.renderer:draw()
end
end
@ -150,21 +150,6 @@ local function setup_autocommands(opts)
vim.api.nvim_create_autocmd(name, vim.tbl_extend("force", default_opts, custom_opts))
end
-- prevent new opened file from opening in the same window as nvim-tree
create_nvim_tree_autocmd("BufWipeout", {
pattern = "NvimTree_*",
callback = function()
if not utils.is_nvim_tree_buf(0) then
return
end
if opts.actions.open_file.eject then
view._prevent_buffer_override()
else
view.abandon_current_window()
end
end,
})
if opts.tab.sync.open then
create_nvim_tree_autocmd("TabEnter", { callback = vim.schedule_wrap(M.tab_enter) })
end
@ -226,17 +211,6 @@ local function setup_autocommands(opts)
})
end
if opts.view.float.enable and opts.view.float.quit_on_focus_loss then
create_nvim_tree_autocmd("WinLeave", {
pattern = "NvimTree_*",
callback = function()
if utils.is_nvim_tree_buf(0) then
view.close()
end
end,
})
end
-- Handles event dispatch when tree is closed by `:q`
create_nvim_tree_autocmd("WinClosed", {
pattern = "*",
@ -273,7 +247,6 @@ local DEFAULT_OPTS = { -- BEGIN_DEFAULT_OPTS
view = {
centralize_selection = false,
cursorline = true,
cursorlineopt = "both",
debounce_delay = 15,
side = "left",
preserve_window_proportions = false,
@ -420,7 +393,6 @@ local DEFAULT_OPTS = { -- BEGIN_DEFAULT_OPTS
warning = "",
error = "",
},
diagnostic_opts = false,
},
modified = {
enable = false,
@ -526,6 +498,7 @@ local DEFAULT_OPTS = { -- BEGIN_DEFAULT_OPTS
dev = false,
diagnostics = false,
git = false,
lifecycle = false,
profile = false,
watcher = false,
},
@ -694,9 +667,11 @@ local function localise_default_opts()
end
function M.purge_all_state()
view.close_all_tabs()
view.abandon_all_windows()
local explorer = core.get_explorer()
if explorer then
explorer.window:close_all_tabs()
end
view.abandon_all_windows()
if explorer then
require("nvim-tree.git").purge_state()
explorer:destroy()
@ -750,7 +725,6 @@ function M.setup(conf)
require("nvim-tree.explorer.watch").setup(opts)
require("nvim-tree.git").setup(opts)
require("nvim-tree.git.utils").setup(opts)
require("nvim-tree.view").setup(opts)
require("nvim-tree.lib").setup(opts)
require("nvim-tree.renderer.components").setup(opts)
require("nvim-tree.buffers").setup(opts)

View File

@ -32,7 +32,7 @@ function M.fn(path)
local profile = log.profile_start("find file %s", path_real)
-- refresh the contents of all parents, expanding groups as needed
if explorer:get_node_from_path(path_real) == nil then
if utils.get_node_from_path(path_real) == nil then
explorer:refresh_parent_nodes_for_path(vim.fn.fnamemodify(path_real, ":h"))
end

View File

@ -31,6 +31,8 @@ local Clipboard = Class:extend()
---@protected
---@param args ClipboardArgs
function Clipboard:new(args)
args.explorer:log_new("Clipboard")
self.explorer = args.explorer
self.data = {
@ -42,6 +44,10 @@ function Clipboard:new(args)
self.reg = self.explorer.opts.actions.use_system_clipboard and "+" or "1"
end
function Clipboard:destroy()
self.explorer:log_destroy("Clipboard")
end
---@param source string
---@param destination string
---@return boolean

View File

@ -1,7 +1,6 @@
local core = require("nvim-tree.core")
local utils = require("nvim-tree.utils")
local events = require("nvim-tree.events")
local view = require("nvim-tree.view")
local lib = require("nvim-tree.lib")
local notify = require("nvim-tree.notify")
@ -14,10 +13,12 @@ local M = {
---@param windows integer[]
local function close_windows(windows)
local explorer = core.get_explorer()
-- Prevent from closing when the win count equals 1 or 2,
-- where the win to remove could be the last opened.
-- For details see #2503.
if view.View.float.enable and #vim.api.nvim_list_wins() < 3 then
if explorer and explorer.window.float.enable and #vim.api.nvim_list_wins() < 3 then
return
end
@ -30,16 +31,17 @@ end
---@param absolute_path string
local function clear_buffer(absolute_path)
local explorer = core.get_explorer()
local bufs = vim.fn.getbufinfo({ bufloaded = 1, buflisted = 1 })
for _, buf in pairs(bufs) do
if buf.name == absolute_path then
local tree_winnr = vim.api.nvim_get_current_win()
if buf.hidden == 0 and (#bufs > 1 or view.View.float.enable) then
if buf.hidden == 0 and (#bufs > 1 or explorer and explorer.window.float.enable) then
vim.api.nvim_set_current_win(buf.windows[1])
vim.cmd(":bn")
end
vim.api.nvim_buf_delete(buf.bufnr, { force = true })
if not view.View.float.quit_on_focus_loss then
if explorer and not explorer.window.float.quit_on_focus_loss then
vim.api.nvim_set_current_win(tree_winnr)
end
if M.config.actions.remove_file.close_window then
@ -69,16 +71,9 @@ local function remove_dir(cwd)
-- Type must come from fs_stat and not fs_scandir_next to maintain sshfs compatibility
local stat = vim.loop.fs_stat(new_cwd)
-- TODO remove once 0.12 is the minimum neovim version
-- path incorrectly specified as an integer, fixed upstream for neovim 0.12 https://github.com/neovim/neovim/pull/33872
---@diagnostic disable-next-line: param-type-mismatch
local lstat = vim.loop.fs_lstat(new_cwd)
local type = stat and stat.type or nil
-- Checks if file is a link file to ensure deletion of the symlink instead of the file it points to
local ltype = lstat and lstat.type or nil
if type == "directory" and ltype ~= "link" then
if type == "directory" then
local success = remove_dir(new_cwd)
if not success then
return false

View File

@ -1,3 +1,4 @@
local utils = require("nvim-tree.utils")
local view = require("nvim-tree.view")
local core = require("nvim-tree.core")
local diagnostics = require("nvim-tree.diagnostics")
@ -35,7 +36,7 @@ end
---@param skip_gitignored boolean? default false
local function move(explorer, where, what, skip_gitignored)
local first_node_line = core.get_nodes_starting_line()
local nodes_by_line = explorer:get_nodes_by_line(first_node_line)
local nodes_by_line = utils.get_nodes_by_line(explorer.nodes, first_node_line)
local iter_start, iter_end, iter_step, cur, first, nex
local cursor = explorer:get_cursor_position()
@ -190,7 +191,7 @@ local function move_prev_recursive(explorer, what, skip_gitignored)
if node_init.name == ".." then -- root node
view.set_cursor({ 1, 0 }) -- move to root node (position 1)
else
local node_init_line = explorer:find_node_line(node_init)
local node_init_line = utils.find_node_line(node_init)
if node_init_line < 0 then
return
end

View File

@ -1,4 +1,6 @@
local view = require("nvim-tree.view")
local utils = require("nvim-tree.utils")
local DirectoryNode = require("nvim-tree.node.directory")
local M = {}
@ -27,7 +29,7 @@ function M.fn(should_close)
return
end
local _, line = parent.explorer:find_node(function(n)
local _, line = utils.find_node(parent.explorer.nodes, function(n)
return n.absolute_path == parent.absolute_path
end)

View File

@ -1,3 +1,4 @@
local utils = require("nvim-tree.utils")
local core = require("nvim-tree.core")
local Iterator = require("nvim-tree.iterators.node-iterator")
@ -11,14 +12,9 @@ function M.fn(direction)
return
end
local explorer = core.get_explorer()
if not explorer then
return
end
local first, last, next, prev = nil, nil, nil, nil
local found = false
local parent = node.parent or explorer
local parent = node.parent or core.get_explorer()
Iterator.builder(parent and parent.nodes or {})
:recursor(function()
return nil
@ -49,7 +45,7 @@ function M.fn(direction)
end
if target_node then
explorer:focus_node_or_parent(target_node)
utils.focus_file(target_node.absolute_path)
end
end
end

View File

@ -2,7 +2,7 @@
local lib = require("nvim-tree.lib")
local notify = require("nvim-tree.notify")
local utils = require("nvim-tree.utils")
local full_name = require("nvim-tree.renderer.components.full-name")
local core = require("nvim-tree.core")
local view = require("nvim-tree.view")
local M = {}
@ -40,12 +40,7 @@ local function usable_win_ids()
end
local win_config = vim.api.nvim_win_get_config(id)
return id ~= tree_winid
and id ~= full_name.popup_win
and win_config.focusable
and not win_config.hide
and not win_config.external
or false
return id ~= tree_winid and win_config.focusable and not win_config.hide and not win_config.external or false
end, win_ids)
end
@ -193,25 +188,23 @@ end
local function open_file_in_tab(filename)
if M.quit_on_open then
view.close()
local explorer = core.get_explorer()
if explorer then
explorer.window:close()
end
end
if M.relative_path then
filename = utils.path_relative(filename, vim.fn.getcwd())
end
vim.cmd.tabnew()
vim.bo.bufhidden = "wipe"
-- Following vim.fn.tabnew the # buffer may be set to the tree buffer. There is no way to clear the # buffer via vim.fn.setreg as it requires a valid buffer. Clear # by setting it to a new temporary scratch buffer.
if utils.is_nvim_tree_buf(vim.fn.bufnr("#")) then
local tmpbuf = vim.api.nvim_create_buf(false, true)
vim.fn.setreg("#", tmpbuf)
vim.api.nvim_buf_delete(tmpbuf, { force = true })
end
vim.cmd.edit(vim.fn.fnameescape(filename))
vim.cmd("tabe " .. vim.fn.fnameescape(filename))
end
local function drop(filename)
if M.quit_on_open then
view.close()
local explorer = core.get_explorer()
if explorer then
explorer.window:close()
end
end
if M.relative_path then
filename = utils.path_relative(filename, vim.fn.getcwd())
@ -221,7 +214,10 @@ end
local function tab_drop(filename)
if M.quit_on_open then
view.close()
local explorer = core.get_explorer()
if explorer then
explorer.window:close()
end
end
if M.relative_path then
filename = utils.path_relative(filename, vim.fn.getcwd())
@ -242,7 +238,10 @@ local function on_preview(buf_loaded)
once = true,
})
end
view.focus()
local explorer = core.get_explorer()
if explorer then
explorer.window:focus()
end
end
local function get_target_winid(mode)
@ -287,6 +286,8 @@ local function set_current_win_no_autocmd(winid, autocmd)
end
local function open_in_new_window(filename, mode)
local explorer = core.get_explorer()
if type(mode) ~= "string" then
mode = ""
end
@ -309,7 +310,11 @@ local function open_in_new_window(filename, mode)
end, vim.api.nvim_list_wins())
local create_new_window = #win_ids == 1 -- This implies that the nvim-tree window is the only one
local new_window_side = (view.View.side == "right") and "aboveleft" or "belowright"
local new_window_side = "belowright"
if explorer and (explorer.window.side == "right") then
new_window_side = "aboveleft"
end
-- Target is invalid: create new window
if not vim.tbl_contains(win_ids, target_winid) then
@ -341,7 +346,7 @@ local function open_in_new_window(filename, mode)
end
end
if (mode == "preview" or mode == "preview_no_picker") and view.View.float.enable then
if (mode == "preview" or mode == "preview_no_picker") and explorer and explorer.window.float.enable then
-- ignore "WinLeave" autocmd on preview
-- because the registered "WinLeave"
-- will kill the floating window immediately
@ -392,6 +397,8 @@ end
---@param filename string
---@return nil
function M.fn(mode, filename)
local explorer = core.get_explorer()
if type(mode) ~= "string" then
mode = ""
end
@ -426,16 +433,16 @@ function M.fn(mode, filename)
vim.bo.bufhidden = ""
end
if M.resize_window then
view.resize()
if M.resize_window and explorer then
explorer.window:resize()
end
if mode == "preview" or mode == "preview_no_picker" then
return on_preview(buf_loaded)
end
if M.quit_on_open then
view.close()
if M.quit_on_open and explorer then
explorer.window:close()
end
end

View File

@ -41,11 +41,12 @@ function M.fn(opts)
return
end
if view.is_visible() then
local explorer = core.get_explorer()
if explorer and view.is_visible() then
-- focus
if opts.focus then
lib.set_target_win()
view.focus()
explorer.window:focus()
end
elseif opts.open then
-- open

View File

@ -56,7 +56,7 @@ local function collapse(node, opts)
:iterate()
explorer.renderer:draw()
explorer:focus_node_or_parent(node_at_cursor)
utils.focus_node_or_parent(node_at_cursor)
end

View File

@ -27,66 +27,20 @@ local function expand(node)
end
end
---@param should_descend fun(expansion_count: integer, node: Node): boolean
---@return fun(expansion_count: integer, node: Node): boolean
local function limit_folder_discovery(should_descend)
return function(expansion_count, node)
local should_halt = expansion_count >= M.MAX_FOLDER_DISCOVERY
if should_halt then
notify.warn("expansion iteration was halted after " .. M.MAX_FOLDER_DISCOVERY .. " discovered folders")
return false
end
return should_descend(expansion_count, node)
end
end
---@param _ integer expansion_count
---@param node Node
---@return boolean
local function descend_until_empty(_, node)
local dir = node:as(DirectoryNode)
if not dir then
return false
end
local should_exclude = M.EXCLUDE[dir.name]
return not should_exclude
end
---@param expansion_count integer
---@param node Node
---@param should_descend fun(expansion_count: integer, node: Node): boolean
---@return boolean
local function should_expand(expansion_count, node, should_descend)
local function should_expand(expansion_count, node)
local dir = node:as(DirectoryNode)
if not dir then
return false
end
if not dir.open and should_descend(expansion_count, node) then
if #node.nodes == 0 then
core.get_explorer():expand(dir) -- populate node.group_next
end
if dir.group_next then
local expand_next = should_expand(expansion_count, dir.group_next, should_descend)
if expand_next then
dir.open = true
end
return expand_next
else
return true
end
end
return false
local should_halt = expansion_count >= M.MAX_FOLDER_DISCOVERY
local should_exclude = M.EXCLUDE[dir.name]
return not should_halt and not dir.open and not should_exclude
end
---@param should_descend fun(expansion_count: integer, node: Node): boolean
---@return fun(node): any
local function gen_iterator(should_descend)
local function gen_iterator()
local expansion_count = 0
return function(parent)
@ -98,7 +52,7 @@ local function gen_iterator(should_descend)
Iterator.builder(parent.nodes)
:hidden()
:applier(function(node)
if should_expand(expansion_count, node, should_descend) then
if should_expand(expansion_count, node) then
expansion_count = expansion_count + 1
node = node:as(DirectoryNode)
if node then
@ -107,32 +61,25 @@ local function gen_iterator(should_descend)
end
end)
:recursor(function(node)
if not should_descend(expansion_count, node) then
return nil
end
if node.group_next then
return { node.group_next }
end
if node.open and node.nodes then
return node.nodes
end
return nil
return expansion_count < M.MAX_FOLDER_DISCOVERY and (node.group_next and { node.group_next } or (node.open and node.nodes))
end)
:iterate()
if expansion_count >= M.MAX_FOLDER_DISCOVERY then
return true
end
end
end
---@param node Node?
---@param expand_opts ApiTreeExpandOpts?
local function expand_node(node, expand_opts)
local function expand_node(node)
if not node then
return
end
local descend_until = limit_folder_discovery((expand_opts and expand_opts.expand_until) or descend_until_empty)
gen_iterator(descend_until)(node)
if gen_iterator()(node) then
notify.warn("expansion iteration was halted after " .. M.MAX_FOLDER_DISCOVERY .. " discovered folders")
end
local explorer = core.get_explorer()
if explorer then
@ -142,20 +89,18 @@ end
---Expand the directory node or the root
---@param node Node
---@param expand_opts ApiTreeExpandOpts?
function M.all(node, expand_opts)
expand_node(node and node:as(DirectoryNode) or core.get_explorer(), expand_opts)
function M.all(node)
expand_node(node and node:as(DirectoryNode) or core.get_explorer())
end
---Expand the directory node or parent node
---@param node Node
---@param expand_opts ApiTreeExpandOpts?
function M.node(node, expand_opts)
function M.node(node)
if not node then
return
end
expand_node(node:is(FileNode) and node.parent or node:as(DirectoryNode), expand_opts)
expand_node(node:is(FileNode) and node.parent or node:as(DirectoryNode))
end
function M.setup(opts)

View File

@ -1,3 +1,4 @@
local core = require("nvim-tree.core")
local lib = require("nvim-tree.lib")
local view = require("nvim-tree.view")
local finders_find_file = require("nvim-tree.actions.finders.find-file")
@ -23,10 +24,12 @@ function M.fn(opts)
opts.path = nil
end
if view.is_visible() then
local explorer = core.get_explorer()
if explorer and view.is_visible() then
-- focus
lib.set_target_win()
view.focus()
explorer.window:focus()
else
-- open
lib.open({

View File

@ -1,14 +1,19 @@
local view = require("nvim-tree.view")
local core = require("nvim-tree.core")
local M = {}
---Resize the tree, persisting the new size.
---@param opts ApiTreeResizeOpts|nil
function M.fn(opts)
local explorer = core.get_explorer()
if not explorer then
return
end
if opts == nil then
-- reset to config values
view.configure_width()
view.resize()
explorer.window:configure_width()
explorer.window:resize()
return
end
@ -16,19 +21,19 @@ function M.fn(opts)
local width_cfg = options.width
if width_cfg ~= nil then
view.configure_width(width_cfg)
view.resize()
explorer.window:configure_width(width_cfg)
explorer.window:resize()
return
end
if not view.is_width_determined() then
if not explorer.window:is_width_determined() then
-- {absolute} and {relative} do nothing when {width} is a function.
return
end
local absolute = options.absolute
if type(absolute) == "number" then
view.resize(absolute)
explorer.window:resize(absolute)
return
end
@ -39,7 +44,7 @@ function M.fn(opts)
relative_size = "+" .. relative_size
end
view.resize(relative_size)
explorer.window:resize(relative_size)
return
end
end

View File

@ -1,3 +1,4 @@
local core = require("nvim-tree.core")
local lib = require("nvim-tree.lib")
local view = require("nvim-tree.view")
local finders_find_file = require("nvim-tree.actions.finders.find-file")
@ -10,6 +11,8 @@ local M = {}
---@param cwd boolean|nil legacy -> opts.path
---@param bang boolean|nil legacy -> opts.update_root
function M.fn(opts, no_focus, cwd, bang)
local explorer = core.get_explorer()
-- legacy arguments
if type(opts) == "boolean" then
opts = {
@ -40,9 +43,9 @@ function M.fn(opts, no_focus, cwd, bang)
opts.path = nil
end
if view.is_visible() then
if explorer and view.is_visible() then
-- close
view.close()
explorer.window:close()
else
-- open
lib.open({

View File

@ -141,9 +141,9 @@ Api.tree.focus = Api.tree.open
---@field focus boolean|nil default true
Api.tree.toggle = wrap(actions.tree.toggle.fn)
Api.tree.close = wrap(view.close)
Api.tree.close_in_this_tab = wrap(view.close_this_tab_only)
Api.tree.close_in_all_tabs = wrap(view.close_all_tabs)
Api.tree.close = wrap_explorer_member("window", "close")
Api.tree.close_in_this_tab = wrap_explorer_member("window", "close_this_tab_only")
Api.tree.close_in_all_tabs = wrap_explorer_member("window", "close_all_tabs")
Api.tree.reload = wrap_explorer("reload_explorer")
---@class ApiTreeResizeOpts
@ -187,10 +187,6 @@ Api.tree.search_node = wrap(actions.finders.search_node.fn)
---@field keep_buffers boolean|nil default false
Api.tree.collapse_all = wrap(actions.tree.modifiers.collapse.all)
---@class ApiTreeExpandOpts
---@field expand_until (fun(expansion_count: integer, node: Node): boolean)|nil
Api.tree.expand_all = wrap_node(actions.tree.modifiers.expand.all)
Api.tree.toggle_enable_filters = wrap_explorer_member("filters", "toggle")
Api.tree.toggle_gitignore_filter = wrap_explorer_member_args("filters", "toggle", "git_ignored")
@ -243,13 +239,17 @@ local function edit(mode, node, edit_opts)
local path = file_link and file_link.link_to or node.absolute_path
local cur_tabpage = vim.api.nvim_get_current_tabpage()
local explorer = core.get_explorer()
actions.node.open_file.fn(mode, path)
edit_opts = edit_opts or {}
local mode_unsupported_quit_on_open = mode == "drop" or mode == "tab_drop" or mode == "edit_in_place"
if not mode_unsupported_quit_on_open and edit_opts.quit_on_open then
view.close(cur_tabpage)
if explorer then
explorer.window:close(cur_tabpage)
end
end
local mode_unsupported_focus = mode == "drop" or mode == "tab_drop" or mode == "edit_in_place"
@ -259,7 +259,9 @@ local function edit(mode, node, edit_opts)
if mode == "tabnew" then
vim.cmd(":tabprev")
end
view.focus()
if explorer then
explorer.window:focus()
end
end
end

View File

@ -134,6 +134,29 @@ M.HIGHLIGHT_GROUPS = {
{ group = "NvimTreeDiagnosticHintFolderHL", link = "NvimTreeDiagnosticHintFileHL" },
}
-- winhighlight for most cases
M.WIN_HL = table.concat({
"EndOfBuffer:NvimTreeEndOfBuffer",
"CursorLine:NvimTreeCursorLine",
"CursorLineNr:NvimTreeCursorLineNr",
"LineNr:NvimTreeLineNr",
"WinSeparator:NvimTreeWinSeparator",
"StatusLine:NvimTreeStatusLine",
"StatusLineNC:NvimTreeStatuslineNC",
"SignColumn:NvimTreeSignColumn",
"Normal:NvimTreeNormal",
"NormalNC:NvimTreeNormalNC",
"NormalFloat:NvimTreeNormalFloat",
"FloatBorder:NvimTreeNormalFloatBorder",
}, ",")
-- winhighlight for help
M.WIN_HL_HELP = table.concat({
"NormalFloat:NvimTreeNormalFloat",
"WinSeparator:NvimTreeWinSeparator",
"CursorLine:NvimTreeCursorLine",
}, ",")
-- nvim-tree highlight groups to legacy
M.LEGACY_LINKS = {
NvimTreeModifiedIcon = "NvimTreeModifiedFile",

View File

@ -1,5 +1,5 @@
local api = require("nvim-tree.api")
local view = require("nvim-tree.view")
local core = require("nvim-tree.core")
local M = {}
@ -111,7 +111,10 @@ local CMDS = {
bar = true,
},
command = function(c)
view.resize(c.args)
local explorer = core.get_explorer()
if explorer then
explorer.window:resize(c.args)
end
end,
},
{

View File

@ -1,6 +1,5 @@
local events = require("nvim-tree.events")
local notify = require("nvim-tree.notify")
local view = require("nvim-tree.view")
local log = require("nvim-tree.log")
local M = {}
@ -55,7 +54,7 @@ end
---@return integer
function M.get_nodes_starting_line()
local offset = 1
if view.is_root_folder_visible(M.get_cwd()) then
if TreeExplorer and TreeExplorer.window:is_root_folder_visible(M.get_cwd()) then
offset = offset + 1
end
if TreeExplorer and TreeExplorer.live_filter.filter then

View File

@ -231,10 +231,7 @@ end
function M.setup(opts)
M.enable = opts.diagnostics.enable
M.debounce_delay = opts.diagnostics.debounce_delay
M.severity = opts.diagnostics.diagnostic_opts and {
min = vim.diagnostic.severity.HINT,
max = vim.diagnostic.severity.ERROR
} or opts.diagnostics.severity
M.severity = opts.diagnostics.severity
if M.enable then
log.line("diagnostics", "setup")

View File

@ -23,6 +23,8 @@ local Filters = Class:extend()
---@protected
---@param args FiltersArgs
function Filters:new(args)
args.explorer:log_new("Filters")
self.explorer = args.explorer
self.ignore_list = {}
self.exclude_list = self.explorer.opts.filters.exclude
@ -50,6 +52,10 @@ function Filters:new(args)
end
end
function Filters:destroy()
self.explorer:log_destroy("Filters")
end
---@private
---@param path string
---@return boolean
@ -280,7 +286,7 @@ function Filters:toggle(type)
local node = self.explorer:get_node_at_cursor()
self.explorer:reload_explorer()
if node then
self.explorer:focus_node_or_parent(node)
utils.focus_node_or_parent(node)
end
end

View File

@ -20,6 +20,7 @@ local LiveFilter = require("nvim-tree.explorer.live-filter")
local Sorter = require("nvim-tree.explorer.sorter")
local Clipboard = require("nvim-tree.actions.fs.clipboard")
local Renderer = require("nvim-tree.renderer")
local Window = require("nvim-tree.explorer.window")
local FILTER_REASON = require("nvim-tree.enum").FILTER_REASON
@ -35,6 +36,7 @@ local config
---@field sorters Sorter
---@field marks Marks
---@field clipboard Clipboard
---@field window Window
local Explorer = RootNode:extend()
---@class Explorer
@ -55,15 +57,18 @@ function Explorer:new(args)
self.uid_explorer = vim.loop.hrtime()
self.augroup_id = vim.api.nvim_create_augroup("NvimTree_Explorer_" .. self.uid_explorer, {})
self.open = true
self.opts = config
self:log_new("Explorer")
self.sorters = Sorter({ explorer = self })
self.renderer = Renderer({ explorer = self })
self.filters = Filters({ explorer = self })
self.live_filter = LiveFilter({ explorer = self })
self.marks = Marks({ explorer = self })
self.clipboard = Clipboard({ explorer = self })
self.open = true
self.opts = config
self.clipboard = Clipboard({ explorer = self })
self.filters = Filters({ explorer = self })
self.live_filter = LiveFilter({ explorer = self })
self.marks = Marks({ explorer = self })
self.renderer = Renderer({ explorer = self })
self.sorters = Sorter({ explorer = self })
self.window = Window({ explorer = self })
self:create_autocmds()
@ -71,7 +76,15 @@ function Explorer:new(args)
end
function Explorer:destroy()
log.line("dev", "Explorer:destroy")
self.explorer:log_destroy("Explorer")
self.clipboard:destroy()
self.filters:destroy()
self.live_filter:destroy()
self.marks:destroy()
self.renderer:destroy()
self.sorters:destroy()
self.window:destroy()
vim.api.nvim_del_augroup_by_id(self.augroup_id)
@ -84,11 +97,23 @@ function Explorer:create_autocmds()
group = self.augroup_id,
callback = function()
appearance.setup()
view.reset_winhl()
self.window:reset_winhl()
self.renderer:draw()
end,
})
if self.opts.view.float.enable and self.opts.view.float.quit_on_focus_loss then
vim.api.nvim_create_autocmd("WinLeave", {
group = self.augroup_id,
pattern = "NvimTree_*",
callback = function()
if utils.is_nvim_tree_buf(0) then
self.window:close()
end
end,
})
end
vim.api.nvim_create_autocmd("BufWritePost", {
group = self.augroup_id,
callback = function()
@ -141,6 +166,22 @@ function Explorer:create_autocmds()
end,
})
-- prevent new opened file from opening in the same window as nvim-tree
vim.api.nvim_create_autocmd("BufWipeout", {
group = self.augroup_id,
pattern = "NvimTree_*",
callback = function()
if not utils.is_nvim_tree_buf(0) then
return
end
if self.opts.actions.open_file.eject then
self.window:prevent_buffer_override()
else
view.abandon_current_window()
end
end,
})
vim.api.nvim_create_autocmd("BufEnter", {
group = self.augroup_id,
pattern = "NvimTree_*",
@ -523,11 +564,11 @@ function Explorer:get_node_at_cursor()
return
end
if cursor[1] == 1 and view.is_root_folder_visible(core.get_cwd()) then
if cursor[1] == 1 and self.window:is_root_folder_visible(core.get_cwd()) then
return self
end
return self:get_nodes_by_line(core.get_nodes_starting_line())[cursor[1]]
return utils.get_nodes_by_line(self.nodes, core.get_nodes_starting_line())[cursor[1]]
end
function Explorer:place_cursor_on_node()
@ -551,120 +592,24 @@ function Explorer:place_cursor_on_node()
end
end
-- Find the line number of a node.
---@param node Node?
---@return integer -1 not found
function Explorer:find_node_line(node)
if not node then
return -1
end
local first_node_line = core.get_nodes_starting_line()
local nodes_by_line = self:get_nodes_by_line(first_node_line)
local iter_start, iter_end = first_node_line, #nodes_by_line
for line = iter_start, iter_end, 1 do
if nodes_by_line[line] == node then
return line
end
end
return -1
end
-- get the node in the tree state depending on the absolute path of the node
-- (grouped or hidden too)
---@param path string
---@return Node|nil
---@return number|nil
function Explorer:get_node_from_path(path)
if self.absolute_path == path then
return self
end
return Iterator.builder(self.nodes)
:hidden()
:matcher(function(node)
return node.absolute_path == path or node.link_to == path
end)
:recursor(function(node)
if node.group_next then
return { node.group_next }
end
if node.nodes then
return node.nodes
end
end)
:iterate()
end
---Focus node passed as parameter if visible, otherwise focus first visible parent.
---If none of the parents is visible focus root.
---If node is nil do nothing.
---@param node Node? node to focus
function Explorer:focus_node_or_parent(node)
while node do
local found_node, i = self:find_node(function(node_)
return node_.absolute_path == node.absolute_path
end)
if found_node or node.parent == nil then
view.set_cursor({ i + 1, 1 })
break
end
node = node.parent
end
end
--- Get the node and index of the node from the tree that matches the predicate.
--- The explored nodes are those displayed on the view.
---@param fn fun(node: Node): boolean
---@return table|nil
---@return number
function Explorer:find_node(fn)
local node, i = Iterator.builder(self.nodes)
:matcher(fn)
:recursor(function(node)
return node.group_next and { node.group_next } or (node.open and #node.nodes > 0 and node.nodes)
end)
:iterate()
i = view.is_root_folder_visible() and i or i - 1
if node and node.explorer.live_filter.filter then
i = i + 1
end
return node, i
end
--- Return visible nodes indexed by line
---@param line_start number
---@return table
function Explorer:get_nodes_by_line(line_start)
local nodes_by_line = {}
local line = line_start
Iterator.builder(self.nodes)
:applier(function(node)
if node.group_next then
return
end
nodes_by_line[line] = node
line = line + 1
end)
:recursor(function(node)
return node.group_next and { node.group_next } or (node.open and #node.nodes > 0 and node.nodes)
end)
:iterate()
return nodes_by_line
end
---Api.tree.get_nodes
---@return nvim_tree.api.Node
function Explorer:get_nodes()
return self:clone()
end
---Log a lifecycle message with uid_explorer and absolute_path
---@param msg string?
function Explorer:log_new(msg)
log.line("lifecycle", "+ %-15s %d %s", msg, self.uid_explorer, self.absolute_path)
end
---Log a lifecycle message with uid_explorer and absolute_path
---@param msg string?
function Explorer:log_destroy(msg)
log.line("lifecycle", "- %-15s %d %s", msg, self.uid_explorer, self.absolute_path)
end
function Explorer:setup(opts)
config = opts
end

View File

@ -21,12 +21,18 @@ local LiveFilter = Class:extend()
---@protected
---@param args LiveFilterArgs
function LiveFilter:new(args)
args.explorer:log_new("LiveFilter")
self.explorer = args.explorer
self.prefix = self.explorer.opts.live_filter.prefix
self.always_show_folders = self.explorer.opts.live_filter.always_show_folders
self.filter = nil
end
function LiveFilter:destroy()
self.explorer:log_destroy("LiveFilter")
end
---@param node_ Node?
local function reset_filter(self, node_)
node_ = node_ or self.explorer
@ -56,14 +62,14 @@ local overlay_bufnr = 0
local overlay_winnr = 0
local function remove_overlay(self)
if view.View.float.enable and view.View.float.quit_on_focus_loss then
if self.explorer.view.float.enable and self.explorer.view.float.quit_on_focus_loss then
-- return to normal nvim-tree float behaviour when filter window is closed
vim.api.nvim_create_autocmd("WinLeave", {
pattern = "NvimTree_*",
group = vim.api.nvim_create_augroup("NvimTree", { clear = false }),
callback = function()
if utils.is_nvim_tree_buf(0) then
view.close()
self.explorer.view:close()
end
end,
})
@ -156,7 +162,7 @@ end
---@return integer
local function calculate_overlay_win_width(self)
local wininfo = vim.fn.getwininfo(view.get_winnr())[1]
local wininfo = vim.fn.getwininfo(self.explorer.view:get_winnr())[1]
if wininfo then
return wininfo.width - wininfo.textoff - #self.prefix
@ -166,7 +172,7 @@ local function calculate_overlay_win_width(self)
end
local function create_overlay(self)
if view.View.float.enable then
if self.explorer.view.float.enable then
-- don't close nvim-tree float when focus is changed to filter window
vim.api.nvim_clear_autocmds({
event = "WinLeave",
@ -188,10 +194,8 @@ local function create_overlay(self)
if vim.fn.has("nvim-0.10") == 1 then
vim.api.nvim_set_option_value("modifiable", true, { buf = overlay_bufnr })
vim.api.nvim_set_option_value("filetype", "NvimTreeFilter", { buf = overlay_bufnr })
else
vim.api.nvim_buf_set_option(overlay_bufnr, "modifiable", true) ---@diagnostic disable-line: deprecated
vim.api.nvim_buf_set_option(overlay_bufnr, "filetype", "NvimTreeFilter") ---@diagnostic disable-line: deprecated
end
vim.api.nvim_buf_set_lines(overlay_bufnr, 0, -1, false, { self.filter })
@ -200,7 +204,7 @@ local function create_overlay(self)
end
function LiveFilter:start_filtering()
view.View.live_filter.prev_focused_node = self.explorer:get_node_at_cursor()
self.explorer.window.live_filter.prev_focused_node = self.explorer:get_node_at_cursor()
self.filter = self.filter or ""
self.explorer.renderer:draw()
@ -215,16 +219,16 @@ end
function LiveFilter:clear_filter()
local node = self.explorer:get_node_at_cursor()
local last_node = view.View.live_filter.prev_focused_node
local last_node = self.explorer.window.live_filter.prev_focused_node
self.filter = nil
reset_filter(self)
self.explorer.renderer:draw()
if node then
self.explorer:focus_node_or_parent(node)
utils.focus_file(node.absolute_path)
elseif last_node then
self.explorer:focus_node_or_parent(last_node)
utils.focus_file(last_node.absolute_path)
end
end

View File

@ -19,9 +19,15 @@ local Sorter = Class:extend()
---@protected
---@param args SorterArgs
function Sorter:new(args)
args.explorer:log_new("Sorter")
self.explorer = args.explorer
end
function Sorter:destroy()
self.explorer:log_destroy("Sorter")
end
---Create a shallow copy of a portion of a list.
---@param t table
---@param first integer First index, inclusive

View File

@ -0,0 +1,504 @@
local appearance = require("nvim-tree.appearance")
local events = require("nvim-tree.events")
local utils = require("nvim-tree.utils")
local log = require("nvim-tree.log")
local notify = require("nvim-tree.notify")
local view = require("nvim-tree.view")
local Class = require("nvim-tree.classic")
---@class OpenInWinOpts
---@field hijack_current_buf boolean|nil default true
---@field resize boolean|nil default true
---@field winid number|nil 0 or nil for current
local DEFAULT_MIN_WIDTH = 30
local DEFAULT_MAX_WIDTH = -1
local DEFAULT_PADDING = 1
---@class (exact) Window: Class
---@field live_filter table
---@field side string
---@field float table
---@field private explorer Explorer
---@field private adaptive_size boolean
---@field private centralize_selection boolean
---@field private hide_root_folder boolean
---@field private winopts table
---@field private height integer
---@field private preserve_window_proportions boolean
---@field private initial_width integer
---@field private width (fun():integer)|integer|string
---@field private max_width integer
---@field private padding integer
local Window = Class:extend()
---@class Window
---@overload fun(args: WindowArgs): Window
---@class (exact) WindowArgs
---@field explorer Explorer
---@protected
---@param args WindowArgs
function Window:new(args)
args.explorer:log_new("Window")
self.explorer = args.explorer
self.adaptive_size = false
self.centralize_selection = self.explorer.opts.view.centralize_selection
self.float = self.explorer.opts.view.float
self.height = self.explorer.opts.view.height
self.hide_root_folder = self.explorer.opts.renderer.root_folder_label == false
self.preserve_window_proportions = self.explorer.opts.view.preserve_window_proportions
self.side = (self.explorer.opts.view.side == "right") and "right" or "left"
self.live_filter = { prev_focused_node = nil, }
self.winopts = {
relativenumber = self.explorer.opts.view.relativenumber,
number = self.explorer.opts.view.number,
list = false,
foldenable = false,
winfixwidth = true,
winfixheight = true,
spell = false,
signcolumn = self.explorer.opts.view.signcolumn,
foldmethod = "manual",
foldcolumn = "0",
cursorcolumn = false,
cursorline = self.explorer.opts.view.cursorline,
cursorlineopt = "both",
colorcolumn = "0",
wrap = false,
winhl = appearance.WIN_HL,
}
self:configure_width(self.explorer.opts.view.width)
self.initial_width = self:get_width()
end
function Window:destroy()
self.explorer:log_destroy("Window")
end
---@type { name: string, value: any }[]
local BUFFER_OPTIONS = {
{ name = "bufhidden", value = "wipe" },
{ name = "buflisted", value = false },
{ name = "buftype", value = "nofile" },
{ name = "filetype", value = "NvimTree" },
{ name = "modifiable", value = false },
{ name = "swapfile", value = false },
}
---@private
---@param bufnr integer|false|nil
function Window:create_buffer(bufnr)
view.wipe_rogue_buffer()
local tab = view.create_buffer(bufnr)
vim.api.nvim_buf_set_name(view.get_bufnr(), "NvimTree_" .. tab)
bufnr = view.get_bufnr()
for _, option in ipairs(BUFFER_OPTIONS) do
vim.api.nvim_set_option_value(option.name, option.value, { buf = bufnr })
end
require("nvim-tree.keymap").on_attach(view.get_bufnr())
events._dispatch_tree_attached_post(view.get_bufnr())
end
---@private
---@param size (fun():integer)|integer|string
---@return integer
function Window:get_size(size)
if type(size) == "number" then
return size
elseif type(size) == "function" then
return self:get_size(size())
end
local size_as_number = tonumber(size:sub(0, -2))
local percent_as_decimal = size_as_number / 100
return math.floor(vim.o.columns * percent_as_decimal)
end
---@private
---@param size (fun():integer)|integer|nil
---@return integer
function Window:get_width(size)
if size then
return self:get_size(size)
else
return self:get_size(self.width)
end
end
---@private
function Window:set_window_options_and_buffer()
pcall(vim.api.nvim_command, "buffer " .. view.get_bufnr())
if vim.fn.has("nvim-0.10") == 1 then
local eventignore = vim.api.nvim_get_option_value("eventignore", {})
vim.api.nvim_set_option_value("eventignore", "all", {})
for k, v in pairs(self.winopts) do
vim.api.nvim_set_option_value(k, v, { scope = "local" })
end
vim.api.nvim_set_option_value("eventignore", eventignore, {})
else
local eventignore = vim.api.nvim_get_option("eventignore") ---@diagnostic disable-line: deprecated
vim.api.nvim_set_option("eventignore", "all") ---@diagnostic disable-line: deprecated
-- #3009 vim.api.nvim_win_set_option does not set local scope without explicit winid.
-- Revert to opt_local instead of propagating it through for just the 0.10 path.
for k, v in pairs(self.winopts) do
vim.opt_local[k] = v
end
vim.api.nvim_set_option("eventignore", eventignore) ---@diagnostic disable-line: deprecated
end
end
---@private
---@return table
function Window:open_win_config()
if type(self.float.open_win_config) == "function" then
return self.float.open_win_config()
else
return self.float.open_win_config
end
end
---@private
function Window:open_window()
if self.float.enable then
vim.api.nvim_open_win(0, true, self:open_win_config())
else
vim.api.nvim_command("vsp")
self:reposition_window()
end
view.setup_tabpage(vim.api.nvim_get_current_tabpage())
self:set_window_options_and_buffer()
end
---@param buf integer
---@return boolean
local function is_buf_displayed(buf)
return vim.api.nvim_buf_is_valid(buf) and vim.fn.buflisted(buf) == 1
end
---@return number|nil
local function get_alt_or_next_buf()
local alt_buf = vim.fn.bufnr("#")
if is_buf_displayed(alt_buf) then
return alt_buf
end
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if is_buf_displayed(buf) then
return buf
end
end
end
local function switch_buf_if_last_buf()
if #vim.api.nvim_list_wins() == 1 then
local buf = get_alt_or_next_buf()
if buf then
vim.cmd("sb" .. buf)
else
vim.cmd("new")
end
end
end
---@param tabpage integer
local function close(tabpage)
if not view.is_visible({ tabpage = tabpage }) then
return
end
view.save_tab_state(tabpage)
switch_buf_if_last_buf()
local tree_win = view.get_winnr(tabpage)
local current_win = vim.api.nvim_get_current_win()
for _, win in pairs(vim.api.nvim_tabpage_list_wins(tabpage)) do
if vim.api.nvim_win_get_config(win).relative == "" then
local prev_win = vim.fn.winnr("#") -- this tab only
if tree_win == current_win and prev_win > 0 then
vim.api.nvim_set_current_win(vim.fn.win_getid(prev_win))
end
if vim.api.nvim_win_is_valid(tree_win or 0) then
local success, error = pcall(vim.api.nvim_win_close, tree_win or 0, true)
if not success then
notify.debug("Failed to close window: " .. error)
return
end
end
return
end
end
end
function Window:close_this_tab_only()
close(vim.api.nvim_get_current_tabpage())
end
function Window:close_all_tabs()
view.all_tabs_callback(function(t)
close(t)
end)
end
---@param tabpage integer|nil
function Window:close(tabpage)
if self.explorer.opts.tab.sync.close then
self:close_all_tabs()
elseif tabpage then
close(tabpage)
else
self:close_this_tab_only()
end
end
---@param options table|nil
function Window:open(options)
if view.is_visible() then
return
end
local profile = log.profile_start("view open")
events._dispatch_on_tree_pre_open()
self:create_buffer()
self:open_window()
self:resize()
local opts = options or { focus_tree = true }
if not opts.focus_tree then
vim.cmd("wincmd p")
end
events._dispatch_on_tree_open()
log.profile_end(profile)
end
---@private
function Window:grow()
local starts_at = self:is_root_folder_visible(require("nvim-tree.core").get_cwd()) and 1 or 0
local lines = vim.api.nvim_buf_get_lines(view.get_bufnr(), starts_at, -1, false)
-- number of columns of right-padding to indicate end of path
local padding = self:get_size(self.padding)
-- account for sign/number columns etc.
local wininfo = vim.fn.getwininfo(view.get_winnr())
if type(wininfo) == "table" and type(wininfo[1]) == "table" then
padding = padding + wininfo[1].textoff
end
local resizing_width = self.initial_width - padding
local max_width
-- maybe bound max
if self.max_width == -1 then
max_width = -1
else
max_width = self:get_width(self.max_width) - padding
end
local ns_id = vim.api.nvim_get_namespaces()["NvimTreeExtmarks"]
for line_nr, l in pairs(lines) do
local count = vim.fn.strchars(l)
-- also add space for right-aligned icons
local extmarks = vim.api.nvim_buf_get_extmarks(view.get_bufnr(), ns_id, { line_nr, 0 }, { line_nr, -1 }, { details = true })
count = count + utils.extmarks_length(extmarks)
if resizing_width < count then
resizing_width = count
end
if self.adaptive_size and max_width >= 0 and resizing_width >= max_width then
resizing_width = max_width
break
end
end
self:resize(resizing_width + padding)
end
function Window:grow_from_content()
if self.adaptive_size then
self:grow()
end
end
---@param size string|number|nil
function Window:resize(size)
if self.float.enable and not self.adaptive_size then
-- if the floating windows's adaptive size is not desired, then the
-- float size should be defined in view.float.open_win_config
return
end
if type(size) == "string" then
size = vim.trim(size)
local first_char = size:sub(1, 1)
size = tonumber(size)
if first_char == "+" or first_char == "-" then
size = self.width + size
end
end
if type(size) == "number" and size <= 0 then
return
end
if size then
self.width = size
self.height = size
end
if not view.is_visible() then
return
end
local winnr = view.get_winnr() or 0
local new_size = self:get_width()
if new_size ~= vim.api.nvim_win_get_width(winnr) then
vim.api.nvim_win_set_width(winnr, new_size)
if not self.preserve_window_proportions then
vim.cmd(":wincmd =")
end
end
events._dispatch_on_tree_resize(new_size)
end
---@private
function Window:reposition_window()
vim.api.nvim_command("wincmd " .. (self.side == "left" and "H" or "L"))
self:resize()
end
---Open the tree in the a window
---@param opts OpenInWinOpts|nil
function Window:open_in_win(opts)
opts = opts or { hijack_current_buf = true, resize = true }
events._dispatch_on_tree_pre_open()
if opts.winid and vim.api.nvim_win_is_valid(opts.winid) then
vim.api.nvim_set_current_win(opts.winid)
end
self:create_buffer(opts.hijack_current_buf and vim.api.nvim_get_current_buf())
view.setup_tabpage(vim.api.nvim_get_current_tabpage())
view.set_current_win()
self:set_window_options_and_buffer()
if opts.resize then
self:reposition_window()
self:resize()
end
events._dispatch_on_tree_open()
end
---@param winnr number|nil
---@param open_if_closed boolean|nil
function Window:focus(winnr, open_if_closed)
local wnr = winnr or view.get_winnr()
if vim.api.nvim_win_get_tabpage(wnr or 0) ~= vim.api.nvim_win_get_tabpage(0) then
self:close()
self:open()
wnr = view.get_winnr()
elseif open_if_closed and not view.is_visible() then
self:open()
end
if wnr then
vim.api.nvim_set_current_win(wnr)
end
end
function Window:prevent_buffer_override()
local view_winnr = view.get_winnr()
local view_bufnr = view.get_bufnr()
-- need to schedule to let the new buffer populate the window
-- because this event needs to be run on bufWipeout.
-- Otherwise the curwin/curbuf would match the view buffer and the view window.
vim.schedule(function()
local curwin = vim.api.nvim_get_current_win()
local curwinconfig = vim.api.nvim_win_get_config(curwin)
local curbuf = vim.api.nvim_win_get_buf(curwin)
local bufname = vim.api.nvim_buf_get_name(curbuf)
if not bufname:match("NvimTree") then
view.clear_tabpage(view_winnr)
end
if curwin ~= view_winnr or bufname == "" or curbuf == view_bufnr then
return
end
-- patch to avoid the overriding window to be fixed in size
-- might need a better patch
vim.cmd("setlocal nowinfixwidth")
vim.cmd("setlocal nowinfixheight")
self:open({ focus_tree = false })
self.explorer.renderer:draw()
pcall(vim.api.nvim_win_close, curwin, { force = true })
-- to handle opening a file using :e when nvim-tree is on floating mode
-- falling back to the current window instead of creating a new one
if curwinconfig.relative ~= "" then
require("nvim-tree.actions.node.open-file").fn("edit_in_place", bufname)
else
require("nvim-tree.actions.node.open-file").fn("edit", bufname)
end
end)
end
---@param cwd string|nil
---@return boolean
function Window:is_root_folder_visible(cwd)
return cwd ~= "/" and not self.hide_root_folder
end
-- used on ColorScheme event
function Window:reset_winhl()
local winnr = view.get_winnr()
if winnr and vim.api.nvim_win_is_valid(winnr) then
vim.wo[view.get_winnr()].winhl = appearance.WIN_HL
end
end
---Check if width determined or calculated on-fly
---@return boolean
function Window:is_width_determined()
return type(self.width) ~= "function"
end
---Configure width-related config
---@param width string|function|number|table|nil
function Window:configure_width(width)
if type(width) == "table" then
self.adaptive_size = true
self.width = width.min or DEFAULT_MIN_WIDTH
self.max_width = width.max or DEFAULT_MAX_WIDTH
self.padding = width.padding or DEFAULT_PADDING
elseif width == nil then
if self.explorer.opts.view.width ~= nil then
-- if we had input config - fallback to it
self:configure_width(self.explorer.opts.view.width)
else
-- otherwise - restore initial width
self.width = self.initial_width
end
else
self.adaptive_size = false
self.width = width
end
end
return Window

View File

@ -193,10 +193,9 @@ function M.get_toplevel(path)
end
end
-- attempt to fetch toplevel, cache if untracked
-- attempt to fetch toplevel
local toplevel, git_dir = git_utils.get_toplevel(path)
if not toplevel or not git_dir then
M._toplevels_by_path[path] = false
return nil
end
local toplevel_norm = vim.fn.fnamemodify(toplevel, ":p")
@ -233,13 +232,7 @@ local function reload_tree_at(toplevel)
end
log.line("watcher", "git event executing '%s'", toplevel)
local explorer = require("nvim-tree.core").get_explorer()
if not explorer then
return nil
end
local root_node = explorer:get_node_from_path(toplevel)
local root_node = utils.get_node_from_path(toplevel)
if not root_node then
return
end
@ -258,7 +251,7 @@ local function reload_tree_at(toplevel)
end)
:iterate()
explorer.renderer:draw()
root_node.explorer.renderer:draw()
end)
end

View File

@ -5,19 +5,6 @@ local M = {
use_cygpath = false,
}
--- Execute system command
---@param cmd string[]
---@return string stdout
---@return integer exit code
local function system(cmd)
if vim.fn.has("nvim-0.10") == 1 then
local obj = vim.system(cmd):wait()
return obj.stdout or "", obj.code
else
return vim.fn.system(cmd), vim.v.shell_error
end
end
--- Retrieve the git toplevel directory
---@param cwd string path
---@return string|nil toplevel absolute path
@ -29,12 +16,12 @@ function M.get_toplevel(cwd)
local cmd = { "git", "-C", cwd, "rev-parse", "--show-toplevel", "--absolute-git-dir" }
log.line("git", "%s", table.concat(cmd, " "))
local out, exitCode = system(cmd)
local out = vim.fn.system(cmd)
log.raw("git", out)
log.profile_end(profile)
if exitCode ~= 0 or not out or #out == 0 or out:match("fatal") then
if vim.v.shell_error ~= 0 or not out or #out == 0 or out:match("fatal") then
return nil, nil
end
@ -86,7 +73,7 @@ function M.should_show_untracked(cwd)
local cmd = { "git", "-C", cwd, "config", "status.showUntrackedFiles" }
log.line("git", table.concat(cmd, " "))
local has_untracked = system(cmd)
local has_untracked = vim.fn.system(cmd)
log.raw("git", has_untracked)
log.profile_end(profile)

View File

@ -1,3 +1,4 @@
local appearance = require("nvim-tree.appearance")
local keymap = require("nvim-tree.keymap")
local api = {} -- circular dependency
@ -5,12 +6,6 @@ local PAT_MOUSE = "^<.*Mouse"
local PAT_CTRL = "^<C%-"
local PAT_SPECIAL = "^<.+"
local WIN_HL = table.concat({
"NormalFloat:NvimTreeNormalFloat",
"WinSeparator:NvimTreeWinSeparator",
"CursorLine:NvimTreeCursorLine",
}, ",")
local namespace_help_id = vim.api.nvim_create_namespace("NvimTreeHelp")
local M = {
@ -210,7 +205,7 @@ local function open()
})
-- style it a bit like the tree
vim.wo[M.winnr].winhl = WIN_HL
vim.wo[M.winnr].winhl = appearance.WIN_HL_HELP
vim.wo[M.winnr].cursorline = M.config.cursorline
local function toggle_sort()

View File

@ -48,7 +48,7 @@ function NodeIterator:recursor(f)
end
---@return Node|nil
---@return number|nil
---@return number
function NodeIterator:iterate()
local iteration_count = 0
local function iter(nodes)

View File

@ -1,74 +1,27 @@
local utils = require("nvim-tree.utils")
local notify = require("nvim-tree.notify")
local M = {}
--- Create empty sub-tables if not present
---@param tbl table to create empty inside of
---@param path string dot separated string of sub-tables
---@return table deepest sub-table
local function create(tbl, path)
local t = tbl
for s in string.gmatch(path, "([^%.]+)%.*") do
if t[s] == nil then
t[s] = {}
end
t = t[s]
end
return t
end
--- Move a value from src to dst if value is nil on dst.
--- Remove value from src
---@param src table to copy from
---@param src_path string dot separated string of sub-tables
---@param src_pos string value pos
---@param dst table to copy to
---@param dst_path string dot separated string of sub-tables, created when missing
---@param dst_pos string value pos
---@param remove boolean
local function move(src, src_path, src_pos, dst, dst_path, dst_pos, remove)
for pos in string.gmatch(src_path, "([^%.]+)%.*") do
if src[pos] and type(src[pos]) == "table" then
src = src[pos]
else
return
end
end
local src_val = src[src_pos]
if src_val == nil then
return
end
dst = create(dst, dst_path)
if dst[dst_pos] == nil then
dst[dst_pos] = src_val
end
if remove then
src[src_pos] = nil
end
end
-- silently move, please add to help nvim-tree-legacy-opts
local function refactored(opts)
-- 2022/06/20
move(opts, "update_focused_file", "update_cwd", opts, "update_focused_file", "update_root", true)
move(opts, "", "update_cwd", opts, "", "sync_root_with_cwd", true)
utils.move_missing_val(opts, "update_focused_file", "update_cwd", opts, "update_focused_file", "update_root", true)
utils.move_missing_val(opts, "", "update_cwd", opts, "", "sync_root_with_cwd", true)
-- 2022/11/07
move(opts, "", "open_on_tab", opts, "tab.sync", "open", false)
move(opts, "", "open_on_tab", opts, "tab.sync", "close", true)
move(opts, "", "ignore_buf_on_tab_change", opts, "tab.sync", "ignore", true)
utils.move_missing_val(opts, "", "open_on_tab", opts, "tab.sync", "open", false)
utils.move_missing_val(opts, "", "open_on_tab", opts, "tab.sync", "close", true)
utils.move_missing_val(opts, "", "ignore_buf_on_tab_change", opts, "tab.sync", "ignore", true)
-- 2022/11/22
move(opts, "renderer", "root_folder_modifier", opts, "renderer", "root_folder_label", true)
utils.move_missing_val(opts, "renderer", "root_folder_modifier", opts, "renderer", "root_folder_label", true)
-- 2023/01/01
move(opts, "update_focused_file", "debounce_delay", opts, "view", "debounce_delay", true)
utils.move_missing_val(opts, "update_focused_file", "debounce_delay", opts, "view", "debounce_delay", true)
-- 2023/01/08
move(opts, "trash", "require_confirm", opts, "ui.confirm", "trash", true)
utils.move_missing_val(opts, "trash", "require_confirm", opts, "ui.confirm", "trash", true)
-- 2023/01/15
if type(opts.view) == "table" and opts.view.adaptive_size ~= nil then
@ -82,13 +35,13 @@ local function refactored(opts)
end
-- 2023/07/15
move(opts, "", "sort_by", opts, "sort", "sorter", true)
utils.move_missing_val(opts, "", "sort_by", opts, "sort", "sorter", true)
-- 2023/07/16
move(opts, "git", "ignore", opts, "filters", "git_ignored", true)
utils.move_missing_val(opts, "git", "ignore", opts, "filters", "git_ignored", true)
-- 2023/08/26
move(opts, "renderer.icons", "webdev_colors", opts, "renderer.icons.web_devicons.file", "color", true)
utils.move_missing_val(opts, "renderer.icons", "webdev_colors", opts, "renderer.icons.web_devicons.file", "color", true)
-- 2023/10/08
if type(opts.renderer) == "table" and type(opts.renderer.highlight_diagnostics) == "boolean" then
@ -106,7 +59,7 @@ local function refactored(opts)
opts.update_focused_file.update_root = { enable = opts.update_focused_file.update_root }
end
end
move(opts, "update_focused_file", "ignore_list", opts, "update_focused_file.update_root", "ignore_list", true)
utils.move_missing_val(opts, "update_focused_file", "ignore_list", opts, "update_focused_file.update_root", "ignore_list", true)
-- 2025/04/30
if opts.renderer and opts.renderer.icons and type(opts.renderer.icons.padding) == "string" then

View File

@ -30,11 +30,16 @@ local function handle_buf_cwd(cwd)
end
local function open_view_and_draw()
local explorer = core.get_explorer()
local cwd = vim.fn.getcwd()
view.open()
if explorer then
explorer.window:open()
end
handle_buf_cwd(cwd)
local explorer = core.get_explorer()
if explorer then
explorer.renderer:draw()
end
@ -110,19 +115,19 @@ function M.open(opts)
local explorer = core.get_explorer()
if should_hijack_current_buf() then
view.close_this_tab_only()
view.open_in_win()
if explorer then
explorer.window:close_this_tab_only()
explorer.window:open_in_win()
explorer.renderer:draw()
end
elseif opts.winid then
view.open_in_win({ hijack_current_buf = false, resize = false, winid = opts.winid })
if explorer then
explorer.window:open_in_win({ hijack_current_buf = false, resize = false, winid = opts.winid })
explorer.renderer:draw()
end
elseif opts.current_window then
view.open_in_win({ hijack_current_buf = false, resize = false })
if explorer then
explorer.window:open_in_win({ hijack_current_buf = false, resize = false })
explorer.renderer:draw()
end
else

View File

@ -1,4 +1,4 @@
---@alias LogTypes "all" | "config" | "copy_paste" | "dev" | "diagnostics" | "git" | "profile" | "watcher"
---@alias LogTypes "all" | "config" | "copy_paste" | "dev" | "diagnostics" | "git" | "lifecycle" | "profile" | "watcher"
---@type table<LogTypes, boolean>
local types = {}

View File

@ -25,11 +25,17 @@ local Marks = Class:extend()
---@protected
---@param args MarksArgs
function Marks:new(args)
args.explorer:log_new("Marks")
self.explorer = args.explorer
self.marks = {}
end
function Marks:destroy()
self.explorer:log_destroy("Marks")
end
---Clear all marks and reload if watchers disabled
---@private
function Marks:clear_reload()
@ -227,9 +233,9 @@ function Marks:navigate(up)
end
if up then
self.explorer:focus_node_or_parent(prev or last)
utils.focus_node_or_parent(prev or last)
else
self.explorer:focus_node_or_parent(next or first)
utils.focus_node_or_parent(next or first)
end
end
@ -263,7 +269,7 @@ function Marks:navigate_select()
if node and not node:is(DirectoryNode) and not utils.get_win_buf_from_path(node.absolute_path) then
open_file.fn("edit", node.absolute_path)
elseif node then
self.explorer:focus_node_or_parent(node)
utils.focus_file(node.absolute_path)
end
end)
end

View File

@ -1,6 +1,5 @@
local notify = require("nvim-tree.notify")
local utils = require("nvim-tree.utils")
local view = require("nvim-tree.view")
local Class = require("nvim-tree.classic")
@ -58,18 +57,18 @@ local Builder = Class:extend()
---@protected
---@param args BuilderArgs
function Builder:new(args)
self.explorer = args.explorer
self.index = 0
self.depth = 0
self.hl_range_args = {}
self.explorer = args.explorer
self.index = 0
self.depth = 0
self.hl_range_args = {}
self.combined_groups = {}
self.lines = {}
self.markers = {}
self.signs = {}
self.extmarks = {}
self.virtual_lines = {}
self.decorators = {}
self.hidden_display = Builder:setup_hidden_display_function(self.explorer.opts)
self.lines = {}
self.markers = {}
self.signs = {}
self.extmarks = {}
self.virtual_lines = {}
self.decorators = {}
self.hidden_display = Builder:setup_hidden_display_function(self.explorer.opts)
-- instantiate all the builtin and user decorator instances
local builtin, user
@ -101,7 +100,7 @@ end
---@param end_ number|nil
function Builder:insert_highlight(groups, start, end_)
for _, higroup in ipairs(groups) do
table.insert(self.hl_range_args, { higroup = higroup, start = { self.index, start }, finish = { self.index, end_ or -1 } })
table.insert(self.hl_range_args, { higroup = higroup, start = { self.index, start, }, finish = { self.index, end_ or -1, } })
end
end
@ -321,7 +320,7 @@ function Builder:add_hidden_count_string(node, idx, num_children)
-- if we change the traversal, we might need to sort by depth before rendering `self.virtual_lines`
-- to maintain proper ordering of parent and child folder hidden count info.
table.insert(self.virtual_lines[line_nr], {
{ indent_string, indent_markers.hl },
{ indent_string, indent_markers.hl },
{ string.rep(indent_padding, (node.parent == nil and 0 or 1)) .. hidden_count_string, "NvimTreeHiddenDisplay" },
})
end
@ -379,30 +378,10 @@ end
---@private
function Builder:build_header()
if view.is_root_folder_visible(self.explorer.absolute_path) then
if self.explorer.window:is_root_folder_visible(self.explorer.absolute_path) then
local root_name = self:format_root_name(self.explorer.opts.renderer.root_folder_label)
-- Pad to window width so the highlight spans the whole row.
local win = view.get_winnr()
local width = 0
if win and vim.api.nvim_win_is_valid(win) then
width = vim.api.nvim_win_get_width(win)
end
-- Use display width for proper padding with Nerd Font / wide glyphs.
local name_display_w = vim.fn.strdisplaywidth(root_name)
local pad = 0
if width and width > name_display_w then
pad = width - name_display_w
end
local padded_root = pad > 0 and (root_name .. string.rep(" ", pad)) or root_name
table.insert(self.lines, padded_root)
-- Highlight the entire padded string (covers the full visible row)
self:insert_highlight({ "NvimTreeRootFolder" }, 0, string.len(padded_root))
-- Keep original indexing behavior
table.insert(self.lines, root_name)
self:insert_highlight({ "NvimTreeRootFolder" }, 0, string.len(root_name))
self.index = 1
end
@ -410,11 +389,12 @@ function Builder:build_header()
local filter_line = string.format("%s/%s/", self.explorer.opts.live_filter.prefix, self.explorer.live_filter.filter)
table.insert(self.lines, filter_line)
local prefix_length = string.len(self.explorer.opts.live_filter.prefix)
self:insert_highlight({ "NvimTreeLiveFilterPrefix" }, 0, prefix_length)
self:insert_highlight({ "NvimTreeLiveFilterValue" }, prefix_length, string.len(filter_line))
self:insert_highlight({ "NvimTreeLiveFilterPrefix" }, 0, prefix_length)
self:insert_highlight({ "NvimTreeLiveFilterValue" }, prefix_length, string.len(filter_line))
self.index = self.index + 1
end
end
---Sanitize lines for rendering.
---Replace newlines with literal \n
---@private
@ -458,18 +438,17 @@ function Builder:setup_hidden_display_function(opts)
-- In case of missing field such as live_filter we zero it, otherwise keep field as is
hidden_stats = vim.tbl_deep_extend("force", {
live_filter = 0,
git = 0,
buf = 0,
dotfile = 0,
custom = 0,
bookmark = 0,
git = 0,
buf = 0,
dotfile = 0,
custom = 0,
bookmark = 0,
}, hidden_stats or {})
local ok, result = pcall(hidden_display, hidden_stats)
if not ok then
notify.warn(
"Problem occurred in the function ``opts.renderer.hidden_display`` see nvim-tree.renderer.hidden_display on :h nvim-tree"
)
"Problem occurred in the function ``opts.renderer.hidden_display`` see nvim-tree.renderer.hidden_display on :h nvim-tree")
return nil
end
return result

View File

@ -1,7 +1,7 @@
local M = {}
local appearance = require("nvim-tree.appearance")
local utils = require("nvim-tree.utils")
local view = require("nvim-tree.view")
local M = {}
local function hide(win)
if win then
@ -72,7 +72,7 @@ local function show(opts)
style = "minimal",
border = "none"
})
vim.wo[M.popup_win].winhl = view.View.winopts.winhl
vim.wo[M.popup_win].winhl = appearance.WIN_HL
local ns_id = vim.api.nvim_get_namespaces()["NvimTreeHighlights"]
local extmarks = vim.api.nvim_buf_get_extmarks(0, ns_id, { line_nr - 1, 0 }, { line_nr - 1, -1 }, { details = true })

View File

@ -22,8 +22,8 @@ local function check_siblings_for_folder(node, with_arrows)
end
local function get_padding_indent_markers(depth, idx, nodes_number, markers, with_arrows, inline_arrows, node, early_stop)
local base_padding = with_arrows and (not node.nodes or depth > 0) and " " or " "
local padding = (inline_arrows or depth == 0) and base_padding or " "
local base_padding = with_arrows and (not node.nodes or depth > 0) and " " or ""
local padding = (inline_arrows or depth == 0) and base_padding or ""
if depth > 0 then
local has_folder_sibling = check_siblings_for_folder(node, with_arrows)

View File

@ -41,29 +41,17 @@ local DiagnosticsDecorator = Decorator:extend()
---@protected
---@param args DecoratorArgs
function DiagnosticsDecorator:new(args)
self.explorer = args.explorer
self.explorer = args.explorer
self.enabled = true
self.highlight_range = self.explorer.opts.renderer.highlight_diagnostics or "none"
self.icon_placement = self.explorer.opts.renderer.icons.diagnostics_placement or "none"
local vim_diagnostic_icons = {}
if self.explorer.opts.diagnostics.diagnostic_opts then
local vim_diagnostic_config = vim.diagnostic.config() or {}
local signs = vim_diagnostic_config.signs or {}
if type(signs) == "function" then
signs = signs(0, 0)
end
vim_diagnostic_icons = (type(signs) == "table" and signs.text) or {}
end
self.enabled = true
self.highlight_range = self.explorer.opts.renderer.highlight_diagnostics or "none"
self.icon_placement = self.explorer.opts.renderer.icons.diagnostics_placement or "none"
if self.explorer.opts.renderer.icons.show.diagnostics then
self.diag_icons = {}
for name, sev in pairs(ICON_KEYS) do
self.diag_icons[sev] = {
str = vim_diagnostic_icons[sev] or self.explorer.opts.diagnostics.icons[name],
str = self.explorer.opts.diagnostics.icons[name],
hl = { HG_ICON[sev] },
}
self:define_sign(self.diag_icons[sev])

View File

@ -131,7 +131,7 @@ function GitDecorator:build_file_folder_hl_by_xy()
["RM"] = "NvimTreeGitFileRenamedHL",
[" R"] = "NvimTreeGitFileRenamedHL",
["!!"] = "NvimTreeGitFileIgnoredHL",
[" A"] = "NvimTreeGitFileNewHL",
[" A"] = "none",
}
self.folder_hl_by_xy = {}

View File

@ -26,9 +26,15 @@ local Renderer = Class:extend()
---@protected
---@param args RendererArgs
function Renderer:new(args)
args.explorer:log_new("Renderer")
self.explorer = args.explorer
end
function Renderer:destroy()
self.explorer:log_destroy("Renderer")
end
---@private
---@param bufnr number
---@param lines string[]
@ -113,7 +119,7 @@ function Renderer:draw()
vim.api.nvim_win_set_cursor(view.get_winnr() or 0, cursor)
end
view.grow_from_content()
self.explorer.window:grow_from_content()
log.profile_end(profile)

View File

@ -1,3 +1,5 @@
local Iterator = require("nvim-tree.iterators.node-iterator")
local M = {
debouncers = {},
}
@ -15,6 +17,22 @@ function M.str_find(haystack, needle)
return vim.fn.stridx(haystack, needle) ~= -1
end
---@param path string
---@return string|uv.uv_fs_t
function M.read_file(path)
local fd = vim.loop.fs_open(path, "r", 438)
if not fd then
return ""
end
local stat = vim.loop.fs_fstat(fd)
if not stat then
return ""
end
local data = vim.loop.fs_read(fd, stat.size, 0)
vim.loop.fs_close(fd)
return data or ""
end
local path_separator = package.config:sub(1, 1)
---@param paths string[]
---@return string
@ -112,6 +130,54 @@ end
M.path_separator = path_separator
--- Get the node and index of the node from the tree that matches the predicate.
--- The explored nodes are those displayed on the view.
---@param nodes Node[]
---@param fn fun(node: Node): boolean
---@return table|nil
---@return number
function M.find_node(nodes, fn)
local node, i = Iterator.builder(nodes)
:matcher(fn)
:recursor(function(node)
return node.group_next and { node.group_next } or (node.open and #node.nodes > 0 and node.nodes)
end)
:iterate()
if node then
if not node.explorer.window:is_root_folder_visible() then
i = i - 1
end
if node.explorer.live_filter.filter then
i = i + 1
end
end
return node, i
end
-- Find the line number of a node.
-- Return -1 is node is nil or not found.
---@param node Node?
---@return integer
function M.find_node_line(node)
if not node then
return -1
end
local first_node_line = require("nvim-tree.core").get_nodes_starting_line()
local nodes_by_line = M.get_nodes_by_line(require("nvim-tree.core").get_explorer().nodes, first_node_line)
local iter_start, iter_end = first_node_line, #nodes_by_line
for line = iter_start, iter_end, 1 do
if nodes_by_line[line] == node then
return line
end
end
return -1
end
---@param extmarks vim.api.keyset.get_extmark_item[] as per vim.api.nvim_buf_get_extmarks
---@return number
function M.extmarks_length(extmarks)
@ -127,6 +193,39 @@ function M.extmarks_length(extmarks)
return length
end
-- get the node in the tree state depending on the absolute path of the node
-- (grouped or hidden too)
---@param path string
---@return Node|nil
---@return number|nil
function M.get_node_from_path(path)
local explorer = require("nvim-tree.core").get_explorer()
-- tree may not yet be loaded
if not explorer then
return
end
if explorer.absolute_path == path then
return explorer
end
return Iterator.builder(explorer.nodes)
:hidden()
:matcher(function(node)
return node.absolute_path == path or node.link_to == path
end)
:recursor(function(node)
if node.group_next then
return { node.group_next }
end
if node.nodes then
return node.nodes
end
end)
:iterate()
end
M.default_format_hidden_count = function(hidden_count, simple)
local parts = {}
local total_count = 0
@ -147,6 +246,30 @@ M.default_format_hidden_count = function(hidden_count, simple)
return nil
end
--- Return visible nodes indexed by line
---@param nodes_all Node[]
---@param line_start number
---@return table
function M.get_nodes_by_line(nodes_all, line_start)
local nodes_by_line = {}
local line = line_start
Iterator.builder(nodes_all)
:applier(function(node)
if node.group_next then
return
end
nodes_by_line[line] = node
line = line + 1
end)
:recursor(function(node)
return node.group_next and { node.group_next } or (node.open and #node.nodes > 0 and node.nodes)
end)
:iterate()
return nodes_by_line
end
function M.rename_loaded_buffers(old_path, new_path)
-- delete new if it exists
for _, buf in pairs(vim.api.nvim_list_bufs()) do
@ -260,6 +383,54 @@ function M.escape_special_chars(path)
return M.is_windows and escape_special_char_for_windows(path) or path
end
--- Create empty sub-tables if not present
---@param tbl table to create empty inside of
---@param path string dot separated string of sub-tables
---@return table deepest sub-table
function M.table_create_missing(tbl, path)
local t = tbl
for s in string.gmatch(path, "([^%.]+)%.*") do
if t[s] == nil then
t[s] = {}
end
t = t[s]
end
return t
end
--- Move a value from src to dst if value is nil on dst.
--- Remove value from src
---@param src table to copy from
---@param src_path string dot separated string of sub-tables
---@param src_pos string value pos
---@param dst table to copy to
---@param dst_path string dot separated string of sub-tables, created when missing
---@param dst_pos string value pos
---@param remove boolean
function M.move_missing_val(src, src_path, src_pos, dst, dst_path, dst_pos, remove)
for pos in string.gmatch(src_path, "([^%.]+)%.*") do
if src[pos] and type(src[pos]) == "table" then
src = src[pos]
else
return
end
end
local src_val = src[src_pos]
if src_val == nil then
return
end
dst = M.table_create_missing(dst, dst_path)
if dst[dst_pos] == nil then
dst[dst_pos] = src_val
end
if remove then
src[src_pos] = nil
end
end
local function round(value)
-- Amount of digits to round to after floating point.
local digits = 2
@ -368,6 +539,38 @@ function M.debounce(context, timeout, callback)
end)
end
function M.focus_file(path)
local _, i = M.find_node(require("nvim-tree.core").get_explorer().nodes, function(node)
return node.absolute_path == path
end)
require("nvim-tree.view").set_cursor({ i + 1, 1 })
end
---Focus node passed as parameter if visible, otherwise focus first visible parent.
---If none of the parents is visible focus root.
---If node is nil do nothing.
---@param node Node? node to focus
function M.focus_node_or_parent(node)
local explorer = require("nvim-tree.core").get_explorer()
if explorer == nil then
return
end
while node do
local found_node, i = M.find_node(explorer.nodes, function(node_)
return node_.absolute_path == node.absolute_path
end)
if found_node or node.parent == nil then
require("nvim-tree.view").set_cursor({ i + 1, 1 })
break
end
node = node.parent
end
end
---@param path string
---@return integer|nil
---@return integer|nil
@ -455,32 +658,29 @@ function M.is_executable(absolute_path)
end
end
---List of all option info/values
---@param opts vim.api.keyset.option passed directly to vim.api.nvim_get_option_info2 and vim.api.nvim_get_option_value
---@param was_set boolean filter was_set
---@return { info: vim.api.keyset.get_option_info, val: any }[]
function M.enumerate_options(opts, was_set)
local res = {}
---@class UtilEnumerateOptionsOpts
---@field keyset_opts vim.api.keyset.option
---@field was_set boolean? as per vim.api.keyset.get_option_info
local infos = vim.tbl_filter(function(info)
if opts.buf and info.scope ~= "buf" then
return false
elseif opts.win and info.scope ~= "win" then
return false
---Option name/values
---@param opts UtilEnumerateOptionsOpts
---@return table<string, any>
function M.enumerate_options(opts)
-- enumerate all options, limiting buf and win scopes
return vim.tbl_map(function(info)
if opts.keyset_opts.buf and info.scope ~= "buf" then
return nil
elseif opts.keyset_opts.win and info.scope ~= "win" then
return nil
else
return true
-- optional, lazy was_set check
if not opts.was_set or vim.api.nvim_get_option_info2(info.name, opts.keyset_opts).was_set then
return vim.api.nvim_get_option_value(info.name, opts.keyset_opts)
else
return nil
end
end
end, vim.api.nvim_get_all_options_info())
for _, info in vim.spairs(infos) do
local _, info2 = pcall(vim.api.nvim_get_option_info2, info.name, opts)
if not was_set or info2.was_set then
local val = pcall(vim.api.nvim_get_option_value, info.name, opts)
table.insert(res, { info = info2, val = val })
end
end
return res
end
return M

View File

@ -1,60 +1,107 @@
local events = require("nvim-tree.events")
local utils = require("nvim-tree.utils")
local log = require("nvim-tree.log")
local notify = require("nvim-tree.notify")
---@class OpenInWinOpts
---@field hijack_current_buf boolean|nil default true
---@field resize boolean|nil default true
---@field winid number|nil 0 or nil for current
local M = {}
local DEFAULT_MIN_WIDTH = 30
local DEFAULT_MAX_WIDTH = -1
local DEFAULT_PADDING = 1
local BUFNR_PER_TAB = {}
local CURSORS = {}
local TABPAGES = {}
M.View = {
adaptive_size = false,
centralize_selection = false,
tabpages = {},
cursors = {},
hide_root_folder = false,
live_filter = {
prev_focused_node = nil,
},
winopts = {
relativenumber = false,
number = false,
list = false,
foldenable = false,
winfixwidth = true,
winfixheight = true,
spell = false,
signcolumn = "yes",
foldmethod = "manual",
foldcolumn = "0",
cursorcolumn = false,
cursorline = true,
cursorlineopt = "both",
colorcolumn = "0",
wrap = false,
winhl = table.concat({
"EndOfBuffer:NvimTreeEndOfBuffer",
"CursorLine:NvimTreeCursorLine",
"CursorLineNr:NvimTreeCursorLineNr",
"LineNr:NvimTreeLineNr",
"WinSeparator:NvimTreeWinSeparator",
"StatusLine:NvimTreeStatusLine",
"StatusLineNC:NvimTreeStatuslineNC",
"SignColumn:NvimTreeSignColumn",
"Normal:NvimTreeNormal",
"NormalNC:NvimTreeNormalNC",
"NormalFloat:NvimTreeNormalFloat",
"FloatBorder:NvimTreeNormalFloatBorder",
}, ","),
},
}
--- Debugging only.
--- Tabs show TABPAGES winnr and BUFNR_PER_TAB bufnr for the tab.
--- Orphans for inexistent tab_ids are shown at the right.
--- lib.target_winid is always shown at the right next to a close button.
--- Enable with:
--- vim.opt.tabline = "%!v:lua.require('nvim-tree.view').tab_line()"
--- vim.opt.showtabline = 2
function M.tab_line()
local tab_ids = vim.api.nvim_list_tabpages()
local cur_tab_id = vim.api.nvim_get_current_tabpage()
local bufnr_per_tab = vim.deepcopy(BUFNR_PER_TAB)
local tabpages = vim.deepcopy(TABPAGES)
local tl = "%#TabLine#"
for i, tab_id in ipairs(tab_ids) do
-- click to select
tl = tl .. "%" .. i .. "T"
-- style
if tab_id == cur_tab_id then
tl = tl .. "%#StatusLine#|"
else
tl = tl .. "|%#TabLine#"
end
-- tab_id itself
tl = tl .. " t" .. tab_id
-- winnr, if present
local tp = TABPAGES[tab_id]
if tp then
tl = tl .. " w" .. tp.winnr
else
tl = tl .. " "
end
-- bufnr, if present
local bpt = BUFNR_PER_TAB[tab_id]
if bpt then
tl = tl .. " b" .. bpt
else
tl = tl .. " "
end
tl = tl .. " "
-- remove actively mapped
bufnr_per_tab[tab_id] = nil
tabpages[tab_id] = nil
end
-- close last and reset
tl = tl .. "|%#CursorLine#%T"
-- collect orphans
local orphans = {}
for tab_id, bufnr in pairs(bufnr_per_tab) do
orphans[tab_id] = orphans[tab_id] or {}
orphans[tab_id].bufnr = bufnr
end
for tab_id, tp in pairs(tabpages) do
orphans[tab_id] = orphans[tab_id] or {}
orphans[tab_id].winnr = tp.winnr
end
-- right-align
tl = tl .. "%=%#TabLine#"
-- print orphans
for tab_id, orphan in pairs(orphans) do
-- inexistent tab
tl = tl .. "%#error#| t" .. tab_id
-- maybe winnr
if orphan.winnr then
tl = tl .. " w" .. orphan.winnr
else
tl = tl .. " "
end
-- maybe bufnr
if orphan.bufnr then
tl = tl .. " b" .. orphan.bufnr
else
tl = tl .. " "
end
tl = tl .. " "
end
-- target win id and close button
tl = tl .. "|%#TabLine# twi" .. (require("nvim-tree.lib").target_winid or "?") .. " %999X| X |"
return tl
end
-- The initial state of a tab
local tabinitial = {
@ -64,18 +111,6 @@ local tabinitial = {
winnr = nil,
}
local BUFNR_PER_TAB = {}
---@type { name: string, value: any }[]
local BUFFER_OPTIONS = {
{ name = "bufhidden", value = "wipe" },
{ name = "buflisted", value = false },
{ name = "buftype", value = "nofile" },
{ name = "filetype", value = "NvimTree" },
{ name = "modifiable", value = false },
{ name = "swapfile", value = false },
}
---@param bufnr integer
---@return boolean
local function matches_bufnr(bufnr)
@ -87,7 +122,7 @@ local function matches_bufnr(bufnr)
return false
end
local function wipe_rogue_buffer()
function M.wipe_rogue_buffer()
for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do
if not matches_bufnr(bufnr) and utils.is_nvim_tree_buf(bufnr) then
pcall(vim.api.nvim_buf_delete, bufnr, { force = true })
@ -96,345 +131,52 @@ local function wipe_rogue_buffer()
end
---@param bufnr integer|boolean|nil
local function create_buffer(bufnr)
wipe_rogue_buffer()
---@return integer tab
function M.create_buffer(bufnr)
local tab = vim.api.nvim_get_current_tabpage()
BUFNR_PER_TAB[tab] = bufnr or vim.api.nvim_create_buf(false, false)
vim.api.nvim_buf_set_name(M.get_bufnr(), "NvimTree_" .. tab)
bufnr = M.get_bufnr()
for _, option in ipairs(BUFFER_OPTIONS) do
vim.api.nvim_set_option_value(option.name, option.value, { buf = bufnr })
end
require("nvim-tree.keymap").on_attach(M.get_bufnr())
events._dispatch_tree_attached_post(M.get_bufnr())
return tab
end
---@param size (fun():integer)|integer|string
---@return integer
local function get_size(size)
if type(size) == "number" then
return size
elseif type(size) == "function" then
return get_size(size())
end
local size_as_number = tonumber(size:sub(0, -2))
local percent_as_decimal = size_as_number / 100
return math.floor(vim.o.columns * percent_as_decimal)
end
---@param size (fun():integer)|integer|nil
---@return integer
local function get_width(size)
if size then
return get_size(size)
else
return get_size(M.View.width)
end
end
local move_tbl = {
left = "H",
right = "L",
}
-- setup_tabpage sets up the initial state of a tab
---@param tabpage integer
local function setup_tabpage(tabpage)
function M.setup_tabpage(tabpage)
local winnr = vim.api.nvim_get_current_win()
M.View.tabpages[tabpage] = vim.tbl_extend("force", M.View.tabpages[tabpage] or tabinitial, { winnr = winnr })
end
local function set_window_options_and_buffer()
pcall(vim.api.nvim_command, "buffer " .. M.get_bufnr())
if vim.fn.has("nvim-0.10") == 1 then
local eventignore = vim.api.nvim_get_option_value("eventignore", {})
vim.api.nvim_set_option_value("eventignore", "all", {})
for k, v in pairs(M.View.winopts) do
vim.api.nvim_set_option_value(k, v, { scope = "local" })
end
vim.api.nvim_set_option_value("eventignore", eventignore, {})
else
local eventignore = vim.api.nvim_get_option("eventignore") ---@diagnostic disable-line: deprecated
vim.api.nvim_set_option("eventignore", "all") ---@diagnostic disable-line: deprecated
-- #3009 vim.api.nvim_win_set_option does not set local scope without explicit winid.
-- Revert to opt_local instead of propagating it through for just the 0.10 path.
for k, v in pairs(M.View.winopts) do
vim.opt_local[k] = v
end
vim.api.nvim_set_option("eventignore", eventignore) ---@diagnostic disable-line: deprecated
end
end
---@return table
local function open_win_config()
if type(M.View.float.open_win_config) == "function" then
return M.View.float.open_win_config()
else
return M.View.float.open_win_config
end
end
local function open_window()
if M.View.float.enable then
vim.api.nvim_open_win(0, true, open_win_config())
else
vim.api.nvim_command("vsp")
M.reposition_window()
end
setup_tabpage(vim.api.nvim_get_current_tabpage())
set_window_options_and_buffer()
end
---@param buf integer
---@return boolean
local function is_buf_displayed(buf)
return vim.api.nvim_buf_is_valid(buf) and vim.fn.buflisted(buf) == 1
end
---@return number|nil
local function get_alt_or_next_buf()
local alt_buf = vim.fn.bufnr("#")
if is_buf_displayed(alt_buf) then
return alt_buf
end
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if is_buf_displayed(buf) then
return buf
end
end
end
local function switch_buf_if_last_buf()
if #vim.api.nvim_list_wins() == 1 then
local buf = get_alt_or_next_buf()
if buf then
vim.cmd("sb" .. buf)
else
vim.cmd("new")
end
end
TABPAGES[tabpage] = vim.tbl_extend("force", TABPAGES[tabpage] or tabinitial, { winnr = winnr })
end
-- save_tab_state saves any state that should be preserved across redraws.
---@param tabnr integer
local function save_tab_state(tabnr)
function M.save_tab_state(tabnr)
local tabpage = tabnr or vim.api.nvim_get_current_tabpage()
M.View.cursors[tabpage] = vim.api.nvim_win_get_cursor(M.get_winnr(tabpage) or 0)
CURSORS[tabpage] = vim.api.nvim_win_get_cursor(M.get_winnr(tabpage) or 0)
end
---@param tabpage integer
local function close(tabpage)
if not M.is_visible({ tabpage = tabpage }) then
return
end
save_tab_state(tabpage)
switch_buf_if_last_buf()
local tree_win = M.get_winnr(tabpage)
local current_win = vim.api.nvim_get_current_win()
for _, win in pairs(vim.api.nvim_tabpage_list_wins(tabpage)) do
if vim.api.nvim_win_get_config(win).relative == "" then
local prev_win = vim.fn.winnr("#") -- this tab only
if tree_win == current_win and prev_win > 0 then
vim.api.nvim_set_current_win(vim.fn.win_getid(prev_win))
end
if vim.api.nvim_win_is_valid(tree_win or 0) then
local success, error = pcall(vim.api.nvim_win_close, tree_win or 0, true)
if not success then
notify.debug("Failed to close window: " .. error)
return
end
end
return
end
---@param fn fun(tabpage: integer)
function M.all_tabs_callback(fn)
for tabpage, _ in pairs(TABPAGES) do
fn(tabpage)
end
end
function M.close_this_tab_only()
close(vim.api.nvim_get_current_tabpage())
end
function M.close_all_tabs()
for tabpage, _ in pairs(M.View.tabpages) do
close(tabpage)
end
end
---@param tabpage integer|nil
function M.close(tabpage)
if M.View.tab.sync.close then
M.close_all_tabs()
elseif tabpage then
close(tabpage)
else
M.close_this_tab_only()
end
end
---@param options table|nil
function M.open(options)
if M.is_visible() then
return
end
local profile = log.profile_start("view open")
events._dispatch_on_tree_pre_open()
create_buffer()
open_window()
M.resize()
local opts = options or { focus_tree = true }
if not opts.focus_tree then
vim.cmd("wincmd p")
end
events._dispatch_on_tree_open()
log.profile_end(profile)
end
local function grow()
local starts_at = M.is_root_folder_visible(require("nvim-tree.core").get_cwd()) and 1 or 0
local lines = vim.api.nvim_buf_get_lines(M.get_bufnr(), starts_at, -1, false)
-- number of columns of right-padding to indicate end of path
local padding = get_size(M.View.padding)
-- account for sign/number columns etc.
local wininfo = vim.fn.getwininfo(M.get_winnr())
if type(wininfo) == "table" and type(wininfo[1]) == "table" then
padding = padding + wininfo[1].textoff
end
local resizing_width = M.View.initial_width - padding
local max_width
-- maybe bound max
if M.View.max_width == -1 then
max_width = -1
else
max_width = get_width(M.View.max_width) - padding
end
local ns_id = vim.api.nvim_get_namespaces()["NvimTreeExtmarks"]
for line_nr, l in pairs(lines) do
local count = vim.fn.strchars(l)
-- also add space for right-aligned icons
local extmarks = vim.api.nvim_buf_get_extmarks(M.get_bufnr(), ns_id, { line_nr, 0 }, { line_nr, -1 }, { details = true })
count = count + utils.extmarks_length(extmarks)
if resizing_width < count then
resizing_width = count
end
if M.View.adaptive_size and max_width >= 0 and resizing_width >= max_width then
resizing_width = max_width
break
end
end
M.resize(resizing_width + padding)
end
function M.grow_from_content()
if M.View.adaptive_size then
grow()
end
end
---@param size string|number|nil
function M.resize(size)
if M.View.float.enable and not M.View.adaptive_size then
-- if the floating windows's adaptive size is not desired, then the
-- float size should be defined in view.float.open_win_config
return
end
if type(size) == "string" then
size = vim.trim(size)
local first_char = size:sub(1, 1)
size = tonumber(size)
if first_char == "+" or first_char == "-" then
size = M.View.width + size
end
end
if type(size) == "number" and size <= 0 then
return
end
if size then
M.View.width = size
M.View.height = size
end
if not M.is_visible() then
return
end
local winnr = M.get_winnr() or 0
local new_size = get_width()
if new_size ~= vim.api.nvim_win_get_width(winnr) then
vim.api.nvim_win_set_width(winnr, new_size)
if not M.View.preserve_window_proportions then
vim.cmd(":wincmd =")
end
end
events._dispatch_on_tree_resize(new_size)
end
function M.reposition_window()
local move_to = move_tbl[M.View.side]
vim.api.nvim_command("wincmd " .. move_to)
M.resize()
end
local function set_current_win()
function M.set_current_win()
local current_tab = vim.api.nvim_get_current_tabpage()
M.View.tabpages[current_tab].winnr = vim.api.nvim_get_current_win()
end
---Open the tree in the a window
---@param opts OpenInWinOpts|nil
function M.open_in_win(opts)
opts = opts or { hijack_current_buf = true, resize = true }
events._dispatch_on_tree_pre_open()
if opts.winid and vim.api.nvim_win_is_valid(opts.winid) then
vim.api.nvim_set_current_win(opts.winid)
end
create_buffer(opts.hijack_current_buf and vim.api.nvim_get_current_buf())
setup_tabpage(vim.api.nvim_get_current_tabpage())
set_current_win()
set_window_options_and_buffer()
if opts.resize then
M.reposition_window()
M.resize()
end
events._dispatch_on_tree_open()
TABPAGES[current_tab].winnr = vim.api.nvim_get_current_win()
end
function M.abandon_current_window()
local tab = vim.api.nvim_get_current_tabpage()
BUFNR_PER_TAB[tab] = nil
if M.View.tabpages[tab] then
M.View.tabpages[tab].winnr = nil
if TABPAGES[tab] then
TABPAGES[tab].winnr = nil
end
end
function M.abandon_all_windows()
for tab, _ in pairs(vim.api.nvim_list_tabpages()) do
BUFNR_PER_TAB[tab] = nil
if M.View.tabpages[tab] then
M.View.tabpages[tab].winnr = nil
if TABPAGES[tab] then
TABPAGES[tab].winnr = nil
end
end
end
@ -443,15 +185,15 @@ end
---@return boolean
function M.is_visible(opts)
if opts and opts.tabpage then
if M.View.tabpages[opts.tabpage] == nil then
if TABPAGES[opts.tabpage] == nil then
return false
end
local winnr = M.View.tabpages[opts.tabpage].winnr
local winnr = TABPAGES[opts.tabpage].winnr
return winnr and vim.api.nvim_win_is_valid(winnr)
end
if opts and opts.any_tabpage then
for _, v in pairs(M.View.tabpages) do
for _, v in pairs(TABPAGES) do
if v.winnr and vim.api.nvim_win_is_valid(v.winnr) then
return true
end
@ -469,24 +211,6 @@ function M.set_cursor(opts)
end
end
---@param winnr number|nil
---@param open_if_closed boolean|nil
function M.focus(winnr, open_if_closed)
local wnr = winnr or M.get_winnr()
if vim.api.nvim_win_get_tabpage(wnr or 0) ~= vim.api.nvim_win_get_tabpage(0) then
M.close()
M.open()
wnr = M.get_winnr()
elseif open_if_closed and not M.is_visible() then
M.open()
end
if wnr then
vim.api.nvim_set_current_win(wnr)
end
end
--- Retrieve the winid of the open tree.
---@param opts ApiTreeWinIdOpts|nil
---@return number|nil winid unlike get_winnr(), this returns nil if the nvim-tree window is not visible
@ -505,7 +229,7 @@ end
--- Restores the state of a NvimTree window if it was initialized before.
function M.restore_tab_state()
local tabpage = vim.api.nvim_get_current_tabpage()
M.set_cursor(M.View.cursors[tabpage])
M.set_cursor(CURSORS[tabpage])
end
--- Returns the window number for nvim-tree within the tabpage specified
@ -513,7 +237,7 @@ end
---@return number|nil
function M.get_winnr(tabpage)
tabpage = tabpage or vim.api.nvim_get_current_tabpage()
local tabinfo = M.View.tabpages[tabpage]
local tabinfo = TABPAGES[tabpage]
if tabinfo and tabinfo.winnr and vim.api.nvim_win_is_valid(tabinfo.winnr) then
return tabinfo.winnr
end
@ -525,116 +249,14 @@ function M.get_bufnr()
return BUFNR_PER_TAB[vim.api.nvim_get_current_tabpage()]
end
function M._prevent_buffer_override()
local view_winnr = M.get_winnr()
local view_bufnr = M.get_bufnr()
-- need to schedule to let the new buffer populate the window
-- because this event needs to be run on bufWipeout.
-- Otherwise the curwin/curbuf would match the view buffer and the view window.
vim.schedule(function()
local curwin = vim.api.nvim_get_current_win()
local curwinconfig = vim.api.nvim_win_get_config(curwin)
local curbuf = vim.api.nvim_win_get_buf(curwin)
local bufname = vim.api.nvim_buf_get_name(curbuf)
if not bufname:match("NvimTree") then
for i, tabpage in ipairs(M.View.tabpages) do
if tabpage.winnr == view_winnr then
M.View.tabpages[i] = nil
break
end
end
---@param winnr number|nil
function M.clear_tabpage(winnr)
for i, tabpage in ipairs(TABPAGES) do
if tabpage.winnr == winnr then
TABPAGES[i] = nil
break
end
if curwin ~= view_winnr or bufname == "" or curbuf == view_bufnr then
return
end
-- patch to avoid the overriding window to be fixed in size
-- might need a better patch
vim.cmd("setlocal nowinfixwidth")
vim.cmd("setlocal nowinfixheight")
M.open({ focus_tree = false })
local explorer = require("nvim-tree.core").get_explorer()
if explorer then
explorer.renderer:draw()
end
pcall(vim.api.nvim_win_close, curwin, { force = true })
-- to handle opening a file using :e when nvim-tree is on floating mode
-- falling back to the current window instead of creating a new one
if curwinconfig.relative ~= "" then
require("nvim-tree.actions.node.open-file").fn("edit_in_place", bufname)
else
require("nvim-tree.actions.node.open-file").fn("edit", bufname)
end
end)
end
---@param cwd string|nil
---@return boolean
function M.is_root_folder_visible(cwd)
return cwd ~= "/" and not M.View.hide_root_folder
end
-- used on ColorScheme event
function M.reset_winhl()
local winnr = M.get_winnr()
if winnr and vim.api.nvim_win_is_valid(winnr) then
vim.wo[M.get_winnr()].winhl = M.View.winopts.winhl
end
end
---Check if width determined or calculated on-fly
---@return boolean
function M.is_width_determined()
return type(M.View.width) ~= "function"
end
---Configure width-related config
---@param width string|function|number|table|nil
function M.configure_width(width)
if type(width) == "table" then
M.View.adaptive_size = true
M.View.width = width.min or DEFAULT_MIN_WIDTH
M.View.max_width = width.max or DEFAULT_MAX_WIDTH
M.View.padding = width.padding or DEFAULT_PADDING
elseif width == nil then
if M.config.width ~= nil then
-- if we had input config - fallback to it
M.configure_width(M.config.width)
else
-- otherwise - restore initial width
M.View.width = M.View.initial_width
end
else
M.View.adaptive_size = false
M.View.width = width
end
end
function M.setup(opts)
local options = opts.view or {}
M.View.centralize_selection = options.centralize_selection
M.View.side = (options.side == "right") and "right" or "left"
M.View.height = options.height
M.View.hide_root_folder = opts.renderer.root_folder_label == false
M.View.tab = opts.tab
M.View.preserve_window_proportions = options.preserve_window_proportions
M.View.winopts.cursorline = options.cursorline
M.View.winopts.cursorlineopt = options.cursorlineopt
M.View.winopts.number = options.number
M.View.winopts.relativenumber = options.relativenumber
M.View.winopts.signcolumn = options.signcolumn
M.View.float = options.float
M.on_attach = opts.on_attach
M.config = options
M.configure_width(options.width)
M.View.initial_width = get_width()
end
return M