overlayBackgroundRangesPreservingAnsi function

String overlayBackgroundRangesPreservingAnsi(
  1. String s,
  2. Iterable<StyleRange> ranges
)

Applies range backgrounds to an ANSI string while preserving existing text styling inside those ranges.

This is useful for selection-style overlays where the selected content should keep its original foreground and inline styling, but still show a shared selection background. If a token already carries its own background, that background is preserved.

Implementation

String overlayBackgroundRangesPreservingAnsi(
  String s,
  Iterable<StyleRange> ranges,
) {
  final rs = ranges.toList(growable: false);
  if (rs.isEmpty) return s;

  final buf = StringBuffer();
  var lastIdx = 0;

  for (final r in rs) {
    if (r.start > lastIdx) {
      buf.write(_cutAnsiByCells(s, lastIdx, r.start));
    }

    final segment = _cutAnsiByCells(s, r.start, r.end);
    buf.write(_overlaySelectionBackground(segment, r.style));
    lastIdx = r.end;
  }

  buf.write(_truncateLeftAnsiByCells(s, lastIdx));
  return buf.toString();
}