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)
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 ofdelete-trailing-whitespace
with 0 as the start and that point as the end. Then calld-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.ethan-wspace
which does not interfer with the cursor position.ethan-wspace
is exactly what I was looking for. If you make your comment an answer, I will mark it as answered.ws-butler
orws-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)