uncurses 0.0.6

A Rust terminal rendering library
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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Terminal capability flags used by the renderer.
//!
//! ## Purpose
//!
//! [`Optimizations`] is not a feature wishlist; it is the renderer's
//! contract for which byte sequences are safe to emit for the current
//! terminal and line discipline. Each flag unlocks a family of shorter
//! sequences. When a flag is absent, the renderer falls back to more
//! conservative cursor movement or explicit cell writes.
//!
//! ## Detection
//!
//! The built-in detector maps `$TERM` families to conservative baseline
//! sets. Unknown, empty, and `dumb` terminals use [`Optimizations::none`].
//! A missing `$TERM` uses [`Optimizations::default`] so in-memory tests
//! and sinks without environment information keep a useful baseline.
//!
//! ## Line-discipline flags
//!
//! [`Optimizations::TABS`], [`Optimizations::BS`], and
//! [`Optimizations::ONLCR`] describe the host's output processing, not
//! the terminal's own abilities, so no baseline here carries them: a
//! `\t` is only usable if the line discipline passes it through, which
//! `$TERM` cannot tell you. A [`Screen`](crate::screen::Screen) enables
//! `TABS` and `BS` on *every* raw-mode entry —
//! [`init`](crate::screen::Screen::init) and
//! [`resume`](crate::screen::Screen::resume) alike — because raw mode
//! turns the host's output processing off, which is exactly what makes
//! `\t` and `\x08` safe to emit.
//!
//! `ONLCR` is never granted: raw mode is also what makes it false. It
//! stays opt-in for callers who know their output crosses a layer that
//! turns `\n` into `\r\n` anyway.
//!
//! Driving a [`Renderer`] yourself, or keeping the host in cooked mode?
//! Then the answer is yours to supply: use [`Optimizations::with_tabs`],
//! [`Optimizations::with_bs`], and [`Optimizations::with_onlcr`]. Leaving
//! all three off is always safe — the renderer then emits escape
//! sequences that no line discipline can rewrite.
//!
//! [`Renderer`]: crate::renderer::Renderer

use bitflags::bitflags;

use crate::terminal::Env;

bitflags! {
    /// Terminal capabilities the renderer may use for shorter output.
    ///
    /// # Usage
    ///
    /// Start from a detector result such as [`Optimizations::from_env`]
    /// or a baseline such as [`Optimizations::xterm`], then use the
    /// `with_*` methods to toggle assumptions confirmed by probing or
    /// terminal-mode setup.
    ///
    /// Flag names follow the short capability names used by `infocmp`
    /// where they exist. `BS` and `ONLCR` are not terminfo caps; they
    /// describe control-character and output-processing behavior.
    ///
    /// [`TABS`](Self::TABS), [`BS`](Self::BS), and
    /// [`ONLCR`](Self::ONLCR) are the odd ones out: they describe the
    /// *host*, not the terminal. A [`Screen`](crate::screen::Screen)
    /// enables `TABS` and `BS` on every raw-mode entry and never touches
    /// `ONLCR`. See the module docs.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct Optimizations: u32 {
        /// Terminal supports ECH (Erase Characters, `CSI Ps X`) for
        /// clearing a run on the current row.
        const ECH    = 1 <<  0;
        /// Terminal supports REP (Repeat preceding character,
        /// `CSI Ps b`) for compact repeated ASCII glyphs.
        const REP    = 1 <<  1;
        /// Terminal supports ICH (Insert Characters, `CSI Ps @`) for
        /// opening cells within a row.
        const ICH    = 1 <<  2;
        /// Terminal supports DCH (Delete Characters, `CSI Ps P`) for
        /// removing cells within a row.
        const DCH    = 1 <<  3;
        /// Terminal supports scroll regions (DECSTBM; terminfo `csr`).
        const CSR    = 1 <<  4;
        /// Terminal supports SU/SD (Scroll Up/Down, `CSI Ps S` /
        /// `CSI Ps T`) for moving full scroll regions.
        const SU_SD  = 1 <<  5;
        /// Terminal supports IL/DL (Insert/Delete Line, `CSI Ps L` /
        /// `CSI Ps M`) for line-level scroll fallbacks.
        const IL_DL  = 1 <<  6;
        /// Terminal supports BCE (Background Color Erase): erase
        /// operations paint with the active background color.
        ///
        /// Also governs cursor motion. An inline downward move is
        /// emitted as a literal `\n`, which scrolls the host when the
        /// destination row does not exist yet; with BCE that scroll
        /// paints the exposed row with the active background, so the
        /// planner resets the pen first. See `PenPolicy`.
        const BCE    = 1 <<  7;
        /// Terminal supports CHA (Cursor Horizontal Absolute,
        /// `CSI Ps G`) for absolute column moves.
        const CHA    = 1 <<  8;
        /// Terminal supports HPA (Horizontal Position Absolute,
        /// `CSI Ps \``) for absolute column moves.
        const HPA    = 1 <<  9;
        /// Terminal supports VPA (Vertical Position Absolute,
        /// `CSI Ps d`) for absolute row moves.
        const VPA    = 1 << 10;
        /// Literal tab bytes move to configured hardware tab stops.
        const TABS   = 1 << 11;
        /// Terminal supports CBT (Cursor Backward Tab, `CSI Ps Z`).
        const CBT    = 1 << 12;
        /// Terminal supports CHT (Cursor Horizontal Tab, `CSI Ps I`).
        const CHT    = 1 << 13;
        /// Terminal supports BS (the backspace control character,
        /// `\x08`) for cursor-left-by-one.
        const BS     = 1 << 14;
        /// Whether the terminal currently maps `\n` to `\r\n`
        /// (termios ONLCR). In raw mode this is unset and `\n` only
        /// moves the cursor down without resetting the column.
        const ONLCR  = 1 << 15;
    }
}

impl Default for Optimizations {
    /// The default is [`Optimizations::xterm`] — the modern baseline
    /// for the overwhelming majority of terminals reachable from a
    /// generic `TERM=xterm-256color` session.
    fn default() -> Self {
        Self::xterm()
    }
}

impl Optimizations {
    /// Return the most conservative useful capability set.
    ///
    /// Every escape-sequence optimization is disabled. Use this for
    /// unknown or genuinely capability-limited terminals when direct
    /// cell output is safer than specialized control sequences.
    pub const fn none() -> Self {
        Self::empty()
    }

    /// Return the modern full-feature baseline.
    ///
    /// Enables every renderer optimization a terminal can advertise.
    /// The line-discipline flags are absent: see the module docs.
    pub const fn modern() -> Self {
        Self::ECH
            .union(Self::REP)
            .union(Self::ICH)
            .union(Self::DCH)
            .union(Self::CSR)
            .union(Self::SU_SD)
            .union(Self::IL_DL)
            .union(Self::BCE)
            .union(Self::CHA)
            .union(Self::HPA)
            .union(Self::VPA)
            .union(Self::CBT)
            .union(Self::CHT)
    }

    /// Return the xterm-compatible conservative baseline.
    ///
    /// Compared to [`Self::modern`], `HPA`,
    /// `CHT`, and `REP` are off:
    /// - `HPA`: konsole and several xterm-compatible terminals lack
    ///   HPA; xterm-256color terminfo defines HPA via the same
    ///   sequence as CHA, so CHA is the safer choice.
    /// - `CHT`: forward-tab support is historically inconsistent
    ///   across xterm-compatible emulators.
    /// - `REP`: REP is not universally implemented across the
    ///   xterm-compatible family.
    pub const fn xterm() -> Self {
        Self::modern().difference(Self::HPA.union(Self::CHT).union(Self::REP))
    }

    /// Return the VT100/VT102 baseline.
    ///
    /// Predates the xterm extensions for
    /// absolute positioning (CHA/HPA/VPA), ECH, REP, BCE, SU/SD, and
    /// CBT, but supports DECSTBM and, on the VT102, the ICH/DCH/IL/DL
    /// editing pairs.
    pub const fn vt100() -> Self {
        Self::ICH
            .union(Self::DCH)
            .union(Self::CSR)
            .union(Self::IL_DL)
    }

    /// Return the Linux console baseline.
    ///
    /// The kernel's terminal driver
    /// implements a narrow subset of ECMA-48 — only absolute
    /// positioning (CHA/HPA/VPA), ECH, and ICH.
    /// See `console_codes(4)`.
    pub const fn linux() -> Self {
        Self::ECH
            .union(Self::ICH)
            .union(Self::CHA)
            .union(Self::HPA)
            .union(Self::VPA)
    }

    /// Return the GNU screen baseline, derived from
    /// `infocmp -x1 screen-256color`. screen multiplexes onto the
    /// host terminal and only re-advertises a conservative subset:
    /// no `BCE`, `ECH`, `REP`, `CHA`, or `CHT`.
    pub const fn screen() -> Self {
        Self::ICH
            .union(Self::DCH)
            .union(Self::CSR)
            .union(Self::SU_SD)
            .union(Self::IL_DL)
            .union(Self::HPA)
            .union(Self::VPA)
            .union(Self::CBT)
    }

    /// Return `self` with hardware tab support (`TABS`) toggled.
    ///
    /// Disable when the
    /// receiving terminal is in cooked mode without `TAB0` set on
    /// `c_oflag` and `\t` would otherwise be expanded to spaces.
    ///
    /// A [`Screen`](crate::screen::Screen) enables this on every raw-mode
    /// entry, since raw mode is what makes `\t` safe, so setting it here
    /// matters only when driving a renderer directly.
    #[must_use]
    pub const fn with_tabs(self, enabled: bool) -> Self {
        self.with_flag(Self::TABS, enabled)
    }

    /// Return `self` with backspace-character support (`BS`) toggled.
    ///
    /// Disable when the
    /// receiving terminal does not interpret `\x08` as cursor-left
    /// by one cell.
    ///
    /// A [`Screen`](crate::screen::Screen) enables this on every raw-mode
    /// entry, since raw mode is what makes `\x08` safe, so setting it here
    /// matters only when driving a renderer directly.
    #[must_use]
    pub const fn with_bs(self, enabled: bool) -> Self {
        self.with_flag(Self::BS, enabled)
    }

    /// Return `self` with the `\n` → `\r\n` assumption (`ONLCR`)
    /// toggled.
    ///
    /// Enable when the terminal is in cooked mode with `ONLCR` set so a
    /// newline both advances a row and resets the column.
    ///
    /// A [`Screen`](crate::screen::Screen) never sets this — raw mode
    /// clears `OPOST`, so `\n` carries no carriage return — but it never
    /// clears it either. It is yours to opt into and yours to keep.
    #[must_use]
    pub const fn with_onlcr(self, enabled: bool) -> Self {
        self.with_flag(Self::ONLCR, enabled)
    }

    /// Return `self` with erase-character (`ECH`) support toggled.
    #[must_use]
    pub const fn with_ech(self, enabled: bool) -> Self {
        self.with_flag(Self::ECH, enabled)
    }

    /// Return `self` with repeat-character (`REP`) support toggled.
    #[must_use]
    pub const fn with_rep(self, enabled: bool) -> Self {
        self.with_flag(Self::REP, enabled)
    }

    /// Return `self` with insert-character (`ICH`) support toggled.
    #[must_use]
    pub const fn with_ich(self, enabled: bool) -> Self {
        self.with_flag(Self::ICH, enabled)
    }

    /// Return `self` with delete-character (`DCH`) support toggled.
    #[must_use]
    pub const fn with_dch(self, enabled: bool) -> Self {
        self.with_flag(Self::DCH, enabled)
    }

    /// Return `self` with DECSTBM scroll-region (`CSR`) support toggled.
    #[must_use]
    pub const fn with_csr(self, enabled: bool) -> Self {
        self.with_flag(Self::CSR, enabled)
    }

    /// Return `self` with scroll-up/scroll-down (`SU_SD`) support toggled.
    #[must_use]
    pub const fn with_su_sd(self, enabled: bool) -> Self {
        self.with_flag(Self::SU_SD, enabled)
    }

    /// Return `self` with insert/delete-line (`IL_DL`) support toggled.
    #[must_use]
    pub const fn with_il_dl(self, enabled: bool) -> Self {
        self.with_flag(Self::IL_DL, enabled)
    }

    /// Return `self` with background-color-erase (`BCE`) support toggled.
    #[must_use]
    pub const fn with_bce(self, enabled: bool) -> Self {
        self.with_flag(Self::BCE, enabled)
    }

    /// Return `self` with cursor-horizontal-absolute (`CHA`) support toggled.
    #[must_use]
    pub const fn with_cha(self, enabled: bool) -> Self {
        self.with_flag(Self::CHA, enabled)
    }

    /// Return `self` with horizontal-position-absolute (`HPA`) support toggled.
    #[must_use]
    pub const fn with_hpa(self, enabled: bool) -> Self {
        self.with_flag(Self::HPA, enabled)
    }

    /// Return `self` with vertical-position-absolute (`VPA`) support toggled.
    #[must_use]
    pub const fn with_vpa(self, enabled: bool) -> Self {
        self.with_flag(Self::VPA, enabled)
    }

    /// Return `self` with cursor-backward-tab (`CBT`) support toggled.
    #[must_use]
    pub const fn with_cbt(self, enabled: bool) -> Self {
        self.with_flag(Self::CBT, enabled)
    }

    /// Return `self` with cursor-horizontal-tab (`CHT`) support toggled.
    #[must_use]
    pub const fn with_cht(self, enabled: bool) -> Self {
        self.with_flag(Self::CHT, enabled)
    }

    /// Const-friendly helper used by the `with_*` builders.
    const fn with_flag(self, flag: Self, enabled: bool) -> Self {
        if enabled {
            self.union(flag)
        } else {
            self.difference(flag)
        }
    }

    /// Derive an optimization set from a `TERM` value.
    ///
    /// # Parameters
    ///
    /// - `term`: terminal name, usually from `$TERM`.
    ///
    /// # Returns
    ///
    /// A baseline capability set for the terminal family. Unknown,
    /// empty, and `dumb` values return [`Self::none`].
    pub fn from_term(term: &str) -> Self {
        let head = term.split('-').next().unwrap_or("");
        // xterm-<vendor> reassignment when the vendor is a known modern
        // terminal advertising xterm compatibility.
        if head == "xterm"
            && let Some(rest) = term.strip_prefix("xterm-")
        {
            let vendor = rest.split('-').next().unwrap_or("");
            if matches!(vendor, "ghostty" | "kitty" | "rio") {
                return Self::modern();
            }
        }
        match head {
            "" | "dumb" => Self::none(),
            // Modern terminals that advertise the full xterm-era cap
            // set. Alacritty falls into this bucket too; the detector
            // uses the shared modern baseline rather than maintaining a
            // vendor-specific single-flag variant here.
            "alacritty" | "contour" | "foot" | "ghostty" | "kitty" | "rio" | "st" | "tmux"
            | "wezterm" => Self::modern(),
            "xterm" => Self::xterm(),
            "screen" => Self::screen(),
            "linux" => Self::linux(),
            _ => Self::none(),
        }
    }

    /// Derive an optimization set from an [`Env`].
    ///
    /// Routes `$TERM` through [`Self::from_term`] when it is set, and
    /// falls back to [`Self::default`] when `$TERM` is unset entirely.
    /// This keeps callers with no environment information (CI harnesses,
    /// embedded sinks, tests) on the xterm baseline rather than
    /// collapsing to [`Self::none`].
    pub fn from_env(env: &dyn Env) -> Self {
        match env.get("TERM") {
            Some(term) => Self::from_term(&term),
            None => Self::default(),
        }
    }

    /// Report whether `env` names a terminal known to implement DECST8C,
    /// the `ESC [ ? 5 W` sequence that resets tab stops to one every
    /// eight columns in a single, cursor-safe write.
    ///
    /// The allowlist covers Ghostty, kitty, Rio, Alacritty, iTerm2, and
    /// Windows Terminal. Terminals outside it fall back to the portable
    /// TBC-then-HTS reset, so a false negative only costs a few extra
    /// bytes, never correctness. This inspects the environment only and
    /// never probes the terminal.
    pub(crate) fn supports_decst8c(env: &dyn Env) -> bool {
        // Windows Terminal announces itself with a session token rather
        // than through $TERM.
        if env.has("WT_SESSION") {
            return true;
        }
        // kitty, Alacritty, and iTerm2 export a session/window id that
        // survives login shells and multiplexers rewriting $TERM.
        if env.has("KITTY_WINDOW_ID")
            || env.has("ALACRITTY_WINDOW_ID")
            || env.has("ITERM_SESSION_ID")
        {
            return true;
        }
        // iTerm2 sets $LC_TERMINAL, which also propagates across ssh.
        if env
            .get("LC_TERMINAL")
            .is_some_and(|t| t.eq_ignore_ascii_case("iterm2"))
        {
            return true;
        }
        // $TERM_PROGRAM outlives some xterm-compatible $TERM rewrites.
        if let Some(program) = env.get("TERM_PROGRAM")
            && matches!(
                program.to_ascii_lowercase().as_str(),
                "ghostty" | "rio" | "iterm.app"
            )
        {
            return true;
        }
        let Some(term) = env.get("TERM") else {
            return false;
        };
        // Match the bare vendor head and the xterm-<vendor> promotion
        // form, mirroring how `from_term` resolves these terminals.
        let head = term.split('-').next().unwrap_or("");
        if matches!(head, "alacritty" | "ghostty" | "kitty" | "rio") {
            return true;
        }
        if let Some(rest) = term.strip_prefix("xterm-") {
            let vendor = rest.split('-').next().unwrap_or("");
            return matches!(vendor, "ghostty" | "kitty" | "rio");
        }
        false
    }
}

#[cfg(test)]
mod tests {
    /// The host-dependent flags, as a test-local group: the public API
    /// deliberately has no name for them, since `Screen` grants `TABS`
    /// and `BS` but leaves `ONLCR` alone.
    const LINE_DISCIPLINE: Optimizations = Optimizations::TABS
        .union(Optimizations::BS)
        .union(Optimizations::ONLCR);

    use super::*;
    use crate::terminal::EnvList;

    fn env_with(pairs: &[(&str, &str)]) -> EnvList {
        EnvList::from_pairs(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())))
    }

    #[test]
    fn supports_decst8c_matches_allowlisted_terms() {
        for term in [
            "alacritty",
            "ghostty",
            "kitty",
            "rio",
            "xterm-kitty",
            "xterm-ghostty",
        ] {
            assert!(
                Optimizations::supports_decst8c(&env_with(&[("TERM", term)])),
                "expected DECST8C support for TERM={term}",
            );
        }
    }

    #[test]
    fn supports_decst8c_rejects_plain_xterm_and_unknown() {
        for term in [
            "xterm-256color",
            "screen-256color",
            "tmux",
            "vt100",
            "dumb",
            "",
        ] {
            assert!(
                !Optimizations::supports_decst8c(&env_with(&[("TERM", term)])),
                "did not expect DECST8C support for TERM={term}",
            );
        }
    }

    #[test]
    fn supports_decst8c_detects_terminals_via_env_tokens() {
        // Windows Terminal and window-id exporters are recognized even when
        // $TERM is rewritten to a generic value.
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("WT_SESSION", "abc"),
        ])));
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("KITTY_WINDOW_ID", "1"),
        ])));
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("ALACRITTY_WINDOW_ID", "1"),
        ])));
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "screen"),
            ("TERM_PROGRAM", "ghostty"),
        ])));
        // iTerm2 keeps $TERM generic and identifies itself through its own
        // tokens, including $LC_TERMINAL which survives ssh.
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("TERM_PROGRAM", "iTerm.app"),
        ])));
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("ITERM_SESSION_ID", "w0t0p0:abc"),
        ])));
        assert!(Optimizations::supports_decst8c(&env_with(&[
            ("TERM", "xterm-256color"),
            ("LC_TERMINAL", "iTerm2"),
        ])));
    }

    #[test]
    fn default_is_xterm() {
        assert_eq!(Optimizations::default(), Optimizations::xterm());
    }

    #[test]
    fn none_disables_escape_caps_only() {
        let o = Optimizations::none();
        assert!(!o.intersects(
            Optimizations::ECH
                | Optimizations::REP
                | Optimizations::ICH
                | Optimizations::DCH
                | Optimizations::CSR
                | Optimizations::SU_SD
                | Optimizations::IL_DL
                | Optimizations::BCE
                | Optimizations::CHA
                | Optimizations::HPA
                | Optimizations::VPA
                | Optimizations::CBT
                | Optimizations::CHT
                | Optimizations::ONLCR,
        ));
        // The line discipline is not a $TERM question; `Screen::init`
        // grants TABS and BS once raw mode has settled it instead.
        assert!(o.is_empty());
    }

    #[test]
    fn modern_enables_every_escape_cap() {
        let o = Optimizations::modern();
        assert_eq!(o, Optimizations::all().difference(LINE_DISCIPLINE));
    }

    #[test]
    fn xterm_drops_hpa_cht_rep() {
        let o = Optimizations::xterm();
        assert!(!o.contains(Optimizations::HPA));
        assert!(!o.contains(Optimizations::CHT));
        assert!(!o.contains(Optimizations::REP));
        let expected = Optimizations::modern()
            .difference(Optimizations::HPA | Optimizations::CHT | Optimizations::REP);
        assert_eq!(o, expected);
    }

    #[test]
    fn vt100_predates_xterm_extensions() {
        let o = Optimizations::vt100();
        // No xterm-era absolute positioning or extensions.
        let missing = Optimizations::CHA
            | Optimizations::HPA
            | Optimizations::VPA
            | Optimizations::ECH
            | Optimizations::REP
            | Optimizations::SU_SD
            | Optimizations::BCE
            | Optimizations::CBT
            | Optimizations::CHT
            | Optimizations::ONLCR;
        assert!(!o.intersects(missing));
        // VT100 era margins + VT102 editing pairs.
        let present =
            Optimizations::CSR | Optimizations::ICH | Optimizations::DCH | Optimizations::IL_DL;
        assert!(o.contains(present));
    }

    #[test]
    fn linux_matches_console_codes_4() {
        let o = Optimizations::linux();
        let present = Optimizations::ECH
            | Optimizations::ICH
            | Optimizations::CHA
            | Optimizations::HPA
            | Optimizations::VPA;
        assert_eq!(o, present);
    }

    #[test]
    fn screen_matches_infocmp_x1_screen_256color() {
        let o = Optimizations::screen();
        let present = Optimizations::ICH
            | Optimizations::DCH
            | Optimizations::CSR
            | Optimizations::SU_SD
            | Optimizations::IL_DL
            | Optimizations::HPA
            | Optimizations::VPA
            | Optimizations::CBT;
        assert_eq!(o, present);
        assert!(!o.contains(Optimizations::BCE));
        assert!(!o.contains(Optimizations::ECH));
        assert!(!o.contains(Optimizations::REP));
        assert!(!o.contains(Optimizations::CHA));
        assert!(!o.contains(Optimizations::CHT));
    }

    /// No `$TERM` baseline may carry a line-discipline flag. `\t`,
    /// `\x08`, and `\n` behave according to the host's output
    /// processing, which `$TERM` cannot describe; `Screen::init` enables
    /// `TABS` and `BS` once raw mode has disabled that processing, and
    /// leaves `ONLCR` to the caller.
    #[test]
    fn no_baseline_carries_line_discipline_flags() {
        let line_discipline = LINE_DISCIPLINE;
        let baselines = [
            ("none", Optimizations::none()),
            ("modern", Optimizations::modern()),
            ("xterm", Optimizations::xterm()),
            ("vt100", Optimizations::vt100()),
            ("linux", Optimizations::linux()),
            ("screen", Optimizations::screen()),
            ("default", Optimizations::default()),
        ];
        for (name, o) in baselines {
            assert!(
                !o.intersects(line_discipline),
                "{name} baseline must not assume the line discipline: {o:?}"
            );
        }
    }

    /// Every `$TERM` the detector recognizes routes to one of the
    /// baselines above, so none of them may carry the flags either.
    #[test]
    fn no_term_carries_line_discipline_flags() {
        let line_discipline = LINE_DISCIPLINE;
        for term in [
            "alacritty",
            "contour",
            "foot",
            "ghostty",
            "kitty",
            "rio",
            "st",
            "tmux",
            "tmux-256color",
            "wezterm",
            "xterm",
            "xterm-256color",
            "screen",
            "screen-256color",
            "linux",
            "vt100",
            "dumb",
            "",
        ] {
            let o = Optimizations::from_term(term);
            assert!(
                !o.intersects(line_discipline),
                "{term} must not assume the line discipline: {o:?}"
            );
        }
    }

    #[test]
    fn from_term_kitty() {
        let o = Optimizations::from_term("kitty");
        assert!(o.contains(Optimizations::REP | Optimizations::HPA | Optimizations::VPA));
    }

    #[test]
    fn from_term_xterm_excludes_hpa_cht_rep() {
        let o = Optimizations::from_term("xterm-256color");
        assert!(!o.contains(Optimizations::HPA));
        assert!(!o.contains(Optimizations::CHT));
        assert!(!o.contains(Optimizations::REP));
        assert!(o.contains(Optimizations::CHA));
    }

    #[test]
    fn from_term_xterm_kitty_promotes() {
        let o = Optimizations::from_term("xterm-kitty");
        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
    }

    #[test]
    fn from_term_xterm_ghostty_promotes() {
        let o = Optimizations::from_term("xterm-ghostty");
        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
    }

    #[test]
    fn from_term_xterm_rio_promotes() {
        let o = Optimizations::from_term("xterm-rio");
        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
    }

    #[test]
    fn from_term_linux_console() {
        assert_eq!(Optimizations::from_term("linux"), Optimizations::linux());
    }

    #[test]
    fn from_term_dumb_is_none() {
        assert_eq!(Optimizations::from_term("dumb"), Optimizations::none());
    }

    #[test]
    fn from_term_empty_is_none() {
        assert_eq!(Optimizations::from_term(""), Optimizations::none());
    }

    #[test]
    fn from_term_unknown_falls_back_to_none() {
        assert_eq!(
            Optimizations::from_term("madeupterm-256color"),
            Optimizations::none(),
        );
    }

    #[test]
    fn xterm_term_enables_cha() {
        let o = Optimizations::from_term("xterm-256color");
        assert!(o.contains(Optimizations::CHA));
        assert!(!o.contains(Optimizations::HPA));
    }

    #[test]
    fn linux_term_supports_vpa_hpa_not_rep() {
        let o = Optimizations::from_term("linux");
        assert!(o.contains(Optimizations::VPA | Optimizations::HPA));
        assert!(!o.contains(Optimizations::REP));
    }

    #[test]
    fn alacritty_term_has_explicit_caps() {
        let o = Optimizations::from_term("alacritty");
        assert!(o.contains(Optimizations::CHA | Optimizations::ECH | Optimizations::REP));
    }

    #[test]
    fn screen_term_uses_screen_profile() {
        assert_eq!(
            Optimizations::from_term("screen-256color"),
            Optimizations::screen(),
        );
    }

    #[test]
    fn tmux_term_supports_vpa() {
        assert!(Optimizations::from_term("tmux-256color").contains(Optimizations::VPA));
    }

    #[test]
    fn from_term_modern_families_all_enable_rep() {
        for term in [
            "contour",
            "foot",
            "ghostty",
            "kitty",
            "rio",
            "st",
            "tmux",
            "wezterm",
            "alacritty",
        ] {
            let o = Optimizations::from_term(term);
            assert!(
                o.contains(Optimizations::REP | Optimizations::HPA),
                "{term} should enable REP and HPA"
            );
        }
    }

    #[test]
    fn with_tabs_toggles_tabs() {
        let on = Optimizations::none().with_tabs(true);
        let off = Optimizations::none().with_tabs(false);
        assert!(on.contains(Optimizations::TABS));
        assert!(!off.contains(Optimizations::TABS));
    }

    #[test]
    fn with_bs_toggles_bs() {
        let on = Optimizations::none().with_bs(true);
        let off = Optimizations::none().with_bs(false);
        assert!(on.contains(Optimizations::BS));
        assert!(!off.contains(Optimizations::BS));
    }

    #[test]
    fn with_onlcr_toggles_onlcr() {
        let on = Optimizations::none().with_onlcr(true);
        let off = Optimizations::modern().with_onlcr(false);
        assert!(on.contains(Optimizations::ONLCR));
        assert!(!off.contains(Optimizations::ONLCR));
    }

    #[test]
    fn with_builders_compose() {
        let o = Optimizations::xterm()
            .with_rep(true)
            .with_hpa(true)
            .with_cha(false);
        assert!(o.contains(Optimizations::REP | Optimizations::HPA));
        assert!(!o.contains(Optimizations::CHA));
    }

    #[test]
    fn from_env_uses_term_when_set() {
        let env = EnvList::from_pairs([("TERM", "xterm-kitty")]);
        assert_eq!(Optimizations::from_env(&env), Optimizations::modern());
    }

    #[test]
    fn from_env_dumb_collapses_to_none() {
        let env = EnvList::from_pairs([("TERM", "dumb")]);
        assert_eq!(Optimizations::from_env(&env), Optimizations::none());
    }

    #[test]
    fn from_env_empty_term_collapses_to_none() {
        let env = EnvList::from_pairs([("TERM", "")]);
        assert_eq!(Optimizations::from_env(&env), Optimizations::none());
    }

    #[test]
    fn from_env_missing_term_falls_back_to_default() {
        let env = EnvList::new();
        assert_eq!(Optimizations::from_env(&env), Optimizations::default());
    }

    #[test]
    fn with_builders_are_idempotent() {
        let a = Optimizations::modern().with_tabs(true).with_tabs(true);
        let b = Optimizations::modern().with_tabs(true);
        assert_eq!(a, b);
        let c = Optimizations::modern().with_rep(false).with_rep(false);
        let d = Optimizations::modern().with_rep(false);
        assert_eq!(c, d);
    }
}