以下行在保存时删除了所有训练空白。
(add-hook 'write-file-hooks 'delete-trailing-whitespace)
但我只想在我处于编程模式时才挂钩这个功能,所以我做到了
(defun nuke_traling ()
(add-hook 'write-file-hooks 'delete-trailing-whitespace)
)
(add-hook 'prog-mode-hook 'nuke_traling)
不停止不处于编程模式。
以下行在保存时删除了所有训练空白。
(add-hook 'write-file-hooks 'delete-trailing-whitespace)
但我只想在我处于编程模式时才挂钩这个功能,所以我做到了
(defun nuke_traling ()
(add-hook 'write-file-hooks 'delete-trailing-whitespace)
)
(add-hook 'prog-mode-hook 'nuke_traling)
不停止不处于编程模式。
已经提到了使钩子变量缓冲区本地化。不要那样做。或者更确切地说,不要使用make-local-variable.
正常的钩子机制具有内置的缓冲区本地支持——这LOCAL就是add-hook. 当钩子运行时,它同时运行全局值和缓冲区局部值。
因此,以问题中的示例代码为例,您可以将其更改为使用:
(add-hook 'write-file-hooks 'delete-trailing-whitespace nil t)
然后delete-trailing-whitespace无论何时运行都会被调用write-file-hooks,但仅在prog-mode-hook已运行的缓冲区中调用。
然而,有更好的方法来实现这一点。
我同意 Drew 的观点,您最好测试一下您的模式是否源自prog-mode,并且使用 juanleonbefore-save-hook是一个更好的使用钩子。所以你可能会做类似的事情:
(add-hook 'before-save-hook 'my-prog-nuke-trailing-whitespace)
(defun my-prog-nuke-trailing-whitespace ()
(when (derived-mode-p 'prog-mode)
(delete-trailing-whitespace)))
但我真正推荐的是使用ws-trim或ws-butler以更智能的方式处理这个问题。
盲目地从文件中删除所有尾随空格是结束将大量不相关行提交到版本控制存储库的好方法。提到的两个库都将确保您自己的提交没有尾随空格,而不会在文件的其他地方引入不需要的修改。
write-file-hooks自 Emacs-22 以来已过时,由write-file-functions. 但是这个钩子用起来有点微妙(因为它也可以用来执行写操作),所以我建议你before-save-hook改用。local为了使其仅适用于当前缓冲区,只需为 的参数传递一个非零值add-hook,如下所示:
(defun nuke_traling ()
(add-hook 'before-save-hook #'delete-trailing-whitespace nil t))
(add-hook 'prog-mode-hook #'nuke_traling)
是的,因为一旦你进入一个prog-mode模式,你就将函数添加到write-file-hooks它保留的地方。并且该钩子适用于写入任何文件,无论其缓冲区的模式如何。
您可以添加一个测试模式的函数,而不是将那个简单的函数放在钩子上,并且仅在您想要执行此操作的模式时才删除空格。
否则,您将需要使write-file-hooks缓冲区本地化(我怀疑您是否想要这样做 --- 更普遍地使用挂钩)。
您需要将变量缓冲区设为本地:
(defun nuke_traling ()
(make-variable-buffer-local 'write-file-hooks)
(add-hook 'write-file-hooks 'delete-trailing-whitespace))
但我建议before-save-hook改用:
(defun nuke_traling ()
(add-to-list 'before-save-hook 'delete-trailing-whitespace))
write-file-hooks如果用作文件局部变量可能会有风险,并且文档建议将before-save-hook其用于您想做的事情。
坏方法:
(add-to-list 'write-file-functions 'delete-trailing-whitespace)
更好的方法是使用ws-butler:
(straight-use-package 'ws-butler)
(add-hook 'prog-mode-hook #'ws-butler-mode)
ws-butler-mode仅在更改的行上删除空格。
在 emacs 21 或更高版本中,您可以将此挂钩添加到特定模式,如下所示:
(add-hook 'prog-mode-hook
(lambda () (add-to-list 'write-file-functions 'delete-trailing-whitespace)))