Format all files in project

Yesterday I discovered an awesomely useful Visual Studio macro: it applies that code formatting rules to all files in the whole solutions. Code formatting includes indentation, spacing, tabs vs. spaces: all the things that people tend to get irate about. By default, these formatting rules are applied only when you write new code. To apply them to an existing page, there’s the command Edit --> Format Document with the keyboard chord Ctrl-K, Ctrl-D. Now this macro goes and opens all files and applies this command – a very good idea to do before a major commit.

Sub FormatProject() 
    For Each Proj As Project In DTE.Solution.Projects 
        For Each Item As ProjectItem In Proj.ProjectItems 
            Dim window As EnvDTE.Window 
            Try 
                window = Item.Open() 
                window.Activate() 
                DTE.ExecuteCommand("Edit.FormatDocument", "") 
            Catch ex As Exception 
            End Try 
        Next 
    Next 
End Sub

Found as a comment by saraford to this MSDN post from 2005.

Advertisement

,

  1. Leave a Comment

Leave a Reply

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

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

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

Follow

Get every new post delivered to your Inbox.