toAnsi method

  1. @override
String toAnsi(
  1. ColorProfile profile, {
  2. bool background = false,
  3. bool underline = false,
  4. bool hasDarkBackground = true,
})
override

Produces the ANSI escape sequence for this color.

profile indicates the terminal's color capabilities. background if true, produces background color sequence. underline if true, produces underline color sequence (SGR 58). hasDarkBackground hints whether terminal has dark background (for adaptive colors).

Implementation

@override
String toAnsi(
  ColorProfile profile, {
  bool background = false,
  bool underline = false,
  bool hasDarkBackground = true,
}) {
  switch (profile) {
    case ColorProfile.ascii:
    case ColorProfile.noColor:
      return '';
    case ColorProfile.ansi:
      if (ansi != null) {
        final code = int.tryParse(ansi!) ?? 0;
        final p = underline ? 58 : (background ? 40 : 30);
        // Note: Underline color (SGR 58) does not have 16-color variants,
        // but we use 58;5;N as a fallback if needed.
        if (underline) {
          return '\x1B[58;5;${code}m';
        }
        return '\x1B[${p + code}m';
      }
      // Fall through to ansi256
      continue ansi256Case;
    ansi256Case:
    case ColorProfile.ansi256:
      if (ansi256 != null) {
        final code = int.tryParse(ansi256!) ?? 0;
        final p = underline ? 58 : (background ? 48 : 38);
        return '\x1B[$p;5;${code}m';
      }
      // Fall through to trueColor
      continue trueColorCase;
    trueColorCase:
    case ColorProfile.trueColor:
      return BasicColor(trueColor).toAnsi(
        profile,
        background: background,
        underline: underline,
        hasDarkBackground: hasDarkBackground,
      );
  }
}