Skip to content

Interaction with git gutters

Ellis Kenyő edited this page Sep 11, 2022 · 1 revision

There are a number of packages that add icons to the fringe on the side of a buffer to indicate that there are changes in the buffer one way or another.

However, by default because of the order in which the various hooks and such are triggered; these can fail to be updated after a buffer is modified using apheleia. (See a discussion here)

See an example below on how to resolve for git-gutter.el (similar solutions apply to other packages)

(remove-hook 'post-command-hook #'git-gutter:post-command-hook)
(advice-remove #'quit-window #'git-gutter:quit-window)
(advice-remove #'switch-to-buffer #'git-gutter:switch-to-buffer)

(defvar git-gutter-last-buffer-and-window nil
  "Cons of current buffer and selected window before last command.
This is used to detect when the current buffer or selected window
changes, which means that `git-gutter' needs to be re-run.")

(defun git-gutter--on-buffer-or-window-change ()
    "Update `git-gutter' when current buffer or selected window changes."
    (let ((new (cons (current-buffer) (selected-window))))
      (unless (equal new git-gutter-last-buffer-and-window)
        (setq git-gutter-last-buffer-and-window new)
        ;; Sometimes the current buffer has not gotten updated yet
        ;; after switching window, for example after `quit-window'.
        (with-current-buffer (window-buffer)
          (when git-gutter-mode
            (when buffer-file-name
              (unless (file-remote-p buffer-file-name)
                (git-gutter))))))))

(defun git-gutter--init-maybe ()
  (when (and (buffer-file-name (buffer-base-buffer))
             (file-remote-p buffer-file-name)
             (bound-and-true-p git-gutter-mode))
    (git-gutter-mode)))

(add-hook 'post-command-hook #'git-gutter--on-buffer-or-window-change)
(add-hook 'apheleia-post-format-hook #'git-gutter--on-buffer-or-window-change)
Clone this wiki locally