我最近为我的(delete-trailing-whitespace)
添加了Emacs 'before-save-hook
函数用于某些编程模式,但我发现它从我当前正在编辑的行中删除空格时非常令人沮丧。有关如何解决此问题的任何建议吗?
答案 0 :(得分:10)
由于delete-trailing-whitespace
尊重缩小,一种解决方案是将缓冲区缩小到当前行之前的部分并调用它,然后缩小到之后的部分当前行并再次调用它:
(defun delete-trailing-whitespace-except-current-line ()
(interactive)
(let ((begin (line-beginning-position))
(end (line-end-position)))
(save-excursion
(when (< (point-min) begin)
(save-restriction
(narrow-to-region (point-min) (1- begin))
(delete-trailing-whitespace)))
(when (> (point-max) end)
(save-restriction
(narrow-to-region (1+ end) (point-max))
(delete-trailing-whitespace))))))
将此功能放在before-save-hook
上,而不是delete-trailing-whitespace
。
答案 1 :(得分:3)
delete-trailing-whitespace
的此包装可用于执行您想要的操作:
(defun delete-trailing-whitespace-except-current-line ()
"do delete-trailing-whitespace, except preserve whitespace of current line"
(interactive)
(let ((current-line (buffer-substring (line-beginning-position) (line-end-position)))
(backward (- (line-end-position) (point))))
(delete-trailing-whitespace)
(when (not (string-equal (buffer-substring (line-beginning-position) (line-end-position))
current-line))
(delete-region (line-beginning-position) (line-end-position))
(insert current-line)
(backward-char backward))))
答案 2 :(得分:1)
我遇到了同样的问题,发现ws-butler完全解决了这个问题。 有一个简单的示例配置代码:
;; autoload ws-butler on file open
(add-hook 'find-file-hook #'ws-butler-global-mode)
(setq require-final-newline t)
答案 3 :(得分:0)
我只需要一个包装器来调用`delete-trailing-whitespace&#39;:
(defun modi/delete-trailing-whitespace-buffer ()
"Delete trailing whitespace in the whole buffer, except on the current line.
The current line exception is because we do want to remove any whitespace
on the current line on saving the file (`before-save-hook') while we are
in-between typing something.
Do not do anything if `do-not-delete-trailing-whitespace' is non-nil."
(interactive)
(when (not (bound-and-true-p do-not-delete-trailing-whitespace))
(delete-trailing-whitespace (point-min) (line-beginning-position))
(delete-trailing-whitespace (line-end-position) (point-max))))
(add-hook 'before-save-hook #'modi/delete-trailing-whitespace-buffer)