2

I have the following before save hook defined which deletes all trailing whitespace and converts tabs to spaces (except in makefile mode since makefiles need tabs to work). This works great, however, it creates a little bit of an annoying side effect where if my cursor has some space before it, removing the space, moves the cursor back. I would like to tweak this a little by removing all trailing space, except if the cursor is at the end of a line.

(defun my-before-save-hook ()
  (progn
    (if (not (string-match ".*makefile.*" (message "%s" major-mode))) ; Makefiles require tabs
        (untabify (point-min) (point-max)))                           ; Convert tabs to spaces
    (delete-trailing-whitespace)))                                    ; Remote trailing spaces
(add-hook 'before-save-hook 'my-before-save-hook)
4
  • You could kill the line you're on, call delete-trailing-whitespace then yank the line back. Of course, any whitespace after your cursor would be saved this way too. Alternatively you could find the last non whitespace character of the line you're on, call the two argument form of delete-trailing-whitespace with 0 as the start and that point as the end. Then call d-t-w again, with the cursor's point (or the point of the start of the next line, if you want to save whitespace after the cursor) as the start and the end of the buffer as the end.
    – nega
    Commented Apr 24, 2019 at 16:50
  • 3
    You could use ethan-wspace which does not interfer with the cursor position. Commented Apr 25, 2019 at 9:13
  • @AndrewSwann ethan-wspace is exactly what I was looking for. If you make your comment an answer, I will mark it as answered.
    – oneself
    Commented May 1, 2019 at 15:38
  • 1
    I highly recommend using either ws-butler or ws-trim -- both libraries will prevent you from creating trailing whitespace in a file, while leaving lines which you haven't edited untouched. (Note that in a version controlled environment, this is exactly what you want.) See Version control friendly options (modify only the lines you have edited)
    – phils
    Commented May 2, 2019 at 9:02

1 Answer 1

1

A useful package for keeping white space in your files clean is ethan-wspace. In particular, it will deal with trailing whitespace, and does not interfere with the cursor position.

The package is not quite automatic, as it takes care not to change files where white space is non-standard, e.g. trailing whitespace at the end of the file. In these cases it flags the non-standard behaviour in the mode line and provides a simple to way to fix that white space. If on the other hand it encounters a file that has no trailing whitespace, then it sets-up hooks so that trailing whitespace is deleted when saving subsequent edits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.