I am trying to execute when the active buffer has changed by either
- Changing the buffer in the current window (e.g.
C-x <left>
). - Switching to another window (
C-x o
). - Switching to another frame.
Are their hooks suitable for detecting this?
What I figured out so far
Looking through the Standard Hooks I found the following options, none of which quite do what I want:
buffer-list-update-hook
is called for both (1) and (2). It is however unsuitable, because it is run before the buffer is changed, while I want to know what thecurrent-buffer
after the change is.window-configuration-change-hook
can be used to detect a change of the buffer displayed in the current window, and it is run after the change, as needed. It is however not run forM-x other-window
.mouse-leave-buffer-hook
seems viable for detecting mouse-based window switching, but it gets called a bit often (for me four times upon switching windows with the mouse, three times before and once after switching), which requires additional logical to prevent multiple execution.post-command-hook
would be viable but a bit heavy handed, risking significant slow-down of the editor by even minor bugs.Since my action would need to use
with-selected-window
, which triggers these hooks, care has to be taken to avoid endless loops where the hook triggers itself.
pre-command-hook
and comparing that data to that which becomes avaialable when running thepost-command-hook
and then put in conditions in your function attached to the latter hook that either exit or continue processing to achieve the desired effect. I'm surprised thebuffer-list-update-hook
is insufficient with certain conditions attached, including, but not limited to using thepre-command-hook
to record the relevant data at the beginning of the command, but if you've already experimented and ....pre-command-hook
, you would be recording things like:(selected-window)
,this-command
,(selected-frame)
,(current-buffer)
. And, compare that result to the same inquiry on whichever hook you attach your custom function to -- e.g., using thepost-command-hook
orbuffer-list-update-hook
or .... Keep in mind thatthis-command
is short-lived, so you want to record it in a separate variable (probably global). Your conditions on the latter hook could compare the recordedthis-command
to a list of certain functions that justify taking further action.buffer-list-update-hook' does indeed become viable (e.g. by setting a flag, that tells
post-command-hook' that an action is necessary). Since I now also do some checks, when merely swichting lines, I need to use `post-command-hook' anyway. Seems like simpler hooks aren't available.window-state-change-hook
is what you want.