RichTextBox中的代码折叠

时间:2013-08-09 22:13:23

标签: c# regex code-folding

我正在使用C#从Winforms RichTextBox派生的代码编辑器。我已经实现了自动完成和语法高亮,但代码折叠有点不同。我想要实现的是:

以下代码:

public static SomeFunction(EventArgs e)
{
    //Some code
    //Some code
    //Some code
    //Some code
    //Some code
    //Some code
}

应该成为:

public static SomeFunction(EventArgs e)[...]

[...]是您在[...]处悬停时在工具提示中显示的缩短代码 任何想法或建议如何使用正则表达式或程序代码?

1 个答案:

答案 0 :(得分:1)

我创建了一个解析器,它将返回代码折叠位置的索引。

  • 折叠分隔符由正则表达式定义。
  • 您可以指定开始和结束索引,这样您就不必在更新某个区域时检查整个代码。
  • 如果代码格式不正确,它将抛出异常,随时可以更改该行为。一种替代方案可能是它一直向上移动堆栈,直到找到合适的结束令牌。

折叠查找器

public class FoldFinder
{
    public static FoldFinder Instance { get; private set; }

    static FoldFinder()
    {
        Instance = new FoldFinder();
    }

    public List<SectionPosition> Find(string code, List<SectionDelimiter> delimiters, int start = 0,
        int end = -1)
    {
        List<SectionPosition> positions = new List<SectionPosition>();
        Stack<SectionStackItem> stack = new Stack<SectionStackItem>();

        int regexGroupIndex;
        bool isStartToken;
        SectionDelimiter matchedDelimiter;
        SectionStackItem currentItem;

        Regex scanner = RegexifyDelimiters(delimiters);

        foreach (Match match in scanner.Matches(code, start))
        {
            // the pattern for every group is that 0 corresponds to SectionDelimter, 1 corresponds to Start
            // and 2, corresponds to End.
            regexGroupIndex = 
                match.Groups.Cast<Group>().Select((g, i) => new {
                    Success = g.Success,
                    Index = i
                })
                .Where(r => r.Success && r.Index > 0).First().Index;

            matchedDelimiter = delimiters[(regexGroupIndex - 1) / 3];
            isStartToken = match.Groups[regexGroupIndex + 1].Success;

            if (isStartToken)
            {
                stack.Push(new SectionStackItem()
                {
                    Delimter = matchedDelimiter,
                    Position = new SectionPosition() { Start = match.Index }
                });
            }
            else
            {
                currentItem = stack.Pop();
                if (currentItem.Delimter == matchedDelimiter)
                {
                    currentItem.Position.End = match.Index + match.Length;
                    positions.Add(currentItem.Position);

                    // if searching for an end, and we've passed it, and the stack is empty then quit.
                    if (end > -1 && currentItem.Position.End >= end && stack.Count == 0) break;
                }
                else
                {
                    throw new Exception(string.Format("Invalid Ending Token at {0}", match.Index)); 
                }
            }
        }

        if (stack.Count > 0) throw new Exception("Not enough closing symbols.");

        return positions;
    }

    public Regex RegexifyDelimiters(List<SectionDelimiter> delimiters)
    {
        return new Regex(
            string.Join("|", delimiters.Select(d =>
                string.Format("(({0})|({1}))", d.Start, d.End))));
    }

}

public class SectionStackItem
{
    public SectionPosition Position;
    public SectionDelimiter Delimter;
}

public class SectionPosition
{
    public int Start;
    public int End;
}

public class SectionDelimiter
{
    public string Start;
    public string End;
}

示例查找

下面的示例匹配由{,}[,]分隔的折叠,并且在符号后面直到;。我没有看到太多的IDE折叠为每一行,但它可能很方便很长的代码片段,如LINQ查询。

var sectionPositions = 
    FoldFinder.Instance.Find("abc { def { qrt; ghi [ abc ] } qrt }", new List<SectionDelimiter>(
        new SectionDelimiter[3] {
            new SectionDelimiter() { Start = "\\{", End = "\\}" },
            new SectionDelimiter() { Start = "\\[", End = "\\]" },
            new SectionDelimiter() { Start = "(?<=\\[|\\{|;|^)[^[{;]*(?=;)", End = ";" },
        }));