88
88
89
89
function M .open (cwd )
90
90
cwd = cwd ~= " " and cwd or nil
91
+ vim .g .nvim_tree_tab_open = 1
91
92
if view .is_visible () then
92
93
lib .set_target_win ()
93
94
view .focus ()
@@ -120,7 +121,7 @@ function M.open_replacing_current_buffer(cwd)
120
121
end
121
122
122
123
function M .tab_change ()
123
- if view . is_visible { any_tabpage = true } then
124
+ if vim . g . nvim_tree_tab_open == 1 then
124
125
local bufname = api .nvim_buf_get_name (0 )
125
126
local ft = api .nvim_buf_get_option (0 , " ft" )
126
127
for _ , filter in ipairs (M .config .ignore_buf_on_tab_change ) do
@@ -130,6 +131,33 @@ function M.tab_change()
130
131
end
131
132
view .open { focus_tree = false }
132
133
require (" nvim-tree.renderer" ).draw ()
134
+ else
135
+ view .close ()
136
+ end
137
+ end
138
+
139
+ function M .tab_win_closed (winnr )
140
+ local tabnr = vim .api .nvim_win_get_tabpage (winnr )
141
+ local bufnr = vim .api .nvim_win_get_buf (winnr )
142
+ local buf_info = vim .fn .getbufinfo (bufnr )[1 ]
143
+ local tab_wins = vim .tbl_filter (function (w ) return w ~= winnr end , vim .api .nvim_tabpage_list_wins (tabnr ))
144
+ local tab_bufs = vim .tbl_map (vim .api .nvim_win_get_buf , tab_wins )
145
+ if buf_info .name :match (" .*NvimTree_%d*$" ) then -- close buffer was nvim tree
146
+ if not vim .tbl_isempty (tab_bufs ) then -- and was not the last window (closed automatically)
147
+ vim .g .nvim_tree_tab_open = 0 -- NOTE: this also catches a lot of cases where nvim tree was already closed.
148
+ end
149
+ else -- closed buffer was normal buffer
150
+ if # tab_bufs == 1 then -- if there is only 1 buffer left
151
+ local last_buf_info = vim .fn .getbufinfo (tab_bufs [1 ])[1 ]
152
+ if last_buf_info .name :match (" .*NvimTree_%d*$" ) then -- and that buffer is nvim tree
153
+ vim .schedule (function ()
154
+ if # vim .api .nvim_list_wins () == 1 then
155
+ vim .cmd " quit"
156
+ end
157
+ vim .api .nvim_win_close (tab_wins [1 ], true ) -- then close that window
158
+ end )
159
+ end
160
+ end
133
161
end
134
162
end
135
163
@@ -365,6 +393,11 @@ local function setup_autocommands(opts)
365
393
366
394
if opts .open_on_tab then
367
395
create_nvim_tree_autocmd (" TabEnter" , { callback = vim .schedule_wrap (M .tab_change ) })
396
+ create_nvim_tree_autocmd (" WinClosed" , { callback = function ()
397
+ local winnr = tonumber (vim .fn .expand (" <amatch>" ))
398
+ vim .schedule_wrap (M .tab_win_closed (winnr ))
399
+ end
400
+ })
368
401
end
369
402
if opts .hijack_cursor then
370
403
create_nvim_tree_autocmd (" CursorMoved" , {
@@ -741,6 +774,8 @@ function M.setup(conf)
741
774
742
775
manage_netrw (opts .disable_netrw , opts .hijack_netrw )
743
776
777
+ vim .g .nvim_tree_tab_open = 0
778
+
744
779
M .config = opts
745
780
require (" nvim-tree.log" ).setup (opts )
746
781
0 commit comments