fromAnsi static method

Buffer fromAnsi(
  1. String ansiText, {
  2. int? width,
  3. int? height,
})

Parses an ANSI sequence string (supporting 24-bit SGR color codes, modifiers, and \r carriage returns) into a Buffer.

When width or height are provided, the returned Buffer is sized to those dimensions and cells beyond the target bounds are clipped.

Implementation

static Buffer fromAnsi(String ansiText, {int? width, int? height}) {
  final rows = <List<_ParsedAnsiCell>>[];
  var currentRow = <_ParsedAnsiCell>[];
  var col = 0;
  var hasLineContent = false;
  var style = _defaultAnsiStyle;

  var idx = 0;
  final len = ansiText.length;

  while (idx < len) {
    final cu = ansiText.codeUnitAt(idx);
    if (cu == 0x1B) {
      final escaped = _consumeAnsiEscape(ansiText, idx, style);
      idx = escaped.nextIdx;
      style = escaped.style;
    } else if (_isStandaloneCarriageReturn(ansiText, idx, cu)) {
      col = 0;
      hasLineContent = true;
      idx++;
    } else if (cu == 0x0D || cu == 0x0A) {
      rows.add(currentRow);
      currentRow = <_ParsedAnsiCell>[];
      col = 0;
      hasLineContent = false;
      idx += cu == 0x0D ? 2 : 1;
    } else {
      final step = _readNextGrapheme(ansiText, idx, cu);
      if (step == null) break;
      col = _writeParsedGrapheme(currentRow, col, step.char, style);
      hasLineContent = true;
      idx = step.nextIdx;
    }
  }

  if (currentRow.isNotEmpty || hasLineContent) {
    rows.add(currentRow);
  }

  return _materializeParsedRows(rows, width: width, height: height);
}