How to automatically remove trailing whitespace in Visual Studio 2008?

Is it possible to configure Visual Studio 2008 to automatically remove whitespace characters at the end of each line when saving a file? There doesn't seem to be a built-in option, so are there any extensions available to do this?


Find/Replacing using Regular Expressions

In the Find and Replace dialog, expand Find Options, check Use, choose Regular expressions

Find What: ":Zs#$"

Replace with: ""

click Replace All

In other editors (a normal Regular Expression parser) ":Zs#$" would be "\s*$".


CodeMaid is a very popular Visual Studio extension and does this automatically along with other useful cleanups.

  • Download: https://github.com/codecadwallader/codemaid/releases/tag/v0.4.3
  • Modern Download: https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid
  • Documentation: http://www.codemaid.net/documentation/#cleaning

I set it to clean up a file on save, which I believe is the default.


You can create a macro that executes after a save to do this for you.

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
        Try
            DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                                 "\t", _
                                 vsFindOptions.vsFindOptionsRegularExpression, _
                                 "  ", _
                                 vsFindTarget.vsFindTargetCurrentDocument, , , _
                                 vsFindResultsLocation.vsFindResultsNone)

            ' Remove all the trailing whitespaces.
            DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                                 ":Zs+$", _
                                 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

I've been using this for some time now without any problems. I didn't create the macro, but modified it from the one in ace_guidelines.vsmacros which can be found with a quick google search.