1 using ICSharpCode.AvalonEdit.Document;
2 using ICSharpCode.AvalonEdit.Folding;
3 using ICSharpCode.NRefactory.Editor;
4 using System;
5 using System.Collections.Generic;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9
10 namespace CMS.Developer.AvalonEditor
11 {
12 /// <summary>
13 /// 大括号折叠策略
14 /// </summary>
15 public class BraceFoldingStrategy
16 {
17 public char OpeningBrace { get; set; }
18
19 public char ClosingBrace { get; set; }
20
21 public BraceFoldingStrategy()
22 {
23 this.OpeningBrace = '{';
24 this.ClosingBrace = '}';
25 }
26
27 public void UpdateFoldings(FoldingManager manager, TextDocument document)
28 {
29 int firstErrorOffset;
30 IEnumerable<NewFolding> newFoldings = CreateNewFoldings(document, out firstErrorOffset);
31 manager.UpdateFoldings(newFoldings, firstErrorOffset);
32 }
33
34 public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
35 {
36 firstErrorOffset = -1;
37 return CreateNewFoldings(document);
38 }
39
40 public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
41 {
42 List<NewFolding> newFoldings = new List<NewFolding>();
43
44 Stack<int> startOffsets = new Stack<int>();
45 int lastNewLineOffset = 0;
46 char openingBrace = this.OpeningBrace;
47 char closingBrace = this.ClosingBrace;
48 for (int i = 0; i < document.TextLength; i++)
49 {
50 char c = document.GetCharAt(i);
51 if (c == openingBrace)
52 {
53 startOffsets.Push(i);
54 }
55 else if (c == closingBrace && startOffsets.Count > 0)
56 {
57 int startOffset = startOffsets.Pop();
58 if (startOffset < lastNewLineOffset)
59 {
60 newFoldings.Add(new NewFolding(startOffset, i + 1));
61 }
62 }
63 else if (c == '/n' || c == '/r')
64 {
65 lastNewLineOffset = i + 1;
66 }
67 }
68 newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
69 return newFoldings;
70 }
71
72 }
73 }
原创文章,作者:dweifng,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/273824.html