Poor man's syntax highlighting

time to read 2 min | 389 words

Before getting to the more complex scenarios of creating professional DSL, I wanted to start by showing how you can easily create your own syntax highlighting.

This was the result:

image

And this is the actual code that makes this happens:

private void codeTextBox_TextChanged(object sender, EventArgs e)
{
    int prevSelectionStart = codeTextBox.SelectionStart;
    int prevSelectionLength = codeTextBox.SelectionLength;
    codeTextBox.SelectionStart = 0;
    codeTextBox.SelectionLength = codeTextBox.TextLength;
    codeTextBox.SelectionColor = DefaultForeColor;

    var keyWords = new[] { "specification", "requires", "users_per_machine", "same_machine_as" };
    foreach (string keyWord in keyWords)
    {
        MatchCollection matches = Regex.Matches(codeTextBox.Text, keyWord);
        foreach (Match match in matches)
        {
            codeTextBox.SelectionStart = match.Index;
            codeTextBox.SelectionLength = match.Length;
            codeTextBox.SelectionColor = Color.DarkOrchid;
        }
    }
    foreach (Match match in Regex.Matches(codeTextBox.Text, @"@[\w\d_]+"))
    {
        codeTextBox.SelectionStart = match.Index;
        codeTextBox.SelectionLength = match.Length;
        codeTextBox.SelectionColor = Color.DarkSeaGreen;
    }
    foreach (Match match in Regex.Matches(codeTextBox.Text, @" \d+"))
    {
        codeTextBox.SelectionStart = match.Index;
        codeTextBox.SelectionLength = match.Length;
        codeTextBox.SelectionColor = Color.DarkRed;
    }

    codeTextBox.SelectionStart = prevSelectionStart;
    codeTextBox.SelectionLength = prevSelectionLength;
}

The code in the book comes with the following warning:

The code suffers from multiple bugs, issues and is generally not suited for anything but the simplest scenarios.