Reputation: 11439
This is driving me nuts. I'm writing a text highlighter, which ultimately calls the code:
TextPointer caret = textBox.CaretPosition;
TextPointer contentStart = textBox.Document.ContentStart;
TextPointer highlightStart = contentStart.GetPositionAtOffset(startPosition + 1, LogicalDirection.Forward);
TextPointer highlightEnd = contentStart.GetPositionAtOffset(endPosition + 2, LogicalDirection.Forward);
textBox.Selection.Select(highlightStart, highlightEnd);
textBox.Selection.ApplyPropertyValue(textElementProperty, value);
textBox.Selection.Select(caret, caret);
textBox.CaretPosition = caret;
The actual code itself works fine.... once. The problem is that once it highlights, it's like the RichTextBox
is adding in hidden padding around my highlighting such that when I run my Regex
over the text, the Regex
returns the correct offsets, but then it doesn't map correctly to the right letter in the RichTextBox
. So for example, if I were to highlight the word 'fox' as in:
The quick brown fox jumped over the lazy dog.
The word 'fox' would be highlighted correctly, but then if I were to change 'dog' to fox it would show up like:
The quick brown fox jumped over the laz y fo ox.
Removing the first 'fox' however would correct the latter version so that it would read:
The quick brown dog jumped over the lazy fox.
It's almost like the RichTextBox
is adding in some padding which I can't account for when doing the text scan.
Update
I found a hacky solution to the problem. But, it only seems to further confirm my suspicions. If I apply the coloration in reverse this seems to fix it, as in:
protected override void TextChanged(TextChangedEventArgs args) {
var matches = regex.Matches(base.Text)
.Cast<Match>()
.Select(match => new {
Start = match.Index,
End = match.Index + match.Length
}).Reverse();
foreach (var match in matches) {
Colorize(match.Start, match.End, TextElement.ForegroundProperty, Brushes.Blue);
}
}
Which seems like I shouldn't have to do it. Seriously look like it's adding padding or something.
Upvotes: 0
Views: 576
Reputation: 332
The TextPointer API is counting not just characters but symbols which can include opening and closing tags etc. See the remarks section here on MSDN on what is counted as a symbol http://msdn.microsoft.com/en-us/library/ms598662.aspx
So when you add in some formatting it will throw out symbol offsets you have saved later in the text. You would have to apply formatting search from there on again etc. Or doing it in reverse also works.
Upvotes: 1