簡體   English   中英

語法僅在一行中突出顯示C#中的richtextbox

[英]Syntax highlighting richtextbox in C# on a single line only

我正在使用Richtextbox開發自己的語法熒光筆。 它已經在工作,但是我注意到,當有許多行代碼時,鍵入速度會大大降低。 這是因為我的語法高亮功能是對每次Richtextbox中的所有更改進行着色。 下面是該函數的最小示例,以了解其工作原理:

private void colorCode()
{
    // getting keywords/functions
    string keywords = @"\b(class|function)\b";
    MatchCollection keywordMatches = Regex.Matches(codeBox.Text, keywords);

    // saving the original caret position + forecolor
    int originalIndex = codeBox.SelectionStart;
    int originalLength = codeBox.SelectionLength;
    Color originalColor = Color.Black

    // focuses a label before highlighting (avoids blinking)
    titleLabel.Focus();;

    // removes any previous highlighting (so modified words won't remain highlighted)
    codeBox.SelectionStart = 0;
    codeBox.SelectionLength = codeBox.Text.Length;
    codeBox.SelectionColor = originalColor;

    foreach (Match m in keywordMatches)
    {
        codeBox.SelectionStart = m.Index;
        codeBox.SelectionLength = m.Length;
        codeBox.SelectionColor = Color.Blue;
    }

    // restoring the original colors, for further writing
    codeBox.SelectionStart = originalIndex;
    codeBox.SelectionLength = originalLength;
    codeBox.SelectionColor = originalColor;

    // giving back the focus
    codeBox.Focus();
}

為了解決該問題,我想編寫一個不會更改整個Richtextbox的函數,而只是更改光標位置的行。 我意識到這仍然會在最小化代碼上引起相同的問題,但這對我來說不是問題。 問題是,我似乎無法正常工作。 到目前為止,這是我得到的:

void changeLine(RichTextBox RTB, int line, Color clr, int curPos){
    string testWords = @"\b(test1|test2)\b";
    MatchCollection testwordMatches = Regex.Matches(RTB.Lines[line], testWords);

    foreach (Match m in testwordMatches)
    {
        //RTB.SelectionStart = m.Index;
        //RTB.SelectionLength = m.Length;
        RTB.SelectionColor = Color.Blue;
    }

    RTB.SelectionStart = curPos;
    RTB.SelectionColor = Color.Black;
}

問題是,當在testWords中找到一個單詞時,它會進行着色,但是會為整個行着色,而不僅僅是單詞。 這是因為我無法找出正確選擇的方法。 所以我希望你們可以幫助我。

編輯:

我想補充一點,我確實考慮過其他解決方案,例如將行放入列表中或使用Stringbuilder。 但是這些會將行變成字符串,並且不允許我像Richtextbox那樣進行顏色格式化。

好吧,您顯然需要語言詞法分析器和解析器。 使用正則表達式無法解決此任務。 由於某些基本的語法規則(或語法的“功率等級”)(只是了解Thomsky語法層次結構),它無法完成此任務。

您需要使用一些語法工具包。 例如,ANTLR4提供語法詞法分析器/解析器生成器和一組預定義的語法。

例如,您可以在此處找到很多用戶編寫的語法(包括最新的C#語法): https : //github.com/antlr/grammars-v4

然后僅通過它生成解析器/詞法分析器,並將其作為字符串輸入。 它將輸出具有每個令牌的索引和長度的完整層次結構,您可以為它們着色而無需跳過整個豐富框。

另外,請考慮在用戶輸入之間使用一些超時,這樣就不會為每個符號着色輸出(只需保存先前標記的顏色,並使用一段時間,直到重新着色輸出然后刷新即可)。 這樣,它將像在Visual Studio中一樣順利進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM