@@ -66,17 +66,52 @@ M.View = {
66
66
}
67
67
}
68
68
69
+ --- Find a rogue NvimTree buffer that might have been spawned by i.e. a session.
70
+ --- @return integer | nil
71
+ local function find_rogue_buffer ()
72
+ for i = 1 , vim .fn .bufnr (" $" ), 1 do
73
+ if vim .fn .bufname (i ) == " NvimTree" then
74
+ return i
75
+ end
76
+ end
77
+ return nil
78
+ end
79
+
80
+ --- Check if the tree buffer is valid and loaded.
81
+ --- @return boolean
82
+ local function is_buf_valid ()
83
+ return a .nvim_buf_is_valid (M .View .bufnr ) and a .nvim_buf_is_loaded (M .View .bufnr )
84
+ end
85
+
86
+ --- Find pre-existing NvimTree buffer, delete its windows then wipe it.
87
+ --- @private
88
+ function M ._wipe_rogue_buffer ()
89
+ local bn = find_rogue_buffer ()
90
+ if bn then
91
+ local win_ids = vim .fn .win_findbuf (bn )
92
+ for _ , id in ipairs (win_ids ) do
93
+ a .nvim_win_close (id , true )
94
+ end
95
+ a .nvim_buf_delete (bn , {})
96
+ end
97
+ end
98
+
69
99
-- set user options and create tree buffer (should never be wiped)
70
100
function M .setup ()
71
101
M .View .auto_resize = vim .g .nvim_tree_auto_resize or M .View .auto_resize
72
102
M .View .side = vim .g .nvim_tree_side or M .View .side
73
103
M .View .width = vim .g .nvim_tree_width or M .View .width
74
104
75
105
M .View .bufnr = a .nvim_create_buf (false , false )
106
+
107
+ if not pcall (a .nvim_buf_set_name , M .View .bufnr , ' NvimTree' ) then
108
+ M ._wipe_rogue_buffer ()
109
+ a .nvim_buf_set_name (M .View .bufnr , ' NvimTree' )
110
+ end
111
+
76
112
for k , v in pairs (M .View .bufopts ) do
77
113
a .nvim_buf_set_option (M .View .bufnr , k , v )
78
114
end
79
- a .nvim_buf_set_name (M .View .bufnr , ' NvimTree' )
80
115
81
116
if not vim .g .nvim_tree_disable_keybindings then
82
117
M .View .bindings = vim .tbl_extend (
@@ -130,6 +165,10 @@ local move_tbl = {
130
165
}
131
166
132
167
function M .open ()
168
+ if not is_buf_valid () then
169
+ M .setup ()
170
+ end
171
+
133
172
a .nvim_command (" vsp" )
134
173
local move_to = move_tbl [M .View .side ]
135
174
a .nvim_command (" wincmd " .. move_to )
0 commit comments