refactor: only create BufAdd autocmd when default_file_explorer is true

Problem: the BufAdd autocmd that hijacks directory buffers was always
created, even when default_file_explorer was false. The guard inside
maybe_hijack_directory_buffer made it a no-op, but the autocmd still
fired on every BufAdd event.

Solution: wrap the BufAdd autocmd creation and initial buffer hijack
in a config.default_file_explorer conditional. The guard inside
maybe_hijack_directory_buffer is kept as defense-in-depth.

Based on: stevearc/oil.nvim#720
This commit is contained in:
Barrett Ruth 2026-02-20 16:26:24 -05:00
parent 723145c9fb
commit 2228f80196

View file

@ -1397,15 +1397,6 @@ M.setup = function(opts)
vim.w.oil_original_alternate = vim.w[parent_win].oil_original_alternate vim.w.oil_original_alternate = vim.w[parent_win].oil_original_alternate
end, end,
}) })
vim.api.nvim_create_autocmd("BufAdd", {
desc = "Detect directory buffer and open oil file browser",
group = aug,
pattern = "*",
nested = true,
callback = function(params)
maybe_hijack_directory_buffer(params.buf)
end,
})
-- mksession doesn't save oil buffers in a useful way. We have to manually load them after a -- mksession doesn't save oil buffers in a useful way. We have to manually load them after a
-- session finishes loading. See https://github.com/stevearc/oil.nvim/issues/29 -- session finishes loading. See https://github.com/stevearc/oil.nvim/issues/29
vim.api.nvim_create_autocmd("SessionLoadPost", { vim.api.nvim_create_autocmd("SessionLoadPost", {
@ -1424,11 +1415,21 @@ M.setup = function(opts)
end, end,
}) })
local bufnr = vim.api.nvim_get_current_buf() if config.default_file_explorer then
if maybe_hijack_directory_buffer(bufnr) and vim.v.vim_did_enter == 1 then vim.api.nvim_create_autocmd("BufAdd", {
-- manually call load on a hijacked directory buffer if vim has already entered desc = "Detect directory buffer and open oil file browser",
-- (the BufReadCmd will not trigger) group = aug,
M.load_oil_buffer(bufnr) pattern = "*",
nested = true,
callback = function(params)
maybe_hijack_directory_buffer(params.buf)
end,
})
local bufnr = vim.api.nvim_get_current_buf()
if maybe_hijack_directory_buffer(bufnr) and vim.v.vim_did_enter == 1 then
M.load_oil_buffer(bufnr)
end
end end
end end