Archive

Posts Tagged ‘search’

Removing trailing spaces in Visual Studio

November 30th, 2010 4 comments

Trailing spaces or tabs is something I dislike. Using the combination CTRL+R, CTRL+W you can show the whitespace distribution in VS. But screening the lines one by one is a tedious job. That’s why we are going to use regular expressions. Regular expressions in VS are a bit of an odd duck as the syntax is not nice and Perly.

You can read more about regular expressions in Visual Studio here.

Putting this together we get the following:

Find what: ^{.@}:b+$
Replace with: \1

This will seach those nasty trailing whitespaces and remove them.
{.@} -> Match everything, non-greedy. This is our capturing group.
:b+$ -> Match one or more spaces or tabs before the end of the line.

Optionally:
You can add the following macro to Visual Studio (and bind some keystroke):

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
 
Public Module Famvdploeg
    'Remove trailing whitespace from document
    Sub RemoveTrailingWhitespace()
        DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, "( |\t)+$", vsFindOptions.vsFindOptionsRegularExpression, String.Empty, vsFindTarget.vsFindTargetCurrentDocument, , , )
    End Sub
End Module