[emacs-berlin] Understanding hooks
jman
emacs-berlin at city17.xyz
Mon Sep 9 14:05:52 UTC 2024
Hi everyone!
Lately I've looked a bit into how hooks work. Using them seems quite straightforwarded; I have some
high-level questions, though, that I cannot figure out by myself, nor The Emacs manual does a good
job at answering.
Is adding hooks /per se/ something that slows emacs down? What is the runtime cost of a hook? Are
there hooks that are on "hot paths" and therefore better not adding additional processing there? For
example, I have a few hooks triggered when switching major-mode:
(add-hook 'prog-mode-hook (lambda () (display-line-numbers-mode 1)))
(add-hook 'text-mode-hook (lambda () (display-line-numbers-mode 1)))
These ensures that line numbers are displayed in all text- and prog- major modes (and
derivatives). I assume these are pretty harmless, correct?
I am working on adding a bit more invasive hooks, like "run a function when saving a buffer, but
only in a specific major-mode (and derivatives)". This came from an insightful comment[0] from
Tassilo Horn in the mu4e issue tracker:
----------s---------s----------
(defun remove-before-save-hook ()
(remove-hook 'before-save-hook 'whitespace-cleanup))
(defun add-before-save-hook ()
(add-hook 'before-save-hook 'whitespace-cleanup))
;; Do not run `whitespace-cleanup` when saving a buffer in message-mode (and derivatives)
(add-hook 'message-mode-hook 'remove-before-save-hook)
;; Run whitespace-cleanup when saving buffers only on text- and prog- major modes
(add-hook 'prog-mode-hook 'add-before-save-hook)
(add-hook 'text-mode-hook 'add-before-save-hook)
----------e---------e----------
Does anybody see an obvious code smell?
Another approach I thought was to plug something to `after-change-major-mode-hook` but I suspect it
would add unnecessary runtime cost.
Another question is: is there a way to "benchmark" how a hook is affecting runtime Emacs
performances? Maybe with `profiler-{start,stop}`?
Thanks for any comment and suggestions!
[0]: https://github.com/djcb/mu/issues/2714#issuecomment-2328996352
More information about the emacs-berlin
mailing list