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!
I know this is a pretty old question, but I thought I would share my solution. I am not sure if this solution has been implemented into AvalonEdit, since this question was originally answered, but I find the OffsetColorizer class doesn't actually select the line: it just changes the line's background colour.
My solution is as follows:
However, this can be extended further like so:
I find that this solution works better is that rather than just colouring the line, it actually selects it: meaning it can be copied using Ctrl+C.
I Hope this helps people in the future.
Did you see this in this article - it seems to be exactly what are you asking for:
It highlights word AvalonEdit with bold.
You need to create a custom ColorizingTransformer to do that. The above example is actually highlighting a specific word. Still, you can change it a little bit to to colorize or highlight a portion.
I used Avalon TextEditor for my Console+ project (which is in a very primitive stage at the moment)
And you can add the colorizer to the editor by adding it to LineTransformers collection.
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.