replaceWordAtCaret function

ReplacementInfo replaceWordAtCaret(
  1. String text,
  2. int caret,
  3. String replacement,
  4. bool isSeparator(
    1. String char
    ),
)

Replaces the word at the caret position with a new string.

Finds the word boundaries around the caret using the separator predicate and replaces that word with the provided replacement string.

Parameters:

  • text (String, required): The text to modify.
  • caret (int, required): The caret position (0 to text.length).
  • replacement (String, required): The replacement text.
  • isSeparator (bool Function(String), required): Predicate to identify separator characters.

Returns: ReplacementInfo — a record (int start, String newText) containing the start index of the replacement and the new text.

Throws RangeError if caret is out of bounds.

Example:

final (start, newText) = replaceWordAtCaret(
  'Hello world',
  7,
  'universe',
  (ch) => ch == ' ',
);
// Returns (6, 'Hello universe')

Implementation

ReplacementInfo replaceWordAtCaret(String text, int caret, String replacement,
    bool Function(String char) isSeparator) {
  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 && !isSeparator(text[start - 1])) {
    start--;
  }

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

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