9

我最近为某些编程模式添加了 Emacs(delete-trailing-whitespace)功能'before-save-hook,但我发现它从我当前正在编辑的行中删除了空格,这让我很沮丧。有关如何解决此问题的任何建议?

4

4 回答 4

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.

于 2010-08-20T18:34:40.080 回答
4

这个包装器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))))
于 2010-08-20T18:49:38.720 回答
1

我遇到了同样的问题,发现ws-butler完美地解决了它。有一个简单的示例配置代码:

;; autoload ws-butler on file open
(add-hook 'find-file-hook #'ws-butler-global-mode)
(setq require-final-newline t)
于 2015-11-10T03:57:48.317 回答
0

I simply have a wrapper to make two calls to `delete-trailing-whitespace':

(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)
于 2016-03-03T19:40:00.050 回答