styleRanges function

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

Styles ranges in an ANSI string.

Existing ANSI styles are preserved outside the styled ranges. Ranges MUST not overlap.

Implementation

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

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

  final stripped = Ansi.stripAnsi(s);

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

    final segment = _cutPlainByCells(stripped, r.start, r.end);
    buf.write(r.style.render(segment));
    lastIdx = r.end;
  }

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