我应该如何解决这个问题?
我在我的中添加了delete-trailing-whitespace
到before-save-hook
,但是似乎delete-trailing-whitespace
被调用了所有文件,而不仅仅是使用c-mode和衍生模式的缓冲区。
我能让before-save-hook
局部于缓冲区吗?
将其添加到write-contents-functions
中:
(add-hook 'c-mode-common-hook
(lambda()
(add-hook 'write-contents-functions
(lambda()
(save-excursion
(delete-trailing-whitespace)))
nil t)))
add-hook
的local
参数来指定您想要全局添加函数还是缓冲区本地添加函数。自Emacs-22.1以来,local-write-file-hooks
已经过时,write-file-hooks
也已经过时(被write-file-functions
替换),因此您可能需要更新参考手册。 - Stefanbefore-save-hook
并非自然缓冲区本地。该变量的文档没有说明它是缓冲区本地的,也没有说在设置时会自动变成缓冲区本地。add-hook
函数的可选LOCAL参数:(add-hook 'before-save-hook 'foo nil t)
LOCAL
参数的一个错误。你看,使用非nil的LOCAL
调用会创建新的空变量,然后将其添加到您的钩子中。也就是说,如果您有任何其他钩子,它们将在缓冲区中消失。因此,您可能希望使用make-local-variable
,然后使用普通的add-hook
而不带任何其他参数。 - Hi-Angel以前从未想过要这样做,但这应该可以起作用:
(set (make-local-variable 'before-save-hook) '((lambda() (rg-msg "foobie"))))
一般情况下,输入C-h v将提示输入变量名,并显示描述,告诉您该变量是否为缓冲区本地变量。
before-save-hook是一个在`files.el'中定义的变量。它的值为nil。
当作为文件本地变量使用时,此变量具有潜在风险。
文档:在将缓冲区保存到其文件之前运行的常规钩子。
您可以自定义此变量。
对比:
next-error-function是一个在`simple.el'中定义的变量。它的值为nil。
当以任何方式设置时,会自动变成缓冲区本地变量。当作为文件本地变量使用时,此变量具有潜在风险。
文档:用于查找当前缓冲区中的下一个错误的函数。该函数使用2个参数调用:
[...]
make-local-variable
将钩子变量设为缓冲区局部变量。相反,使用add-hook
并为LOCAL参数指定t
。” - philsmake-local-variable
函数对于钩子的弃用可以追溯到 Emacs-21。 - Stefan是的,在您的项目根目录中创建一个.dir-locals.el
文件,并将其内容设置为以下内容:
((c-mode . ((before-save-hook . (lambda() (delete-trailing-whitespace)) )) ))
这将仅将此钩子添加到该目录下的c-mode
缓冲区。
但是如果您只想要一个特定的文件而不是整个目录,则应该能够使用文件本地变量将其添加到文件顶部:
-*- eval: (setq before-save-hook (lambda() (delete-trailing-whitespace))); -*-
;;; Local Variables: ***
;;; eval: (setq before-save-hook (lambda() (delete-trailing-whitespace))) ***
;;; End: ***
write-contents-function
代替:write-contents-functions is a variable defined in `files.el'.
Its value is nil
Automatically becomes buffer-local when set in any fashion.
Documentation:
List of functions to be called before writing out a buffer to a file.
If one of them returns non-nil, the file is considered already written
and the rest are not called and neither are the functions in
`write-file-functions'.
This variable is meant to be used for hooks that pertain to the
buffer's contents, not to the particular visited file; thus,
`set-visited-file-name' does not clear this variable; but changing the
major mode does clear it.
For hooks that _do_ pertain to the particular visited file, use
`write-file-functions'. Both this variable and
`write-file-functions' relate to how a buffer is saved to file.
To perform various checks or updates before the buffer is saved,
use `before-save-hook'.
delete-trailing-whitespace
,因为你希望确保从包装器中返回nil
,以便进行进一步处理(和最终保存)。
ws-trim
:ftp://ftp.lysator.liu.se/pub/emacs/ws-trim.el - Joe Casadonteadd-hook
的local
参数)。 - Stefan