Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a hook to multiple Emacs modes at once?

Tags:

emacs

elisp

I was reading an article about well-formatted Git commits, and I was wondering how I could apply some of the rules to the Magit log mode.

It seems to use 3 major modes simultaneously: Magit, Log, Edit.

So how would I get just those modes, when used together, to hard-wrap at 72 characters automatically?

like image 794
Brad Wright Avatar asked Sep 13 '11 07:09

Brad Wright


3 Answers

In answer to the original stated question, if you have a single function to add to numerous hook variables, you could do it like this:

(defun my-add-to-multiple-hooks (function hooks)
  (mapc (lambda (hook)
          (add-hook hook function))
        hooks))

(defun my-turn-on-auto-fill ()
  (setq fill-column 72)
  (turn-on-auto-fill))

(my-add-to-multiple-hooks
 'my-turn-on-auto-fill
 '(text-mode-hook
   magit-log-edit-mode-hook
   change-log-mode-hook))

Not the best example, perhaps, but I have something similar for some common behaviours I want enabled in programming modes, of which there are a great many more to list.

like image 179
phils Avatar answered Nov 06 '22 22:11

phils


Emacs modes have "base modes" which is to say bade modes. For example python-mode extends prog-mode which itself extends fundamental-mode. All modes extend fundamental-mode. So to hook python-mode plus c-mode but not text-mode, you could hook prog-mode.

like image 45
Ross Patterson Avatar answered Nov 06 '22 21:11

Ross Patterson


There can be only one major mode in Emacs buffer (unless you are using something like MMM or MuMaMo). In your case that one major mode is magit-log-edit-mode, whose name consists of three words ("Magit Log Edit"). You can just add to it whatever hook you like:

(defun my-turn-on-auto-fill ()
  (setq fill-column 72)
  (turn-on-auto-fill))

(add-hook 'magit-log-edit-mode-hook 'my-turn-on-auto-fill)
like image 38
Victor Deryagin Avatar answered Nov 06 '22 22:11

Victor Deryagin