Skip to content
Alexander Courtis edited this page Nov 13, 2022 · 10 revisions

Background

A desirable feature is to close the tab/nvim when nvim-tree is the last window.

Unfortunately such functionality is problematic and is not present in nvim-tree:

  • vim events are the only mechanism we can use for auto close
  • vim events are unpredictably ordered, especially when other plugins and automation are involved
  • BufEnter is the last event that can be acted upon and that event can have side effects
  • Event nesting may be disabled by other plugins / automation, resulting in missing events

Naive Solution

This is a minimal viable solution that will achieve the auto close functionality.

vim.api.nvim_create_autocmd("BufEnter", {
  nested = true,
  callback = function()
    if #vim.api.nvim_list_wins() == 1 and require("nvim-tree.utils").is_nvim_tree_buf() then
      vim.cmd "quit"
    end
  end
})

It will likely fail for most complex nvim setups. Consider this a starting point.

You could adopt the complete solutions developed by users.

Source

vim.api.nvim_create_autocmd("BufEnter", {
  group = vim.api.nvim_create_augroup("NvimTreeClose", {clear = true}),
  pattern = "NvimTree_*",
  callback = function()
    local layout = vim.api.nvim_call_function("winlayout", {})
    if layout[1] == "leaf" and vim.api.nvim_buf_get_option(vim.api.nvim_win_get_buf(layout[2]), "filetype") == "NvimTree" and layout[3] == nil then vim.cmd("confirm quit") end
  end
})

Source

-- nvim-tree is also there in modified buffers so this function filter it out
local modifiedBufs = function(bufs)
    local t = 0
    for k,v in pairs(bufs) do
        if v.name:match("NvimTree_") == nil then
            t = t + 1
        end
    end
    return t
end

vim.api.nvim_create_autocmd("BufEnter", {
    nested = true,
    callback = function()
        if #vim.api.nvim_list_wins() == 1 and
        vim.api.nvim_buf_get_name(0):match("NvimTree_") ~= nil and
        modifiedBufs(vim.fn.getbufinfo({bufmodified = 1})) == 0 then
            vim.cmd "quit"
        end
    end
})
Clone this wiki locally