Elektito
Elektito

Reputation: 4155

Stop running a hook in certain Emacs modes

I have this line in my GNU Emacs configuration which cleans up white spaces when I save:

(add-hook 'before-save-hook 'whitespace-cleanup)

How can I keep this from running in certain modes (Makefile mode, for example)?

Upvotes: 1

Views: 254

Answers (1)

Jorgen Schäfer
Jorgen Schäfer

Reputation: 1216

The following definition will run whitespace-cleanup in modes except the ones given in the condition:

(defun elektito/whitespace-cleanup ()
  (when (not (derived-mode-p 'makefile-mode))
    (whitespace-cleanup)))

(add-hook 'before-save-hook 'elektito/whitespace-cleanup)

This uses derived-mode-p to check the current mode instead of direct comparison, as you mention makefiles, and makefiles use a large number of slightly different modes, all of which are derived from makefile-mode. derived-mode-p accepts multiple arguments to check for different parent modes.

(NB: It is possible to use (unless COND EXPR) instead of (when (not COND) EXPR), but I find that less readable; you might have different preferences.)

Upvotes: 3

Related Questions