Search code examples
c#visual-studio-2015visual-studio-sdk

With Visual Studio SDK, how would I collapse a section of code?


I can get a selection of text via TextSelection. And I can highlight specific sections. How would I collapse said section, couldn’t find anything in the documentation for the Visual Studio SDK about collapsing or hiding a section.

Edit 1 The code I want to collapse uses c++ syntax

Edit 2 I am attempting to writing an extension which allows me to collapse code, however I can not seem to find a reference to how to invoke such an option from the visual studio SDK documentation.


Solution

  • IOutliningManager might be what you're looking for.

    It provides methods that will allow you to get all collapsible regions, collapsed regions, and methods that allow you to expand or collapse a given region.

    As for an example, you might find this useful. Although the OP had issues with their code that weren't resolved via the linked thread, the provided code snippet might get you going in the right direction. I've included the snippet below:

    [Microsoft.VisualStudio.Utilities.ContentType("text")]
    [Microsoft.VisualStudio.Text.Editor.TextViewRole(Microsoft.VisualStudio.Text.Editor.PredefinedTextViewRoles.Editable)]
    [Export(typeof(IVsTextViewCreationListener))]
    public class Main : IVsTextViewCreationListener
    {
        private IOutliningManager _outliningManager;
        private IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
    
        public void VsTextViewCreated(IVsTextView textViewAdapter)
        {
    
            IComponentModel componentModel = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
            if (componentModel != null)
            {
                IOutliningManagerService outliningManagerService = componentModel.GetService<IOutliningManagerService>();
                _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
    
                if (outliningManagerService != null)
                {
                    if (textViewAdapter != null && _editorAdaptersFactoryService != null)
                    {
                        var textView = _editorAdaptersFactoryService.GetWpfTextView(textViewAdapter);
                        var snapshot = textView.TextSnapshot;
                        var snapshotSpan = new Microsoft.VisualStudio.Text.SnapshotSpan(snapshot, new Microsoft.VisualStudio.Text.Span(0, snapshot.Length));
                        _outliningManager = outliningManagerService.GetOutliningManager(textView);
                        var regions = _outliningManager.GetAllRegions(snapshotSpan);
                        foreach (var reg in regions)
                        {
                            _outliningManager.TryCollapse(reg);
                        }
                    }
                }
            }
        }
    }
    

    Good luck!