6

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?

Drew
  • 75,699
  • 9
  • 109
  • 225
HippoMan
  • 582
  • 2
  • 11

1 Answers1

4

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

phils
  • 48,657
  • 3
  • 76
  • 115
  • Thank you! I'm on 26.3, as I mentioned ... but I guess it's time for me to upgrade. :) – HippoMan Nov 28 '21 at 01:55
  • I managed to miss that, sorry. FWIW you can see the relevant part of the manual online at https://www.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 Nov 28 '21 at 03: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 Nov 28 '21 at 03:31
  • Well, I managed to upgrade fairly painlessly to 27.2, so all is well. Thank you again! – HippoMan Nov 28 '21 at 03: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 Nov 28 '21 at 03:40
  • Oh, excellent :) – phils Nov 28 '21 at 03:41