Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetPositionAtOffset equivalent for text only?

Is there a pretty solution of a GetPositionAtOffset() equivalent which only counts text insertion positions instead of all symbols?

Motivation example in C#:

TextRange GetRange(RichTextBox rtb, int startIndex, int length) {
    TextPointer startPointer = rtb.Document.ContentStart.GetPositionAtOffset(startIndex);
    TextPointer endPointer = startPointer.GetPositionAtOffset(length);
    return new TextRange(startPointer, endPointer);
}

Edit: Until now i "solved" it this way

public static TextPointer GetInsertionPositionAtOffset(this TextPointer position, int offset, LogicalDirection direction)
{
    if (!position.IsAtInsertionPosition) position = position.GetNextInsertionPosition(direction);
    while (offset > 0 && position != null)
    {
        position = position.GetNextInsertionPosition(direction);
        offset--;
        if (Environment.NewLine.Length == 2 && position != null && position.IsAtLineStartPosition) offset --; 
    }
    return position;
}
like image 999
Markus Hartmair Avatar asked Apr 05 '13 16:04

Markus Hartmair


1 Answers

As far as I'm aware, there isn't. My suggestion is that you create your own GetPositionAtOffset method for this purpose. You can check which PointerContext the TextPointer is adjacent to by using:

TextPointer.GetPointerContext(LogicalDirection);

To get the next TextPointer which points to a different PointerContext:

TextPointer.GetNextContextPosition(LogicalDirection);

Some sample code I used in a recent project, this makes sure that the pointer context is of type Text, by looping until one is found. You could use this in your implementation and skip an offset increment if it is found:

// for a TextPointer start

while (start.GetPointerContext(LogicalDirection.Forward) 
                             != TextPointerContext.Text)
{
    start = start.GetNextContextPosition(LogicalDirection.Forward);
    if (start == null) return;
}

Hopefully you can make use of this information.

like image 56
JessMcintosh Avatar answered Nov 03 '22 09:11

JessMcintosh