textJoinLines function

TextLineCommandResult textJoinLines({
  1. required List<String> lines,
  2. required TextLineStateSnapshot state,
})

Implementation

TextLineCommandResult textJoinLines({
  required List<String> lines,
  required TextLineStateSnapshot state,
}) {
  final nextLines = lines.isEmpty ? <String>[''] : List<String>.from(lines);
  final clampedState = _clampLineStateSnapshot(state, nextLines);
  final selectedSpan = _selectedLineSpan(clampedState);
  final endLine = clampedState.hasSelection
      ? selectedSpan.endLine
      : (selectedSpan.startLine + 1).clamp(0, nextLines.length - 1);
  if (selectedSpan.startLine >= endLine) {
    return _lineResultFromSnapshot(nextLines, clampedState, changed: false);
  }

  var joined = nextLines[selectedSpan.startLine];
  for (
    var lineIndex = selectedSpan.startLine + 1;
    lineIndex <= endLine;
    lineIndex++
  ) {
    final trimmed = _trimLeadingHorizontalWhitespace(nextLines[lineIndex]);
    final separator = _lineJoinSeparator(joined, trimmed);
    if (separator.isNotEmpty) {
      joined = '$joined$separator';
    }
    joined = '$joined$trimmed';
  }

  nextLines[selectedSpan.startLine] = joined;
  nextLines.removeRange(selectedSpan.startLine + 1, endLine + 1);
  return _lineResultFromSnapshot(
    nextLines,
    TextLineStateSnapshot.collapsed(
      cursor: TextPosition(line: selectedSpan.startLine, column: joined.length),
    ),
  );
}