How can I delete-trailing-whitespace when saving, except for certain modes? With this attempt, whitespace is deleted for all modes, including fundamental-mode, which I'm trying to avoid.

(add-hook 'before-save-hook
             (when '(not fundamental-mode))
(add-hook 'before-save-hook
          (when '(not fundamental-mode))

You are not passing a function as the second arg to add-hook. You are passing the symbol delete-trailing-whitespace, systematically.

add-hook is a function, so all of its args are evaluated before it does its thing (using their values). The value of the sexp you passed as its second arg is the symbol delete-trailing-whitespace, because the arg to when is a non-nil list (because you quoted it). So the when condition is always true.

And you never invoke function delete-trailing-whitespace; you just return the symbol that names that function.

You need to pass a function to add-hook. Something like this:

(add-hook 'before-save-hook
          (lambda ()
            (unless (eq major-mode 'fundamental-mode)

But are you sure that you want to do that for every possible mode other than fundamental-mode? If not, consider checking major-mode against a whitelist or a blacklist of modes.

And consider using derived-mode-p to test modes - it is typically more appropriate than testing them using eq.

  • Very good answer! I realise I really must sit down some day and try to learn the fascinating relic of another realm that is (Emacs) Lisp. Another user mentioned something about derived-mode-p not being straight-forward to use. Do you have an example of how you would set it up? (I do think I would like to use delete-trailing-whitespace for almost all files, except a certain file type which I've set to fundamental-mode). – forthrin Mar 31 '18 at 17:40
  • (defun diredp-hide-details-if-dired () "In Dired mode hide details. Outside Dired, do nothing." (when (derived-mode-p 'dired-mode) (dired-hide-details-mode 1))) The point is that eq a mode does not allow for very similar modes that are just derived from that mode. In most cases, you want derived-mode-p, to treat derived modes the same way as the mode they're derived from. – Drew Mar 31 '18 at 19:02
  • OK, this deletes whitespace while in hexl-mode which is definitely not desirable. How do I turn this off? (unless (eq major-mode '(fundamental-mode hexl-mode)) did not work. – forthrin Apr 10 '18 at 12:46
  • Do yourself a favor and read a bit in the Intro to Emacs Lisp manual (C-h i. You are trying to test equality (eq) between a symbol (the value of major-mode and a list ((fundamental-mode hexl-mode)). – Drew Apr 10 '18 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.