Edit: with the latest versions of magit and git-gutter, this no longer requires so much configuration, see lunaryorns answer for a more up to date and simple solution.
Original Answer:
The switching window method might be a bit overkill since you'll be refreshing more than you need to be.
Magit does not offer before/after stage/unstage hooks, however we can make our own hooks using advice!
You can define two variables for your stage and unstage hooks.
(defvar my-magit-after-stage-hooks nil
"Hooks to be run after staging one item in magit.")
(defvar my-magit-after-unstage-hooks nil
"Hooks to be run after unstaging one item in magit.")
There is a nice wrapper function for running hooks: run-hooks
we will use function advice to run our custom hooks after magit-stage-item
and magit-unstage-item
(defadvice magit-stage-item (after run-my-after-stage-hooks activate)
"Run `my-magit-after-stage-hooks` after staging an item in magit."
(when (called-interactively-p 'interactive)
(run-hooks 'my-magit-after-stage-hooks)))
(defadvice magit-unstage-item (after run-my-after-unstage-hooks activate)
"Run `my-magit-after-unstage-hooks` after unstaging an item in magit."
(when (called-interactively-p 'interactive)
(run-hooks 'my-magit-after-unstage-hooks)))
For our hook we can just iterate over all the buffers, and refresh git-gutter when applicable because we don't know what is staged or unstaged. So We will just refresh the git-gutter display on all visible buffers that are running git-gutter-mode. (If you'd like to do all git-gutter buffers, just remove the get-buffer-window
call.)
(defun my-refresh-visible-git-gutter-buffers ()
"Refresh git-gutter-mode on all visible git-gutter-mode buffers."
(dolist (buff (buffer-list))
(with-current-buffer buff
(when (and git-gutter-mode (get-buffer-window buff))
(git-gutter-mode t)))))
Finally, just add your hook function to your custom hook!
(add-hook 'my-magit-after-unstage-hooks
'my-refresh-visible-git-gutter-buffers)
(add-hook 'my-magit-after-stage-hooks
'my-refresh-visible-git-gutter-buffers)
Ideally we would know what file(s) got staged/unstaged and only refresh those buffers, if you could use around advice on a deeper magit function and get the name of the magit status buffer item you are acting on and refresh only that. But this is a good start!