I use the BraceFoldingStrategy by Daniel Grünwald:
public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
{
List<NewFolding> newFoldings = new List<NewFolding>();
Stack<int> startOffsets = new Stack<int>();
int lastNewLineOffset = 0;
char openingBrace = this.OpeningBrace;
char closingBrace = this.ClosingBrace;
for (int i = 0; i < document.TextLength; i++) {
char c = document.GetCharAt(i);
if (c == openingBrace) {
startOffsets.Push(i);
} else if (c == closingBrace && startOffsets.Count > 0) {
int startOffset = startOffsets.Pop();
// don't fold if opening and closing brace are on the same line
if (startOffset < lastNewLineOffset) {
newFoldings.Add(new NewFolding(startOffset, i + 1));
}
} else if (c == '\n' || c == '\r') {
lastNewLineOffset = i + 1;
}
}
newFoldings.Sort((a,b) => a.StartOffset.CompareTo(b.StartOffset));
return newFoldings;
}
This works as expected but one issue is remaining
There is always a last - icon on the last brace. I tried to remove that,but when I look at the list newFoldings I can see that there are only 3 foldings there. So where is the fourth coming from?
EDIT
According to Daniel Grünwald the problem is that I have to be using to different folding managers. However I can't find any statement in my initialisation code where I set a second FoldingManager. Maybe any hints?
private void textEditor_Loaded(object sender, RoutedEventArgs e)
{
LoadSourceCode();
textEditor.Background = Brushes.Green;
textEditor.IsReadOnly = true;
textEditor.ShowLineNumbers = true;
using (Stream s = this.GetType().Assembly.GetManifestResourceStream("Prototype_Concept_2.View.Layouts.CustomHighlighting.xshd"))
{
using (XmlTextReader reader = new XmlTextReader(s))
{
textEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
}
}
(textEditor.TextArea as IScrollInfo).ScrollOwner.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
(textEditor.TextArea as IScrollInfo).ScrollOwner.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
FoldingManager foldingManager = FoldingManager.Install(textEditor.TextArea);
BraceFoldingStrategy foldingStrategy = new BraceFoldingStrategy();
foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document);
TextArea txt = textEditor.TextArea;
ObservableCollection<UIElement> margins = txt.LeftMargins;
foreach (UIElement margin in margins)
{
if ((margin as FoldingMargin) != null)
{
Contacts.AddPreviewContactDownHandler(margin as FoldingMargin, OnDown);
}
}
Main.Children.Remove(textEditor);
ScrollHost.Width = textEditor.Width;
ScrollHost.Height = textEditor.Height;
ScrollHost.Content = textEditor;
textEditor.Background = Brushes.Transparent;
ScrollHost.Background = Brushes.Transparent;
}
EDIT 2
I checked that the currently installed FoldingManager has 3 foldings, but I still don't know where the fourth folding is defined.