2010-03-18

Removing trailing whitespaces in Visual Studio

The following will remove trailing whitespaces whenever you save a file in Visual Studio 2008. Convenient!
  1. Go to Tools -> Macros -> Macro Explorer
  2. Double click "MyMacros -> Module1
  3. In the new Project Explorer Tree, double click on "EnvironmentEvents" above "Module1"
  4. After the #End Region for #Region "Automatically generated code, do not modify", add the following:
    Private saved As Boolean = False
        Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
                                                 Handles DocumentEvents.DocumentSaved
            If Not saved Then
                Try
                    ' Remove all the trailing whitespaces.
                    DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                                         "{:Zs|\t}+$", _
                                         vsFindOptions.vsFindOptionsRegularExpression, _
                                         String.Empty, _
                                         vsFindTarget.vsFindTargetCurrentDocument, , , _
                                         vsFindResultsLocation.vsFindResultsNone)
    
                    saved = True
                    document.Save()
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
                End Try
            Else
                saved = False
            End If
        End Sub

1 comment:

  1. I have made a simple plugin which does just that thing.

    Available on github:
    https://github.com/ideaconnect/vs-trim-line-ends-on-save-plugin

    Feel free to use and extend it :)

    ReplyDelete