rvf0068
rvf0068

Reputation: 1389

Add several functions as hooks in Emacs

How could I simplify something like the following code in my init.el file?

(add-hook 'org-mode-hook 'turn-on-auto-revert-mode)
(add-hook 'org-mode-hook 'turn-on-org-cdlatex)
(add-hook 'org-mode-hook 'smartparens-mode)
(add-hook 'org-mode-hook 'abbrev-mode)

I have several other rows like this, including some lambda functions added to org-mode-hook...

Upvotes: 3

Views: 1059

Answers (3)

Triavanicus
Triavanicus

Reputation: 41

This is kinda a combination of the other two answers, which creates a re-usable function, to compress the later semantics down for other hooks in the future.

(defun add-hooks (hooked hooks)
  (dolist (fn hooks) (add-hook hooked fn)))

(add-hooks 'org-mode-hook '(turn-on-auto-revert-mode
                            turn-on-org-cdlatex
                            smartparens-mode
                            abbrev-mode))

Upvotes: 1

user355252
user355252

Reputation:

I use a simple dolist:

(dolist (fn '(turn-on-auto-revert-mode
              turn-on-org-cdlatex
              smartparens-mode
              abbrev-mode))
  (add-hook 'org-mode-hook fn))

This let's you still remove individual hooks afterwards, with remove-hook or from the customize interface.

Upvotes: 4

Lindydancer
Lindydancer

Reputation: 26094

Personally, I would strongly advice against adding lambda functions to hooks. The main reason is that if you change the content and reevaluate the add-hook expression, the hook contains both the old and new lambda expression. The second reason is that it looks bad when you inspect a hook -- it's better to see a function name compared to a large lambda expression.

Instead, I would suggest using:

(defun my-org-mode-hook ()
  (turn-on-auto-revert-mode)
  (turn-on-org-cdlatex)
  (smartparens-mode 1)
  (abbrev-mode 1)))
(add-hook 'org-mode-hook 'my-org-mode-hook)

A side note: You can use global-auto-revert-mode to enable auto-revert on all buffers, that way you don't have to enable it for all major modes.

Upvotes: 12

Related Questions