codeInsertIndentedNewline function

TextCommandResult codeInsertIndentedNewline({
  1. required TextDocument document,
  2. required TextOffsetStateSnapshot state,
  3. required int indentWidth,
  4. String? language,
})

Implementation

TextCommandResult codeInsertIndentedNewline({
  required TextDocument document,
  required TextOffsetStateSnapshot state,
  required int indentWidth,
  String? language,
}) {
  final cursor = document.positionForOffset(state.cursorOffset);
  final lineGraphemes = document.lineGraphemesAt(cursor.line);
  final beforeCursor = lineGraphemes.take(cursor.column).join();
  final afterCursor = lineGraphemes.skip(cursor.column).join();
  final currentLine = lineGraphemes.join();
  final baseIndent = codeLeadingIndent(currentLine);
  final trimmedBefore = beforeCursor.trimRight();
  final blockSuffix = state.hasSelection
      ? null
      : codeBlockNewlineSuffix(
          beforeCursor: trimmedBefore,
          afterCursor: afterCursor,
          baseIndent: baseIndent,
        );

  final additionalIndent =
      codeShouldIncreaseIndentAfter(trimmedBefore, language: language)
      ? ' ' * (indentWidth < 1 ? 1 : indentWidth)
      : '';
  final trailingSuffix = blockSuffix?.text ?? '';
  final trailingSuffixReplaceCount = blockSuffix?.consumedColumns ?? 0;
  final cursorInsertion = '\n$baseIndent$additionalIndent';
  final replacement = '$cursorInsertion$trailingSuffix';

  final start = state.hasSelection
      ? normalizedSelectionRange(
              state.selectionBaseOffset,
              state.selectionExtentOffset,
            )?.start ??
            state.cursorOffset
      : state.cursorOffset;
  final endBase = state.hasSelection
      ? normalizedSelectionRange(
              state.selectionBaseOffset,
              state.selectionExtentOffset,
            )?.end ??
            state.cursorOffset
      : state.cursorOffset;
  final end = state.hasSelection
      ? endBase
      : (endBase + trailingSuffixReplaceCount).clamp(endBase, document.length);

  final working = document.copy();
  final result = edit_ops.replaceDocumentTextRange(
    working,
    start: start,
    end: end,
    replacement: replacement,
    cursorOffset: start + cursorInsertion.characters.length,
  );
  return _codeResultFromDocument(
    working,
    cursorOffset: result.cursorOffset,
    documentChange: result.change,
    changed: result.changed,
  );
}