Skip to main content

Emacs: Dynamic buffer-local fringes

Emacs has a global fringe-mode for fringes, which I always keep disabled as it takes a bit of space in the frame and I like to start typing the first character on a line to the very left. But there are some cases where fringes are quite useful e.g. when flycheck shows different checker warnings/errors in code, it uses fringes (if enabled) to have a nice arrow to indicate the line(s) with the warnings/errors -- great to have a quick glance at everything.

I found the following workflow works for me the best:

  • keep global fringe-mode disabled
  • when flycheck minor mode in enabled in a buffer, enable fringes temporarily in that buffer for any warnings/errors; when there's no warning/error, disable fringes again

To keep the fringe-mode disabled globally, only the following is needed in the emacs init file:

(fringe-mode -1)

Now, for the tricky part of enabling-disabling fringes dynamically/on-demand for flycheck, I've come up with the following elisp function, which is to be applied as an advice around (keyword :around) the call to the flycheck-finish-current-syntax-check function (which does the actual syntax checking in flycheck using configured checkers):

(defun local-flycheck-auto-manage-fringe-advice (oldfunc &rest args)
  "Enable fringes dynamically when `flycheck' checks for syntax in the current buffer."

  (when (or (not left-fringe-width) (<= left-fringe-width 0))
    (setq left-fringe-width 10
      right-fringe-width 0)
    (flycheck-refresh-fringes-and-margins))

  (apply oldfunc args)

  (unless flycheck-current-errors
    (setq left-fringe-width 0
      right-fringe-width 0)
    (flycheck-refresh-fringes-and-margins)))

The above uses the buffer-local left-fringe-width and right-fringe-width variables to set the fringe widths.

Now, just adding the above as an advice would suffice:

(advice-add #'flycheck-finish-current-syntax-check :around #'local-flycheck-auto-manage-fringe-advice)

As mentioned earlier, our advice function (local-flycheck-auto-manage-fringe-advice) is added :around the call to the flycheck's target function flycheck-finish-current-syntax-check; so the expression (apply oldfunc args) in our advice function actually does the flycheck-finish-current-syntax-check call.

As usual, the above should go in the emacs init file.


References:

  1. Fringes
  2. Flycheck
  3. Advice
  4. flycheck-finish-current-syntax-check
  5. left-fringe-width/right-fringe-width
  6. Init file

Comments

Comments powered by Disqus