plannotator-tui 0.11.5

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Light and dark terminals: the palette of roles that carry an absolute colour.
//!
//! Almost everything on screen uses the terminal's own colours, so only the backgrounds we
//! paint ourselves need a light variant. Which palette is in force is decided once, before
//! the screen is taken over (`install`), and read from everywhere by [`palette`]. Nothing
//! installs a palette in tests or in headless runs, so those keep the dark one.
//!
//! Precedence: `PLANNOTATOR_TUI_THEME` → `[ui] theme` in the config file → asking the
//! terminal → dark. `[colors]` then replaces individual roles of whichever palette won.

use std::fmt;
use std::io::IsTerminal as _;
use std::str::FromStr;
use std::sync::OnceLock;
use std::time::Duration;

use anyhow::Result;
use ratatui::style::{Color, Modifier, Style};
use serde::{Deserialize, Serialize};

/// How long the terminal gets to answer the background-colour query.
///
/// Most terminals answer the query itself, or the `DA1` sent behind it, within a few
/// milliseconds, so the answer arrives long before this. Herdr answers the colour query for
/// its panes but not `DA1`, so inside a pane the wait always runs to this deadline, and a key
/// pressed during it is lost: keep it short. A terminal that answers nothing at all is
/// treated as dark.
const DETECT_TIMEOUT: Duration = Duration::from_millis(30);

/// What the user asked for, as written in `[ui] theme` or `PLANNOTATOR_TUI_THEME`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum ThemeSetting {
    /// Ask the terminal, and use the dark palette when it does not answer.
    #[default]
    Auto,
    Light,
    Dark,
}

impl ThemeSetting {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Light => "light",
            Self::Dark => "dark",
        }
    }
}

impl fmt::Display for ThemeSetting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for ThemeSetting {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "auto" => Ok(Self::Auto),
            "light" => Ok(Self::Light),
            "dark" => Ok(Self::Dark),
            other => anyhow::bail!("unknown theme {other:?}; expected auto, light or dark"),
        }
    }
}

/// The palette actually in force, once `auto` has been settled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Theme {
    Dark,
    Light,
}

impl Theme {
    fn palette(self) -> &'static Palette {
        match self {
            Self::Dark => &DARK,
            Self::Light => &LIGHT,
        }
    }
}

/// Every colour a theme or `[colors]` can change.
///
/// The backgrounds are here because they are painted *under* text whose colour belongs to
/// the terminal: a fixed dark background hides dark text on a light terminal, and the other
/// way round. The foregrounds are ANSI colours that already follow the terminal, so both
/// palettes share them; they are here so `[colors]` can reach them. The text of the header
/// buttons and the floating toolbar, which sits on a background we paint, is in `ui::chips`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Palette {
    /// Focused borders and gutter, the open file in the tree, active header text.
    pub(crate) accent: Color,
    /// Level one and two headings.
    pub(crate) heading: Color,
    /// Level three and deeper headings.
    pub(crate) subheading: Color,
    /// Comment titles, the compose box, annotated rows in the gutter, tree counts.
    pub(crate) comment: Color,
    /// Looks-good titles.
    pub(crate) looks_good: Color,
    /// Delete titles and struck-through text.
    pub(crate) delete: Color,
    /// The focused block's bar, and the focused row of the file tree.
    pub(crate) block_bg: Color,
    /// The floating toolbar and the idle header buttons. The text on it is `ui::chips`'.
    pub(crate) toolbar_bg: Color,
    /// The foreground of a header button with nothing to do.
    pub(crate) idle_fg: Color,
    /// Text carrying a comment.
    pub(crate) comment_bg: Color,
    /// Text marked as looking good.
    pub(crate) approve_bg: Color,
    /// The keyboard cursor cell.
    pub(crate) cursor: Style,
    /// A character selection, a picker row, a review-menu row.
    pub(crate) selection: Style,
    /// Inline code, and fenced code in a language without a bundled grammar.
    pub(crate) code: Color,
    /// Fenced code with a known language: keywords and storage.
    pub(crate) code_keyword: Color,
    /// Strings and characters in code.
    pub(crate) code_string: Color,
    /// Numbers and named constants in code.
    pub(crate) code_number: Color,
    /// Function names in code.
    pub(crate) code_function: Color,
    /// Type names in code.
    pub(crate) code_type: Color,
    /// Comments in code, drawn italic as well.
    pub(crate) code_comment: Color,
    /// Every match of the document search.
    pub(crate) search: Style,
    /// The match the cursor is on.
    pub(crate) search_current: Style,
}

/// The palette this app has always had. Dark terminals must see no change at all.
pub(crate) static DARK: Palette = Palette {
    accent: Color::Cyan,
    heading: Color::Cyan,
    subheading: Color::LightCyan,
    comment: Color::Yellow,
    looks_good: Color::Green,
    delete: Color::Red,
    block_bg: Color::Indexed(236),
    toolbar_bg: Color::Indexed(238),
    idle_fg: Color::Gray,
    comment_bg: Color::Indexed(58),
    approve_bg: Color::Indexed(22),
    cursor: Style::new().bg(Color::Indexed(240)),
    selection: Style::new().add_modifier(Modifier::REVERSED),
    code: Color::LightYellow,
    code_keyword: Color::Magenta,
    code_string: Color::Green,
    code_number: Color::Yellow,
    code_function: Color::Blue,
    code_type: Color::Cyan,
    code_comment: Color::DarkGray,
    // Blue and orange: no annotation tint, the block bar or the cursor uses either hue.
    search: Style::new().bg(Color::Indexed(24)),
    // Black from the 256-colour cube: ANSI black is whatever the terminal theme makes it.
    search_current: Style::new().bg(Color::Indexed(208)).fg(Color::Indexed(16)),
};

/// The same roles, light. The greys mirror the dark ones about the middle of the ramp, so
/// the focused block still sits just off the page and the cursor is a shade firmer. The
/// annotation tints are the pale ends of the same hues. `REVERSED` becomes a real
/// background: reversing dark-on-light gives a black bar that swallows the tints under it.
pub(crate) static LIGHT: Palette = Palette {
    accent: DARK.accent,
    heading: DARK.heading,
    subheading: DARK.subheading,
    comment: DARK.comment,
    looks_good: DARK.looks_good,
    delete: DARK.delete,
    block_bg: Color::Indexed(254),
    // 253, not 252: the darkest grey the light toolbar's dark amber comment label still
    // reads on at 4.5:1 (`ui::chips`).
    toolbar_bg: Color::Indexed(253),
    idle_fg: Color::DarkGray,
    comment_bg: Color::Indexed(222),
    approve_bg: Color::Indexed(157),
    // A dark cell with its own light foreground, so the glyph under the cursor stays legible.
    cursor: Style::new().bg(Color::Indexed(238)).fg(Color::Indexed(231)),
    selection: Style::new().bg(Color::Indexed(153)),
    // Light yellow, the code colour on dark, all but vanishes on white: a dark amber instead.
    code: Color::Indexed(94),
    code_keyword: DARK.code_keyword,
    // Light themes' ANSI green and cyan are often too pale for text on white; these 256-colour
    // ones are darker on every terminal.
    code_string: Color::Indexed(28),
    // Yellow is the one ANSI hue most light themes leave too pale to read on white.
    code_number: Color::Indexed(130),
    code_function: DARK.code_function,
    code_type: Color::Indexed(30),
    code_comment: DARK.code_comment,
    search: Style::new().bg(Color::Indexed(117)),
    search_current: Style::new().bg(Color::Indexed(214)).fg(Color::Indexed(16)),
};

/// A colour as `[colors]` writes it: a name (`yellow`, `light-cyan`), a 256-colour index
/// (`238`) or `#rrggbb`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ColorValue(pub(crate) Color);

impl FromStr for ColorValue {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        s.parse().map(Self).map_err(|_| {
            anyhow::anyhow!("unknown color {s:?}; expected a name like yellow, an index 0-255, or #rrggbb")
        })
    }
}

/// Prints the colour the way `[colors]` writes it, so `plannotator-tui config` output can be
/// pasted back: `light-blue`, `238`, `#1e1e2e`.
impl fmt::Display for ColorValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self.0 {
            Color::Indexed(index) => return write!(f, "{index}"),
            Color::Rgb(r, g, b) => return write!(f, "#{r:02x}{g:02x}{b:02x}"),
            Color::Reset => "reset",
            Color::Black => "black",
            Color::Red => "red",
            Color::Green => "green",
            Color::Yellow => "yellow",
            Color::Blue => "blue",
            Color::Magenta => "magenta",
            Color::Cyan => "cyan",
            Color::Gray => "gray",
            Color::DarkGray => "dark-gray",
            Color::LightRed => "light-red",
            Color::LightGreen => "light-green",
            Color::LightYellow => "light-yellow",
            Color::LightBlue => "light-blue",
            Color::LightMagenta => "light-magenta",
            Color::LightCyan => "light-cyan",
            Color::White => "white",
        };
        f.write_str(name)
    }
}

impl Serialize for ColorValue {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

/// A string as above, or a bare 256-colour index: `heading = 238`.
impl<'de> Deserialize<'de> for ColorValue {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        struct Visitor;

        impl serde::de::Visitor<'_> for Visitor {
            type Value = ColorValue;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a color name, an index 0-255, or #rrggbb")
            }

            fn visit_str<E: serde::de::Error>(self, text: &str) -> std::result::Result<ColorValue, E> {
                text.parse().map_err(E::custom)
            }

            fn visit_i64<E: serde::de::Error>(self, index: i64) -> std::result::Result<ColorValue, E> {
                u8::try_from(index)
                    .map(|index| ColorValue(Color::Indexed(index)))
                    .map_err(|_| E::custom(format!("unknown color {index}; a color index is 0-255")))
            }

            fn visit_u64<E: serde::de::Error>(self, index: u64) -> std::result::Result<ColorValue, E> {
                u8::try_from(index)
                    .map(|index| ColorValue(Color::Indexed(index)))
                    .map_err(|_| E::custom(format!("unknown color {index}; a color index is 0-255")))
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// `[colors]`: per-role replacements for the palette in force. A role left out keeps the
/// light or dark value; `cursor`, `selection` and the search roles become plain backgrounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default, rename_all = "kebab-case")]
pub(crate) struct Colors {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) accent: Option<ColorValue>,
    /// Every heading level.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) heading: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) comment: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) looks_good: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) delete: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) comment_bg: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) looks_good_bg: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) block: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) toolbar: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) cursor: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) selection: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_keyword: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_string: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_number: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_function: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_type: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) code_comment: Option<ColorValue>,
    /// Every match of the document search.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) search: Option<ColorValue>,
    /// The match the cursor is on.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) search_current: Option<ColorValue>,
}

impl Palette {
    /// This palette with every role `colors` names replaced.
    pub(crate) fn with(mut self, colors: &Colors) -> Self {
        let set = |slot: &mut Color, value: Option<ColorValue>| {
            if let Some(ColorValue(color)) = value {
                *slot = color;
            }
        };
        set(&mut self.accent, colors.accent);
        set(&mut self.heading, colors.heading);
        set(&mut self.subheading, colors.heading);
        set(&mut self.comment, colors.comment);
        set(&mut self.looks_good, colors.looks_good);
        set(&mut self.delete, colors.delete);
        set(&mut self.comment_bg, colors.comment_bg);
        set(&mut self.approve_bg, colors.looks_good_bg);
        set(&mut self.block_bg, colors.block);
        set(&mut self.toolbar_bg, colors.toolbar);
        set(&mut self.code, colors.code);
        set(&mut self.code_keyword, colors.code_keyword);
        set(&mut self.code_string, colors.code_string);
        set(&mut self.code_number, colors.code_number);
        set(&mut self.code_function, colors.code_function);
        set(&mut self.code_type, colors.code_type);
        set(&mut self.code_comment, colors.code_comment);
        if let Some(ColorValue(color)) = colors.cursor {
            self.cursor = Style::new().bg(color);
        }
        if let Some(ColorValue(color)) = colors.selection {
            self.selection = Style::new().bg(color);
        }
        if let Some(ColorValue(color)) = colors.search {
            self.search = Style::new().bg(color);
        }
        if let Some(ColorValue(color)) = colors.search_current {
            self.search_current = Style::new().bg(color);
        }
        self
    }
}

static PALETTE: OnceLock<Palette> = OnceLock::new();
static THEME: OnceLock<Theme> = OnceLock::new();

/// The palette in force. Dark until [`install`] says otherwise, which is what tests,
/// `--snapshot`, `--export` and every other headless run get.
pub(crate) fn palette() -> &'static Palette {
    PALETTE.get().unwrap_or(&DARK)
}

/// Fix the palette for this process. The first call wins; later ones are ignored.
pub(crate) fn install(theme: Theme, colors: &Colors) {
    let _ = PALETTE.set(theme.palette().with(colors));
    let _ = THEME.set(theme);
}

/// The theme in force: dark until [`install`] says otherwise. The diff viewer colours its
/// code by it, and the Send button picks its colours by it.
pub(crate) fn theme() -> Theme {
    THEME.get().copied().unwrap_or(Theme::Dark)
}

/// Ask the terminal whether its background is light or dark.
///
/// The query opens the tty itself rather than reading our stdin, so it cannot race the
/// event loop's reader or leave a half-parsed escape sequence behind it. It does hold the
/// tty in raw mode for one round trip, and anything typed into that window is read and
/// discarded with the reply; `theme = "light"`, `theme = "dark"` or `PLANNOTATOR_TUI_THEME`
/// skip the query outright for anyone that window bothers.
///
/// `None` means the terminal did not answer, answered something unreadable, or there is no
/// terminal to ask - all of which keep the dark palette.
pub(crate) fn detect() -> Option<Theme> {
    if !std::io::stdout().is_terminal() {
        return None;
    }
    #[allow(
        clippy::field_reassign_with_default,
        reason = "QueryOptions is #[non_exhaustive]; struct-update syntax is not available to us"
    )]
    let options = {
        let mut options = terminal_colorsaurus::QueryOptions::default();
        options.timeout = DETECT_TIMEOUT;
        options
    };
    match terminal_colorsaurus::theme_mode(options) {
        Ok(terminal_colorsaurus::ThemeMode::Light) => Some(Theme::Light),
        Ok(terminal_colorsaurus::ThemeMode::Dark) => Some(Theme::Dark),
        Err(_) => None,
    }
}

/// `PLANNOTATOR_TUI_THEME`, when it is set to something. An unreadable value is an error
/// that names it, like a bad value in the config file.
fn setting_from_env(env: &impl Fn(&str) -> Option<String>) -> Result<Option<ThemeSetting>> {
    match env("PLANNOTATOR_TUI_THEME").filter(|value| !value.is_empty()) {
        Some(value) => value.parse().map(Some),
        None => Ok(None),
    }
}

/// What `plannotator-tui config` should print: the environment's answer if it has one,
/// else the file's.
pub(crate) fn effective_setting(
    env: impl Fn(&str) -> Option<String>,
    configured: ThemeSetting,
) -> Result<ThemeSetting> {
    Ok(setting_from_env(&env)?.unwrap_or(configured))
}

/// Settle on a palette: environment, then config file, then the terminal, then dark.
pub(crate) fn resolve(
    env: impl Fn(&str) -> Option<String>,
    configured: ThemeSetting,
    detect: impl FnOnce() -> Option<Theme>,
) -> Result<Theme> {
    Ok(match effective_setting(env, configured)? {
        ThemeSetting::Light => Theme::Light,
        ThemeSetting::Dark => Theme::Dark,
        ThemeSetting::Auto => detect().unwrap_or(Theme::Dark),
    })
}

#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
    use super::*;

    fn env(vars: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |key: &str| vars.iter().find(|(name, _)| *name == key).map(|(_, v)| (*v).to_owned())
    }

    #[test]
    fn the_environment_beats_the_config_file() {
        let vars = env(&[("PLANNOTATOR_TUI_THEME", "light")]);
        assert_eq!(resolve(vars, ThemeSetting::Dark, || None).expect("resolves"), Theme::Light);
    }

    #[test]
    fn the_config_file_beats_detection() {
        let detect = || Some(Theme::Light);
        assert_eq!(resolve(env(&[]), ThemeSetting::Dark, detect).expect("resolves"), Theme::Dark);
    }

    #[test]
    fn auto_in_the_environment_reopens_the_question_a_configured_theme_closed() {
        let vars = env(&[("PLANNOTATOR_TUI_THEME", "auto")]);
        let resolved = resolve(vars, ThemeSetting::Dark, || Some(Theme::Light)).expect("resolves");
        assert_eq!(resolved, Theme::Light);
    }

    #[test]
    fn auto_uses_the_terminals_answer_and_falls_back_to_dark_without_one() {
        let auto = ThemeSetting::Auto;
        assert_eq!(resolve(env(&[]), auto, || Some(Theme::Light)).expect("resolves"), Theme::Light);
        assert_eq!(resolve(env(&[]), auto, || None).expect("resolves"), Theme::Dark);
    }

    #[test]
    fn an_empty_environment_variable_is_not_a_choice() {
        let vars = env(&[("PLANNOTATOR_TUI_THEME", "")]);
        assert_eq!(resolve(vars, ThemeSetting::Light, || None).expect("resolves"), Theme::Light);
    }

    #[test]
    fn an_unreadable_environment_variable_is_an_error_naming_the_value() {
        let vars = env(&[("PLANNOTATOR_TUI_THEME", "solarized")]);
        let err = resolve(vars, ThemeSetting::Auto, || None).expect_err("rejected");
        assert!(err.to_string().contains("solarized"), "{err}");
    }

    /// The dark palette is the one shipped before light terminals were supported; a change
    /// here is a visible change for every existing user.
    #[test]
    fn the_dark_palette_is_unchanged() {
        assert_eq!(DARK.block_bg, Color::Indexed(236));
        assert_eq!(DARK.toolbar_bg, Color::Indexed(238));
        assert_eq!(DARK.idle_fg, Color::Gray);
        assert_eq!(DARK.comment_bg, Color::Indexed(58));
        assert_eq!(DARK.approve_bg, Color::Indexed(22));
        assert_eq!(DARK.cursor, Style::new().bg(Color::Indexed(240)));
        assert_eq!(DARK.selection, Style::new().add_modifier(Modifier::REVERSED));
        assert_eq!(
            (DARK.accent, DARK.heading, DARK.subheading),
            (Color::Cyan, Color::Cyan, Color::LightCyan)
        );
        assert_eq!((DARK.comment, DARK.looks_good, DARK.delete), (Color::Yellow, Color::Green, Color::Red));
    }

    /// Nothing installs a palette in a test binary, so every existing snapshot and style
    /// assertion keeps reading the dark one.
    #[test]
    fn the_palette_is_dark_until_something_installs_one() {
        assert_eq!(*palette(), DARK);
    }

    /// Both palettes must answer for every role; a light background painted on a light
    /// terminal is the bug this exists to fix.
    #[test]
    fn no_light_role_reuses_its_dark_value() {
        assert_ne!(LIGHT.block_bg, DARK.block_bg);
        assert_ne!(LIGHT.toolbar_bg, DARK.toolbar_bg);
        assert_ne!(LIGHT.comment_bg, DARK.comment_bg);
        assert_ne!(LIGHT.approve_bg, DARK.approve_bg);
        assert_ne!(LIGHT.cursor, DARK.cursor);
        assert_ne!(LIGHT.selection, DARK.selection);
        assert_ne!(LIGHT.search, DARK.search);
        assert_ne!(LIGHT.search_current, DARK.search_current);
    }

    /// A search match must never read as a note: its background is none of the tints the
    /// annotations, the focused block or the cursor paint, in either palette.
    #[test]
    fn search_highlights_share_no_background_with_annotations() {
        for palette in [&DARK, &LIGHT] {
            let taken = [
                Some(palette.comment_bg),
                Some(palette.approve_bg),
                Some(palette.block_bg),
                palette.cursor.bg,
            ];
            for role in [palette.search, palette.search_current] {
                assert_ne!(role.bg, None);
                assert!(!taken.contains(&role.bg), "{role:?}");
            }
            assert_ne!(palette.search, palette.search_current);
        }
    }

    #[test]
    fn the_search_roles_are_configurable_like_the_others() {
        let colors = Colors {
            search: Some(ColorValue(Color::Indexed(5))),
            search_current: Some(ColorValue(Color::Indexed(6))),
            ..Colors::default()
        };
        let palette = DARK.with(&colors);
        assert_eq!(
            (palette.search, palette.search_current),
            (Style::new().bg(Color::Indexed(5)), Style::new().bg(Color::Indexed(6)))
        );
        assert_eq!(Palette { search: DARK.search, search_current: DARK.search_current, ..palette }, DARK);
    }

    /// `REVERSED` is what made a selection unreadable on a light terminal; the light
    /// palette must not reach for it again.
    #[test]
    fn the_light_selection_is_a_background_not_a_reversal() {
        assert!(!LIGHT.selection.add_modifier.contains(Modifier::REVERSED));
        assert!(LIGHT.selection.bg.is_some());
    }

    #[test]
    fn no_colors_leave_both_palettes_alone() {
        assert_eq!(DARK.with(&Colors::default()), DARK);
        assert_eq!(LIGHT.with(&Colors::default()), LIGHT);
    }

    #[test]
    fn a_color_replaces_its_role_and_nothing_else() {
        let colors = Colors { block: Some(ColorValue(Color::Rgb(1, 2, 3))), ..Colors::default() };
        let palette = LIGHT.with(&colors);
        assert_eq!(palette.block_bg, Color::Rgb(1, 2, 3));
        assert_eq!(Palette { block_bg: LIGHT.block_bg, ..palette }, LIGHT);
    }

    #[test]
    fn heading_covers_every_level() {
        let colors = Colors { heading: Some(ColorValue(Color::Magenta)), ..Colors::default() };
        let palette = DARK.with(&colors);
        assert_eq!((palette.heading, palette.subheading), (Color::Magenta, Color::Magenta));
    }

    /// A configured cursor or selection is the whole style: the dark selection's reversal
    /// and the light cursor's white glyph would fight a colour picked to match a theme.
    #[test]
    fn cursor_and_selection_become_plain_backgrounds() {
        let colors = Colors {
            cursor: Some(ColorValue(Color::Indexed(7))),
            selection: Some(ColorValue(Color::Indexed(8))),
            ..Colors::default()
        };
        assert_eq!(LIGHT.with(&colors).cursor, Style::new().bg(Color::Indexed(7)));
        assert_eq!(DARK.with(&colors).selection, Style::new().bg(Color::Indexed(8)));
    }

    /// On white, code avoids the pale ANSI hues light themes tend to ship: light yellow,
    /// yellow, green and cyan. `[colors] code` still sets the one code colour.
    #[test]
    fn light_code_colours_stay_dark_enough_for_white_and_code_is_configurable() {
        let pale = [Color::LightYellow, Color::Yellow, Color::Green, Color::Cyan];
        for color in [LIGHT.code, LIGHT.code_string, LIGHT.code_number, LIGHT.code_type] {
            assert!(!pale.contains(&color), "{color:?}");
        }
        let colors = Colors { code: Some(ColorValue(Color::Indexed(166))), ..Colors::default() };
        assert_eq!(LIGHT.with(&colors).code, Color::Indexed(166));
        assert_eq!(DARK.code, Color::LightYellow, "dark terminals see the code colour they always had");
    }

    #[test]
    fn a_color_reads_names_indexes_and_hex_and_prints_back_the_same() {
        for (text, color) in [
            ("light-cyan", Color::LightCyan),
            ("238", Color::Indexed(238)),
            ("#1e1e2e", Color::Rgb(30, 30, 46)),
        ] {
            let parsed: ColorValue = text.parse().expect("parses");
            assert_eq!(parsed.0, color);
            assert_eq!(parsed.to_string(), text);
        }
    }

    #[test]
    fn every_color_prints_in_a_spelling_that_parses_back() {
        for color in [
            Color::Reset,
            Color::Black,
            Color::Red,
            Color::Green,
            Color::Yellow,
            Color::Blue,
            Color::Magenta,
            Color::Cyan,
            Color::Gray,
            Color::DarkGray,
            Color::LightRed,
            Color::LightGreen,
            Color::LightYellow,
            Color::LightBlue,
            Color::LightMagenta,
            Color::LightCyan,
            Color::White,
            Color::Indexed(0),
            Color::Indexed(255),
            Color::Rgb(0, 0, 255),
        ] {
            let text = ColorValue(color).to_string();
            assert_eq!(text.parse::<ColorValue>().expect("parses").0, color, "{text}");
        }
    }

    #[test]
    fn an_unreadable_color_is_an_error_naming_it() {
        let err = "chartreuse".parse::<ColorValue>().expect_err("rejected");
        assert!(err.to_string().contains("chartreuse"), "{err}");
    }

    #[test]
    fn a_theme_setting_roundtrips_through_its_own_name() {
        for setting in [ThemeSetting::Auto, ThemeSetting::Light, ThemeSetting::Dark] {
            assert_eq!(setting.as_str().parse::<ThemeSetting>().expect("parses"), setting);
        }
    }
}