Cleaning extra white spaces in Visual Studio

Sometimes, the Visual Studio’s text editor doesn’t do a perfect job formatting your code.

Fortunately, with its built Macros system we can help it to help us. By creating a simple Macro, we can eliminate those annoying extra spaces that insist showing off.

First, let’s open the Macro IDE, found at Tools -> Macros -> Macros IDE…
Open the EnviromentEvents file and paste the code below anywhere before the End Module:

    Private saved As Boolean = False    

    Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
         Handles DocumentEvents.DocumentSaved
        If Not saved And Not DTE.ActiveDocument.Name.ToLower().EndsWith("aspx") Then
                ' 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

This code won’t affect your aspx files. When you run the macro on that kind of file, the colors highlighting get screwed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s