Skip to content

Instantly share code, notes, and snippets.

@transcendr
Created January 28, 2024 16:38
Show Gist options
  • Save transcendr/9e2afd5436945d175575d592a6a74b17 to your computer and use it in GitHub Desktop.
Save transcendr/9e2afd5436945d175575d592a6a74b17 to your computer and use it in GitHub Desktop.
Lua function to close hidden buffers in Neovim on buffer switch
-- Define the close_hidden_buffers function
local function close_hidden_buffers()
local curr_buf_num = vim.api.nvim_get_current_buf()
local all_buf_nums = vim.api.nvim_list_bufs()
for _, buf_num in ipairs(all_buf_nums) do
if buf_num ~= curr_buf_num and vim.api.nvim_buf_is_valid(buf_num) and vim.api.nvim_buf_is_loaded(buf_num) and vim.fn.bufwinnr(buf_num) == -1 then
if vim.fn.getbufvar(buf_num, '&buftype') ~= 'terminal' then
vim.api.nvim_buf_delete(buf_num, { force = true })
end
end
end
end
-- Set up the autocommand to run the function when switching buffers
vim.api.nvim_create_autocmd('BufLeave', {
callback = close_hidden_buffers
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment