代码中自动缩进括号的算法

Ele*_*iac 4 c# auto-indent winforms

我正在研究代码编辑器(WinForms),我想知道如何使用 { 和 } 的功能,特别是使用括号(打开和关闭)的自动缩进,就像在实际代码编辑器中一样。

---|> { 和 }

像这样 1:

在此处输入图片说明

编辑器是一个名为 rtb 的富文本框。

Wii*_*axx 5

好的,我的解决方案有问题,但足以让您了解它是如何工作的

我的结果:

{
        {
                {
                        }
                }
        }
Run Code Online (Sandbox Code Playgroud)

这里是我的代码

public partial class Form1 : Form
{
    private bool FLAG_Selftimer = false;
    private bool FLAG_KeyPressed = false;
    private int pos = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        var rtb = sender as RichTextBox;
        var point = rtb.SelectionStart;

        if (!FLAG_Selftimer)
        {
            rtb.Text = ReGenerateRTBText(rtb.Text);
            FLAG_KeyPressed = false;
        }
        else
        {
            point ++;
            FLAG_Selftimer = false;
        }

        rtb.SelectionStart = point;
    }



    private string ReGenerateRTBText(string Text)
    {
        string[] text = Regex.Split(Text,"\n");

        int lvl = 0;
        string newString = "";
        foreach (string line in text)
        {
            line.TrimStart(' ');
            newString += indentation(lvl) + line.TrimStart(' ') + "\n";
            if (line.Contains("{"))
                lvl++;
            if (line.Contains("}"))
                lvl--;
        }

        FLAG_Selftimer = true;
        return (!FLAG_KeyPressed) ? newString : newString.TrimEnd('\n');
    }

    private string indentation(int IndentLevel)
    {
        string space = "";
        if(IndentLevel>0)
            for (int lvl = 0; lvl < IndentLevel; lvl++)
            {
                    space += " ".PadLeft(8);
            }

        return space;
    }

    private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        FLAG_KeyPressed = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您