sgrColor function

String sgrColor({
  1. required Profile profile,
  2. bool background = false,
  3. bool underline = false,
  4. int? ansi16,
  5. int? ansi256,
  6. Rgb? rgb,
})

Implementation

String sgrColor({
  required Profile profile,
  bool background = false,
  bool underline = false,
  int? ansi16,
  int? ansi256,
  Rgb? rgb,
}) {
  if (profile <= Profile.noTty) return '';

  if (profile == Profile.ascii) {
    return '';
  }

  if (profile == Profile.trueColor) {
    if (rgb == null) {
      if (ansi256 != null) rgb = ansi256ToRgb(ansi256);
      if (ansi16 != null) rgb = _ansi16Palette[ansi16.clamp(0, 15)];
    }
    if (rgb == null) return '';
    if (underline) {
      // SGR 58 uses xterm-style colon parameters for underline color.
      // Example: ESC[58:2::R:G:Bm
      return '\x1B[58:2::${rgb.r}:${rgb.g}:${rgb.b}m';
    }
    final p = background ? 48 : 38;
    return '\x1B[$p;2;${rgb.r};${rgb.g};${rgb.b}m';
  }

  if (profile == Profile.ansi256) {
    final idx =
        ansi256 ??
        (rgb != null
            ? rgbToAnsi256(rgb.r, rgb.g, rgb.b)
            : (ansi16 != null ? _ansi16ToAnsi256(ansi16) : 0));
    if (underline) {
      // SGR 58 uses colon parameters for underline color.
      return '\x1B[58:5:${idx}m';
    }
    final p = background ? 48 : 38;
    return '\x1B[$p;5;${idx}m';
  }

  // Profile.ansi
  if (underline) {
    // Underline color doesn't have 16-color SGR codes, use 256-color fallback
    final idx =
        ansi256 ??
        (rgb != null
            ? rgbToAnsi256(rgb.r, rgb.g, rgb.b)
            : (ansi16 != null ? _ansi16ToAnsi256(ansi16) : 0));
    // SGR 58 uses colon parameters for underline color.
    return '\x1B[58:5:${idx}m';
  }

  final idx16 =
      ansi16 ??
      (ansi256 != null
          ? ansi256ToAnsi16(ansi256)
          : (rgb != null ? rgbToAnsi16(rgb.r, rgb.g, rgb.b) : 0));
  return _sgrAnsi16(idx16, background: background);
}