Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AvalonEdit WPF TextEditor (SharpDevelop): How to highlight a specific range of text?

The incredibly awesome AvalonEdit WPF TextEditor control seems to lack an important feature, or at least i can't figure it out. Given an offset and a length, highlight that portion in the TextDocument with a HighlightColor. Simple, right?

Apprentely not. I've RTFM, and the documentation on "Syntax Highlighting" confused me even more. Someone else asked the same question in the SharpDevelop forums, and i'm afraid i can't make sense of Herr Grunwald's answer.

Here's my attempt, using the DocumentHighlighter class (of course it doesn't work):

    textEditor1.Text = "1234567890";

    HighlightingColor c = new HighlightingColor() { FontWeight = FontWeights.ExtraBold };

    DocumentHighlighter dh = new DocumentHighlighter(textEditor1.Document, new HighlightingRuleSet());
    HighlightedLine hl = dh.HighlightLine(1);

    hl.Sections.Add(new HighlightedSection() { Color = c, Offset = 1, Length = 3 });

Thank you for helping!

like image 224
Matt Crouch Avatar asked Feb 17 '11 13:02

Matt Crouch


2 Answers

Did you see this in this article - it seems to be exactly what are you asking for:

public class ColorizeAvalonEdit : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
    int lineStartOffset = line.Offset;
    string text = CurrentContext.Document.GetText(line);
    int start = 0;
    int index;
    while ((index = text.IndexOf("AvalonEdit", start)) >= 0) {
        base.ChangeLinePart(
            lineStartOffset + index, // startOffset
            lineStartOffset + index + 10, // endOffset
            (VisualLineElement element) => {
                // This lambda gets called once for every VisualLineElement
                // between the specified offsets.
                Typeface tf = element.TextRunProperties.Typeface;
                // Replace the typeface with a modified version of
                // the same typeface
                element.TextRunProperties.SetTypeface(new Typeface(
                    tf.FontFamily,
                    FontStyles.Italic,
                    FontWeights.Bold,
                    tf.Stretch
                ));
            });
        start = index + 1; // search for next occurrence
}   }   }

It highlights word AvalonEdit with bold.

like image 67
Matěj Zábský Avatar answered Sep 20 '22 11:09

Matěj Zábský


Some background info: AvalonEdit is a code editor, not a rich text editor. There is no such thing as "highlight a portion of the document" - the document only stores plain text.

Highlighting is computed on-demand, only for the lines currently in view. If you want custom highlighting, you need to add a step to the highlighting computation - this is what the ColorizeAvalonEdit class in the example posted by mzabsky is doing.

like image 28
Daniel Avatar answered Sep 23 '22 11:09

Daniel