开发者

emacs delete-trailing-whitespace except current line

I recently added Emacs (delete-trailing-whitespace) function to my 'before-save-hook for some programming modes, but I find it rather frustrating that it deletes whitespace from the line I a开发者_如何转开发m currently editing. Any suggestions as to how to fix this problem?


Since delete-trailing-whitespace respects narrowing, one solution is to narrow the buffer to the portion before the current line and call it, then narrow to the portion after the current line and call it again:

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

Put this function on your before-save-hook instead of delete-trailing-whitespace.


This wrapper for delete-trailing-whitespace can be used to do what you want:

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


I ran into the same problem, and found out that ws-butler perfectly solves it. There is a simple sample config code:

;; autoload ws-butler on file open
(add-hook 'find-file-hook #'ws-butler-global-mode)
(setq require-final-newline t)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜