replaceText method

void replaceText(
  1. int index,
  2. int len,
  3. Object? data,
  4. TextSelection? textSelection, {
  5. bool ignoreFocus = false,
})

Implementation

void replaceText(int index, int len, Object? data, TextSelection? textSelection, {bool ignoreFocus = false}) {
  assert(data is String || data is Embeddable);

  if (onReplaceText != null && !onReplaceText!(index, len, data)) {
    return;
  }

  Delta? delta;
  if (len > 0 || data is! String || data.isNotEmpty) {
    delta = document.replace(index, len, data);
    var shouldRetainDelta = toggledStyle.isNotEmpty && delta.isNotEmpty && delta.length <= 2 && delta.last.isInsert;
    if (shouldRetainDelta && toggledStyle.isNotEmpty && delta.length == 2 && delta.last.data == '\n') {
      // if all attributes are inline, shouldRetainDelta should be false
      final anyAttributeNotInline = toggledStyle.values.any((attr) => !attr.isInline);
      if (!anyAttributeNotInline) {
        shouldRetainDelta = false;
      }
    }
    if (shouldRetainDelta) {
      final retainDelta = Delta()
        ..retain(index)
        ..retain(data is String ? data.length : 1, toggledStyle.toJson());
      document.compose(retainDelta, ChangeSource.local);
    }
  }

  if (_keepStyleOnNewLine) {
    final style = getSelectionStyle();
    final notInlineStyle = style.attributes.values.where((s) => !s.isInline);
    toggledStyle = style.removeAll(notInlineStyle.toSet());
  } else {
    toggledStyle = Style();
  }

  if (textSelection != null) {
    if (delta == null || delta.isEmpty) {
      _updateSelection(textSelection, ChangeSource.local);
    } else {
      final user = Delta()
        ..retain(index)
        ..insert(data)
        ..delete(len);
      final positionDelta = getPositionDelta(user, delta);
      _updateSelection(
        textSelection.copyWith(
          baseOffset: textSelection.baseOffset + positionDelta,
          extentOffset: textSelection.extentOffset + positionDelta,
        ),
        ChangeSource.local,
      );
    }
  }

  if (ignoreFocus) {
    ignoreFocusOnTextChange = true;
  }
  notifyListeners();
  ignoreFocusOnTextChange = false;
}