Ok, after some quality time with ChatGPT, the built-in and online docs, and Neovim itself here's what I came up with:
-- This is in my bufferline_setup.lua file
-- which is in my ~/nvim/lua/config folder
require("bufferline").setup {
options = {
indicator = {
style = 'underline'
},
separator_style = "slant",
show_buffer_icons = false
}
}
local this_module = {}
-- Function to close empty and unnamed buffers
function this_module.close_empty_unnamed_buffers()
-- Get a list of all buffers
local buffers = vim.api.nvim_list_bufs()
-- Iterate over each buffer
for _, bufnr in ipairs(buffers) do
-- Check if the buffer is empty and doesn't have a name
if vim.api.nvim_buf_is_loaded(bufnr) and vim.api.nvim_buf_get_name(bufnr) == '' and
vim.api.nvim_buf_get_option(bufnr, 'buftype') == '' then
-- Get all lines in the buffer
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
-- Initialize a variable to store the total number of characters
local total_characters = 0
-- Iterate over each line and calculate the number of characters
for _, line in ipairs(lines) do
total_characters = total_characters + #line
end
-- Close the buffer if it's empty:
if total_characters == 0 then
vim.api.nvim_buf_delete(bufnr, {
force = true
})
end
end
end
end
-- Clear the mandatory, empty, unnamed buffer when a real file is opened:
vim.api.nvim_command('autocmd BufReadPost * lua require("config.bufferline_setup").close_empty_unnamed_buffers()')
return this_module
This works well with :bdelete! and :%bdelete! (in the sense that it'll close buffers for me but won't quit out of nvim)
:help :ls
)