insertNewlineKeepIndent function

bool insertNewlineKeepIndent(
  1. StateCommandTarget target
)

Replace the selection with a newline and keep the same indentation.

Implementation

bool insertNewlineKeepIndent(StateCommandTarget target) {
  final state = target.state;

  final result = state.changeByRange((range) {
    final line = state.doc.lineAt(range.from);
    final match = RegExp(r'^\s*').firstMatch(line.text);
    final indent = match?.group(0) ?? '';

    return ChangeByRangeResult(
      changes: [ChangeSpec(from: range.from, to: range.to, insert: '${state.lineBreak}$indent')],
      range: EditorSelection.cursor(range.from + indent.length + 1),
    );
  });

  target.dispatch(state.update([
    TransactionSpec(
      changes: result.changes,
      selection: result.selection,
      scrollIntoView: true,
      userEvent: 'input',
    ),
  ]));
  return true;
}