indent method

void indent()

Indent the current selection or insert an indent at the caret.

If a range is selected, each line in the selected block is prefixed with three spaces. The selection is adjusted to account for the added characters. If there is no selection (collapsed caret), three spaces are inserted at the caret position.

The method uses replaceRange and setSelectionSilently to update the document and selection without triggering external selection side effects.

Implementation

void indent() {
  if (selection.baseOffset != selection.extentOffset) {
    final selStart = selection.start;
    final selEnd = selection.end;

    final lineStart = text.lastIndexOf('\n', selStart - 1) + 1;
    int lineEnd = text.indexOf('\n', selEnd);
    if (lineEnd == -1) lineEnd = text.length;

    final selectedBlock = text.substring(lineStart, lineEnd);
    final indentedBlock = selectedBlock
        .split('\n')
        .map((line) => '   $line')
        .join('\n');

    final lines = selectedBlock.split('\n');
    final addedChars = 3 * lines.length;
    final newSelection = TextSelection(
      baseOffset: selection.baseOffset + 3,
      extentOffset: selection.extentOffset + addedChars,
    );

    replaceRange(lineStart, lineEnd, indentedBlock);
    setSelectionSilently(newSelection);
  } else {
    insertAtCurrentCursor('   ');
  }
}