AvaloniaUI / AvaloniaEdit

Avalonia-based text editor (port of AvalonEdit)
MIT License
746 stars 148 forks source link

Folding does not work #384

Closed michalss closed 10 months ago

michalss commented 10 months ago

Hi,

Folding for c# does not work at all. It does work only for XML.

Thx mike

michalss commented 10 months ago

never mind if someone needs it here its works like charm

 public class CSharpFoldingStrategy
 {
     public void UpdateFoldings(FoldingManager manager, TextDocument document)
     {
         var foldings = CreateNewFoldings(document, out var firstErrorOffset);
         manager.UpdateFoldings(foldings, firstErrorOffset);
     }

     public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
     {
         firstErrorOffset = -1;
         var newFoldings = new List<NewFolding>();
         var startOffsets = new Stack<int>();

         for (int offset = 0; offset < document.TextLength; offset++)
         {
             char c = document.GetCharAt(offset);
             switch (c)
             {
                 case '{':
                     startOffsets.Push(offset);
                     break;
                 case '}':
                     if (startOffsets.Count > 0)
                     {
                         int startOffset = startOffsets.Pop();
                         // Add a folding if the block spans more than one line
                         int startLine = document.GetLineByOffset(startOffset).LineNumber;
                         int endLine = document.GetLineByOffset(offset).LineNumber;
                         if (startLine < endLine)
                         {
                             newFoldings.Add(new NewFolding(startOffset, offset + 1));
                         }
                     }
                     break;
             }
         }

         newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
         return newFoldings;
     }
 }
antoniovalentini commented 7 months ago

Hey @michalss, thanks for this snippet. Apparently, this can be used with JSON files too. The logic seems to be based mostly on curly brackets, right?