Skip to main content

uncurses/renderer/
caps.rs

1//! Terminal capability flags used by the renderer.
2//!
3//! ## Purpose
4//!
5//! [`Optimizations`] is not a feature wishlist; it is the renderer's
6//! contract for which byte sequences are safe to emit for the current
7//! terminal and line discipline. Each flag unlocks a family of shorter
8//! sequences. When a flag is absent, the renderer falls back to more
9//! conservative cursor movement or explicit cell writes.
10//!
11//! ## Detection
12//!
13//! The built-in detector maps `$TERM` families to conservative baseline
14//! sets. Unknown, empty, and `dumb` terminals use [`Optimizations::none`].
15//! A missing `$TERM` uses [`Optimizations::default`] so in-memory tests
16//! and sinks without environment information keep a useful baseline.
17//!
18//! ## Line-discipline flags
19//!
20//! [`Optimizations::TABS`], [`Optimizations::BS`], and
21//! [`Optimizations::ONLCR`] describe the host's output processing, not
22//! the terminal's own abilities, so no baseline here carries them: a
23//! `\t` is only usable if the line discipline passes it through, which
24//! `$TERM` cannot tell you. A [`Program`](crate::program::Program) enables
25//! `TABS` and `BS` on *every* raw-mode entry —
26//! [`init`](crate::program::Program::init) and
27//! [`resume`](crate::program::Program::resume) alike — because raw mode
28//! turns the host's output processing off, which is exactly what makes
29//! `\t` and `\x08` safe to emit.
30//!
31//! `ONLCR` is never granted: raw mode is also what makes it false. It
32//! stays opt-in for callers who know their output crosses a layer that
33//! turns `\n` into `\r\n` anyway.
34//!
35//! Driving a [`Renderer`] yourself, or keeping the host in cooked mode?
36//! Then the answer is yours to supply: use [`Optimizations::with_tabs`],
37//! [`Optimizations::with_bs`], and [`Optimizations::with_onlcr`]. Leaving
38//! all three off is always safe — the renderer then emits escape
39//! sequences that no line discipline can rewrite.
40//!
41//! [`Renderer`]: crate::renderer::Renderer
42
43use bitflags::bitflags;
44
45use crate::terminal::Env;
46
47bitflags! {
48    /// Terminal capabilities the renderer may use for shorter output.
49    ///
50    /// # Usage
51    ///
52    /// Start from a detector result such as [`Optimizations::from_env`]
53    /// or a baseline such as [`Optimizations::xterm`], then use the
54    /// `with_*` methods to toggle assumptions confirmed by probing or
55    /// terminal-mode setup.
56    ///
57    /// Flag names follow the short capability names used by `infocmp`
58    /// where they exist. `BS` and `ONLCR` are not terminfo caps; they
59    /// describe control-character and output-processing behavior.
60    ///
61    /// [`TABS`](Self::TABS), [`BS`](Self::BS), and
62    /// [`ONLCR`](Self::ONLCR) are the odd ones out: they describe the
63    /// *host*, not the terminal. A [`Program`](crate::program::Program)
64    /// enables `TABS` and `BS` on every raw-mode entry and never touches
65    /// `ONLCR`. See the module docs.
66    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67    pub struct Optimizations: u32 {
68        /// Terminal supports ECH (Erase Characters, `CSI Ps X`) for
69        /// clearing a run on the current row.
70        const ECH    = 1 <<  0;
71        /// Terminal supports REP (Repeat preceding character,
72        /// `CSI Ps b`) for compact repeated ASCII glyphs.
73        const REP    = 1 <<  1;
74        /// Terminal supports ICH (Insert Characters, `CSI Ps @`) for
75        /// opening cells within a row.
76        const ICH    = 1 <<  2;
77        /// Terminal supports DCH (Delete Characters, `CSI Ps P`) for
78        /// removing cells within a row.
79        const DCH    = 1 <<  3;
80        /// Terminal supports scroll regions (DECSTBM; terminfo `csr`).
81        const CSR    = 1 <<  4;
82        /// Terminal supports SU/SD (Scroll Up/Down, `CSI Ps S` /
83        /// `CSI Ps T`) for moving full scroll regions.
84        const SU_SD  = 1 <<  5;
85        /// Terminal supports IL/DL (Insert/Delete Line, `CSI Ps L` /
86        /// `CSI Ps M`) for line-level scroll fallbacks.
87        const IL_DL  = 1 <<  6;
88        /// Terminal supports BCE (Background Color Erase): erase
89        /// operations paint with the active background color.
90        ///
91        /// Also governs cursor motion. An inline downward move is
92        /// emitted as a literal `\n`, which scrolls the host when the
93        /// destination row does not exist yet; with BCE that scroll
94        /// paints the exposed row with the active background, so the
95        /// planner resets the pen first. See `PenPolicy`.
96        const BCE    = 1 <<  7;
97        /// Terminal supports CHA (Cursor Horizontal Absolute,
98        /// `CSI Ps G`) for absolute column moves.
99        const CHA    = 1 <<  8;
100        /// Terminal supports HPA (Horizontal Position Absolute,
101        /// `CSI Ps \``) for absolute column moves.
102        const HPA    = 1 <<  9;
103        /// Terminal supports VPA (Vertical Position Absolute,
104        /// `CSI Ps d`) for absolute row moves.
105        const VPA    = 1 << 10;
106        /// Literal tab bytes move to configured hardware tab stops.
107        const TABS   = 1 << 11;
108        /// Terminal supports CBT (Cursor Backward Tab, `CSI Ps Z`).
109        const CBT    = 1 << 12;
110        /// Terminal supports CHT (Cursor Horizontal Tab, `CSI Ps I`).
111        const CHT    = 1 << 13;
112        /// Terminal supports BS (the backspace control character,
113        /// `\x08`) for cursor-left-by-one.
114        const BS     = 1 << 14;
115        /// Whether the terminal currently maps `\n` to `\r\n`
116        /// (termios ONLCR). In raw mode this is unset and `\n` only
117        /// moves the cursor down without resetting the column.
118        const ONLCR  = 1 << 15;
119    }
120}
121
122impl Default for Optimizations {
123    /// The default is [`Optimizations::xterm`] — the modern baseline
124    /// for the overwhelming majority of terminals reachable from a
125    /// generic `TERM=xterm-256color` session.
126    fn default() -> Self {
127        Self::xterm()
128    }
129}
130
131impl Optimizations {
132    /// Return the most conservative useful capability set.
133    ///
134    /// Every escape-sequence optimization is disabled. Use this for
135    /// unknown or genuinely capability-limited terminals when direct
136    /// cell output is safer than specialized control sequences.
137    pub const fn none() -> Self {
138        Self::empty()
139    }
140
141    /// Return the modern full-feature baseline.
142    ///
143    /// Enables every renderer optimization a terminal can advertise.
144    /// The line-discipline flags are absent: see the module docs.
145    pub const fn modern() -> Self {
146        Self::ECH
147            .union(Self::REP)
148            .union(Self::ICH)
149            .union(Self::DCH)
150            .union(Self::CSR)
151            .union(Self::SU_SD)
152            .union(Self::IL_DL)
153            .union(Self::BCE)
154            .union(Self::CHA)
155            .union(Self::HPA)
156            .union(Self::VPA)
157            .union(Self::CBT)
158            .union(Self::CHT)
159    }
160
161    /// Return the xterm-compatible conservative baseline.
162    ///
163    /// Compared to [`Self::modern`], `HPA`,
164    /// `CHT`, and `REP` are off:
165    /// - `HPA`: konsole and several xterm-compatible terminals lack
166    ///   HPA; xterm-256color terminfo defines HPA via the same
167    ///   sequence as CHA, so CHA is the safer choice.
168    /// - `CHT`: forward-tab support is historically inconsistent
169    ///   across xterm-compatible emulators.
170    /// - `REP`: REP is not universally implemented across the
171    ///   xterm-compatible family.
172    pub const fn xterm() -> Self {
173        Self::modern().difference(Self::HPA.union(Self::CHT).union(Self::REP))
174    }
175
176    /// Return the VT100/VT102 baseline.
177    ///
178    /// Predates the xterm extensions for
179    /// absolute positioning (CHA/HPA/VPA), ECH, REP, BCE, SU/SD, and
180    /// CBT, but supports DECSTBM and, on the VT102, the ICH/DCH/IL/DL
181    /// editing pairs.
182    pub const fn vt100() -> Self {
183        Self::ICH
184            .union(Self::DCH)
185            .union(Self::CSR)
186            .union(Self::IL_DL)
187    }
188
189    /// Return the Linux console baseline.
190    ///
191    /// The kernel's terminal driver
192    /// implements a narrow subset of ECMA-48 — only absolute
193    /// positioning (CHA/HPA/VPA), ECH, and ICH.
194    /// See `console_codes(4)`.
195    pub const fn linux() -> Self {
196        Self::ECH
197            .union(Self::ICH)
198            .union(Self::CHA)
199            .union(Self::HPA)
200            .union(Self::VPA)
201    }
202
203    /// Return the GNU screen baseline, derived from
204    /// `infocmp -x1 screen-256color`. screen multiplexes onto the
205    /// host terminal and only re-advertises a conservative subset:
206    /// no `BCE`, `ECH`, `REP`, `CHA`, or `CHT`.
207    pub const fn screen() -> Self {
208        Self::ICH
209            .union(Self::DCH)
210            .union(Self::CSR)
211            .union(Self::SU_SD)
212            .union(Self::IL_DL)
213            .union(Self::HPA)
214            .union(Self::VPA)
215            .union(Self::CBT)
216    }
217
218    /// Return `self` with hardware tab support (`TABS`) toggled.
219    ///
220    /// Disable when the
221    /// receiving terminal is in cooked mode without `TAB0` set on
222    /// `c_oflag` and `\t` would otherwise be expanded to spaces.
223    ///
224    /// A [`Program`](crate::program::Program) enables this on every raw-mode
225    /// entry, since raw mode is what makes `\t` safe, so setting it here
226    /// matters only when driving a renderer directly.
227    #[must_use]
228    pub const fn with_tabs(self, enabled: bool) -> Self {
229        self.with_flag(Self::TABS, enabled)
230    }
231
232    /// Return `self` with backspace-character support (`BS`) toggled.
233    ///
234    /// Disable when the
235    /// receiving terminal does not interpret `\x08` as cursor-left
236    /// by one cell.
237    ///
238    /// A [`Program`](crate::program::Program) enables this on every raw-mode
239    /// entry, since raw mode is what makes `\x08` safe, so setting it here
240    /// matters only when driving a renderer directly.
241    #[must_use]
242    pub const fn with_bs(self, enabled: bool) -> Self {
243        self.with_flag(Self::BS, enabled)
244    }
245
246    /// Return `self` with the `\n` → `\r\n` assumption (`ONLCR`)
247    /// toggled.
248    ///
249    /// Enable when the terminal is in cooked mode with `ONLCR` set so a
250    /// newline both advances a row and resets the column.
251    ///
252    /// A [`Program`](crate::program::Program) never sets this — raw mode
253    /// clears `OPOST`, so `\n` carries no carriage return — but it never
254    /// clears it either. It is yours to opt into and yours to keep.
255    #[must_use]
256    pub const fn with_onlcr(self, enabled: bool) -> Self {
257        self.with_flag(Self::ONLCR, enabled)
258    }
259
260    /// Return `self` with erase-character (`ECH`) support toggled.
261    #[must_use]
262    pub const fn with_ech(self, enabled: bool) -> Self {
263        self.with_flag(Self::ECH, enabled)
264    }
265
266    /// Return `self` with repeat-character (`REP`) support toggled.
267    #[must_use]
268    pub const fn with_rep(self, enabled: bool) -> Self {
269        self.with_flag(Self::REP, enabled)
270    }
271
272    /// Return `self` with insert-character (`ICH`) support toggled.
273    #[must_use]
274    pub const fn with_ich(self, enabled: bool) -> Self {
275        self.with_flag(Self::ICH, enabled)
276    }
277
278    /// Return `self` with delete-character (`DCH`) support toggled.
279    #[must_use]
280    pub const fn with_dch(self, enabled: bool) -> Self {
281        self.with_flag(Self::DCH, enabled)
282    }
283
284    /// Return `self` with DECSTBM scroll-region (`CSR`) support toggled.
285    #[must_use]
286    pub const fn with_csr(self, enabled: bool) -> Self {
287        self.with_flag(Self::CSR, enabled)
288    }
289
290    /// Return `self` with scroll-up/scroll-down (`SU_SD`) support toggled.
291    #[must_use]
292    pub const fn with_su_sd(self, enabled: bool) -> Self {
293        self.with_flag(Self::SU_SD, enabled)
294    }
295
296    /// Return `self` with insert/delete-line (`IL_DL`) support toggled.
297    #[must_use]
298    pub const fn with_il_dl(self, enabled: bool) -> Self {
299        self.with_flag(Self::IL_DL, enabled)
300    }
301
302    /// Return `self` with background-color-erase (`BCE`) support toggled.
303    #[must_use]
304    pub const fn with_bce(self, enabled: bool) -> Self {
305        self.with_flag(Self::BCE, enabled)
306    }
307
308    /// Return `self` with cursor-horizontal-absolute (`CHA`) support toggled.
309    #[must_use]
310    pub const fn with_cha(self, enabled: bool) -> Self {
311        self.with_flag(Self::CHA, enabled)
312    }
313
314    /// Return `self` with horizontal-position-absolute (`HPA`) support toggled.
315    #[must_use]
316    pub const fn with_hpa(self, enabled: bool) -> Self {
317        self.with_flag(Self::HPA, enabled)
318    }
319
320    /// Return `self` with vertical-position-absolute (`VPA`) support toggled.
321    #[must_use]
322    pub const fn with_vpa(self, enabled: bool) -> Self {
323        self.with_flag(Self::VPA, enabled)
324    }
325
326    /// Return `self` with cursor-backward-tab (`CBT`) support toggled.
327    #[must_use]
328    pub const fn with_cbt(self, enabled: bool) -> Self {
329        self.with_flag(Self::CBT, enabled)
330    }
331
332    /// Return `self` with cursor-horizontal-tab (`CHT`) support toggled.
333    #[must_use]
334    pub const fn with_cht(self, enabled: bool) -> Self {
335        self.with_flag(Self::CHT, enabled)
336    }
337
338    /// Const-friendly helper used by the `with_*` builders.
339    const fn with_flag(self, flag: Self, enabled: bool) -> Self {
340        if enabled {
341            self.union(flag)
342        } else {
343            self.difference(flag)
344        }
345    }
346
347    /// Derive an optimization set from a `TERM` value.
348    ///
349    /// # Parameters
350    ///
351    /// - `term`: terminal name, usually from `$TERM`.
352    ///
353    /// # Returns
354    ///
355    /// A baseline capability set for the terminal family. Unknown,
356    /// empty, and `dumb` values return [`Self::none`].
357    pub fn from_term(term: &str) -> Self {
358        let head = term.split('-').next().unwrap_or("");
359        // xterm-<vendor> reassignment when the vendor is a known modern
360        // terminal advertising xterm compatibility.
361        if head == "xterm"
362            && let Some(rest) = term.strip_prefix("xterm-")
363        {
364            let vendor = rest.split('-').next().unwrap_or("");
365            if matches!(vendor, "ghostty" | "kitty" | "rio") {
366                return Self::modern();
367            }
368        }
369        match head {
370            "" | "dumb" => Self::none(),
371            // Modern terminals that advertise the full xterm-era cap
372            // set. Alacritty falls into this bucket too; the detector
373            // uses the shared modern baseline rather than maintaining a
374            // vendor-specific single-flag variant here.
375            "alacritty" | "contour" | "foot" | "ghostty" | "kitty" | "rio" | "st" | "wezterm" => {
376                Self::modern()
377            }
378            // tmux 3.8 ignores CHT; literal tabs still work.
379            "tmux" => Self::modern().difference(Self::CHT),
380            "xterm" => Self::xterm(),
381            "screen" => Self::screen(),
382            "linux" => Self::linux(),
383            _ => Self::none(),
384        }
385    }
386
387    /// Derive an optimization set from an [`Env`].
388    ///
389    /// Routes `$TERM` through [`Self::from_term`] when it is set, and
390    /// falls back to [`Self::default`] when `$TERM` is unset entirely.
391    /// This keeps callers with no environment information (CI harnesses,
392    /// embedded sinks, tests) on the xterm baseline rather than
393    /// collapsing to [`Self::none`].
394    pub fn from_env(env: &dyn Env) -> Self {
395        match env.get("TERM") {
396            Some(term) => Self::from_term(&term),
397            None => Self::default(),
398        }
399    }
400
401    /// Report whether `env` names a terminal known to implement DECST8C,
402    /// the `ESC [ ? 5 W` sequence that resets tab stops to one every
403    /// eight columns in a single, cursor-safe write.
404    ///
405    /// The allowlist covers Ghostty, kitty, Rio, Alacritty, iTerm2, and
406    /// Windows Terminal. Terminals outside it fall back to the portable
407    /// TBC-then-HTS reset, so a false negative only costs a few extra
408    /// bytes, never correctness. This inspects the environment only and
409    /// never probes the terminal. tmux and GNU Screen use the portable
410    /// reset even when they inherit an outer terminal's environment.
411    pub(crate) fn supports_decst8c(env: &dyn Env) -> bool {
412        let term = env.get("TERM");
413        if env.has("TMUX")
414            || env.has("STY")
415            || term.as_deref().is_some_and(|term| {
416                matches!(term.split(['-', '.']).next(), Some("tmux" | "screen"))
417            })
418        {
419            return false;
420        }
421        // Windows Terminal announces itself with a session token rather
422        // than through $TERM.
423        if env.has("WT_SESSION") {
424            return true;
425        }
426        // kitty, Alacritty, and iTerm2 export a session/window id that
427        // survives login shells rewriting $TERM.
428        if env.has("KITTY_WINDOW_ID")
429            || env.has("ALACRITTY_WINDOW_ID")
430            || env.has("ITERM_SESSION_ID")
431        {
432            return true;
433        }
434        // iTerm2 sets $LC_TERMINAL, which also propagates across ssh.
435        if env
436            .get("LC_TERMINAL")
437            .is_some_and(|t| t.eq_ignore_ascii_case("iterm2"))
438        {
439            return true;
440        }
441        // $TERM_PROGRAM outlives some xterm-compatible $TERM rewrites.
442        if let Some(program) = env.get("TERM_PROGRAM")
443            && matches!(
444                program.to_ascii_lowercase().as_str(),
445                "ghostty" | "rio" | "iterm.app"
446            )
447        {
448            return true;
449        }
450        let Some(term) = term else {
451            return false;
452        };
453        // Match the bare vendor head and the xterm-<vendor> promotion
454        // form, mirroring how `from_term` resolves these terminals.
455        let head = term.split('-').next().unwrap_or("");
456        if matches!(head, "alacritty" | "ghostty" | "kitty" | "rio") {
457            return true;
458        }
459        if let Some(rest) = term.strip_prefix("xterm-") {
460            let vendor = rest.split('-').next().unwrap_or("");
461            return matches!(vendor, "ghostty" | "kitty" | "rio");
462        }
463        false
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    /// The host-dependent flags, as a test-local group: the public API
470    /// deliberately has no name for them, since `Screen` grants `TABS`
471    /// and `BS` but leaves `ONLCR` alone.
472    const LINE_DISCIPLINE: Optimizations = Optimizations::TABS
473        .union(Optimizations::BS)
474        .union(Optimizations::ONLCR);
475
476    use super::*;
477    use crate::terminal::EnvList;
478
479    fn env_with(pairs: &[(&str, &str)]) -> EnvList {
480        EnvList::from_pairs(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())))
481    }
482
483    #[test]
484    fn supports_decst8c_matches_allowlisted_terms() {
485        for term in [
486            "alacritty",
487            "ghostty",
488            "kitty",
489            "rio",
490            "xterm-kitty",
491            "xterm-ghostty",
492        ] {
493            assert!(
494                Optimizations::supports_decst8c(&env_with(&[("TERM", term)])),
495                "expected DECST8C support for TERM={term}",
496            );
497        }
498    }
499
500    #[test]
501    fn supports_decst8c_rejects_plain_xterm_and_unknown() {
502        for term in [
503            "xterm-256color",
504            "screen-256color",
505            "tmux",
506            "vt100",
507            "dumb",
508            "",
509        ] {
510            assert!(
511                !Optimizations::supports_decst8c(&env_with(&[("TERM", term)])),
512                "did not expect DECST8C support for TERM={term}",
513            );
514        }
515    }
516
517    #[test]
518    fn supports_decst8c_rejects_multiplexers_with_outer_terminal_hints() {
519        for pairs in [
520            [("TERM", "tmux"), ("WT_SESSION", "abc")],
521            [("TERM", "tmux-256color"), ("KITTY_WINDOW_ID", "1")],
522            [("TERM", "screen"), ("TERM_PROGRAM", "ghostty")],
523            [("TERM", "screen-256color"), ("LC_TERMINAL", "iTerm2")],
524            [
525                ("TERM", "screen.xterm-256color"),
526                ("ITERM_SESSION_ID", "w0t0p0:abc"),
527            ],
528            [
529                ("TERM", "xterm-kitty"),
530                ("TMUX", "/tmp/tmux-1000/default,123,0"),
531            ],
532            [("TERM", "alacritty"), ("STY", "123.session")],
533            [
534                ("ALACRITTY_WINDOW_ID", "1"),
535                ("TMUX", "/tmp/tmux-1000/default,123,0"),
536            ],
537        ] {
538            assert!(
539                !Optimizations::supports_decst8c(&env_with(&pairs)),
540                "multiplexer must use the portable tab reset: {pairs:?}",
541            );
542        }
543    }
544
545    #[test]
546    fn supports_decst8c_detects_terminals_via_env_tokens() {
547        // Windows Terminal and window-id exporters are recognized even when
548        // $TERM is rewritten to a generic value.
549        assert!(Optimizations::supports_decst8c(&env_with(&[
550            ("TERM", "xterm-256color"),
551            ("WT_SESSION", "abc"),
552        ])));
553        assert!(Optimizations::supports_decst8c(&env_with(&[
554            ("TERM", "xterm-256color"),
555            ("KITTY_WINDOW_ID", "1"),
556        ])));
557        assert!(Optimizations::supports_decst8c(&env_with(&[
558            ("TERM", "xterm-256color"),
559            ("ALACRITTY_WINDOW_ID", "1"),
560        ])));
561        assert!(Optimizations::supports_decst8c(&env_with(&[
562            ("TERM", "xterm-256color"),
563            ("TERM_PROGRAM", "ghostty"),
564        ])));
565        // iTerm2 keeps $TERM generic and identifies itself through its own
566        // tokens, including $LC_TERMINAL which survives ssh.
567        assert!(Optimizations::supports_decst8c(&env_with(&[
568            ("TERM", "xterm-256color"),
569            ("TERM_PROGRAM", "iTerm.app"),
570        ])));
571        assert!(Optimizations::supports_decst8c(&env_with(&[
572            ("TERM", "xterm-256color"),
573            ("ITERM_SESSION_ID", "w0t0p0:abc"),
574        ])));
575        assert!(Optimizations::supports_decst8c(&env_with(&[
576            ("TERM", "xterm-256color"),
577            ("LC_TERMINAL", "iTerm2"),
578        ])));
579    }
580
581    #[test]
582    fn default_is_xterm() {
583        assert_eq!(Optimizations::default(), Optimizations::xterm());
584    }
585
586    #[test]
587    fn none_disables_escape_caps_only() {
588        let o = Optimizations::none();
589        // The line discipline is not a $TERM question; `Screen::init`
590        // grants TABS and BS once raw mode has settled it instead.
591        assert!(o.is_empty());
592    }
593
594    #[test]
595    fn modern_enables_every_escape_cap() {
596        let o = Optimizations::modern();
597        assert_eq!(o, Optimizations::all().difference(LINE_DISCIPLINE));
598    }
599
600    #[test]
601    fn xterm_drops_hpa_cht_rep() {
602        let o = Optimizations::xterm();
603        let expected = Optimizations::modern()
604            .difference(Optimizations::HPA | Optimizations::CHT | Optimizations::REP);
605        assert_eq!(o, expected);
606    }
607
608    #[test]
609    fn vt100_predates_xterm_extensions() {
610        let o = Optimizations::vt100();
611        // No xterm-era absolute positioning or extensions.
612        let missing = Optimizations::CHA
613            | Optimizations::HPA
614            | Optimizations::VPA
615            | Optimizations::ECH
616            | Optimizations::REP
617            | Optimizations::SU_SD
618            | Optimizations::BCE
619            | Optimizations::CBT
620            | Optimizations::CHT;
621        assert!(!o.intersects(missing));
622        // VT100 era margins + VT102 editing pairs.
623        let present =
624            Optimizations::CSR | Optimizations::ICH | Optimizations::DCH | Optimizations::IL_DL;
625        assert!(o.contains(present));
626    }
627
628    #[test]
629    fn linux_matches_console_codes_4() {
630        let o = Optimizations::linux();
631        let present = Optimizations::ECH
632            | Optimizations::ICH
633            | Optimizations::CHA
634            | Optimizations::HPA
635            | Optimizations::VPA;
636        assert_eq!(o, present);
637    }
638
639    #[test]
640    fn screen_matches_infocmp_x1_screen_256color() {
641        let o = Optimizations::screen();
642        let present = Optimizations::ICH
643            | Optimizations::DCH
644            | Optimizations::CSR
645            | Optimizations::SU_SD
646            | Optimizations::IL_DL
647            | Optimizations::HPA
648            | Optimizations::VPA
649            | Optimizations::CBT;
650        assert_eq!(o, present);
651    }
652
653    /// No `$TERM` baseline may carry a line-discipline flag. `\t`,
654    /// `\x08`, and `\n` behave according to the host's output
655    /// processing, which `$TERM` cannot describe; `Screen::init` enables
656    /// `TABS` and `BS` once raw mode has disabled that processing, and
657    /// leaves `ONLCR` to the caller.
658    #[test]
659    fn no_baseline_carries_line_discipline_flags() {
660        let o = Optimizations::vt100();
661        assert!(
662            !o.intersects(LINE_DISCIPLINE),
663            "vt100 baseline must not assume the line discipline: {o:?}"
664        );
665    }
666
667    /// Every `$TERM` the detector recognizes routes to one of the
668    /// baselines above, so none of them may carry the flags either.
669    #[test]
670    fn no_term_carries_line_discipline_flags() {
671        let line_discipline = LINE_DISCIPLINE;
672        for term in [
673            "alacritty",
674            "contour",
675            "foot",
676            "ghostty",
677            "kitty",
678            "rio",
679            "st",
680            "tmux",
681            "tmux-256color",
682            "wezterm",
683            "xterm",
684            "xterm-256color",
685            "screen",
686            "vt100",
687        ] {
688            let o = Optimizations::from_term(term);
689            assert!(
690                !o.intersects(line_discipline),
691                "{term} must not assume the line discipline: {o:?}"
692            );
693        }
694    }
695
696    #[test]
697    fn from_term_kitty() {
698        let o = Optimizations::from_term("kitty");
699        assert!(o.contains(Optimizations::REP | Optimizations::HPA | Optimizations::VPA));
700    }
701
702    #[test]
703    fn from_term_xterm_excludes_hpa_cht_rep() {
704        let o = Optimizations::from_term("xterm-256color");
705        assert!(!o.contains(Optimizations::HPA));
706        assert!(!o.contains(Optimizations::CHT));
707        assert!(!o.contains(Optimizations::REP));
708        assert!(o.contains(Optimizations::CHA));
709    }
710
711    #[test]
712    fn from_term_xterm_kitty_promotes() {
713        let o = Optimizations::from_term("xterm-kitty");
714        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
715    }
716
717    #[test]
718    fn from_term_xterm_ghostty_promotes() {
719        let o = Optimizations::from_term("xterm-ghostty");
720        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
721    }
722
723    #[test]
724    fn from_term_xterm_rio_promotes() {
725        let o = Optimizations::from_term("xterm-rio");
726        assert!(o.contains(Optimizations::HPA | Optimizations::REP));
727    }
728
729    #[test]
730    fn from_term_linux_console() {
731        assert_eq!(Optimizations::from_term("linux"), Optimizations::linux());
732    }
733
734    #[test]
735    fn from_term_dumb_is_none() {
736        assert_eq!(Optimizations::from_term("dumb"), Optimizations::none());
737    }
738
739    #[test]
740    fn from_term_empty_is_none() {
741        assert_eq!(Optimizations::from_term(""), Optimizations::none());
742    }
743
744    #[test]
745    fn from_term_unknown_falls_back_to_none() {
746        assert_eq!(
747            Optimizations::from_term("madeupterm-256color"),
748            Optimizations::none(),
749        );
750    }
751
752    #[test]
753    fn alacritty_term_has_explicit_caps() {
754        let o = Optimizations::from_term("alacritty");
755        assert!(o.contains(Optimizations::CHA | Optimizations::ECH | Optimizations::REP));
756    }
757
758    #[test]
759    fn screen_term_uses_screen_profile() {
760        for term in ["screen", "screen-256color"] {
761            assert_eq!(Optimizations::from_term(term), Optimizations::screen());
762        }
763    }
764
765    #[test]
766    fn tmux_term_excludes_cht() {
767        for term in ["tmux", "tmux-256color"] {
768            assert_eq!(
769                Optimizations::from_term(term),
770                Optimizations::modern().difference(Optimizations::CHT),
771                "TERM={term}",
772            );
773        }
774    }
775
776    #[test]
777    fn from_term_modern_families_all_enable_rep() {
778        for term in [
779            "contour",
780            "foot",
781            "ghostty",
782            "rio",
783            "st",
784            "tmux",
785            "wezterm",
786            "alacritty",
787        ] {
788            let o = Optimizations::from_term(term);
789            assert!(
790                o.contains(Optimizations::REP | Optimizations::HPA),
791                "{term} should enable REP and HPA"
792            );
793        }
794    }
795
796    #[test]
797    fn with_tabs_toggles_tabs() {
798        let on = Optimizations::none().with_tabs(true);
799        let off = Optimizations::none().with_tabs(false);
800        assert!(on.contains(Optimizations::TABS));
801        assert!(!off.contains(Optimizations::TABS));
802    }
803
804    #[test]
805    fn with_bs_toggles_bs() {
806        let on = Optimizations::none().with_bs(true);
807        let off = Optimizations::none().with_bs(false);
808        assert!(on.contains(Optimizations::BS));
809        assert!(!off.contains(Optimizations::BS));
810    }
811
812    #[test]
813    fn with_onlcr_toggles_onlcr() {
814        let on = Optimizations::none().with_onlcr(true);
815        let off = Optimizations::modern().with_onlcr(false);
816        assert!(on.contains(Optimizations::ONLCR));
817        assert!(!off.contains(Optimizations::ONLCR));
818    }
819
820    #[test]
821    fn with_builders_compose() {
822        let o = Optimizations::xterm()
823            .with_rep(true)
824            .with_hpa(true)
825            .with_cha(false);
826        assert!(o.contains(Optimizations::REP | Optimizations::HPA));
827        assert!(!o.contains(Optimizations::CHA));
828    }
829
830    #[test]
831    fn from_env_uses_term_when_set() {
832        let env = EnvList::from_pairs([("TERM", "xterm-kitty")]);
833        assert_eq!(Optimizations::from_env(&env), Optimizations::modern());
834    }
835
836    #[test]
837    fn from_env_dumb_collapses_to_none() {
838        let env = EnvList::from_pairs([("TERM", "dumb")]);
839        assert_eq!(Optimizations::from_env(&env), Optimizations::none());
840    }
841
842    #[test]
843    fn from_env_empty_term_collapses_to_none() {
844        let env = EnvList::from_pairs([("TERM", "")]);
845        assert_eq!(Optimizations::from_env(&env), Optimizations::none());
846    }
847
848    #[test]
849    fn from_env_missing_term_falls_back_to_default() {
850        let env = EnvList::new();
851        assert_eq!(Optimizations::from_env(&env), Optimizations::default());
852    }
853
854    #[test]
855    fn with_builders_are_idempotent() {
856        let a = Optimizations::modern().with_tabs(true).with_tabs(true);
857        let b = Optimizations::modern().with_tabs(true);
858        assert_eq!(a, b);
859        let c = Optimizations::modern().with_rep(false).with_rep(false);
860        let d = Optimizations::modern().with_rep(false);
861        assert_eq!(c, d);
862    }
863}