wordBoundaryAtPt method
Returns the TextRange for the text at the provided Offset.
Implementation
TextRange? wordBoundaryAtPt(Offset pt, {bool onlyIfInRect = true}) {
assert(rp != null);
if (rp != null && (!onlyIfInRect || rect.contains(pt))) {
// Get the text position closest to the provided [Offset].
final textPosition = rp!.getPositionForOffset(_toLocalPt(pt));
// If the `pt` is on the right side of the last letter of a word,
// `getPositionForOffset` returns the position AFTER the word, so
// we subtract 1 from the position to counteract that.
//
// Note, word boundary ranges are clamped to the length of [text]
// because they can extend into clipped hidden trailing text, which
// [from] excludes from [text].
final range = _clampedToTextLength(
rp!.getWordBoundary(
textPosition.offset == 0
? textPosition
: TextPosition(offset: textPosition.offset - 1),
),
);
if (range.start >= 0 && range.end > range.start) {
// If the `pt` is on the left side of the first letter of a word,
// the range will be of the whitespace or punctuation before the
// word, so check for that...
if (textPosition.offset > 0 && _isNonWordRange(range)) {
final next = _clampedToTextLength(rp!.getWordBoundary(textPosition));
if (!_isNonWordRange(next)) {
return next;
}
// Otherwise, `next` is still non-word, which happens when the
// position has upstream affinity (e.g. it was clamped to the end
// of a line). If the range is visible punctuation (e.g. a closing
// quote at the end of a paragraph), select it; if it is invisible
// whitespace, select the word before it.
if (!_isWhitespaceRange(range)) {
return range;
}
if (range.start > 0) {
return _clampedToTextLength(
rp!.getWordBoundary(TextPosition(offset: range.start - 1)),
);
}
}
return range;
} else {
// dmPrint('Word not found, invalid text range: $range');
}
}
return null;
}