Smarter Syntax Highlighting

time to read 2 min | 376 words

My previous approach isn't really suited to anything but the most trivial of tasks. What we can do, however, is to utilize existing components that already built this functionality. Let us say that we want to embed a Boo's code editor in our application. Here is what we need to do:

public class TextEditorForm : Form
{
    public TextEditorForm()
    {
        var editorControl = new TextEditorControl
        {
            Dock = DockStyle.Fill
        };
        Controls.Add(editorControl);
        editorControl.Document.FormattingStrategy = new BooFormattingStrategy();
        editorControl.SetHighlighting("Boo");
    }
}
public class BooFormattingStrategy : DefaultFormattingStrategy
{
    public override void IndentLines(TextArea textArea, int begin, int end)
    {
    }

    protected override int SmartIndentLine(TextArea area, int line)
    {
        IDocument document = area.Document;
        LineSegment lineSegment = document.GetLineSegment(line - 1);
        if (document.GetText(lineSegment).EndsWith(":"))
        {
            LineSegment segment = document.GetLineSegment(line);
            string str = base.GetIndentation(area, line - 1) + Tab.GetIndentationString(document);
            document.Replace(segment.Offset, segment.Length, str + document.GetText(segment));
            return str.Length;
        }
        return base.SmartIndentLine(area, line);
    }
}

And that gives us this:

image

Nice :-)