Wednesday, 3 February 2010

Fed up with Visual Studio leaving trailing white-space in your units?

Fear not.

In VS2008 select Tools|Macros|Macros IDE...

Open MyMacros and double-click EnvironmentEvents.

Paste the following:



  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


Now every time you save a file it'll strip trailing white-space

No comments: