Skip to content

Commit

Permalink
fix(attach): detach on when the buffer name changes
Browse files Browse the repository at this point in the history
Fixes #1021
  • Loading branch information
lewis6991 committed May 29, 2024
1 parent af3fdad commit 75dc649
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
16 changes: 14 additions & 2 deletions lua/gitsigns.lua
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ local function setup_attach()

local attach_autocmd_disabled = false

api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'BufWritePost' }, {
-- Need to attach in 'BufFilePost' since we always detach in 'BufFilePre'
api.nvim_create_autocmd({ 'BufFilePost', 'BufRead', 'BufNewFile', 'BufWritePost' }, {
group = 'gitsigns',
desc = 'Gitsigns: attach',
callback = function(args)
local bufnr = args.buf --[[@as integer]]
if attach_autocmd_disabled then
Expand All @@ -142,11 +144,21 @@ local function setup_attach()
end,
})

-- If the buffer name is about to change, then detach
api.nvim_create_autocmd('BufFilePre', {
group = 'gitsigns',
desc = 'Gitsigns: detach when changing buffer names',
callback = function(args)
require('gitsigns.attach').detach(args.buf)
end,
})

--- vimpgrep creates and deletes lots of buffers so attaching to each one will
--- waste lots of resource and even slow down vimgrep.
--- waste lots of resource and slow down vimgrep.
api.nvim_create_autocmd({ 'QuickFixCmdPre', 'QuickFixCmdPost' }, {
group = 'gitsigns',
pattern = '*vimgrep*',
desc = 'Gitsigns: disable attach during vimgrep',
callback = function(args)
attach_autocmd_disabled = args.event == 'QuickFixCmdPre'
end,
Expand Down
9 changes: 9 additions & 0 deletions lua/gitsigns/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ function M.buf_rename(bufnr, name)
delete_alt(bufnr)
end

--- @param events string[]
--- @param f fun()
function M.noautocmd(events, f)
local ei = vim.o.eventignore
vim.o.eventignore = table.concat(events, ',')
f()
vim.o.eventignore = ei
end

--- @param bufnr integer
--- @param start_row integer
--- @param end_row integer
Expand Down
7 changes: 6 additions & 1 deletion lua/gitsigns/watcher.lua
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ local function handle_moved(bufnr, old_relpath)
local old_name = api.nvim_buf_get_name(bufnr)

if not bufexists then
util.buf_rename(bufnr, bcache.file)
-- Do not trigger BufFilePre/Post
-- TODO(lewis6991): figure out how to avoid reattaching without
-- disabling all autocommands.
util.noautocmd({ 'BufFilePre', 'BufFilePost' }, function()
util.buf_rename(bufnr, bcache.file)
end)
end

local msg = bufexists and 'Cannot rename' or 'Renamed'
Expand Down

0 comments on commit 75dc649

Please sign in to comment.