I'm running emacs 26.3. I want to run a hook every time I switch to a buffer. However, I have not been able to find any kind of "buffer switch hook".

If I want to always run a function when switching to a buffer, do I have to do something like wrapping switch-to-buffer with advice? Or is there some other way to accomplish this?

1 Answer 1


If you're using Emacs 27.1 or later, you can use:

C-hv window-selection-change-functions

Use add-hook with the LOCAL argument set a function for a specific buffer.

For more details see C-hig (elisp)Window Hooks

  • Thank you! I'm on 26.3, as I mentioned ... but I guess it's time for me to upgrade. :)
    – HippoMan
    Commented Nov 28, 2021 at 1:55
  • I managed to miss that, sorry. FWIW you can see the relevant part of the manual online at gnu.org/software/emacs/manual/html_node/elisp/Window-Hooks.html (which still doesn't help unless you upgrade, but in case you wanted to check those docs first).
    – phils
    Commented Nov 28, 2021 at 3:29
  • In 26.3, you could take a look at C-h v buffer-list-update-hook and see if you can carefully bend that to your purposes.
    – phils
    Commented Nov 28, 2021 at 3:31
  • Well, I managed to upgrade fairly painlessly to 27.2, so all is well. Thank you again!
    – HippoMan
    Commented Nov 28, 2021 at 3:35
  • If by "switch to a buffer" you only mean cases when the buffer gets displayed in a window in which it was not already displayed (i.e. a window configuration is going to change in some frame), then you can use a buffer-local window-configuration-change-hook in 26.3.
    – phils
    Commented Nov 28, 2021 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.