Blogo Baggins home

Waging War on Whitespace (using TextMate)

March 31, 2009 – Leesburg, VA

If you’ve ever written code on a team, you’ve likely encountered what I call diff cruft. Diff cruft is what happens when a developer commits a change to some code that has trailing whitespace (either tabs or spaces) at the end of a line. When viewing the code changes in a diff, this extraneous whitespace stands out and often distracts from what is important.

For example:

Evil whitespace

will look like this in a diff (GitHub’s diff in this case)…

Distracting diff cruft

To avoid diff cruft you’ll need to instruct your text editor to remove trailing whitespace, preferably every time you save so you don’t have to remember to do it. If this is a built-in feature, great; if not, hopefully your editor empowers you to emulate this functionality yourself1.

My preferred editor on Mac OS X is TextMate2. While it ships with a “Remove Trailing Spaces in Document / Selection”3 command it does not run it on save. Here is how I created a macro to do just that:

So, along with its unruly cousin, the tab5, trailing whitespace is evil. Avoiding both, your peers will (or should) thank you for it.

1 It doesn’t? It’s time to reconsider your editor.

2 Despite the lack of multiple window panes, and no major update in years. :/

3 Included in the “Text” bundle.

4 There is one caveat: any bookmarks you’ve set will get blown away upon running the “Remove Trailing Spaces in Document / Selection” command (which is run when you save). This is an annoyance that I’ve learned to live with out of respect for my peers’ diffs.

5 I’m aware of the religious debate about tabs vs. spaces, but please, please use spaces instead of tabs. Tabs cause even more diff cruft, and screws up the formatting in other editors. This isn’t a problem if everyone instructs their editors to use spaces instead of tabs; the inverse is not true.