compressAnsi function

String compressAnsi(
  1. String input
)

Removes redundant SGR sequences to reduce output size.

This intentionally removes repeated SGR sequences even when separated by text (e.g. "\x1b[31mred\x1b[31mred" -> "\x1b[31mredred").

Implementation

String compressAnsi(String input) {
  final sgr = RegExp(r'\x1B\[[0-9;:]*m');
  final out = StringBuffer();
  var lastEnd = 0;
  String? lastSgr;

  for (final m in sgr.allMatches(input)) {
    out.write(input.substring(lastEnd, m.start));
    final seq = m.group(0)!;

    // Normalize the empty-param reset to a stable form.
    final normalized = seq == '\x1B[m' ? '\x1B[0m' : seq;

    if (normalized != lastSgr) {
      out.write(seq);
      lastSgr = normalized;
    }

    lastEnd = m.end;
  }

  out.write(input.substring(lastEnd));
  return out.toString();
}