SOMS/test/ISMSTcpCmdWpfAppDemo/JsonFoldingStrategy.cs
2025-03-10 18:15:27 +08:00

43 lines
1.2 KiB
C#

using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
namespace ISMSTcpCmdWpfAppDemo
{
public class JsonFoldingStrategy
{
public void UpdateFoldings(FoldingManager manager, TextDocument document)
{
var foldings = new List<NewFolding>();
var text = document.Text;
Stack<int> startOffsets = new Stack<int>();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == '{' || c == '[')
{
startOffsets.Push(i);
}
else if (c == '}' || c == ']')
{
if (startOffsets.Count > 0)
{
int start = startOffsets.Pop();
foldings.Add(new NewFolding(start, i + 1));
}
}
}
// 按 StartOffset 升序排序并去重
var sortedFoldings = foldings
.GroupBy(f => f.StartOffset)
.Select(g => g.First())
.OrderBy(f => f.StartOffset)
.ToList();
manager.UpdateFoldings(sortedFoldings, document.TextLength);
}
}
}