A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Wednesday, May 27, 2009

Strip trailing spaces on save in Visual Studio

My preferred windows text editor is TextPad. It's rock solid, the keystrokes were intuitive coming from vi, allows regular expressions in search and replac and allows for the definition of custom classes. One of the features I love is its ability to strip trailing whitespace
when you save a file. It's just an OCD trait that for code files, I only want what needs to be in there.

Assuming it's always been done, it makes code diffs easier, takes up less space, etc, etc. Historical arguments, I'm sure people will argue. Diff tools exist that ignore differences in whitespace. While it's entirely true, sometimes I've only had rudimentary tools like windows file compare (fc). Space on disk for code files hasn't been an issue for eons but for the want of a nail[1], the kingdom was lost.

Today, a small measure of happiness entered my life when I found the posting by Dyaus at http://stackoverflow.com/questions/82971/how-to-automatically-remove-trailing-whitespace-in-visual-studio-2008/83043 They had a macro that runs after save to strip trailing whitespace and it works like a champ thus far. Although the question was for VS 2008, I'm running it on 2005 without an issue. Reproduced in case the link goes dead

' Add the following into the EnvironmentEvents Module for your macros
Private saved As Boolean = False
Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
Handles DocumentEvents.DocumentSaved
If Not saved Then
DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
"\t", _
vsFindOptions.vsFindOptionsRegularExpression, _
"  ", _
vsFindTarget.vsFindTargetCurrentDocument, , , _

' Remove all the trailing whitespaces.
DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
":Zs+$", _
vsFindOptions.vsFindOptionsRegularExpression, _
String.Empty, _
vsFindTarget.vsFindTargetCurrentDocument, , , _

saved = True
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
End Try
saved = False
End If
End Sub

[1] http://en.wikipedia.org/wiki/For_Want_of_a_Nail

No comments: