# Whitespace Cleanup on Diff Lines in Emacs

Some of us are particular about whitespace, especially in files under version control (PS: you should be using version control, e.g. git). If you’re like me and you use emacs, then you can often use whitespace-cleanup (from whitespace.el) to keep your source files pristine.

The trouble comes if a collaborator doesn’t respect your whitespace wishes. If you just run whitespace-cleanup on your entire buffer, your revision history and git blame will be useless.

So far, my solution is to sanitize the whitespace only on the lines that I’m editing. I was doing this by hand, but since I use emacs, it was time to automate things and learn some rudimentary elisp in the process. Without further ado:

The end-user command is whitespace-cleanup-git-diff-regions, which you can run interactively from a file that’s under git control. Though you can also use the general function buffer-file-git-diff-regions-apply to run any function of the type (function region-beginning region-end) on all the “dirty” regions.

This uses magit, but just to test if we are in a directory under git control. You could swap this out if desired. The magic command-line incantation git diff -U0 <filename> | grep "^@@" | cut -d' ' -f3 | tr +, ' ' will generate a newline-delimited list of “dirty” regions of the form " lineno numlines". I then run whitespace-cleanup-region on each of these regions, and we’re done!

So I’ve learned a bit of elisp, and potentially saved my future self entire minutes of editing. I hope somebody else benefits, too!

Sorry about the lack of documentation. Use at your own risk (which is basically zilch, because you use git, right?). Ping me if you have improvements.

Tags:

Categories:

Updated: