How can I trim trailing whitespace in Visual Studio 2012 on save?
WhitespaceVisual Studio-2012Whitespace Problem Overview
Now that macros are gone from Visual Studio 2012, what is the best way to automatically trim trailing whitespace whenever a file is saved?
I'm aware that Format Document (Ctrl + K, Ctrl + D) will do this, but it presumably changes the file in other ways, and it's not automatic either.
The motivation is given here:
Trailing whitespace is evil. Don't commit evil into your repo
Whitespace Solutions
Solution 1 - Whitespace
There are at least two extensions that can do this. One is CodeMaid which explicitly will trim trailing blanks on save, and the other is Productivity Power Tools which can run the Format Document automatically on save.
To add an extension from within Visual Studio 2012, select menu Tools → Extensions and Updates.... In the window, select Online on the left and enter your search string for CodeMaid or Productivity Power Tools in the box on the upper right.
Solution 2 - Whitespace
Ctrl + H
Find what:
[\u0020]+\r?\n
Replace with:
\r\n
\s instead of [\u0020] delete empty line feeds, probably because it matches line feeds...
Solution 3 - Whitespace
You can use Mads Kristensen's Trailing Whitespace Visualizer. It has a keyboard shortcut to remove trailing whitespace from the current file. Ctrl + K, Ctrl + \
Note: this doesn't run on save. You have to explicitly run the command. On the bright side, it visually highlights the offending whitespace, so it's easier to identify cleanup opportunities even in code you haven't modified.
Solution 4 - Whitespace
EditorConfig has an option for removing trailing whitespace, and it has a Visual Studio extension. You'll need to add trim_trailing_whitespace = true
to your .editorconfig to make it work.