clipAnsiByCells function

String clipAnsiByCells(
  1. String s,
  2. int start,
  3. int end
)

Clips a styled line to the exact cell interval [start, end).

Unlike cutAnsiByCells, boundaries do not snap backward to whole graphemes. A partially intersected wide glyph or graphics payload becomes spaces with its active pen state, keeping overlays and following text at fixed columns. Missing text beyond the line's end is not padded. SGR and OSC 8 state is restored at the start; the caller owns resetting that state after the clip.

Implementation

String clipAnsiByCells(String s, int start, int end) {
  if (start < 0) start = 0;
  if (end <= start) return '';
  final tokens = _tokenizeAnsi(s);
  final length = tokens.fold<int>(0, (sum, token) => sum + token.visibleWidth);
  if (start >= length) return '';
  final out = StringBuffer()..write(_penStateAt(tokens, start));
  var cell = 0;
  for (final token in tokens) {
    if (cell >= end) break;
    if (token.visibleWidth == 0) {
      if (cell >= start) out.write(token.raw);
      continue;
    }
    final next = cell + token.visibleWidth;
    if (next > start && cell < end) {
      if (cell >= start && next <= end) {
        out.write(token.raw);
      } else {
        final left = cell < start ? start : cell;
        final right = next > end ? end : next;
        out.write(' ' * (right - left));
      }
    }
    cell = next;
  }
  return out.toString();
}