使用C#匹配RichTextBox中的括号和缩进



我想制作一个代码编辑控件,它可以像Visual Studio一样格式化文本,到目前为止,我已经实现了语法高亮显示和自动补全,但我想用嵌套大括号格式化文本。例如:考虑一个For循环,

for(int i=0;i<=10;i++)
{
Function_One();              //This should be a tab away from first brace
Function_Two();              //So with this
if(a==b)                     //So with this
{                            //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
}                            //This should be four tabs away from first brace
}

现在我想要的是这个应该看起来像这样,

for(int i=0;i<=10;i++)
{
   Function_One();              
   Function_Two();              
   if(a==b)                     
   {                            
      MessageBox.Show("Some text");
   }                            
}

我已经尝试过正则表达式,但在某些时候它们无法匹配,所以我尝试将其与代码匹配,但代码无法匹配嵌套很深的代码,或者很难实现,那么有什么方法可以实现这一点吗?还有一件事我正在使用C#在Winforms控件RichTextBox中完成。

这绝不是一个简单的壮举,我不知道有任何工具或插件可以让你利用,我唯一的建议是研究Monosdevelop对此的实现。

有关详细信息,请参阅MonoDevelop的github。

我认为实现这一点的最佳方法是为表单创建一些全局变量:

private int _nestedBracketCount = 0;
private const string TabString = "    ";
private const int TabSpaces = 4;

然后在富文本框的KeyPressed事件处理程序中处理所有这些:

private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
    var currentLength = richTextBox1.Text.Length;
    if (e.KeyChar == '{') {
        // need to increment bracket counter
        _nestedBracketCount++;
    } else if (e.KeyChar == '}') {
        // remove last #(TabSpaces) characters from the richtextbox
        richTextBox1.Text.Remove(currentLength - TabSpaces);
        _nestedBracketCount--;
        richTextBox1.AppendText("}");
        e.Handled = true;
    } else if (e.KeyChar == (char)13) {
        // append newline and correct number of tabs.
        var formattedSpaces = string.Empty;
        for (var i = 0; i < _nestedBracketCount; i++)
            formattedSpaces += TabString;
        richTextBox1.AppendText("n" + formattedSpaces);
        e.Handled = true;
    }
}

我认为这应该为你提供一个体面的起点。

相关内容

最新更新