moveLineUp method

void moveLineUp()

Moves the current line up by one line.

If the selection spans multiple lines, all selected lines are moved. The selection is adjusted accordingly after the move. Does nothing if the line is already at the top or if the controller is read-only.

Implementation

void moveLineUp() {
  if (readOnly) return;
  final selection = this.selection;
  final text = this.text;
  final selStart = selection.start;
  final selEnd = selection.end;
  final lineStart = selStart > 0
      ? text.lastIndexOf('\n', selStart - 1) + 1
      : 0;
  int lineEnd = text.indexOf('\n', selEnd);
  if (lineEnd == -1) lineEnd = text.length;
  if (lineStart == 0) return;

  final prevLineEnd = lineStart - 1;
  final prevLineStart = text.lastIndexOf('\n', prevLineEnd - 1) + 1;
  final prevLine = text.substring(prevLineStart, prevLineEnd);
  final currentLines = text.substring(lineStart, lineEnd);

  replaceRange(prevLineStart, lineEnd, '$currentLines\n$prevLine');

  final prevLineLen = prevLineEnd - prevLineStart;
  final offsetDelta = prevLineLen + 1;
  final newSelection = TextSelection(
    baseOffset: selection.baseOffset - offsetDelta,
    extentOffset: selection.extentOffset - offsetDelta,
  );
  setSelectionSilently(newSelection);
}