Fix: File deleted outside of Neovim doesn't change the buffer name to []:file removed. Now changes instantly after deletion.

This commit is contained in:
psychhim
2025-10-14 03:44:16 +05:30
parent 323949d48a
commit 8ff9e3fa9e

View File

@@ -10,35 +10,48 @@ local function should_skip(buf)
if not vim.api.nvim_buf_is_valid(buf) then
return true
end
local ft = vim.api.nvim_buf_get_option(buf, 'filetype')
local bufname = vim.api.nvim_buf_get_name(buf)
if bufname == '' then
local ft = vim.api.nvim_buf_get_option(buf, 'filetype')
local listed = vim.api.nvim_buf_get_option(buf, 'buflisted')
local modifiable = vim.api.nvim_buf_get_option(buf, 'modifiable')
-- Skip empty, unlisted, or unmodifiable buffers (usually floating windows)
if bufname == '' or not listed or not modifiable then
return true
end
-- Skip known plugin filetypes
for _, v in ipairs(skip_buffers) do
if ft == v or bufname:match(v) then
return true
end
end
return false
end
-- Detect deleted files and rename their buffers
vim.api.nvim_create_autocmd({ 'BufEnter', 'BufWritePost' }, {
callback = function()
local current_buf = vim.api.nvim_get_current_buf()
if should_skip(current_buf) then
return
end
local bufname = vim.api.nvim_buf_get_name(current_buf)
-- If this file no longer exists, mark all buffers showing it
if vim.fn.filereadable(bufname) == 0 then
local filename = vim.fn.fnamemodify(bufname, ':t')
local new_name = string.format('[%s]: file removed', filename)
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_is_valid(buf) then
local name = vim.api.nvim_buf_get_name(buf)
if name == bufname and not name:match 'file removed' then
local function rename_deleted_buffers()
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_is_valid(buf) and not should_skip(buf) then
local bufname = vim.api.nvim_buf_get_name(buf)
if bufname ~= '' and vim.fn.filereadable(bufname) == 0 then
local filename = vim.fn.fnamemodify(bufname, ':t')
local new_name = string.format('[%s]: file removed', filename)
-- Skip if already renamed
if not vim.api.nvim_buf_get_name(buf):match 'file removed' then
-- Ensure no other buffer already has this name
local exists = false
for _, b in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_is_valid(b) and vim.api.nvim_buf_get_name(b) == new_name then
exists = true
break
end
end
if not exists then
-- Temporarily unlist so renaming works cleanly
vim.api.nvim_buf_set_option(buf, 'buflisted', false)
vim.api.nvim_buf_set_name(buf, new_name)
@@ -47,6 +60,19 @@ vim.api.nvim_create_autocmd({ 'BufEnter', 'BufWritePost' }, {
end
end
end
end
end
-- Trigger both on focus and buffer entry
vim.api.nvim_create_autocmd({ 'FocusGained', 'BufEnter' }, {
callback = function()
local buf = vim.api.nvim_get_current_buf()
if should_skip(buf) then
return
end
-- Force Neovim to check external changes
vim.cmd 'checktime'
rename_deleted_buffers()
end,
})