Skip to main content

vtcode_commons/
terminal_capabilities.rs

1//! Canonical terminal capability probe.
2//!
3//! VT Code paints box-drawing chrome in more than one surface (the CLI
4//! transcript, the TUI panels, the modal lists) and each surface used to
5//! answer "can this terminal draw Unicode?" on its own. Those answers
6//! disagreed, so the same machine could render Unicode chrome in one surface
7//! and ASCII chrome in another.
8//!
9//! This module owns the single answer: one probe, one verdict, evaluated once
10//! per process. The verdict is a deterministic fallback ladder:
11//!
12//! 1. `VTCODE_NO_UNICODE` set to an affirmative value drops straight to ASCII.
13//! 2. A terminal that advertises Unicode (`TERM`), or a UTF-8 locale, earns
14//!    Unicode box drawing.
15//! 3. A terminal known to render the dashed box-drawing variants correctly
16//!    earns the rich tier.
17//! 4. Everything else stays on ASCII, which never renders as mojibake.
18//!
19//! The probe never guesses from the terminal *name* alone: iTerm2, WezTerm,
20//! and Hyper all advertise `TERM=xterm-256color`, so `TERM_PROGRAM` is the
21//! signal that identifies them.
22
23use std::sync::LazyLock;
24use std::sync::atomic::{AtomicU8, Ordering};
25
26use crate::utils::env_flag_value_enabled;
27
28/// Richness of the box-drawing chrome the terminal can render.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
30pub enum BoxGlyphTier {
31    /// ASCII-only chrome (`+`, `-`, `|`).
32    #[default]
33    Ascii,
34    /// Unicode box drawing (`╭ ─ ╮ │`).
35    Unicode,
36    /// Unicode plus the dashed variants only some terminals render correctly.
37    RichUnicode,
38}
39
40impl BoxGlyphTier {
41    /// Whether this tier can draw Unicode box-drawing glyphs.
42    #[must_use]
43    pub fn supports_unicode(self) -> bool {
44        !matches!(self, Self::Ascii)
45    }
46}
47
48/// Terminal environment inputs the capability probe reads.
49///
50/// The verdict is a pure function of this snapshot, so callers that need to
51/// evaluate a hypothetical environment can do so without mutating the
52/// process environment.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct TerminalEnv {
55    /// `TERM` — the terminal's generic capability string.
56    pub term: Option<String>,
57    /// `TERM_PROGRAM` — the terminal program's own name.
58    pub term_program: Option<String>,
59    /// `LANG` — the primary locale.
60    pub lang: Option<String>,
61    /// `LC_ALL` — the locale override.
62    pub lc_all: Option<String>,
63    /// `LC_CTYPE` — the character-encoding locale.
64    pub lc_ctype: Option<String>,
65    /// `VTCODE_NO_UNICODE` — opt out of Unicode chrome.
66    pub no_unicode: Option<String>,
67    /// `VTCODE_NO_RICH_UNICODE` — opt out of the dashed box-drawing variants.
68    pub no_rich_unicode: Option<String>,
69}
70
71impl TerminalEnv {
72    /// Snapshot the current process environment.
73    #[must_use]
74    pub fn capture() -> Self {
75        Self {
76            term: std::env::var("TERM").ok(),
77            term_program: std::env::var("TERM_PROGRAM").ok(),
78            lang: std::env::var("LANG").ok(),
79            lc_all: std::env::var("LC_ALL").ok(),
80            lc_ctype: std::env::var("LC_CTYPE").ok(),
81            no_unicode: std::env::var("VTCODE_NO_UNICODE").ok(),
82            no_rich_unicode: std::env::var("VTCODE_NO_RICH_UNICODE").ok(),
83        }
84    }
85
86    /// Whether the user asked for ASCII-only chrome.
87    ///
88    /// Uses the repository's canonical env-flag semantics: only an affirmative
89    /// value (`1`, `true`, `yes`, `on`, `debug`) disables Unicode, so
90    /// `VTCODE_NO_UNICODE=0` leaves Unicode chrome enabled.
91    #[must_use]
92    pub fn no_unicode_requested(&self) -> bool {
93        env_flag_value_enabled(self.no_unicode.as_deref())
94    }
95
96    /// Whether the user asked to skip the dashed box-drawing variants.
97    #[must_use]
98    pub fn no_rich_unicode_requested(&self) -> bool {
99        env_flag_value_enabled(self.no_rich_unicode.as_deref())
100    }
101
102    /// Whether the terminal can draw Unicode box-drawing glyphs.
103    ///
104    /// `TERM` is authoritative because it describes the terminal program; the
105    /// locale only decides the question when `TERM` says nothing. A UTF-8
106    /// locale is the only positive evidence left, so without one the answer
107    /// stays at "no" and the terminal keeps ASCII chrome.
108    #[must_use]
109    pub fn supports_unicode_box_drawing(&self) -> bool {
110        if let Some(term) = self.term.as_deref() {
111            if term_supports_unicode(term) {
112                return true;
113            }
114            if term_lacks_unicode(term) {
115                return false;
116            }
117        }
118
119        [self.lang.as_deref(), self.lc_all.as_deref(), self.lc_ctype.as_deref()]
120            .iter()
121            .flatten()
122            .any(|locale| locale_is_utf8(locale))
123    }
124
125    /// Whether the terminal renders the dashed box-drawing variants correctly.
126    ///
127    /// `TERM_PROGRAM` identifies the terminal program; `TERM` only names it
128    /// for the terminals that put their name in `TERM` as well.
129    #[must_use]
130    pub fn supports_rich_box_drawing(&self) -> bool {
131        const RICH_TERMINALS: [&str; 6] = ["ghostty", "wezterm", "iterm", "hyper", "kitty", "alacritty"];
132
133        let term_program = self.term_program.as_deref().unwrap_or_default();
134        let term = self.term.as_deref().unwrap_or_default();
135        RICH_TERMINALS.iter().any(|name| {
136            crate::formatting::contains_ignore_ascii_case(term_program, name)
137                || crate::formatting::contains_ignore_ascii_case(term, name)
138        })
139    }
140}
141
142/// Whether the environment advertises Unicode box-drawing support.
143///
144/// Also consults the ambiguous-width override: on a terminal that renders
145/// East-Asian-ambiguous glyphs as double width, every Unicode box-drawing
146/// glyph breaks layout, so ASCII is the only safe chrome.
147#[must_use]
148pub fn box_glyph_tier() -> BoxGlyphTier {
149    if ambiguous_width_wide() {
150        return BoxGlyphTier::Ascii;
151    }
152    *BOX_GLYPH_TIER
153}
154
155/// Evaluate the capability ladder against a captured environment.
156#[must_use]
157pub fn box_glyph_tier_for(env: &TerminalEnv) -> BoxGlyphTier {
158    if env.no_unicode_requested() {
159        return BoxGlyphTier::Ascii;
160    }
161    if !env.supports_unicode_box_drawing() {
162        return BoxGlyphTier::Ascii;
163    }
164    if env.no_rich_unicode_requested() {
165        return BoxGlyphTier::Unicode;
166    }
167    if env.supports_rich_box_drawing() {
168        return BoxGlyphTier::RichUnicode;
169    }
170    BoxGlyphTier::Unicode
171}
172
173/// One-time runtime override for the ambiguous-width verdict.
174///
175/// The env-derived ladder cannot see `ui.ambiguous_width` (config loads after
176/// process start), so the session shell applies the resolved config value
177/// here before first render. First setter wins: the verdict is captured once
178/// per process because a mid-session flip would re-wrap already-rendered
179/// transcript geometry. Callers that never set it (headless mode, host
180/// examples) keep the narrow default.
181static AMBIGUOUS_WIDTH: AtomicU8 = AtomicU8::new(AMBIGUOUS_WIDTH_UNSET);
182
183const AMBIGUOUS_WIDTH_UNSET: u8 = 0;
184const AMBIGUOUS_WIDTH_NARROW: u8 = 1;
185const AMBIGUOUS_WIDTH_WIDE: u8 = 2;
186
187/// Apply the resolved `ui.ambiguous_width` verdict.
188///
189/// No-op when a verdict was already applied this process: first setter wins,
190/// so a config reload cannot flip already-rendered geometry mid-session.
191pub fn set_ambiguous_width(mode: crate::ui_protocol::AmbiguousWidthMode) {
192    let value = match mode {
193        crate::ui_protocol::AmbiguousWidthMode::Narrow => AMBIGUOUS_WIDTH_NARROW,
194        crate::ui_protocol::AmbiguousWidthMode::Wide => AMBIGUOUS_WIDTH_WIDE,
195    };
196    // The Err arm carries the current verdict and is deliberately ignored.
197    let _applied = AMBIGUOUS_WIDTH.compare_exchange(AMBIGUOUS_WIDTH_UNSET, value, Ordering::Relaxed, Ordering::Relaxed);
198}
199
200/// Whether the terminal renders East-Asian-ambiguous glyphs (UAX #11) as two
201/// cells. Width math and chrome selection must agree with this verdict.
202#[must_use]
203pub fn ambiguous_width_wide() -> bool {
204    AMBIGUOUS_WIDTH.load(Ordering::Relaxed) == AMBIGUOUS_WIDTH_WIDE
205}
206
207/// The cached verdict; the environment does not change while VT Code runs.
208static BOX_GLYPH_TIER: LazyLock<BoxGlyphTier> = LazyLock::new(|| box_glyph_tier_for(&TerminalEnv::capture()));
209
210/// Terminals whose `TERM` value advertises Unicode box-drawing support.
211fn term_supports_unicode(term: &str) -> bool {
212    let term = term.to_ascii_lowercase();
213    term.contains("utf")
214        || term.contains("unicode")
215        || term.contains("256color")
216        || term.contains("truecolor")
217        || term.contains("direct")
218        || term.contains("alacritty")
219        || term.contains("wezterm")
220        || term.contains("kitty")
221        || term.contains("iterm")
222        || term.contains("hyper")
223        || term.contains("ghostty")
224        || term.contains("konsole")
225        || term.contains("contour")
226        || term.contains("foot")
227}
228
229/// Terminals that cannot render Unicode box-drawing glyphs at all.
230fn term_lacks_unicode(term: &str) -> bool {
231    let term = term.to_ascii_lowercase();
232    term == "dumb" || term == "emacs" || term == "ansi" || term == "cons25" || term == "basic" || term.starts_with("vt")
233}
234
235/// Whether a locale value declares a UTF-8 encoding.
236fn locale_is_utf8(locale: &str) -> bool {
237    locale.to_ascii_lowercase().contains("utf")
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    fn env(term: Option<&str>, term_program: Option<&str>, lang: Option<&str>) -> TerminalEnv {
245        TerminalEnv {
246            term: term.map(str::to_owned),
247            term_program: term_program.map(str::to_owned),
248            lang: lang.map(str::to_owned),
249            ..TerminalEnv::default()
250        }
251    }
252
253    #[test]
254    fn ascii_is_the_fallback_without_evidence() {
255        assert_eq!(box_glyph_tier_for(&TerminalEnv::default()), BoxGlyphTier::Ascii);
256        assert_eq!(box_glyph_tier_for(&env(None, None, None)), BoxGlyphTier::Ascii);
257    }
258
259    #[test]
260    fn term_advertisement_earns_unicode_even_with_a_c_locale() {
261        let tier = box_glyph_tier_for(&env(Some("xterm-256color"), None, Some("C")));
262        assert_eq!(tier, BoxGlyphTier::Unicode);
263    }
264
265    #[test]
266    fn utf8_locale_earns_unicode_when_term_says_nothing() {
267        assert_eq!(box_glyph_tier_for(&env(None, None, Some("en_US.UTF-8"))), BoxGlyphTier::Unicode);
268        assert_eq!(
269            box_glyph_tier_for(&TerminalEnv {
270                lc_ctype: Some("en_US.UTF-8".to_owned()),
271                ..TerminalEnv::default()
272            }),
273            BoxGlyphTier::Unicode
274        );
275    }
276
277    #[test]
278    fn explicitly_non_utf8_locale_stays_ascii() {
279        assert_eq!(box_glyph_tier_for(&env(None, None, Some("C"))), BoxGlyphTier::Ascii);
280    }
281
282    #[test]
283    fn dumb_terminal_stays_ascii_even_with_a_utf8_locale() {
284        assert_eq!(box_glyph_tier_for(&env(Some("dumb"), None, Some("en_US.UTF-8"))), BoxGlyphTier::Ascii);
285    }
286
287    #[test]
288    fn term_program_identifies_rich_terminals_that_share_a_generic_term() {
289        for (program, term) in [
290            ("iTerm.app", "xterm-256color"),
291            ("WezTerm", "xterm-256color"),
292            ("Hyper.app", "xterm-256color"),
293            ("kitty", "xterm-kitty"),
294            ("ghostty", "xterm-ghostty"),
295            ("Alacritty", "alacritty"),
296        ] {
297            let tier = box_glyph_tier_for(&env(Some(term), Some(program), Some("en_US.UTF-8")));
298            assert_eq!(tier, BoxGlyphTier::RichUnicode, "{program} should reach the rich tier");
299        }
300    }
301
302    #[test]
303    fn plain_terminals_stay_on_the_unicode_tier() {
304        assert_eq!(box_glyph_tier_for(&env(Some("xterm-256color"), None, Some("en_US.UTF-8"))), BoxGlyphTier::Unicode);
305        assert_eq!(
306            box_glyph_tier_for(&env(Some("xterm-256color"), Some("Apple_Terminal"), Some("en_US.UTF-8"))),
307            BoxGlyphTier::Unicode
308        );
309    }
310
311    #[test]
312    fn opt_out_flags_use_canonical_flag_semantics() {
313        let base = env(Some("xterm-256color"), Some("WezTerm"), Some("en_US.UTF-8"));
314        assert_eq!(box_glyph_tier_for(&base), BoxGlyphTier::RichUnicode);
315
316        let no_unicode = TerminalEnv { no_unicode: Some("1".to_owned()), ..base.clone() };
317        assert_eq!(box_glyph_tier_for(&no_unicode), BoxGlyphTier::Ascii);
318
319        let no_rich = TerminalEnv {
320            no_rich_unicode: Some("1".to_owned()),
321            ..base.clone()
322        };
323        assert_eq!(box_glyph_tier_for(&no_rich), BoxGlyphTier::Unicode);
324    }
325
326    #[test]
327    fn falsy_opt_out_values_do_not_disable_unicode() {
328        for value in ["0", "false", "off", "no", ""] {
329            let disabled = TerminalEnv {
330                no_unicode: Some(value.to_owned()),
331                no_rich_unicode: Some(value.to_owned()),
332                ..env(Some("xterm-256color"), Some("WezTerm"), Some("en_US.UTF-8"))
333            };
334            assert_eq!(
335                box_glyph_tier_for(&disabled),
336                BoxGlyphTier::RichUnicode,
337                "VTCODE_NO_UNICODE={value:?} must not disable Unicode"
338            );
339        }
340    }
341
342    #[test]
343    fn tier_supports_unicode_matches_the_ladder() {
344        assert!(!BoxGlyphTier::Ascii.supports_unicode());
345        assert!(BoxGlyphTier::Unicode.supports_unicode());
346        assert!(BoxGlyphTier::RichUnicode.supports_unicode());
347    }
348}