replaceWordAtCaret function

ReplacementInfo replaceWordAtCaret(
  1. String text,
  2. int caret,
  3. String replacement, [
  4. String separator = ' ',
])

Implementation

ReplacementInfo replaceWordAtCaret(String text, int caret, String replacement,
    [String separator = ' ']) {
  if (caret < 0 || caret > text.length) {
    throw RangeError('Caret position is out of bounds.');
  }

  // Get the start and end of the word
  int start = caret;
  while (start > 0 && !separator.contains(text[start - 1])) {
    start--;
  }

  int end = caret;
  while (end < text.length && !separator.contains(text[end])) {
    end++;
  }

  // Replace the word with the replacement
  String newText = text.replaceRange(start, end, replacement);
  return (start, newText);
}