Alex
Alex

Reputation: 77329

Visual Studio: Collapse Methods, but not Comments (Summary etc.)

is there a way (settings? "macro"? extension?) that I can simply toggle outlining so that only the using section and my methods collapse to their signature line, but my comments (summary and double slash comments) and classes stay expanded?

Examples:

1) Uncollapsed

using System;
using MachineGun;

namespace Animals
{

    /// <summary>
    /// Angry animal
    /// Pretty Fast, too
    /// </summary>
    public partial class Lion
    {
        //
        // Dead or Alive
        public Boolean Alive;

        /// <summary>
        /// Bad bite
        /// </summary>
        public PieceOfAnimal Bite(Animal animalToBite)
        {
              return animalToBite.Shoulder;
        }

        /// <summary>
        /// Fatal bite
        /// </summary>
        public PieceOfAnimal Kill(Animal animalToKill)
        {
              return animalToKill.Head;
        }
     }
}

2) Collapsed (the following is my desired result):

using[...]

namespace Animals
{

    /// <summary>
    /// Angry animal
    /// Pretty Fast, too
    /// </summary>
    public partial class Lion
    {
        //
        // Dead or Alive
        public Boolean Alive;

        /// <summary>
        /// Bad bite
        /// </summary>
        public PieceOfAnimal Bite(Animal animalToBite)[...]

        /// <summary>
        /// Fatal bite
        /// </summary>
        public PieceOfAnimal Kill(Animal animalToKill)[...]
     }
}

This is how I prefer seeing my class files (the collapsed form). I've been doing the collapsing by hand a million times by now and I think there should be a way to automate/customize/extend VS to do it the way I want?

Every time I debug/hit a breakpoint, it uncollapses and messes up things. If I collapse via the context menu's collapse to outline etc. it also collapses my comments which isn't desired.

Appreciate your help!

Upvotes: 22

Views: 7873

Answers (8)

joeyr
joeyr

Reputation: 21

In VS2022 the best way I have found is to use the Collapse Comments extension by Matt Lacey (free extension, no affiliation).

Go to Extensions -> Manage Extensions and search for "Collapse Comments" and install the extension. After restarting Visual Studio, you can now do:

Ctrl+M, Ctrl+K: Collapse Definitions, Show Comments

To expand again, use the built-in shortcut Ctrl+M, Ctrl+X.

Upvotes: 0

Yaroslav Yakovlev
Yaroslav Yakovlev

Reputation: 6483

Maybe this link will help you: VS Macro / Shortcuts to Expand / Collapse all regions.

The gist of it is that you can wrap everything in regions so that you could manage it and keep comments unwrapped. Also you can modify that macro to fit your needs.

Upvotes: 1

Hilmi Bilal &#199;am
Hilmi Bilal &#199;am

Reputation: 199

Although this question is old and answered, I was looking for the same thing as question but I think this is the simpler way than writing macro:

Tools > Options > Text Editor > C# > Advanced > Outlining > Uncheck "Show outlining for comments and preprocessor regions" checkbox

If you do that and than use CTRL+M and CTRL+O shortcut, methods will collapse but summaries and regions will remain uncollapsed.

Upvotes: 7

Dhruva N
Dhruva N

Reputation: 94

Extending John's answer for VS2017:

var selection = dte.ActiveDocument.Selection;

dte.ExecuteCommand("Edit.CollapsetoDefinitions");
dte.ActiveDocument.Selection.StartOfDocument();
dte.ActiveDocument.Selection.FindText("/// <summary>")

var startLine = selection.CurrentLine;
do {
    dte.ExecuteCommand("Edit.FindNext");
} while (startLine != selection.CurrentLine);

Upvotes: 1

John Stritenberger
John Stritenberger

Reputation: 1264

I know this question is super old, but I was looking for a way to do this myself that works with VS 2015. I came across this Macros for Visual Studio extension that works with VS 2013 and 2015...

https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.MacrosforVisualStudio

I wrote this macro that collapses all methods but leaves the summary comments, using directives, classes, etc alone.

/// <reference path="C:\Users\johnc\AppData\Local\Microsoft\VisualStudio\14.0\Macros\dte.js" />
var selection = dte.ActiveDocument.Selection;

dte.ExecuteCommand("Edit.ExpandAllOutlining");
dte.ActiveDocument.Selection.StartOfDocument();
dte.ExecuteCommand("Edit.NextMethod");

var startLine = selection.CurrentLine;
dte.ExecuteCommand("Edit.CollapseCurrentRegion");
dte.ExecuteCommand("Edit.NextMethod");

do {
    dte.ExecuteCommand("Edit.CollapseCurrentRegion");
    dte.ExecuteCommand("Edit.NextMethod");
} while (startLine != selection.CurrentLine);

Hope this helps somebody out.

Upvotes: 0

Daniel Elliott
Daniel Elliott

Reputation: 22857

Ctrl M, Ctrl O

Collapses to definitions.

From this point a macro might not be too hard to write.

Something like find /// <summary> ... and toggle outlining. Then lather, rinse, repeat.

Upvotes: 11

Tono Nam
Tono Nam

Reputation: 36048

I created a macro that will enable to collapse members. you can place your custom filter in the function IncludeMember for example in this example I collapse everything but comments and enums

' filter some mebers. for example using statemets cannot be collapsed so exclude them. 
Function IncludeMember(ByVal member As EnvDTE.CodeElement)

    If member.Kind = vsCMElement.vsCMElementIDLImport Then
        Return False
    ElseIf member.Kind = vsCMElement.vsCMElementEnum Then
        Return False  ' I do not want to colapse enums
    End If

    Return True

End Function

Sub CollapseNodes()

    ' activate working window
    DTE.Windows.Item(DTE.ActiveDocument.Name).Activate()

    ' expand everything to start

    Try
        DTE.ExecuteCommand("Edit.StopOutlining")
    Catch
    End Try

    Try
        DTE.ExecuteCommand("Edit.StartAutomaticOutlining")
    Catch
    End Try


    ' get text of document and replace all new lines with \r\n
    Dim objTextDoc As TextDocument
    Dim objEditPt As EnvDTE.EditPoint
    Dim text As String
    ' Get a handle to the new document and create an EditPoint.
    objTextDoc = DTE.ActiveDocument.Object("TextDocument")
    objEditPt = objTextDoc.StartPoint.CreateEditPoint
    ' Get all Text of active document
    text = objEditPt.GetText(objTextDoc.EndPoint)
    text = System.Text.RegularExpressions.Regex.Replace( _
                    text, _
                    "(\r\n?|\n\r?)", ChrW(13) & ChrW(10) _
                )

    ' add new line to text so that lines of visual studio match with index of array
    Dim lines As String() = System.Text.RegularExpressions.Regex.Split(vbCrLf & text, vbCrLf)

    ' list where whe will place all colapsable items
    Dim targetLines As New System.Collections.Generic.List(Of Integer)

    ' regex that we will use to check if a line contains a #region
    Dim reg As New System.Text.RegularExpressions.Regex(" *#region( |$)")

    Dim i As Integer
    For i = 1 To lines.Length - 1

        If reg.Match(lines(i)).Success Then
            targetLines.Add(i)
        End If

    Next


    Dim fileCM As FileCodeModel
    Dim elts As EnvDTE.CodeElements
    Dim elt As EnvDTE.CodeElement

    Dim projectItem = DTE.ActiveDocument.ProjectItem

    Dim temp = projectItem.Collection.Count

    Dim b = DirectCast(DirectCast(projectItem.Document, EnvDTE.Document).ActiveWindow, EnvDTE.Window).ContextAttributes

    fileCM = projectItem.FileCodeModel
    elts = fileCM.CodeElements
    For i = 1 To elts.Count
        elt = elts.Item(i)
        CollapseE(elt, elts, i, targetLines)
    Next

    ' now that we have the lines that we will plan to collapse sort them. it is important to go in order
    targetLines.Sort()

    ' go in reverse order so that we can collapse nested regions
    For i = targetLines.Count - 1 To 0 Step -1

        GotoLine(targetLines(i) & "")
        DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")

    Next


End Sub

'' Helper to OutlineCode. Recursively outlines members of elt.
''
Sub CollapseE(ByVal elt As EnvDTE.CodeElement, ByVal elts As EnvDTE.CodeElements, ByVal loc As Integer, ByRef targetLines As System.Collections.Generic.List(Of Integer))
    Dim epStart As EnvDTE.EditPoint
    Dim epEnd As EnvDTE.EditPoint

    epStart = elt.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint()
    epEnd = elt.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes).CreateEditPoint() ' Copy it because we move it later.
    epStart.EndOfLine()
    If ((elt.IsCodeType()) And (elt.Kind <> EnvDTE.vsCMElement.vsCMElementDelegate) Or elt.Kind = EnvDTE.vsCMElement.vsCMElementNamespace) Then
        Dim i As Integer
        Dim mems As EnvDTE.CodeElements

        mems = elt.Members
        For i = 1 To mems.Count

            CollapseE(mems.Item(i), mems, i, targetLines)

        Next

    End If


    If (epStart.LessThan(epEnd)) Then
        If IncludeMember(elt) Then
            targetLines.Add(epStart.Line)
        End If
    End If



End Sub

Upvotes: 3

Scott Dorman
Scott Dorman

Reputation: 42516

There is nothing built-in to Visual Studio which will allow you to collapse code regions in this fashion. It might be possible with a macro, but I don't think it would be very simple to write. Visual Studio 2010 might provide some relief by allowing you to write an actual plug-in that has more direct accessibility in to the syntax parser, but that is pure speculation at this point.

Upvotes: 0

Related Questions