Visual Studio macro to collapse all <Summary> comment blocks

Commenting your source is recommended and pretty helpful. But while implementing (e.g. SharpTM) most time it is annoying to scroll through all the big comment blocks. To get an overview of all class members it would be great to have the opportunity to collapse all comment blocks above all methods, properties, etc. That’s why I tried to find a macro to do this - without success. So I wrote it by my own based on a region collapse macro I found here. And this is the modified function to do the job:

Public IsSummaryCommentsOutlineCollapsed As Dictionary(Of Document, Boolean)

''
'' Toggling all <summary> comment blocks from collapsed to expanded outline.
'' Please add [Imports System.Collections.Generic] on top of this module.
''
Sub ToggleSummaryCommentsOutlineExpansion()
    If (DTE.ActiveDocument Is Nothing) Then
        Exit Sub
    End If

    If (DTE.UndoContext.IsOpen) Then
        DTE.UndoContext.Close()
    End If

    DTE.SuppressUI = True

    Try
        DTE.UndoContext.Open("ToggleSummaryCommentsOutline")
    Catch
    End Try

    If (IsSummaryCommentsOutlineCollapsed Is Nothing) Then
       IsSummaryCommentsOutlineCollapsed = New Dictionary(Of Document, Boolean)
    End If

    If (Not IsSummaryCommentsOutlineCollapsed.ContainsKey(DTE.ActiveDocument)) Then
        IsSummaryCommentsOutlineCollapsed.Add(DTE.ActiveDocument, False)
    End If

    Dim objSelection As TextSelection = DTE.ActiveDocument.Selection
    Dim line As Integer = objSelection.CurrentLine
    objSelection.StartOfDocument()

    ' find all <summary> blocks
    While objSelection.FindText("^:b*///:b*\<summary\>.*$", vsFindOptions.vsFindOptionsRegularExpression Or vsFindOptions.vsFindOptionsMatchInHiddenText)
        If (Not IsSummaryCommentsOutlineCollapsed.Item(DTE.ActiveDocument)) Then
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
        End If
    End While
    IsSummaryCommentsOutlineCollapsed.Item(DTE.ActiveDocument) = Not IsSummaryCommentsOutlineCollapsed.Item(DTE.ActiveDocument)

    objSelection.StartOfDocument()
    objSelection.GotoLine(line)

    DTE.UndoContext.Close()
    DTE.SuppressUI = False
End Sub

In addition I just assigned a shortcut (Ctrl-M, C) to this macro to provide quick access while editing my sources.

Assign shortcut to Visual Studio macro

Update: Due to a comment of Torsten to add an undo option I implemented the support for toggling between collapsed and expanded mode and the undo functionality. Now running the ToggleSummaryCommentsOutlineExpansion function will collapse the first time for each document and toggles between expanded and collapsed mode each time you trigger this method.