shell-color 1.0.1

`shell-color` provides a portable, reliable way of determining color support for applications spawned by the shell.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Parsing for terminal color

use std::fmt::Debug;

#[derive(Clone, PartialEq, Eq)]
pub struct SuggestionColor {
    pub fg: Option<VTermColor>,
    pub bg: Option<VTermColor>,
}

impl SuggestionColor {
    pub fn fg(&self) -> Option<VTermColor> {
        self.fg.clone()
    }

    pub fn bg(&self) -> Option<VTermColor> {
        self.bg.clone()
    }
}

impl Debug for SuggestionColor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SuggestionColor")
            .field("fg", &self.fg())
            .field("bg", &self.bg())
            .finish()
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum VTermColor {
    Rgb { red: u8, green: u8, blue: u8 },
    Indexed { idx: u8 },
}

impl VTermColor {
    const fn from_idx(idx: u8) -> Self {
        VTermColor::Indexed { idx }
    }

    const fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
        VTermColor::Rgb { red, green, blue }
    }
}

impl From<nu_ansi_term::Color> for VTermColor {
    fn from(color: nu_ansi_term::Color) -> Self {
        use nu_ansi_term::Color;
        match color {
            Color::Black => VTermColor::from_idx(0),
            Color::Red => VTermColor::from_idx(1),
            Color::Green => VTermColor::from_idx(2),
            Color::Yellow => VTermColor::from_idx(3),
            Color::Blue => VTermColor::from_idx(4),
            Color::Purple => VTermColor::from_idx(5),
            Color::Magenta => VTermColor::from_idx(5),
            Color::Cyan => VTermColor::from_idx(6),
            Color::White => VTermColor::from_idx(7),
            Color::DarkGray => VTermColor::from_idx(8),
            Color::LightRed => VTermColor::from_idx(9),
            Color::LightGreen => VTermColor::from_idx(10),
            Color::LightYellow => VTermColor::from_idx(11),
            Color::LightBlue => VTermColor::from_idx(12),
            Color::LightPurple => VTermColor::from_idx(13),
            Color::LightMagenta => VTermColor::from_idx(13),
            Color::LightCyan => VTermColor::from_idx(14),
            Color::LightGray => VTermColor::from_idx(16),
            Color::Fixed(i) => VTermColor::from_idx(i),
            Color::Rgb(r, g, b) => VTermColor::from_rgb(r, g, b),
            Color::Default => VTermColor::from_idx(7),
        }
    }
}

bitflags::bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct ColorSupport: u32 {
        const TERM256 = 1 << 1;
        const TERM24BIT = 1 << 2;
    }
}

#[allow(clippy::if_same_then_else)]
// Updates our idea of whether we support term256 and term24bit (see issue #10222).
pub fn get_color_support() -> ColorSupport {
    // Detect or infer term256 support. If fish_term256 is set, we respect it;
    // otherwise infer it from the TERM variable or use terminfo.
    let mut support_term256 = false;
    let mut support_term24bit = false;

    let term = std::env::var("TERM").ok();
    let fish_term256 = std::env::var("fish_term256").ok();

    if let Some(fish_term256) = fish_term256 {
        support_term256 = bool_from_string(&fish_term256);
    } else if term.is_some() && term.as_ref().unwrap().contains("256color") {
        support_term256 = true;
    } else if term.is_some() && term.as_ref().unwrap().contains("xterm") {
        // Assume that all 'xterm's can handle 256, except for Terminal.app from Snow Leopard
        let term_program = std::env::var("TERM_PROGRAM").ok();
        if term_program.is_some() && term_program.unwrap() == "Apple_Terminal" {
            let tpv = std::env::var("TERM_PROGRAM_VERSION").ok();
            if tpv.is_some() && tpv.unwrap().parse::<i32>().unwrap_or(0) > 299 {
                support_term256 = true;
            }
        } else {
            support_term256 = true;
        }
    }

    let ct = std::env::var("COLORTERM").ok();
    let it = std::env::var("ITERM_SESSION_ID").ok();
    let vte = std::env::var("VTE_VERSION").ok();
    let fish_term24bit = std::env::var("fish_term24bit").ok();
    // Handle $fish_term24bit
    if let Some(fish_term24bit) = fish_term24bit {
        support_term24bit = bool_from_string(&fish_term24bit);
    } else if std::env::var("STY").is_ok() || (term.is_some() && term.as_ref().unwrap().starts_with("eterm")) {
        // Screen and emacs' ansi-term swallow truecolor sequences,
        // so we ignore them unless force-enabled.
        support_term24bit = false;
    } else if let Some(ct) = ct {
        // If someone set $COLORTERM, that's the sort of color they want.
        if ct == "truecolor" || ct == "24bit" {
            support_term24bit = true;
        }
    } else if std::env::var("KONSOLE_VERSION").is_ok() || std::env::var("KONSOLE_PROFILE_NAME").is_ok() {
        // All konsole versions that use $KONSOLE_VERSION are new enough to support this,
        // so no check is necessary.
        support_term24bit = true;
    } else if it.is_some() {
        // Supporting versions of iTerm include a colon here.
        // We assume that if this is iTerm, it can't also be st, so having this check
        // inside is okay.
        if it.unwrap().contains(':') {
            support_term24bit = true;
        }
    } else if term.as_ref().is_some() && term.unwrap().starts_with("st-") {
        support_term24bit = true;
    } else if vte.is_some() && vte.unwrap().parse::<i32>().unwrap_or(0) > 3600 {
        support_term24bit = true;
    }

    let mut support = ColorSupport::empty();

    if support_term256 {
        support |= ColorSupport::TERM256;
    }

    if support_term24bit {
        support |= ColorSupport::TERM24BIT;
    }

    support
}

pub fn parse_suggestion_color_zsh_autosuggest(suggestion_str: &str, color_support: ColorSupport) -> SuggestionColor {
    let mut sc = SuggestionColor { fg: None, bg: None };

    for mut color_name in suggestion_str.split(',') {
        let is_fg = color_name.starts_with("fg=");
        let is_bg = color_name.starts_with("bg=");
        if is_fg || is_bg {
            (_, color_name) = color_name.split_at(3);
            // TODO: currently using fish's parsing logic for named colors.
            // This can fail in two cases:
            // 1. false positives from fish colors that aren't supported in zsh (e.g. brblack)
            // 2. false negatives that aren't supported in fish (e.g. abbreviations like bl for black)
            // note: this todo was in the old c code - maybe it isn't needed anymore?
            let mut color = try_parse_named(color_name);
            if color.is_none() && color_name.starts_with('#') {
                color = try_parse_rgb(color_name);
            }
            if color.is_none() {
                // custom zsh logic - try 256 indexed colors first.
                let index = color_name.parse::<u64>().unwrap_or(0);
                let index_supported = if color_support.is_empty() {
                    index < 16
                } else {
                    index < 256
                };
                if index_supported {
                    let vc = VTermColor::Indexed { idx: index as u8 };
                    if is_fg {
                        sc.fg = Some(vc);
                    } else {
                        sc.bg = Some(vc);
                    }
                }
            } else {
                let vc = color_to_vterm_color(color, color_support);
                if is_fg {
                    sc.fg = vc;
                } else {
                    sc.bg = vc;
                }
            }
        }
    }

    sc
}

pub fn parse_suggestion_color_fish(suggestion_str: &str, color_support: ColorSupport) -> Option<SuggestionColor> {
    let c = parse_fish_color_from_string(suggestion_str, color_support);
    let vc = color_to_vterm_color(c, color_support)?;
    Some(SuggestionColor { fg: Some(vc), bg: None })
}

pub fn parse_hint_color_nu(suggestion_str: impl AsRef<str>) -> SuggestionColor {
    let color = nu_color_config::lookup_ansi_color_style(suggestion_str.as_ref());
    SuggestionColor {
        fg: color.foreground.map(VTermColor::from),
        bg: color.background.map(VTermColor::from),
    }
}

#[derive(PartialEq, Eq, Debug)]
#[repr(u8)]
enum ColorType {
    Named = 1,
    Rgb   = 2,
}

#[derive(Debug, PartialEq, Eq)]
struct Color {
    kind: ColorType,
    name_idx: u8,
    rgb: [u8; 3],
}

fn bool_from_string(x: &str) -> bool {
    match x.chars().next() {
        Some(first) => "YTyt1".contains(first),
        None => false,
    }
}

const fn squared_difference(p1: i64, p2: i64) -> u64 {
    let diff = (p1 - p2).unsigned_abs();
    diff * diff
}

const fn convert_color(rgb: [u8; 3], colors: &[u32]) -> u8 {
    let r = rgb[0] as i64;
    let g = rgb[1] as i64;
    let b = rgb[2] as i64;

    let mut best_distance = u64::MAX;
    let mut best_index = u8::MAX;

    let mut i = 0;
    while i < colors.len() {
        let color = colors[i];
        let test_r = ((color >> 16) & 0xff) as i64;
        let test_g = ((color >> 8) & 0xff) as i64;
        let test_b = (color & 0xff) as i64;
        let distance = squared_difference(r, test_r) + squared_difference(g, test_g) + squared_difference(b, test_b);
        if distance <= best_distance {
            best_index = i as u8;
            best_distance = distance;
        }
        i += 1;
    }

    best_index
}

/// We support the following style of rgb formats (case insensitive):
/// `#FA3`, `#F3A035`, `FA3`, `F3A035`
fn try_parse_rgb(name: &str) -> Option<Color> {
    // Skip any leading #.
    let name = match name.strip_prefix('#') {
        Some(name) => name,
        None => name,
    };

    let mut color = Color {
        kind: ColorType::Rgb,
        name_idx: 0,
        rgb: [0, 0, 0],
    };

    let name = name.as_bytes();

    match name.len() {
        // Format: FA3
        3 => {
            for (i, c) in name.iter().enumerate().take(3) {
                let val = char::from(*c).to_digit(16)? as u8;
                color.rgb[i] = val * 16 + val;
            }
            Some(color)
        },
        // Format: F3A035
        6 => {
            for i in 0..3 {
                let val_hi = char::from(name[i * 2]).to_digit(16)? as u8;
                let val_low = char::from(name[i * 2 + 1]).to_digit(16)? as u8;
                color.rgb[i] = val_hi * 16 + val_low;
            }
            Some(color)
        },
        _ => None,
    }
}

struct NamedColor {
    name: &'static str,
    idx: u8,
    _rgb: [u8; 3],
}

macro_rules! decl_named_colors {
    ($({$name: expr, $idx: expr, { $r: expr, $g: expr, $b: expr }}),*,) => {
        &[
            $(
                NamedColor {
                    name: $name,
                    idx: $idx,
                    _rgb: [$r, $g, $b],
                },
            )*
        ]
    };
}

// Keep this sorted alphabetically
static NAMED_COLORS: &[NamedColor] = decl_named_colors! {
    {"black", 0, {0x00, 0x00, 0x00}},      {"blue", 4, {0x00, 0x00, 0x80}},
    {"brblack", 8, {0x80, 0x80, 0x80}},    {"brblue", 12, {0x00, 0x00, 0xFF}},
    {"brbrown", 11, {0xFF, 0xFF, 0x00}},    {"brcyan", 14, {0x00, 0xFF, 0xFF}},
    {"brgreen", 10, {0x00, 0xFF, 0x00}},   {"brgrey", 8, {0x55, 0x55, 0x55}},
    {"brmagenta", 13, {0xFF, 0x00, 0xFF}}, {"brown", 3, {0x72, 0x50, 0x00}},
    {"brpurple", 13, {0xFF, 0x00, 0xFF}},   {"brred", 9, {0xFF, 0x00, 0x00}},
    {"brwhite", 15, {0xFF, 0xFF, 0xFF}},   {"bryellow", 11, {0xFF, 0xFF, 0x00}},
    {"cyan", 6, {0x00, 0x80, 0x80}},       {"green", 2, {0x00, 0x80, 0x00}},
    {"grey", 7, {0xE5, 0xE5, 0xE5}},        {"magenta", 5, {0x80, 0x00, 0x80}},
    {"purple", 5, {0x80, 0x00, 0x80}},      {"red", 1, {0x80, 0x00, 0x00}},
    {"white", 7, {0xC0, 0xC0, 0xC0}},      {"yellow", 3, {0x80, 0x80, 0x00}},
};

fn try_parse_named(s: &str) -> Option<Color> {
    let idx_res = NAMED_COLORS.binary_search_by(|elem| elem.name.cmp(&s.to_ascii_lowercase()));
    if let Ok(idx) = idx_res {
        return Some(Color {
            kind: ColorType::Named,
            name_idx: NAMED_COLORS[idx].idx,
            rgb: [0, 0, 0],
        });
    }
    None
}

const fn term16_color_for_rgb(rgb: [u8; 3]) -> u8 {
    const K_COLORS: &[u32] = &[
        0x000000, // Black
        0x800000, // Red
        0x008000, // Green
        0x808000, // Yellow
        0x000080, // Blue
        0x800080, // Magenta
        0x008080, // Cyan
        0xc0c0c0, // White
        0x808080, // Bright Black
        0xff0000, // Bright Red
        0x00ff00, // Bright Green
        0xffff00, // Bright Yellow
        0x0000ff, // Bright Blue
        0xff00ff, // Bright Magenta
        0x00ffff, // Bright Cyan
        0xffffff, // Bright White
    ];
    convert_color(rgb, K_COLORS)
}

const fn term256_color_for_rgb(rgb: [u8; 3]) -> u8 {
    const K_COLORS: &[u32] = &[
        0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7,
        0x005fff, 0x008700, 0x00875f, 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf,
        0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7, 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87,
        0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
        0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00,
        0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7, 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff,
        0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f, 0x870087, 0x8700af, 0x8700d7,
        0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af,
        0x8787d7, 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787,
        0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f, 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f,
        0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7, 0xaf5fff, 0xaf8700,
        0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff,
        0xafd700, 0xafd75f, 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7,
        0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7, 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf,
        0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f, 0xd7af87,
        0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f,
        0xd7ff87, 0xd7ffaf, 0xd7ffd7, 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00,
        0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f, 0xff8787, 0xff87af, 0xff87d7, 0xff87ff,
        0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
        0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626,
        0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e, 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494,
        0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4, 0xeeeeee,
    ];
    16 + convert_color(rgb, K_COLORS)
}

fn parse_fish_color_from_string(s: &str, color_support: ColorSupport) -> Option<Color> {
    let mut first_rgb = None;
    let mut first_named = None;

    for color_name in s.split([' ', '\t']) {
        if !color_name.starts_with('-') {
            let mut color = try_parse_named(color_name);
            if color.is_none() {
                color = try_parse_rgb(color_name);
            }
            if let Some(color) = color {
                if first_rgb.is_none() && color.kind == ColorType::Rgb {
                    first_rgb = Some(color);
                } else if first_named.is_none() && color.kind == ColorType::Named {
                    first_named = Some(color);
                }
            }
        }
    }

    if (first_rgb.is_some() && color_support.contains(ColorSupport::TERM24BIT)) || first_named.is_none() {
        return first_rgb;
    }

    first_named
}

fn color_to_vterm_color(c: Option<Color>, color_support: ColorSupport) -> Option<VTermColor> {
    let c = c?;
    if c.kind == ColorType::Rgb {
        if color_support.contains(ColorSupport::TERM24BIT) {
            Some(VTermColor::from_rgb(c.rgb[0], c.rgb[1], c.rgb[2]))
        } else if color_support.contains(ColorSupport::TERM256) {
            Some(VTermColor::from_idx(term256_color_for_rgb(c.rgb)))
        } else {
            Some(VTermColor::from_idx(term16_color_for_rgb(c.rgb)))
        }
    } else {
        Some(VTermColor::from_idx(c.name_idx))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn color_support() {
        // make sure it doesn't panic
        get_color_support();

        for (key, _) in std::env::vars() {
            std::env::remove_var(key);
        }

        let assert_supports = |vars: &[(&str, &str)], expected: ColorSupport| {
            for (key, value) in vars {
                std::env::set_var(key, value);
            }

            assert_eq!(get_color_support(), expected);

            for (key, _) in vars {
                std::env::remove_var(key);
            }
        };

        // no env
        assert_supports(&[], ColorSupport::empty());

        // TERM256
        // fish_term256
        assert_supports(&[("fish_term256", "y")], ColorSupport::TERM256);
        assert_supports(&[("fish_term256", "n")], ColorSupport::empty());
        // TERM=*256color*
        assert_supports(&[("TERM", "foo_256color_bar")], ColorSupport::TERM256);
        // xterm
        assert_supports(&[("TERM", "xterm")], ColorSupport::TERM256);
        // recent Terminal.app
        assert_supports(
            &[
                ("TERM", "xterm"),
                ("TERM_PROGRAM", "Apple_Terminal"),
                ("TERM_PROGRAM_VERSION", "300"),
            ],
            ColorSupport::TERM256,
        );
        // old Terminal.app
        assert_supports(
            &[
                ("TERM", "xterm"),
                ("TERM_PROGRAM", "Apple_Terminal"),
                ("TERM_PROGRAM_VERSION", "200"),
            ],
            ColorSupport::empty(),
        );

        // TERM24BIT
        // fish_term24bit
        assert_supports(&[("fish_term24bit", "y")], ColorSupport::TERM24BIT);
        assert_supports(&[("fish_term24bit", "n")], ColorSupport::empty());
        // screen/emacs
        assert_supports(&[("TERM", "eterm"), ("STY", "foo")], ColorSupport::empty());
        // colorterm
        assert_supports(&[("COLORTERM", "truecolor")], ColorSupport::TERM24BIT);
        assert_supports(&[("COLORTERM", "24bit")], ColorSupport::TERM24BIT);
        assert_supports(&[("COLORTERM", "foo")], ColorSupport::empty());
        // konsole
        assert_supports(&[("KONSOLE_VERSION", "foo")], ColorSupport::TERM24BIT);
        // iterm
        assert_supports(&[("ITERM_SESSION_ID", "1:2")], ColorSupport::TERM24BIT);
        // st
        assert_supports(&[("TERM", "st-foo")], ColorSupport::TERM24BIT);
        // vte
        assert_supports(&[("VTE_VERSION", "3500")], ColorSupport::empty());
        assert_supports(&[("VTE_VERSION", "3700")], ColorSupport::TERM24BIT);
    }

    #[test]
    fn assert_named_colors_sort() {
        NAMED_COLORS
            .windows(2)
            .for_each(|elems| assert!(elems[0].name.cmp(elems[1].name).is_lt()));
    }

    #[test]
    fn parse_color() {
        // parse_rgb
        // Should parse
        assert!(try_parse_rgb("#ffffff").is_some());
        assert!(try_parse_rgb("#000000").is_some());
        assert!(try_parse_rgb("#ababab").is_some());
        assert!(try_parse_rgb("000000").is_some());
        assert!(try_parse_rgb("ffffff").is_some());
        assert!(try_parse_rgb("abcabc").is_some());
        assert!(try_parse_rgb("#123").is_some());
        assert!(try_parse_rgb("#fff").is_some());
        assert!(try_parse_rgb("abc").is_some());
        assert!(try_parse_rgb("123").is_some());
        assert!(try_parse_rgb("fff").is_some());
        assert!(try_parse_rgb("000").is_some());

        // Should not parse
        assert!(try_parse_rgb("#xyz").is_none());
        assert!(try_parse_rgb("12").is_none());
        assert!(try_parse_rgb("abcdeh").is_none());
        assert!(try_parse_rgb("#ffff").is_none());
        assert!(try_parse_rgb("12345").is_none());
        assert!(try_parse_rgb("1234567").is_none());

        // parse_named
        // Should parse
        assert!(try_parse_named("blue").is_some());
        assert!(try_parse_named("white").is_some());
        assert!(try_parse_named("yellow").is_some());
        assert!(try_parse_named("brblack").is_some());
        assert!(try_parse_named("BrBlue").is_some());
        assert!(try_parse_named("bRYelLow").is_some());

        // Should not parse
        assert!(try_parse_named("aaa").is_none());
        assert!(try_parse_named("blu").is_none());
        assert!(try_parse_named("other").is_none());
    }

    #[test]
    fn parse_fish_autosuggest() {
        assert_eq!(
            parse_fish_color_from_string("cyan", ColorSupport::TERM256),
            Some(Color {
                kind: ColorType::Named,
                name_idx: 6,
                rgb: [0, 0, 0]
            })
        );
        assert_eq!(
            parse_fish_color_from_string("#123", ColorSupport::TERM256),
            Some(Color {
                kind: ColorType::Rgb,
                name_idx: 0,
                rgb: [0x11, 0x22, 0x33]
            })
        );
        assert_eq!(
            parse_fish_color_from_string("-ignore\t-white\t-#123\tcyan", ColorSupport::TERM256),
            Some(Color {
                kind: ColorType::Named,
                name_idx: 6,
                rgb: [0, 0, 0]
            })
        );
        assert_eq!(
            parse_fish_color_from_string("555 brblack", ColorSupport::TERM256),
            Some(Color {
                kind: ColorType::Named,
                name_idx: 8,
                rgb: [0, 0, 0]
            })
        );
        assert_eq!(
            parse_fish_color_from_string("555 brblack", ColorSupport::TERM24BIT),
            Some(Color {
                kind: ColorType::Rgb,
                name_idx: 0,
                rgb: [0x55, 0x55, 0x55]
            })
        );
        assert_eq!(
            parse_fish_color_from_string("-ignore -all", ColorSupport::TERM256),
            None
        );
    }

    #[test]
    fn parse_zsh_autosuggest() {
        assert_eq!(
            // color support supports rgb
            parse_suggestion_color_zsh_autosuggest("fg=#123,bg=#456", ColorSupport::TERM24BIT),
            SuggestionColor {
                fg: Some(VTermColor::from_rgb(0x11, 0x22, 0x33)),
                bg: Some(VTermColor::from_rgb(0x44, 0x55, 0x66)),
            }
        );
        assert_eq!(
            // color support doesn't support rgb
            parse_suggestion_color_zsh_autosuggest("fg=#123,bg=#456", ColorSupport::empty()),
            SuggestionColor {
                fg: Some(VTermColor::from_idx(0)),
                bg: Some(VTermColor::from_idx(8)),
            }
        );
        assert_eq!(
            // default
            parse_suggestion_color_zsh_autosuggest("fg=8", ColorSupport::empty()),
            SuggestionColor {
                fg: Some(VTermColor::from_idx(8)),
                bg: None,
            }
        );
        assert_eq!(
            // ignore and recover from invalid data
            parse_suggestion_color_zsh_autosuggest("invalid=!,,=,bg=cyan", ColorSupport::empty()),
            SuggestionColor {
                fg: None,
                bg: Some(VTermColor::from_idx(6))
            }
        );
    }
}