Emacs: is before-save-hook a local variable

elispemacs

how would I figure this out?

I added delete-trailing-whitespace to the before-save-hook in my c-mode-common-hook, but it looks like delete-trailing-whitespace is getting called for every file, not just buffers using c-mode and derivatives.

Can I make the before-save-hook buffer local?

Best Solution

Add it to write-contents-functions instead:

(add-hook 'c-mode-common-hook
  (lambda()
    (add-hook 'write-contents-functions
      (lambda()
        (save-excursion
          (delete-trailing-whitespace)))
      nil t)))

As the Emacs Lisp Reference Manual explains:

This works just like write-file-functions, but it is intended for hooks that pertain to the buffer's contents, not to the particular visited file or its location. Such hooks are usually set up by major modes, as buffer-local bindings for this variable. This variable automatically becomes buffer-local whenever it is set; switching to a new major mode always resets this variable, but calling set-visited-file-name does not.

This works properly for me in Emacs 24.2.1 (i.e., it deletes all trailing whitespace from C files but preserves trailing whitespace in all other file types).

Related Question