insertAtCurrentCursor method

void insertAtCurrentCursor(
  1. String textToInsert, {
  2. bool replaceTypedChar = false,
})

Insert text at the current cursor position (or replace selection).

Implementation

void insertAtCurrentCursor(
  String textToInsert, {
  bool replaceTypedChar = false,
}) {
  _flushBuffer();

  final cursorPosition = selection.extentOffset;
  final safePosition = cursorPosition.clamp(0, _rope.length);
  final currentLine = _rope.getLineAtOffset(safePosition);
  final isFolded = foldings.any(
    (fold) =>
        fold.isFolded &&
        currentLine > fold.startIndex &&
        currentLine <= fold.endIndex,
  );

  if (isFolded) {
    final newPosition = visibleText.length;
    selection = TextSelection.collapsed(offset: newPosition);
    return;
  }

  if (replaceTypedChar) {
    final ropeText = _rope.getText();
    final prefix = _getCurrentWordPrefix(ropeText, safePosition);
    final prefixStart = (safePosition - prefix.length).clamp(0, _rope.length);

    replaceRange(prefixStart, safePosition, textToInsert);
  } else {
    replaceRange(safePosition, safePosition, textToInsert);
  }
}