duplicateLine method

void duplicateLine()

Duplicates the current line or selected text.

If text is selected, duplicates the selected text. If no selection, duplicates the line at the cursor position. The cursor is moved to the end of the duplicated content. Does nothing if the controller is read-only.

Implementation

void duplicateLine() {
  if (readOnly) return;
  final text = this.text;
  final selection = this.selection;

  if (selection.start != selection.end) {
    final selectedText = text.substring(selection.start, selection.end);
    replaceRange(selection.end, selection.end, selectedText);
    setSelectionSilently(
      TextSelection.collapsed(offset: selection.end + selectedText.length),
    );
  } else {
    final caret = selection.extentOffset;
    final prevNewline = (caret > 0) ? text.lastIndexOf('\n', caret - 1) : -1;
    final nextNewline = text.indexOf('\n', caret);
    final lineStart = prevNewline == -1 ? 0 : prevNewline + 1;
    final lineEnd = nextNewline == -1 ? text.length : nextNewline;
    final lineText = text.substring(lineStart, lineEnd);

    replaceRange(lineEnd, lineEnd, '\n$lineText');
    setSelectionSilently(TextSelection.collapsed(offset: lineEnd + 1));
  }
}