expandPositionToWord function

TextSelection expandPositionToWord({
  1. required String text,
  2. required TextPosition textPosition,
})

Expands a selection in both directions starting at textPosition until the selection reaches a space, or the end of the available text.

Implementation

TextSelection expandPositionToWord({
  required String text,
  required TextPosition textPosition,
}) {
  if (text.isEmpty) {
    return const TextSelection.collapsed(offset: -1);
  }

  int start = min(textPosition.offset, text.length);
  int end = min(textPosition.offset, text.length);

  // We're checking for the character before the start index because
  // TextPosition's offset indexes the character after the caret
  while (start > 0 && text[start - 1] != ' ') {
    start -= 1;
  }
  while (end < text.length && text[end] != ' ') {
    end += 1;
  }
  return TextSelection(
    baseOffset: start,
    extentOffset: end,
  );
}