Thursday, 11 October 2012

Collapse and Expand All Regions Macro for Visual Studio

I use regions really quite extensively in my .NET projects and did a hunt around for a sneaky Visual Studio macro that would collapse all my regions after I have finished with the file. I came across this article on David Yack's blog that demonstrates some keyboard shortcuts to use. Further down in the article a contributor called Dry put a comment on that was the macro I was after :)

The macro posted worked fine in Visual Studio 2005 but when I put it into 2010 the collapse function didn't stop looping. So I did a little pimp to it and all good - works in 2010 now.

I hope David and Dry don't mind, but I have posted the code here too in case it becomes unavailable...

Sub ExpandAllRegions()
 DTE.SuppressUI = True

 Dim objSelection As TextSelection
 objSelection = DTE.ActiveDocument.Selection

 objSelection.StartOfDocument()

 Do While objSelection.FindText( _
  "#Region", _
  vsFindOptions.vsFindOptionsMatchInHiddenText _
 )
  objSelection.WordRight()
 Loop

 DTE.ActiveDocument.Selection().StartOfDocument()
 DTE.SuppressUI = False
End Sub

Sub CollapseAllRegions()
 ExpandAllRegions()

 Dim objSelection As TextSelection
 objSelection = DTE.ActiveDocument.Selection

 objSelection.EndOfDocument()

 Do While objSelection.FindText( _
  "#Region", vsFindOptions.vsFindOptionsBackwards _
 )
  objSelection.StartOfLine( _
   vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn _
  )
  DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")

  objSelection.LineUp()
 Loop

 DTE.ActiveDocument.Selection.StartOfDocument()
End Sub

You could of course now tie the collapse region function into the EnvironmentEvents module and make it automatically collapse all regions when a document closes. Play about with the DocumentEvents_DocumentClosing(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentClosing event. May want to limit it to cs and vb files only...

No comments:

Post a Comment