airblade/vim-gitgutter

Gitgutter fails to open preview window in some case

swnakamura opened this issue · 3 comments

What is the latest commit SHA in your installed vim-gitgutter?
edb607c
What vim/nvim version are you on?
edb607c

Problem Description
When I try to view hunk preview in floating window with GitGutterPreviewHunk, sometimes I get

Error detected while processing function gitgutter#hunk#preview[3]..<SNR>101_hunk_op[63]..<SNR>101_preview[5]..<SNR>101_open_hunk_preview_window:                                     
line   12:                                                                                                                                                                            
E5555: API call: Vim:E95: Buffer with this name already exists                                                                                                                        

error.
This happens probably because the old hunk preview window remains when gitgutter tries to rename the new one. Gitgutter deletes old preview window by

autocmd CursorMoved <buffer> ++once call gitgutter#hunk#close_hunk_preview_window()

but in my use case, this is not triggered. Here's why:

How to reproduce the problem

  1. nmap <Space>hp <Plug>(GitGutterPreviewHunk) . This is a handy mapping I use, which shows preview but without moving the cursor
  2. Prepare two tabs, each having a window with a hunk. Move the cursor within the hunk in both of the window.
  3. <Space>hp to show the first preview window
  4. gt to move to the other tab
  5. Do<Space>hp again to show the second

From 3. to 5., Cursor movement doesn't happen and the autocmd is not triggered, hence the error above.

How to solve the problem
I could fix this by simply triggering the autocmd in TabLeave too.

diff --git a/autoload/gitgutter/hunk.vim b/autoload/gitgutter/hunk.vim
index 8bf0100..87719b8 100644
--- a/autoload/gitgutter/hunk.vim
+++ b/autoload/gitgutter/hunk.vim
@@ -436,7 +436,7 @@ function! s:open_hunk_preview_window()
       call nvim_buf_set_name(buf, 'gitgutter://hunk-preview')
 
       " Assumes cursor is in original window.
-      autocmd CursorMoved <buffer> ++once call gitgutter#hunk#close_hunk_preview_window()
+      autocmd CursorMoved,TabLeave <buffer> ++once call gitgutter#hunk#close_hunk_preview_window()
 
       if g:gitgutter_close_preview_on_escape
         " Map <Esc> to close the floating preview.

(Maybe there's a better solution...)

Thanks for fixing a problem I wasn't even aware of! Your solution looks good to me.

Do you want to send a pull request or should I just update the code?

Thank you for quick response! Made a PR: #853