Skip to content

Instantly share code, notes, and snippets.

@Inc0n
Last active March 5, 2021 11:27
Show Gist options
  • Save Inc0n/a92ec28d4abc563c0dfe6f438496f3f6 to your computer and use it in GitHub Desktop.
Save Inc0n/a92ec28d4abc563c0dfe6f438496f3f6 to your computer and use it in GitHub Desktop.
My emacs auto delete trailing white space setup, that only operate on the region of the buffer that is show in the current window
(setq show-trailing-whitespace t)
(defun my-prog-nuke-trailing-whitespace ()
(when (derived-mode-p 'prog-mode)
(let ((win-beg (window-start))
(win-end (window-end))
(line-beg (line-beginning-position))
(line-end (line-end-position)))
(if (or (< line-beg win-start)
(> line-end win-end))
(delete-trailing-whitespace win-beg win-end)
(delete-trailing-whitespace win-beg line-beg)
(delete-trailing-whitespace line-end win-end)))))
(add-hook 'before-save-hook 'my-prog-nuke-trailing-whitespace)
@Inc0n
Copy link
Author

Inc0n commented Mar 5, 2021

Normally i would just recommend to use the following

(defun my-prog-nuke-trailing-whitespace ()
  "Delete trailing space only in the window region."
  (when (derived-mode-p 'prog-mode)
	(delete-trailing-whitespace (window-start) (window-end))))

Unless you found yourself like me thinking while having the current line auto indented, and this little helper will delete that indentation as trailing space, which would break my train of thoughts, only to repeat this nightmare numerous time, decided to overhual it to delete all region in current window besides current line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment