9

I need to highlight all occurrences of selected word in AvalonEdit. I created an instance of HihglinghtingRule class:

 var rule = new HighlightingRule()
   {
       Regex = regex, //some regex for finding occurences
       Color = new HighlightingColor {Background = new SimpleHighlightingBrush(Colors.Red)}
   };

What should I do after it ? Thanks.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Yury Permiakov
  • 135
  • 1
  • 8

2 Answers2

9

To use that HighlightingRule, you would have to create another instance of the highlighting engine (HighlightingColorizer etc.)

It's easier and more efficient to write a DocumentColorizingTransformer that highlights your word:

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
        }
    }
}
Daniel
  • 15,944
  • 2
  • 54
  • 60
  • I don't see how this answers the question. The user wanted a behavior where all words get highlighted in a text if they match. Something similar like visual studio does. – Devid Apr 13 '17 at 19:28
2

We have to decide if there is a selection or not:

TextEditor.TextArea.SelectionChanged += (sender, args) =>
{
  if (string.IsNullOrWhiteSpace(TextEditor.SelectedText))
  {
    foreach (var markSameWord in TextEditor.TextArea.TextView.LineTransformers.OfType<MarkSameWord>().ToList())
    {
      TextEditor.TextArea.TextView.LineTransformers.Remove(markSameWord);
    }
  }
  else
  {
    TextEditor.TextArea.TextView.LineTransformers.Add(new MarkSameWord(TextEditor.SelectedText));
  }
};

And here is the DocumentColorizingTransformer class:

public class MarkSameWord : DocumentColorizingTransformer
{
  private readonly string _selectedText;

  public MarkSameWord(string selectedText)
  {
    _selectedText = selectedText;
  }

  protected override void ColorizeLine(DocumentLine line)
  {
    if (string.IsNullOrEmpty(_selectedText))
    {
      return;
    }

    int lineStartOffset = line.Offset;
    string text = CurrentContext.Document.GetText(line);
    int start = 0;
    int index;

    while ((index = text.IndexOf(_selectedText, start, StringComparison.Ordinal)) >= 0)
    {
      ChangeLinePart(
        lineStartOffset + index, // startOffset
        lineStartOffset + index + _selectedText.Length, // endOffset
        element => element.TextRunProperties.SetBackgroundBrush(Brushes.LightSkyBlue));
      start = index + 1; // search for next occurrence
    }
  }
}
Suplanus
  • 1,523
  • 16
  • 30
  • There is a bug in your initial event handling logic. No matter what, even in the case of `IsNullOrWhiteSpace` you still want to iterate and remove all `LineTransformers`, otherwise when you drag-select you will accumulate all previous selections and the result will be incorrect. See this: https://pastebin.com/Z8ryZjkL – fmotion1 Aug 03 '22 at 03:47