textWrapSelection function

TextCommandResult textWrapSelection({
  1. required TextDocument document,
  2. required TextOffsetStateSnapshot state,
  3. required String before,
  4. String? after,
})

Implementation

TextCommandResult textWrapSelection({
  required TextDocument document,
  required TextOffsetStateSnapshot state,
  required String before,
  String? after,
}) {
  final selection = normalizedSelectionRange(
    state.selectionBaseOffset,
    state.selectionExtentOffset,
  );
  if (selection == null || selection.start == selection.end) {
    return _unchangedDocumentCommandResult(document, state);
  }

  final suffix = after ?? before;
  if (before.isEmpty && suffix.isEmpty) {
    return _unchangedDocumentCommandResult(document, state);
  }

  final selected = document.textInRange(
    startOffset: selection.start,
    endOffset: selection.end,
  );
  final working = document.copy();
  final result = edit_ops.replaceDocumentTextRange(
    working,
    start: selection.start,
    end: selection.end,
    replacement: '$before$selected$suffix',
  );
  final nextSelectionStart = selection.start + before.characters.length;
  final nextSelectionEnd = nextSelectionStart + selected.characters.length;

  return _documentCommandResult(
    working,
    cursorOffset: nextSelectionEnd,
    selectionBaseOffset: nextSelectionStart,
    selectionExtentOffset: nextSelectionEnd,
    documentChange: result.change,
    changed: result.changed,
  );
}