emacs: is before-save-hook a local variable?

前端 未结 5 1400
陌清茗
陌清茗 2021-01-02 04:11

how would I figure this out?

I added delete-trailing-whitespace to the before-save-hook in my c-mode-common-hook, but it loo

5条回答
  •  耶瑟儿~
    2021-01-02 04:35

    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).

提交回复
热议问题