A
A
Avery0072013-11-29 16:59:22
Syntax highlighting
Avery007, 2013-11-29 16:59:22

Syntax highlighting in RichTextBox

I am writing a PHP editor for myself, I ran into a problem with syntax highlighting. For 2 days I searched for solutions on the Internet, but all either do not work as they should, or do not fit. Please write a piece of code so that at least the word class is highlighted . Then I'll finish it for myself. Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
noname_d, 2013-11-30
@Avery007

As far as I know, this can only be done using the SelectionColor property. Those. first you need to set the Selection to the desired section of the text, and then set the color. More or less like this:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    var currentSelStart = richTextBox1.SelectionStart;
    var currentSelLength = richTextBox1.SelectionLength;

    richTextBox1.SelectAll();
    richTextBox1.SelectionColor = SystemColors.WindowText;

    var matches = Regex.Matches(richTextBox1.Text, @"\bclass\b");
    foreach (var match in matches.Cast<Match>())
    {
        richTextBox1.Select(match.Index, match.Length);
        richTextBox1.SelectionColor = Color.Blue;
    }

    richTextBox1.Select(currentSelStart, currentSelLength);
    richTextBox1.SelectionColor = SystemColors.WindowText;
}

Of course, recoloring all the text with each change is wrong. It needs to be done in a better way. In addition, it is desirable to disable redrawing for the duration of colorization, otherwise unwanted blinking is possible with a large text size. In the example, this is not, but there seems to be a solution.

A
Avery007, 2013-12-01
@Avery007

Thank you very much. But if it's wrong to colorize all the text with every change, then how to proceed? For example, how is this implemented in notepad++?

N
noname_d, 2013-12-01
@noname_d

I don't know how Notepad++ implements this, but it's best to only update highlighting for lines that have changed. Although in this case there are 2 difficulties: firstly, it is necessary to somehow track changes and, secondly, to handle the case when the highlighted token is located on several lines (for example, many languages ​​​​allow you to split strings enclosed in quotes; is this fair? for PHP - I don't remember).

A
Avery007, 2013-12-01
@Avery007

In principle, there is such an idea:
In TextChanged, track where the cursor was, and compare what has changed with the previous version, and color the changed text, and recolor everything when copying. By the way, do you know how to track the moment when text is copied in the RichTextBox?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question