Code Folding

Code folding allows users to collapse sections of text.

Installation

To enable folding, you must install a FoldingManager on the TextArea and use a FoldingStrategy to calculate where folds should occur.

using AvaloniaEdit.Folding;

// ... inside your setup code

// 1. Install the manager
var foldingManager = FoldingManager.Install(editor.TextArea);

// 2. Choose a strategy (e.g., XML)
var strategy = new XmlFoldingStrategy();

// 3. Update foldings (usually done on a timer or after document changes)
strategy.UpdateFoldings(foldingManager, editor.Document);

Built-in Strategies

  • XmlFoldingStrategy: Folds XML/HTML tags.

Custom Strategies

To create a custom folding strategy (e.g., for C# braces), you do not strictly need to implement an interface, but you must generate NewFolding instances and pass them to foldingManager.UpdateFoldings.

public void UpdateFoldings(FoldingManager manager, TextDocument document)
{
    var newFoldings = new List<NewFolding>();

    // Logic to find start and end offsets...
    newFoldings.Add(new NewFolding(startOffset, endOffset));

    manager.UpdateFoldings(newFoldings, -1);
}