emacs仅在编程模式下保存时删除尾随空格

时间:2013-10-04 05:58:45

标签: emacs whitespace mode

以下行会在保存时删除所有训练空白区域。

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

没有停止哪些没有处于编程模式。

6 个答案:

答案 0 :(得分:6)

提到了hook变量buffer-local。不要那样做。或者更确切地说,不要使用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,还是juanleon before-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-trimws-butler以更智能的方式处理此问题。

盲目地从文件中删除所有尾随空格是一种很好的方法,可以将大量不相关的行提交到版本控制存储库。提到的两个库都将确保您自己的提交没有尾随空格,没有也会在文件的其他位置引入不需要的修改。

答案 1 :(得分:4)

自从Emacs-22取代write-file-hooks后,

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)

答案 2 :(得分:1)

是的,因为只要您进入prog-mode模式,就会将功能添加到write-file-hooks,并保留其中。无论缓冲区的模式如何,该钩子都适用于写入任何文件。

不是将这个简单的函数放在钩子上,而是可以添加一个测试模式的函数,只有在你想要这样做的模式下才能删除空格。

否则你需要让write-file-hooks缓冲区本地(我怀疑你想要做什么 - 更普遍地使用钩子。)

答案 3 :(得分:0)

您需要将变量缓冲区设为local:

(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来代替您想做的事情。

答案 4 :(得分:0)

糟糕的方式:

(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 仅删除更改行上的空格。

答案 5 :(得分:-1)

在emacs 21或更高版本中,您可以将此钩子添加到垂直模式,如下所示:

(add-hook 'prog-mode-hook
                (lambda () (add-to-list 'write-file-functions 'delete-trailing-whitespace)))
相关问题