【问题标题】:Visual Studio: Collapse Methods, but not Comments (Summary etc.)Visual Studio:折叠方法,但不是注释(摘要等)
【发布时间】:2020-05-04 14:33:12
【问题描述】:

有没有一种方法(设置?“宏”?扩展?)我可以简单地切换大纲,以便 only 使用部分和我的方法折叠到他们的签名行,但我的 cmets(总结和双斜线 cmets) 和类保持扩展?

例子:

1) 未折叠

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) 折叠(以下是我想要的结果):

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)[...]
     }
}

这就是我更喜欢看到我的类文件(折叠形式)的方式。到目前为止,我已经手动进行了一百万次折叠,我认为应该有一种方法可以自动化/自定义/扩展 VS 以按照我想要的方式进行操作?

每次我调试/遇到断点时,它都会崩溃并搞砸事情。如果我通过上下文菜单的折叠到轮廓等折叠它也会折叠我不需要的 cmets。

感谢您的帮助!

【问题讨论】:

    标签: visual-studio


    【解决方案1】:

    Ctrl M, Ctrl O

    折叠到定义。

    从这一点来看,宏可能不会太难写了。

    类似查找/// &lt;summary&gt; ... 并切换大纲。然后起泡、冲洗、重复。

    【讨论】:

    • 仅作记录,这在 Visual Studio 2019 中不起作用,它会折叠所有内容。
    【解决方案2】:

    虽然这个问题很老且已回答,但我一直在寻找与问题相同的东西,但我认为这是比编写宏更简单的方法:

    Tools &gt; Options &gt; Text Editor &gt; C# &gt; Advanced &gt; Outlining > 取消选中"Show outlining for comments and preprocessor regions" 复选框

    如果您这样做,而不是使用 CTRL+MCTRL+O 快​​捷方式,方法将折叠,但摘要和区域将保持未折叠。

    【讨论】:

    • 这个答案在几乎放弃寻找答案后解决了我的问题......谢谢比拉尔!我喜欢将我的方法保持折叠以保持紧凑,直到我需要处理其中一个,然后我会扩展它。问题是(直到我读到这个答案)所有折叠区域的快捷方式都会折叠循环和条件......这是我不想要的。但是现在在阅读了这个答案之后,我能够弄清楚如何让快捷方式按照我想要的方式工作,这让我的生活更轻松!
    • 这个答案对我来说也是最好的,特别是因为宏很难使用,因为它们不久前将它们从 VS 中取出。我只是希望他们能给你显示 cmets 或区域的大纲的选项(而不是把它们切换在一起)。我希望区域折叠但不是 cmets,所以我必须关闭 cmets/regions 的大纲,然后执行 Ctrl-M+O,然后重新打开并手动折叠区域。
    【解决方案3】:

    我创建了一个可以折叠成员的宏。您可以将自定义过滤器放在函数IncludeMember 中,例如在此示例中,我折叠除 cmets 和枚举之外的所有内容

    ' 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
    

    【讨论】:

    • 这正是我需要的,但我不知道如何使用宏。你能帮帮我吗?我在哪里放置这段代码以及如何执行它?我正在使用 Visual Studio 2012。
    【解决方案4】:

    也许这个链接会对你有所帮助:http://weblogs.asp.net/mrdave/archive/2004/09/17/230732.aspx。您可以将所有内容包装在区域中,以便您可以管理它并保持 cmets 未包装。您也可以修改该宏以满足您的需要。

    【讨论】:

      【解决方案5】:

      为 VS2017 扩展 John's answer

      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);
      

      【讨论】:

        【解决方案6】:

        Visual Studio 没有任何内置功能可以让您以这种方式折叠代码区域。使用宏可能是可能的,但我认为编写起来并不容易。 Visual Studio 2010 允许您编写一个可以更直接地访问语法解析器的实际插件,这可能会提供一些缓解,但这纯粹是推测。

        【讨论】:

          【解决方案7】:

          我知道这个问题已经过时了,但我一直在寻找一种方法来自己解决这个问题,它适用于 VS 2015。我遇到了这个适用于 VS 2013 和 2015 的 Visual Studio 扩展宏...

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

          我编写了这个宏,它折叠所有方法,但只使用指令、类等保留摘要 cmets。

          /// <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);
          

          希望这对某人有所帮助。

          【讨论】:

            猜你喜欢
            • 2011-03-03
            • 2019-01-16
            • 2020-02-01
            • 2012-01-06
            • 1970-01-01
            • 1970-01-01
            • 2011-02-10
            • 1970-01-01
            • 2014-07-20
            相关资源
            最近更新 更多