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
}
}
}