replaceRange method

void replaceRange(
  1. int start,
  2. int end,
  3. String replacement, {
  4. bool preserveOldCursor = false,
})

Replace a range of text with new text. Used for clipboard operations and text manipulation.

Implementation

void replaceRange(
  int start,
  int end,
  String replacement, {
  bool preserveOldCursor = false,
}) {
  if (_undoController?.isUndoRedoInProgress ?? false) return;

  final selectionBefore = _selection;
  _flushBuffer();
  final safeStart = start.clamp(0, _rope.length);
  final safeEnd = end.clamp(safeStart, _rope.length);
  final deletedText = safeStart < safeEnd
      ? _rope.substring(safeStart, safeEnd)
      : '';
  final supportsPullSemanticSync =
      lspConfig?.supportsSemanticTokensPull ?? true;

  _suppressLspFallbackSync = true;
  try {
    if (supportsPullSemanticSync) {
      _scheduleLspIncrementalSync(safeStart, safeEnd, replacement);
    }

    final result = _rope.core.replaceRangeAndUpdateSelection(
      start: BigInt.from(safeStart),
      end: BigInt.from(safeEnd),
      replacement: replacement,
      preserveOldCursor: preserveOldCursor,
      oldBase: BigInt.from(selectionBefore.baseOffset),
      oldExtent: BigInt.from(selectionBefore.extentOffset),
    );
    _currentVersion++;
    final newSelection = TextSelection(
      baseOffset: result.baseOffset.toInt(),
      extentOffset: result.extentOffset.toInt(),
    );
    _selection = newSelection;
    dirtyLine = _rope.getLineAtOffset(safeStart);
    dirtyRegion = TextRange(
      start: safeStart,
      end: safeStart + replacement.length,
    );

    if (deletedText.isNotEmpty && replacement.isNotEmpty) {
      _recordReplacement(
        safeStart,
        deletedText,
        replacement,
        selectionBefore,
        _selection,
      );
    } else if (deletedText.isNotEmpty) {
      _recordDeletion(safeStart, deletedText, selectionBefore, _selection);
    } else if (replacement.isNotEmpty) {
      _recordInsertion(safeStart, replacement, selectionBefore, _selection);
    }

    if (!supportsPullSemanticSync) {
      _scheduleLspFullSync(text);
    }

    _invalidateImeSnapshotAndScheduleSync();
    notifyListeners();
  } finally {
    _suppressLspFallbackSync = false;
  }
}