Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an Emacs hook that runs after every buffer is created?

Tags:

I'm looking to run some code every time Emacs creates a buffer. Is there a hook for this? Something with a name like after-make-buffer-functions?

Edit: If anyone wants to know what I wanted this for, you can read the relevant portion of my Emacs config here: https://github.com/DarwinAwardWinner/dotemacs/blob/master/site-lisp/settings/tempbuf-settings.el

Basically, I want tempbuf-mode to be enabled in all buffers with certain major modes. So Lindydancer's answer is actually more appropriate than what I was originally looking for.

I know that I could already enable tempbuf-mode in specific modes by adding the tempbuf mode hook to all of those major mode hooks, but I wanted to make it editable through M-x customize, and this was the easiest way.

like image 494
Ryan C. Thompson Avatar asked Oct 26 '11 07:10

Ryan C. Thompson


2 Answers

Unfortunately, no. Emacs use the low-level function ´get-buffer-create´ to create buffers, and it does not provide any hook mechanism.

You could use advice to pick-up all calls to this function, even though I would not recommend this method as it is quite intrusive. (Update: The advice hook will only see calls from elisp, not calls from the Emacs C core parts.)

There are some alternatives which you could use, depending on what you are implementing:

  • change-major-mode-hook -- called before a major mode change.
  • after-change-major-mode-hook -- called when the major mode is beginning to change.
like image 59
Lindydancer Avatar answered Sep 28 '22 07:09

Lindydancer


You can use buffer-list-update-hook

buffer-list-update-hook

This is a normal hook run whenever the buffer list changes

You can define a function to do whatever you want.

 (defun awesome-foo ()
     ;;  do awesome things
   )

Hook that function to buffer list hook

 (add-hook 'buffer-list-update-hook 'awesome-foo)
like image 24
Pandikunta Anand Reddy Avatar answered Sep 28 '22 05:09

Pandikunta Anand Reddy