AvalonEdit
Folding
How to use Folding in your application

Folding (code collapsing) is implemented as an extension to the editor. It could have been implemented in a separate assembly without having to modify the AvalonEdit code. A VisualLineElementGenerator takes care of the collapsed sections in the text document; and a custom margin draws the plus and minus buttons.

You could use the relevant classes separately; but, to make it a bit easier to use, the static FoldingManager..::..Install(TextArea) method will create and register the necessary parts automatically.

All that's left for you is to regularly call FoldingManager..::..UpdateFoldings(IEnumerable<(Of <<'(NewFolding>)>>), Int32) with the list of foldings you want to provide. You could calculate that list yourself, or you could use a built-in folding strategy to do it for you.

Here is the full code required to enable folding:

C# Copy imageCopy
foldingManager = FoldingManager.Install(textEditor.TextArea);
foldingStrategy = new XmlFoldingStrategy();
foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document);
If you want the folding markers to update when the text is changed, you have to repeat the foldingStrategy.UpdateFoldings call regularly.

How the FoldingManager works

The FoldingManager maintains a list of foldings. The FoldMargin displays those foldings and provides the UI for collapsing/expanding.

Folded foldings cause the FoldingElementGenerator to produce a line element that spans the whole folded text section, causing the text generation for the visual line that contains the folding start to continue after the folding end in another line.

To ensure scrolling works correctly in the presence of foldings, lines inside folded regions must not be used as start lines for the visual line generation. This is done by setting the line height of all such lines to 0. To efficiently set the height on a large number of lines and support reverting to the old height when the folding is uncollapsed, a CollapsedLineSection is used.

See Also