edamame 0.1.4

A fast TUI Markdown editor and viewer
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
//! Terminal capability detection: color depth, mouse, image protocol, UTF-8 locale, and
//! the kitty keyboard enhancement protocol.
//!
//! Three signals: environment variables, crossterm's `supports_keyboard_enhancement()`,
//! and `Picker::from_query_stdio`.  [`Capabilities::detect`] must never panic and never
//! block noticeably — every probe either finishes in milliseconds or falls back to a
//! conservative default.

use std::env;

use ratatui_image::picker::{Picker, ProtocolType};

/// Color bit-depth supported by the terminal.  Ordered poorest to richest, so
/// `depth >= ColorDepth::Ansi256` works.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColorDepth {
    /// No color at all (`TERM=dumb`); rendering emits no ANSI style escapes.
    NoColor,
    /// Classic 8/16-color palette.
    Ansi16,
    /// 256-indexed color palette (xterm-256color and friends).
    Ansi256,
    /// 24-bit / true-color palette (`COLORTERM=truecolor` or `24bit`).
    TrueColor,
}

/// Image protocol supported by the terminal emulator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageProtocol {
    /// DEC Sixel graphics (xterm with `--enable-sixel-graphics`, foot, wezterm).
    Sixel,
    /// Kitty graphics protocol (kitty, ghostty, wezterm).
    KittyGraphics,
    /// iTerm2 inline-images protocol.
    ITerm2,
    /// Unicode half-block fallback (works in any truecolor terminal).
    Halfblocks,
}

/// Detected terminal capabilities.
#[derive(Debug, Clone)]
pub struct Capabilities {
    /// Color bit-depth the terminal advertises.
    pub color_depth: ColorDepth,
    /// Whether the terminal appears to support mouse reporting.
    pub mouse: bool,
    /// `None` when image display is not supported.
    pub image_protocol: Option<ImageProtocol>,
    /// The startup probe's `Picker`, retained so cold image loads reuse the probed
    /// configuration instead of re-running `Picker::from_query_stdio`.  `None` iff
    /// `image_protocol` is.
    pub image_picker: Option<Picker>,
    /// A second `Picker` pinned to halfblocks at the native picker's font size (no extra
    /// probe).  The fallback path renders through it while an image is partly visible or
    /// scrolling — halfblocks are position-independent and cheap to cell-copy — and
    /// upgrades back once the view quiesces.  `None` iff image support is absent.
    pub halfblocks_picker: Option<Picker>,
    /// Whether the locale env vars advertise UTF-8; a proxy for "full Unicode support".
    pub unicode_full: bool,
    /// Whether `supports_keyboard_enhancement()` answered affirmatively.  Without it the
    /// terminal is limited to the legacy control-byte encoding, which can represent
    /// neither shifted modifier combinations nor `Ctrl` with a non-alphabetic key, so
    /// features relying on those (e.g. `Ctrl-Shift-Z` redo) must degrade.
    pub keyboard_enhancement: bool,
}

impl Capabilities {
    /// Detect all capabilities.  Must be called **after** the terminal enters the
    /// alternate screen and raw mode, since the Picker probes stdout/stdin with escape
    /// sequences.  `kbd_enhancement` is passed in rather than re-queried: both it and the
    /// Picker probe read replies off the tty, and one could consume the other's.
    pub fn detect(kbd_enhancement: bool) -> Self {
        let term = env::var("TERM").unwrap_or_default();
        let color_depth = detect_color_depth(&term);
        let mouse = detect_mouse(&term);
        let unicode_full = detect_unicode_full();
        let (image_protocol, image_picker) = detect_image_protocol();
        let halfblocks_picker = image_picker
            .as_ref()
            .map(|p| halfblocks_from(p.font_size()));

        Self {
            color_depth,
            mouse,
            image_protocol,
            image_picker,
            halfblocks_picker,
            unicode_full,
            keyboard_enhancement: kbd_enhancement,
        }
    }

    /// Color depth from environment variables only, with no escape-sequence I/O, so it is
    /// safe before [`terminal::setup()`](fn@crate::terminal::setup) — the config loader
    /// needs it to pick a fallback theme.  [`Self::detect`] is the source of truth
    /// everywhere else.
    pub fn detect_color_depth_from_env() -> ColorDepth {
        let term = env::var("TERM").unwrap_or_default();
        detect_color_depth(&term)
    }

    /// Everything knowable from the environment alone, leaving the two probe-derived
    /// facts at their [`Self::minimal`] values.
    ///
    /// For `--doctor` when stdout or stdin is not a terminal: the image and keyboard
    /// probes would write escape sequences into the user's redirected file and then report
    /// "no support" for a terminal that has it.  [`crate::cli::doctor`] prints the two as
    /// *unknown*.
    pub fn env_only() -> Self {
        let term = env::var("TERM").unwrap_or_default();
        Self {
            color_depth: detect_color_depth(&term),
            mouse: detect_mouse(&term),
            unicode_full: detect_unicode_full(),
            ..Self::minimal()
        }
    }

    /// True iff the terminal advertises 24-bit color.  Anything less quantizes the RGB
    /// every theme and image is authored in, so this gates the theme picker, the welcome
    /// modal's image / diagram options, and the first-run default theme.
    pub fn full_color(&self) -> bool {
        self.color_depth == ColorDepth::TrueColor
    }

    /// Minimum-common-denominator terminal, for tests and when probing is impossible.
    pub fn minimal() -> Self {
        Self {
            color_depth: ColorDepth::Ansi16,
            mouse: false,
            image_protocol: None,
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: false,
            keyboard_enhancement: false,
        }
    }

    /// Stable terminal identity for the startup capabilities notice's new-terminal
    /// detection: the env-level identity plus the detected capability tuple (so two
    /// environments that probe differently count as different terminals) plus a tmux
    /// marker.  `$TERM_PROGRAM_VERSION` is excluded, or every minor update would re-notify.
    pub fn fingerprint(&self) -> String {
        let term_program = env::var("TERM_PROGRAM").unwrap_or_default();
        let term = env::var("TERM").unwrap_or_default();
        let tmux = if env::var("TMUX").is_ok() { "tmux" } else { "" };
        let color = match self.color_depth {
            ColorDepth::NoColor => "none",
            ColorDepth::Ansi16 => "16",
            ColorDepth::Ansi256 => "256",
            ColorDepth::TrueColor => "truecolor",
        };
        let image = match self.image_protocol {
            None => "none",
            Some(ImageProtocol::Sixel) => "sixel",
            Some(ImageProtocol::KittyGraphics) => "kitty",
            Some(ImageProtocol::ITerm2) => "iterm2",
            Some(ImageProtocol::Halfblocks) => "halfblocks",
        };
        format!(
            "{term_program}|{term}|{tmux}|{color}|{image}|mouse={}|kbd={}|unicode={}",
            self.mouse, self.keyboard_enhancement, self.unicode_full,
        )
    }
}

impl Default for Capabilities {
    fn default() -> Self {
        Self::minimal()
    }
}

// ── Probing helpers ──────────────────────────────────────────────────────────

/// Infer color depth from environment variables: `$COLORTERM` first, then `$TERM`'s
/// conventional `-256color` suffix, then 8/16-color.
fn detect_color_depth(term: &str) -> ColorDepth {
    if term == "dumb" || term.is_empty() {
        return ColorDepth::NoColor;
    }
    let colorterm = env::var("COLORTERM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    if colorterm == "truecolor" || colorterm == "24bit" {
        return ColorDepth::TrueColor;
    }
    if term.contains("direct") {
        return ColorDepth::TrueColor;
    }
    // Some modern terminals support truecolor with `$COLORTERM` unset (e.g. a remote
    // session that stripped it).
    if env::var("KITTY_WINDOW_ID").is_ok() || env::var("WEZTERM_PANE").is_ok() {
        return ColorDepth::TrueColor;
    }
    if let Ok(tp) = env::var("TERM_PROGRAM") {
        match tp.as_str() {
            // Deliberately NOT `Apple_Terminal`: it silently quantizes 24-bit SGR, so
            // claiming truecolor would hand it themes and images it renders wrong.
            "iTerm.app" | "WezTerm" | "ghostty" | "Ghostty" => return ColorDepth::TrueColor,
            _ => {}
        }
    }
    if term.contains("256color") {
        return ColorDepth::Ansi256;
    }
    ColorDepth::Ansi16
}

/// Infer mouse support from `$TERM`.  Essentially every xterm-compatible terminal has it;
/// the exceptions are `dumb`, empty, and `linux` (the framebuffer console).
fn detect_mouse(term: &str) -> bool {
    if term == "dumb" || term == "linux" || term.is_empty() {
        return false;
    }
    true
}

/// True when the active locale advertises UTF-8.
fn detect_unicode_full() -> bool {
    for var in ["LC_ALL", "LC_CTYPE", "LANG"] {
        if let Ok(v) = env::var(var) {
            let upper = v.to_ascii_uppercase();
            if upper.contains("UTF-8") || upper.contains("UTF8") {
                return true;
            }
        }
    }
    false
}

/// A picker **guaranteed** to encode halfblocks, at the terminal's real `font_size`.
/// Neither ratatui-image constructor manages both, so take the font size from one and
/// stamp the protocol onto it.
///
/// `Picker::halfblocks()` hardcodes a (10, 20) font size, which changes the image's aspect
/// ratio every time it crosses the native↔halfblocks boundary.  `Picker::from_fontsize()`
/// keeps the size but *infers* the protocol from `$TERM_PROGRAM`, yielding an iTerm2
/// picker on many terminals — whose scratch buffer is one base64-PNG escape cell rather
/// than position-independent halfblock cells, which the row-clipping partial painter
/// cannot slice.
fn halfblocks_from(font_size: ratatui_image::FontSize) -> Picker {
    // Deprecated in ratatui-image 9+, but the only constructor taking a probed font size.
    #[allow(deprecated)]
    let mut picker = Picker::from_fontsize(font_size);
    picker.set_protocol_type(ProtocolType::Halfblocks);
    picker
}

/// True when we are talking to iTerm2.app, directly or over ssh — `$LC_TERMINAL` is
/// iTerm2's own forwarded marker, and the far end of the pipe is what matters here.
fn is_iterm2_app() -> bool {
    env::var("TERM_PROGRAM").is_ok_and(|v| v.contains("iTerm"))
        || env::var("LC_TERMINAL").is_ok_and(|v| v.contains("iTerm"))
}

/// Whether the iTerm2 env hint may override an affirmative Kitty probe (see
/// [`resolve_protocol`]).  Under tmux it may not: `update-environment` covers neither
/// `TERM_PROGRAM` nor `LC_TERMINAL`, so a pane created from iTerm2 and reattached from
/// Ghostty still advertises iTerm2 — and pinning `Iterm2` would break images on a terminal
/// that had them working.  The stdio probe asks the live terminal, so inside tmux we defer
/// to it.  The case given up is tmux *inside* iTerm2, which costs blank rows that the
/// halfblocks fallback can recover; a wrong-protocol pin on Ghostty cannot be.
fn iterm2_hint_is_trustworthy() -> bool {
    is_iterm2_app() && env::var_os("TMUX").is_none()
}

/// Resolve the protocol to encode with from the one `Picker::from_query_stdio` probed.
///
/// iTerm2 3.5+ answers the Kitty capability query affirmatively, so the picker comes back
/// as `Kitty` — but ratatui-image's Kitty backend renders only through the
/// unicode-placeholder extension, which iTerm2 does not implement, so the image is
/// transmitted and never placed and the reserved rows stay blank.  Pin it to `Iterm2`.
///
/// Only `Kitty` is overridden.  `iterm2` must come from [`iterm2_hint_is_trustworthy`],
/// not `is_iterm2_app` directly.
fn resolve_protocol(probed: ProtocolType, iterm2: bool) -> ProtocolType {
    match probed {
        ProtocolType::Kitty if iterm2 => ProtocolType::Iterm2,
        other => other,
    }
}

/// Probe for an image protocol, returning it alongside the `Picker` the rendering layer
/// reuses.  Halfblocks count as support — lower fidelity, still usable.
fn detect_image_protocol() -> (Option<ImageProtocol>, Option<Picker>) {
    // A panic here would corrupt terminal state, so catch and swallow.  Scoping the guard
    // to the `catch_unwind` alone is load-bearing: this runs on the main thread after the
    // hook is installed, so a guard live over the code below would let a real panic unwind
    // out of `main` with the alternate screen up and nothing printed.
    let result = {
        let _expected = super::ExpectedPanic::new();
        std::panic::catch_unwind(Picker::from_query_stdio)
    };
    let mut picker = match result {
        Ok(Ok(p)) => p,
        _ => return (None, None),
    };

    picker.set_protocol_type(resolve_protocol(
        picker.protocol_type(),
        iterm2_hint_is_trustworthy(),
    ));

    let protocol = match picker.protocol_type() {
        ProtocolType::Sixel => ImageProtocol::Sixel,
        ProtocolType::Kitty => ImageProtocol::KittyGraphics,
        ProtocolType::Iterm2 => ImageProtocol::ITerm2,
        ProtocolType::Halfblocks => ImageProtocol::Halfblocks,
    };
    (Some(protocol), Some(picker))
}

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

    // `env_lock` is crate-wide because the race is process-wide: a lock private to this
    // module could not exclude `cli::doctor`'s reads of the very variables set below.
    use crate::test_env::{env_lock, EnvGuard};

    // ── Image protocol ────────────────────────────────────────────────

    /// Regression: `Picker::from_fontsize` infers its protocol from `$TERM_PROGRAM`, so
    /// the "halfblocks" picker came back as an iTerm2 one.  See [`halfblocks_from`].
    #[test]
    fn halfblocks_picker_is_halfblocks_even_under_iterm2() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "iTerm.app");
        let _g2 = EnvGuard::unset("TMUX");
        let picker = halfblocks_from(ratatui_image::FontSize::new(7, 15));
        assert_eq!(picker.protocol_type(), ProtocolType::Halfblocks);
    }

    /// The probed font size must survive; `Picker::halfblocks()` would hardcode (10, 20).
    #[test]
    fn halfblocks_picker_keeps_the_probed_font_size() {
        let _lock = env_lock();
        let _g = EnvGuard::unset("TERM_PROGRAM");
        let picker = halfblocks_from(ratatui_image::FontSize::new(7, 15));
        assert_eq!(picker.font_size().width, 7);
        assert_eq!(picker.font_size().height, 15);
    }

    #[test]
    fn iterm2_app_detected_from_term_program_and_lc_terminal() {
        let _lock = env_lock();
        {
            let _g1 = EnvGuard::set("TERM_PROGRAM", "iTerm.app");
            let _g2 = EnvGuard::unset("LC_TERMINAL");
            assert!(is_iterm2_app());
        }
        {
            let _g1 = EnvGuard::unset("TERM_PROGRAM");
            let _g2 = EnvGuard::set("LC_TERMINAL", "iTerm2");
            assert!(is_iterm2_app());
        }
        {
            let _g1 = EnvGuard::set("TERM_PROGRAM", "ghostty");
            let _g2 = EnvGuard::unset("LC_TERMINAL");
            assert!(!is_iterm2_app());
        }
    }

    /// The headline override — see [`resolve_protocol`].
    #[test]
    fn kitty_probe_under_iterm2_is_pinned_to_iterm2() {
        assert_eq!(
            resolve_protocol(ProtocolType::Kitty, true),
            ProtocolType::Iterm2
        );
    }

    /// Only `Kitty` is overridden, and only under the iTerm2 hint.
    #[test]
    fn resolve_protocol_leaves_every_other_probe_alone() {
        for probed in [
            ProtocolType::Kitty,
            ProtocolType::Sixel,
            ProtocolType::Iterm2,
            ProtocolType::Halfblocks,
        ] {
            assert_eq!(
                resolve_protocol(probed, false),
                probed,
                "{probed:?} must survive without an iTerm2 hint"
            );
        }
        for probed in [
            ProtocolType::Sixel,
            ProtocolType::Iterm2,
            ProtocolType::Halfblocks,
        ] {
            assert_eq!(
                resolve_protocol(probed, true),
                probed,
                "{probed:?} must survive even under iTerm2"
            );
        }
    }

    /// See [`iterm2_hint_is_trustworthy`]: a stale forwarded marker inside tmux must not
    /// pin a protocol the live terminal cannot render.
    #[test]
    fn iterm2_hint_is_distrusted_inside_tmux() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LC_TERMINAL", "iTerm2");
        let _g2 = EnvGuard::unset("TERM_PROGRAM");
        {
            let _g3 = EnvGuard::unset("TMUX");
            assert!(iterm2_hint_is_trustworthy(), "bare iTerm2 is trusted");
        }
        {
            let _g3 = EnvGuard::set("TMUX", "/tmp/tmux-501/default,1234,0");
            assert!(
                !iterm2_hint_is_trustworthy(),
                "a stale forwarded marker inside tmux must not pin Iterm2"
            );
            assert_eq!(
                resolve_protocol(ProtocolType::Kitty, iterm2_hint_is_trustworthy()),
                ProtocolType::Kitty,
                "the live capability probe wins inside tmux"
            );
        }
    }

    /// The guard must gate on the hint, not merely on tmux.
    #[test]
    fn iterm2_hint_is_absent_without_an_iterm2_marker() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "ghostty");
        let _g2 = EnvGuard::unset("LC_TERMINAL");
        let _g3 = EnvGuard::unset("TMUX");
        assert!(!iterm2_hint_is_trustworthy());
    }

    #[test]
    fn color_depth_no_color_for_dumb_terminal() {
        assert_eq!(detect_color_depth("dumb"), ColorDepth::NoColor);
        assert_eq!(detect_color_depth(""), ColorDepth::NoColor);
    }

    #[test]
    fn color_depth_truecolor_from_colorterm() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("COLORTERM", "truecolor");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::TrueColor);
    }

    #[test]
    fn color_depth_256_from_term_suffix() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::Ansi256);
    }

    #[test]
    fn color_depth_16_for_plain_xterm() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm"), ColorDepth::Ansi16);
    }

    #[test]
    fn color_depth_truecolor_for_kitty_envvar() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::set("KITTY_WINDOW_ID", "1");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm"), ColorDepth::TrueColor);
    }

    #[test]
    fn color_depth_256_for_apple_terminal() {
        // Terminal.app quantizes 24-bit SGR, so it must resolve to Ansi256 despite
        // `TERM=xterm-256color`.
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::set("TERM_PROGRAM", "Apple_Terminal");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::Ansi256);
    }

    #[test]
    fn full_color_only_for_truecolor() {
        let caps = Capabilities {
            color_depth: ColorDepth::TrueColor,
            ..Capabilities::minimal()
        };
        assert!(caps.full_color());
        for depth in [ColorDepth::Ansi256, ColorDepth::Ansi16, ColorDepth::NoColor] {
            let caps = Capabilities {
                color_depth: depth,
                ..Capabilities::minimal()
            };
            assert!(!caps.full_color(), "{depth:?} is not full color");
        }
    }

    #[test]
    fn mouse_false_for_dumb_and_linux() {
        assert!(!detect_mouse("dumb"));
        assert!(!detect_mouse("linux"));
        assert!(!detect_mouse(""));
    }

    #[test]
    fn mouse_true_for_modern_terminals() {
        assert!(detect_mouse("xterm-256color"));
        assert!(detect_mouse("alacritty"));
        assert!(detect_mouse("tmux-256color"));
    }

    #[test]
    fn unicode_full_from_lang() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LANG", "en_US.UTF-8");
        let _g2 = EnvGuard::unset("LC_ALL");
        let _g3 = EnvGuard::unset("LC_CTYPE");
        assert!(detect_unicode_full());
    }

    #[test]
    fn unicode_false_for_c_locale() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LANG", "C");
        let _g2 = EnvGuard::unset("LC_ALL");
        let _g3 = EnvGuard::unset("LC_CTYPE");
        assert!(!detect_unicode_full());
    }

    #[test]
    fn minimal_capabilities_are_conservative() {
        let caps = Capabilities::minimal();
        assert_eq!(caps.color_depth, ColorDepth::Ansi16);
        assert!(!caps.mouse);
        assert!(caps.image_protocol.is_none());
        assert!(!caps.unicode_full);
        assert!(!caps.keyboard_enhancement);
    }

    #[test]
    fn fingerprint_is_stable_for_identical_caps() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "xterm-256color");
        let _g3 = EnvGuard::unset("TMUX");
        let caps = Capabilities {
            color_depth: ColorDepth::TrueColor,
            mouse: true,
            image_protocol: Some(ImageProtocol::KittyGraphics),
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: true,
            keyboard_enhancement: true,
        };
        assert_eq!(caps.fingerprint(), caps.fingerprint());
    }

    #[test]
    fn fingerprint_differs_when_a_capability_flips() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "xterm-256color");
        let _g3 = EnvGuard::unset("TMUX");
        let base = Capabilities {
            color_depth: ColorDepth::TrueColor,
            mouse: true,
            image_protocol: Some(ImageProtocol::KittyGraphics),
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: true,
            keyboard_enhancement: true,
        };
        let mouseless = Capabilities {
            mouse: false,
            ..base.clone()
        };
        let no_kbd = Capabilities {
            keyboard_enhancement: false,
            ..base.clone()
        };
        let no_image = Capabilities {
            image_protocol: None,
            ..base.clone()
        };
        assert_ne!(base.fingerprint(), mouseless.fingerprint());
        assert_ne!(base.fingerprint(), no_kbd.fingerprint());
        assert_ne!(base.fingerprint(), no_image.fingerprint());
    }

    #[test]
    fn fingerprint_includes_tmux_marker() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "tmux-256color");
        let caps = Capabilities::minimal();
        let _no_tmux = EnvGuard::unset("TMUX");
        let outside = caps.fingerprint();
        let _in_tmux = EnvGuard::set("TMUX", "/tmp/tmux-1000/default,123,0");
        let inside = caps.fingerprint();
        assert_ne!(outside, inside);
        assert!(inside.contains("tmux"));
    }
}