detect_terminal/lib.rs
1//! Identify terminal applications and multiplexers from environment hints.
2//!
3//! [`detect()`] reads the current environment; [`detect_from_env`] accepts a snapshot for
4//! repeatable detection. Both return [`TerminalInfo`] without running commands.
5//! [`detect_with_options`] can opt into synchronous multiplexer probes. The library has no runtime
6//! dependencies.
7//!
8//! # Usage
9//!
10//! ```
11//! let info = detect_terminal::detect();
12//! println!("Terminal: {}", info.kind);
13//!
14//! if let Some(multiplexer) = info.multiplexer {
15//! println!("Multiplexer: {}", multiplexer.kind);
16//! }
17//! ```
18//!
19//! # Interpret the result
20//!
21//! `TERM_PROGRAM` names an application; `TERM` names its terminfo description. Many applications
22//! use `TERM=xterm-256color`, so an [`Xterm`](TerminalKind::Xterm) fallback identifies an emulation
23//! family, not proof that the application is xterm. Prefer explicit program markers when present.
24//! [`TerminalInfo::detected_via`] explains the chosen match, and raw values remain available even
25//! when [`TerminalInfo::kind`] is [`Unknown`](TerminalKind::Unknown).
26//!
27//! [`TerminalInfo::version`] may be absent even when a terminal is recognized: it is populated
28//! only when a recognized `TERM_PROGRAM` has a `TERM_PROGRAM_VERSION`. The raw version is retained
29//! separately. [`TerminalInfo::multiplexer`] describes tmux, Screen, or Zellij independently of the
30//! terminal; a recognized multiplexer can coexist with an unknown terminal.
31//!
32//! For an unfamiliar result, start with the selected kind and its evidence:
33//!
34//! ```
35//! let info = detect_terminal::detect();
36//! println!("Terminal: {}", info.kind);
37//! for source in &info.detected_via {
38//! println!("Evidence: {source}");
39//! }
40//! if info.kind == detect_terminal::TerminalKind::Unknown {
41//! println!(
42//! "Unrecognized hints: {:?}, {:?}",
43//! info.term_program, info.term
44//! );
45//! }
46//! ```
47//!
48//! Environment hints may be inherited, overridden, or absent after SSH, sudo, or nested sessions.
49//! This crate does not verify a live terminal, query escape sequences, detect whether stdout is a
50//! TTY, or infer keyboard protocol support. Color support is inferred, not measured. Use
51//! `std::io::IsTerminal` for a TTY check.
52//!
53//! # Choose an entry point
54//!
55//! | Input and purpose | Function |
56//! | --- | --- |
57//! | Inspect the current process environment | [`detect()`] |
58//! | Reuse or construct an environment snapshot | [`detect_from_env`] |
59//! | Enable probes or disable diagnostic capture | [`detect_with_options`] |
60//!
61//! All three return a result even if no terminal is recognized. [`EnvMap`] shows how to collect
62//! a snapshot; [`DetectOptions`] documents the defaults and available overrides.
63//!
64//! # Optional command probes
65//!
66//! Set [`DetectOptions::allow_commands`] to query `tmux -V`, tmux client term name and type,
67//! `screen --version`, or `zellij --version` after a matching mux marker is found. Commands use the
68//! supplied snapshot as their environment and do not invoke a shell. They block without a timeout;
69//! leave them disabled when latency must be bounded. Multiple tmux clients may make the selected
70//! client ambiguous. Missing tools, failed commands, and unrecognized banners leave metadata
71//! absent.
72//!
73//! This example requires a matching multiplexer environment and its executable on `PATH`.
74//!
75//! ```no_run
76//! use detect_terminal::{DetectOptions, detect_with_options};
77//!
78//! let env = std::env::vars_os().collect();
79//! let options = DetectOptions {
80//! allow_commands: true,
81//! ..DetectOptions::default()
82//! };
83//! let info = detect_with_options(&env, options);
84//! for probe in &info.command_probes {
85//! println!("{}: {:?}", probe.command, probe.status);
86//! }
87//! ```
88//!
89//! # Detection logic
90//!
91//! When a result is surprising, compare its evidence with this precedence order.
92//!
93//! Detection selects one multiplexer and one terminal:
94//!
95//! 1. Nonempty `TMUX`, `ZELLIJ`, then `STY` select a multiplexer in that order. Multiple markers
96//! cannot reliably establish nesting order; the result does not model a session stack.
97//! 2. A recognized `TERM_PROGRAM` wins over vendor markers. Vendor markers are checked in a fixed
98//! order, beginning with `WT_SESSION`, WezTerm, Kitty, and Alacritty. Each successful
99//! environment match records the matching key and value. See [`TerminalKind`] for supported
100//! hints.
101//! 3. With commands enabled, a recognized tmux client term name takes precedence over the pane's
102//! `TERM`. Each probe runs once and its full command string identifies any resulting match.
103//! 4. `TERM` is a fallback. Matching uses complete family names followed by `-` or `.`, avoiding
104//! substring matches such as `stupid` or `not-xterm`. The `screen` family identifies Screen
105//! emulation only when neither tmux nor zellij was selected.
106//!
107//! Empty markers do not identify an application. Unrecognized `TERM_PROGRAM` values are retained
108//! and allow later rules to match. `TERM_PROGRAM_VERSION` becomes [`TerminalInfo::version`] only
109//! when `TERM_PROGRAM` itself identifies the result; otherwise it remains raw metadata in
110//! [`TerminalInfo::term_program_version`]. `SESSIONNAME=Console` does not identify Windows Console
111//! Host, and is not used for detection. `GHOSTTY_RESOURCES_DIR` is also ignored: resource paths
112//! can survive into nested applications such as VS Code and tmux. If those applications replace
113//! the program marker and no other recognized hint remains, the result is `Unknown`.
114//!
115//! This controlled snapshot demonstrates why a program marker wins over a multiplexer
116//! emulation name. It does not describe the environment of every tmux session.
117//!
118//! ```
119//! use detect_terminal::{EnvMap, MultiplexerKind, TerminalKind, detect_from_env};
120//!
121//! let env = EnvMap::from([
122//! ("TMUX".into(), "/tmp/tmux-1000/default,1234,0".into()),
123//! ("TERM_PROGRAM".into(), "ghostty".into()),
124//! ("TERM".into(), "screen-256color".into()),
125//! ]);
126//! let info = detect_from_env(&env);
127//! assert_eq!(info.kind, TerminalKind::Ghostty);
128//! assert_eq!(info.multiplexer.unwrap().kind, MultiplexerKind::Tmux);
129//! assert!(info.command_probes.is_empty());
130//! ```
131//!
132//! # Color support
133//!
134//! [`TerminalInfo::color`] infers color support from the hints and keeps its evidence separate from
135//! identity evidence. It does not decide whether to emit color: `NO_COLOR`, TTY checks, and the
136//! default for [`Unknown`](ColorSupport::Unknown) belong to the application. Optional command
137//! probes do not supply color evidence. The first matching rule applies:
138//!
139//! 1. Detected tmux with `TERM_PROGRAM=tmux`, a release version of 3.2 or later, and `TERM` other
140//! than `dumb` yields [`TrueColor`](ColorSupport::TrueColor). Such a tmux accepts RGB. It
141//! converts colors for an outer terminal it does not know supports RGB, so this does not
142//! establish what that terminal displays.
143//! 2. Any other multiplexer, or a `TERM` family of `tmux`, `screen`, or `dumb`, yields `Unknown`.
144//! Remaining hints can be inherited from an outer terminal.
145//! 3. Apple Terminal builds before 464 yield [`Ansi256`](ColorSupport::Ansi256); build 464 (macOS
146//! 26.0 Tahoe) and later yield `TrueColor`. A dotted build uses its leading integer. A parsed
147//! build overrides `COLORTERM`.
148//! 4. Windows Terminal, or iTerm2 3 or later, yields `TrueColor`.
149//! 5. `COLORTERM` of `truecolor` or `24bit` yields `TrueColor`.
150//! 6. `TERM` ending in `-direct` yields `TrueColor`, except for Apple Terminal.
151//! 7. Anything else yields `Unknown`, including Apple Terminal with no parsable build.
152//! `TERM=xterm-256color` is a common default that does not rule out RGB support.
153//!
154//! See the [Apple Terminal evidence](https://github.com/joshka/detect-terminal/blob/main/docs/terminal-environments.md#apple-terminal-color)
155//! for the build reports and their limits.
156//!
157//! To choose a color encoding, use the `supports_*` methods, which include higher levels. The
158//! `is_*` methods match one variant exactly. See [`ColorSupport`] for the comparison.
159//!
160//! # Edge cases and likely mismatches
161//!
162//! A matched hint is evidence about the process environment, not proof of the application
163//! currently drawing the terminal. The following cases are especially relevant on Windows and
164//! Linux. See [`TerminalInfo::detected_via`] and [`TerminalInfo::identifiers`] to check which hint
165//! won when several are present.
166//!
167//! ## Windows Terminal
168//!
169//! Its normal connection path supplies `WT_SESSION`. When Windows Terminal attaches as the
170//! default host after the shell starts, that shell may receive no marker. With no other recognized
171//! hint, detection returns [`Unknown`](TerminalKind::Unknown) or a `TERM` emulation family.
172//!
173//! ## Alacritty
174//!
175//! Without its terminfo entry, Alacritty uses `TERM=xterm-256color`. Its `ALACRITTY_SOCKET`
176//! marker is Unix-only and can be absent. With only that shared `TERM`, detection returns
177//! [`Xterm`](TerminalKind::Xterm), not Alacritty.
178//!
179//! ## foot
180//!
181//! A build without foot terminfo can also use `TERM=xterm-256color`. Without another marker, the
182//! result is [`Xterm`](TerminalKind::Xterm), not foot.
183//!
184//! ## Tilix
185//!
186//! Tilix sets `TILIX_ID` but copies many parent variables. If it inherits a nonempty `WT_SESSION`
187//! and no recognized `TERM_PROGRAM` is present, this detector selects Windows Terminal because
188//! `WT_SESSION` precedes `TILIX_ID`. This is a possible precedence outcome, not a live observation.
189//!
190//! ## Cmder
191//!
192//! Cmder can run on ConEmu, supplying `CMDER_ROOT` alongside ConEmu markers. The Cmder marker wins
193//! when both are present.
194//!
195//! ## ConEmu
196//!
197//! If `CMDER_ROOT` remains set in a later ConEmu session, detection selects Cmder before ConEmu's
198//! own markers. This is a possible inherited-variable outcome, not a live observation.
199//!
200//! ## GNU Screen
201//!
202//! `TERM=screen*` describes emulation rather than proof of a Screen session. If no multiplexer
203//! marker is present, this terminfo name alone can yield a misleading
204//! [`Screen`](TerminalKind::Screen) result.
205//!
206//! ## tmux
207//!
208//! A nonempty `TMUX` marker prevents `TERM=screen*` from claiming Screen. With commands enabled,
209//! the client term name is a terminfo name and may be ambiguous when several clients are attached.
210//!
211//! ## Zellij
212//!
213//! A nonempty `ZELLIJ` marker also prevents `TERM=screen*` from claiming Screen. If the marker is
214//! absent, the shared terminfo name alone can still yield Screen.
215//!
216//! No combination of these environment hints can prove terminal capabilities or recover an
217//! identity that was never passed to the process. See the repository's
218//! [source-backed environment fixtures](https://github.com/joshka/detect-terminal/blob/main/docs/terminal-environments.md)
219//! for upstream code and representative inputs.
220//!
221//! # Diagnostics and privacy
222//!
223//! [`TerminalInfo::raw_env_subset`] captures consulted variables by default. Disabling
224//! [`DetectOptions::capture_env_subset`] removes that map, but matched [`Identifier`] values and
225//! raw terminal names still appear in the result. Probe records include failures as well as output
226//! from successful commands. Non-Unicode environment values and output are decoded lossily.
227//! Review these fields before logging: session identifiers, paths, and command errors may contain
228//! private information. Detection stops after a match, so the capture can omit existing variables
229//! that were never consulted. Missing entries do not prove those variables were unset.
230//! Use debug formatting or escape control characters when displaying raw values in a terminal;
231//! the library preserves decoded input rather than sanitizing it for display.
232
233#![forbid(unsafe_code)]
234#![warn(missing_docs, missing_debug_implementations)]
235
236mod color;
237mod command;
238mod detect;
239mod env;
240mod multiplexer;
241mod options;
242mod terminal;
243
244pub use crate::color::{ColorInfo, ColorSupport};
245pub use crate::detect::{detect, detect_from_env, detect_with_options};
246pub use crate::env::EnvMap;
247pub use crate::multiplexer::{MultiplexerInfo, MultiplexerKind};
248pub use crate::options::DetectOptions;
249pub use crate::terminal::{CommandProbe, DetectionSource, Identifier, TerminalInfo, TerminalKind};