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

8

22

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!

Supersonic answered 9/8, 2009 at 4:0 Comment(0)
C
11

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.

Cockneyism answered 13/8, 2009 at 7:34 Comment(1)
Just for the record, this doesn't work in Visual Studio 2019, it collapses everything.Squinty
A
7

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.

Auberge answered 4/5, 2020 at 6:33 Comment(2)
This answer solved my issue after almost giving up on finding an answer...thank you Bilal! I like to keep my methods collapsed for compactness until I need to work on one of them, and then I will expand it. The problem was (until I read this answer) that all the shortcuts to collapse regions would collapse the loops and conditionals also...which I did not want. But now after reading this answer I was able to figure out how to make the shortcuts work the way I wanted, which makes my life easier!Cantonment
This answer was also the best for me, especially since macros are a lot harder to use since they took them out of VS a while back. I just wish they would give you the option to show outlining for comments OR regions (instead of toggling them together). I want regions collapsed but not comments, so I have to turn off outlining for comments/regions, then do Ctrl-M+O, then turn it back on and collapse just the regions manually.Fidellia
Z
3

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
Zelaya answered 20/7, 2012 at 23:17 Comment(1)
This is exactly what I need, but I have no idea how to use the macro. Could you help me out? Where do I put this code and how to I execute it? I'm using Visual Studio 2012.Duplessis
C
1

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.

Colangelo answered 10/8, 2009 at 11:32 Comment(0)
D
1

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);
Disrespectable answered 23/1, 2018 at 6:36 Comment(0)
O
0

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.

Oldfangled answered 10/8, 2009 at 3:14 Comment(0)
C
0

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.

Cristiano answered 3/12, 2016 at 17:52 Comment(0)
H
0

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.

Hindoo answered 21/6 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.