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 am currently editing. Any suggestions as to how to fix this problem?
Remove trailing whitespace. To remove trailing whitespace from the entire buffer, use any of the following: ‘M-x delete-trailing-whitespace’ ( GnuEmacs version 21 or later). You can put this in ‘before-save-hook’ to ensure that your files have no trailing whitespace:
Remove whitespace at the end of the document. To remove whitespace at the end of a document, use any of the following: ‘C-x C-o’ ( ‘delete-blank-lines’) at the end of the buffer (` M-> ’).
Last updated: 2021-07-19. Deletes trailing whitespace, and also deletes trailing blank lines if delete-trailing-lines is t. (works on whole buffer or selection) Delete whitespaces that are normally considered problem.
From the commentary: “This package contains tools to do various sorts of whitespace trimming on buffer lines. The main part is WS Trim mode, which is a minor mode that automatically trims whitespace on text lines. You can control how thorough this mode should be, e.g. whether all lines or only lines you edit should be trimmed.”
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))))
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With