fitAnsiToColumns function

String fitAnsiToColumns(
  1. String text,
  2. int columns, {
  3. bool closeStyles = false,
})

Truncates text to at most columns - 1 visible columns, appending an ellipsis when it is clipped.

Each grapheme cluster counts as one column and is never split, so wide characters may take more terminal cells than counted. ANSI escape sequences do not count as columns and are never cut mid-sequence. With closeStyles, clipped text that holds escape sequences ends with a reset, so a style cut off before its own reset does not bleed into later output.

Implementation

String fitAnsiToColumns(String text, int columns, {bool closeStyles = false}) {
  final maxWidth = columns - 1;
  if (maxWidth <= 0 || _visibleLength(text) <= maxWidth) return text;
  final clipped = maxWidth <= 1
      ? _takeVisibleColumns(text, maxWidth)
      : '${_takeVisibleColumns(text, maxWidth - 1)}…';
  if (closeStyles && clipped.contains(_ansiEscape)) {
    return '$clipped$_ansiReset';
  }
  return clipped;
}