Skip to main content

detect_terminal/
terminal.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use crate::color::ColorInfo;
5use crate::multiplexer::MultiplexerInfo;
6
7/// A terminal application or emulation family inferred from available hints.
8///
9/// A variant does not always identify the application hosting the session. For example, `Xterm`
10/// can mean only that `TERM` names an xterm-compatible emulation. Inspect
11/// [`TerminalInfo::detected_via`] to distinguish a program marker from a terminfo fallback.
12/// See [Detection logic](crate#detection-logic) for precedence and each variant for its markers.
13/// See [Edge cases and likely mismatches](crate#edge-cases-and-likely-mismatches) before treating a
14/// result as the current application's identity.
15/// Listed `TERM` families match the exact name or a suffix beginning with `-` or `.`.
16/// Program names and terminfo names are matched case-insensitively; presence markers must be
17/// nonempty.
18///
19/// [`Unknown`](Self::Unknown) means no supported hint matched; raw values remain in
20/// [`TerminalInfo`]. [`fmt::Display`] returns a user-facing name, not a capability guarantee.
21/// The enum is non-exhaustive, so matches need a fallback for other and future variants.
22///
23/// # Example
24///
25/// ```
26/// use detect_terminal::{TerminalKind, detect};
27///
28/// match detect().kind {
29///     TerminalKind::Ghostty => println!("Ghostty hint found"),
30///     TerminalKind::Unknown => println!("No recognized terminal hint"),
31///     other => println!("Other application or emulation: {other}"),
32/// }
33/// ```
34#[non_exhaustive]
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum TerminalKind {
37    /// Alacritty terminal emulator. <https://alacritty.org>
38    ///
39    /// Markers: `ALACRITTY_SOCKET`, `TERM=alacritty`.
40    /// If Alacritty falls back to `TERM=xterm-256color` and has no socket marker, this variant
41    /// cannot be selected from those hints alone.
42    Alacritty,
43    /// Terminal.app on macOS. <https://support.apple.com/guide/terminal/welcome/mac>
44    ///
45    /// Markers: `TERM_PROGRAM=Apple_Terminal`.
46    AppleTerminal,
47    /// Cmder terminal emulator. <https://cmder.app>
48    ///
49    /// Markers: `CMDER_ROOT`.
50    /// An inherited `CMDER_ROOT` can outlive the Cmder window that originally set it.
51    Cmder,
52    /// ConEmu terminal emulator. <https://conemu.github.io>
53    ///
54    /// Markers: `ConEmuPID`, `ConEmuHWND`.
55    ConEmu,
56    /// foot terminal emulator. <https://codeberg.org/dnkl/foot>
57    ///
58    /// Markers: `TERM=foot`.
59    /// A build without foot terminfo can use `TERM=xterm-256color` and will not select this kind
60    /// from `TERM` alone.
61    Foot,
62    /// Ghostty terminal emulator. <https://ghostty.org>
63    ///
64    /// Markers: `TERM_PROGRAM=ghostty`, `TERM=xterm-ghostty`,
65    /// `TERM=ghostty`.
66    Ghostty,
67    /// GNOME Terminal. <https://wiki.gnome.org/Apps/Terminal>
68    ///
69    /// Markers: `GNOME_TERMINAL_SERVICE`, `GNOME_TERMINAL_SCREEN`.
70    GnomeTerminal,
71    /// Hyper terminal emulator. <https://hyper.is>
72    ///
73    /// Markers: `TERM_PROGRAM=Hyper`.
74    Hyper,
75    /// iTerm2 terminal emulator. <https://iterm2.com>
76    ///
77    /// Markers: `TERM_PROGRAM=iTerm.app`. `TERM_PROGRAM_VERSION` supplies optional version
78    /// metadata.
79    ITerm2,
80    /// JetBrains IDE terminal. <https://www.jetbrains.com/help/idea/terminal-emulator.html>
81    ///
82    /// Markers: `TERMINAL_EMULATOR` containing `jetbrains`.
83    JetBrains,
84    /// Kitty terminal emulator. <https://sw.kovidgoyal.net/kitty/>
85    ///
86    /// Markers: `KITTY_WINDOW_ID`, `KITTY_PID`, `TERM=xterm-kitty`.
87    Kitty,
88    /// Konsole terminal emulator. <https://konsole.kde.org>
89    ///
90    /// Markers: `KONSOLE_VERSION`.
91    Konsole,
92    /// mintty terminal emulator. <https://mintty.github.io>
93    ///
94    /// Markers: `TERM_PROGRAM=mintty`.
95    Mintty,
96    /// Rio terminal emulator. <https://rioterm.com>
97    ///
98    /// Markers: `TERM_PROGRAM=rio`, `TERM=rio`.
99    Rio,
100    /// rxvt-unicode terminal emulator. <https://software.schmorp.de/pkg/rxvt-unicode.html>
101    ///
102    /// Markers: `RXVT_SOCKET`, `RXVT_TERM`, `TERM=rxvt`.
103    Rxvt,
104    /// GNU Screen terminal emulation. <https://www.gnu.org/software/screen/>
105    ///
106    /// Markers: `TERM=screen` (mux marker `STY` only affects multiplexer detection).
107    Screen,
108    /// Simple terminal (st). <https://st.suckless.org>
109    ///
110    /// Markers: `TERM=st`.
111    St,
112    /// Terminator terminal emulator. <https://gnome-terminator.org>
113    ///
114    /// Markers: `TERMINATOR_UUID`.
115    Terminator,
116    /// Tilix terminal emulator. <https://gnunn1.github.io/tilix-web/>
117    ///
118    /// Markers: `TILIX_ID`.
119    /// Tilix copies many parent variables. A retained higher-priority marker can mask `TILIX_ID`.
120    Tilix,
121    /// VTE-based terminal emulator. <https://wiki.gnome.org/Apps/Terminal/VTE>
122    ///
123    /// Markers: `VTE_VERSION`.
124    /// This names the VTE emulation family, not a particular application using VTE.
125    Vte,
126    /// Visual Studio Code terminal. <https://code.visualstudio.com/docs/terminal/basics>
127    ///
128    /// Markers: `TERM_PROGRAM=vscode`.
129    VSCode,
130    /// Warp terminal emulator. <https://www.warp.dev>
131    ///
132    /// Markers: `TERM_PROGRAM=WarpTerminal`.
133    Warp,
134    /// WezTerm terminal emulator. <https://wezfurlong.org/wezterm/>
135    ///
136    /// Markers: `TERM_PROGRAM=WezTerm`, `WEZTERM_EXECUTABLE`, `WEZTERM_PANE`.
137    WezTerm,
138    /// Windows Terminal. <https://aka.ms/terminal>
139    ///
140    /// Markers: `WT_SESSION`, `TERM_PROGRAM=Windows_Terminal` or `WindowsTerminal`.
141    /// `WT_SESSION` can be absent when Windows Terminal attaches as the default console host
142    /// after the shell has started. The `TERM_PROGRAM` values are recognized when supplied, but
143    /// Windows Terminal does not inject them in its normal connection path.
144    WindowsTerminal,
145    /// xterm terminal emulator. <https://invisible-island.net/xterm/>
146    ///
147    /// Markers: `XTERM_VERSION`, `TERM=xterm`.
148    /// A `TERM=xterm*` match identifies an emulation family; Alacritty, foot, and other
149    /// applications can use `xterm-256color`.
150    Xterm,
151    /// Unknown or unsupported terminal.
152    Unknown,
153}
154
155impl fmt::Display for TerminalKind {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        let label = match self {
158            TerminalKind::Alacritty => "Alacritty",
159            TerminalKind::AppleTerminal => "Terminal.app",
160            TerminalKind::Cmder => "Cmder",
161            TerminalKind::ConEmu => "ConEmu",
162            TerminalKind::Foot => "foot",
163            TerminalKind::Ghostty => "Ghostty",
164            TerminalKind::GnomeTerminal => "GNOME Terminal",
165            TerminalKind::Hyper => "Hyper",
166            TerminalKind::ITerm2 => "iTerm2",
167            TerminalKind::JetBrains => "JetBrains IDE Terminal",
168            TerminalKind::Kitty => "Kitty",
169            TerminalKind::Konsole => "Konsole",
170            TerminalKind::Mintty => "mintty",
171            TerminalKind::Rio => "Rio",
172            TerminalKind::Rxvt => "rxvt-unicode",
173            TerminalKind::Screen => "GNU Screen",
174            TerminalKind::St => "st",
175            TerminalKind::Terminator => "Terminator",
176            TerminalKind::Tilix => "Tilix",
177            TerminalKind::Vte => "VTE-based terminal",
178            TerminalKind::VSCode => "Visual Studio Code Terminal",
179            TerminalKind::Warp => "Warp",
180            TerminalKind::WezTerm => "WezTerm",
181            TerminalKind::WindowsTerminal => "Windows Terminal",
182            TerminalKind::Xterm => "xterm",
183            TerminalKind::Unknown => "Unknown",
184        };
185        formatter.write_str(label)
186    }
187}
188
189/// An environment key and value that identified the terminal.
190///
191/// Command-derived matches have a [`DetectionSource::Command`] and no environment identifier.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct Identifier {
194    /// Name of the matching variable, using the detector's canonical spelling.
195    pub key: String,
196
197    /// Lossily decoded value of the matching variable.
198    pub value: String,
199}
200
201/// Evidence for a terminal kind or inferred color support, separate from multiplexer metadata.
202///
203/// Found in [`TerminalInfo::detected_via`] and [`ColorInfo::inferred_via`]. Environment sources
204/// name a key; a value matched for identity is in [`TerminalInfo::identifiers`]. Command sources
205/// name a successful probe; its output is in [`TerminalInfo::command_probes`]. The display form
206/// prefixes these with `env:` or `command:`.
207#[non_exhaustive]
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub enum DetectionSource {
210    /// The full diagnostic command string of a successful probe.
211    Command(String),
212    /// The matching environment key, using the detector's canonical spelling.
213    EnvVar(String),
214}
215
216impl fmt::Display for DetectionSource {
217    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
218        match self {
219            Self::Command(command) => write!(formatter, "command: {command}"),
220            Self::EnvVar(key) => write!(formatter, "env: {key}"),
221        }
222    }
223}
224
225/// A completed or failed command attempt, recorded in execution order.
226///
227/// `stdout` and `stderr` are trimmed and decoded lossily. Output from unsuccessful commands is
228/// retained for diagnostics but cannot supply detected metadata. See the crate's
229/// [probe contract](crate#optional-command-probes) for execution behavior.
230///
231/// An exit status of zero is necessary but not sufficient to supply metadata: the output must also
232/// be nonempty and, for a version, have a recognized banner. A `None` status with no `error` can
233/// indicate signal termination. These records describe probe attempts, not just successful matches.
234#[non_exhaustive]
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct CommandProbe {
237    /// Diagnostic command string. Arguments are joined by spaces, without shell escaping.
238    pub command: String,
239
240    /// Captured standard output, empty when execution failed before collection.
241    pub stdout: String,
242
243    /// Captured standard error, empty when execution failed before collection.
244    pub stderr: String,
245
246    /// Exit code, or `None` for a signal termination or execution failure.
247    pub status: Option<i32>,
248
249    /// Process creation or output collection error, if any.
250    pub error: Option<String>,
251}
252
253/// Terminal identity, multiplexer metadata, inferred color support, and their evidence.
254///
255/// Obtain this result with [`detect`](crate::detect()),
256/// [`detect_from_env`](crate::detect_from_env),
257/// or [`detect_with_options`](crate::detect_with_options). An unknown terminal is a valid result,
258/// and a known multiplexer does not imply a known terminal application.
259///
260/// # Reading the result
261///
262/// Start with [`kind`](Self::kind), [`version`](Self::version), and
263/// [`multiplexer`](Self::multiplexer). A kind can identify an emulation family rather than an
264/// application, and version metadata may be absent even for a known kind.
265///
266/// For unexpected or unknown results, inspect [`detected_via`](Self::detected_via) and
267/// [`identifiers`](Self::identifiers). The raw `term_program`, `term_program_version`, `term`,
268/// and `colorterm` fields preserve the input hints even when they do not affect the result.
269/// `raw_name` is a convenience fallback label, not the detected application's name.
270///
271/// [`raw_env_subset`](Self::raw_env_subset) contains consulted variables when capture is enabled;
272/// [`command_probes`](Self::command_probes) contains attempted commands when probing is enabled.
273/// These diagnostics can contain private values. See [Diagnostics and
274/// privacy](crate#diagnostics-and-privacy) and [Detection logic](crate#detection-logic).
275///
276/// # Example
277///
278/// ```
279/// let info = detect_terminal::detect();
280/// println!("Terminal: {}", info.kind);
281/// if let Some(version) = &info.version {
282///     println!("Version: {version}");
283/// }
284/// for source in &info.detected_via {
285///     println!("Selected using: {source}");
286/// }
287/// // Debug formatting escapes control characters in raw environment values.
288/// println!(
289///     "Program hint: {:?}; emulation hint: {:?}",
290///     info.term_program, info.term
291/// );
292/// ```
293#[non_exhaustive]
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct TerminalInfo {
296    /// Application or emulation family selected from the available hints.
297    ///
298    /// See [Edge cases and likely mismatches](crate#edge-cases-and-likely-mismatches) when a
299    /// marker may be inherited or a `TERM` name is shared by multiple applications.
300    pub kind: TerminalKind,
301
302    /// `TERM_PROGRAM_VERSION` only when `TERM_PROGRAM` identified the selected kind.
303    ///
304    /// A fallback match never borrows a version belonging to another application or multiplexer.
305    pub version: Option<String>,
306
307    /// Raw `TERM_PROGRAM`, including unknown or empty values.
308    pub term_program: Option<String>,
309
310    /// Raw `TERM_PROGRAM_VERSION`, including when its owner is unknown.
311    pub term_program_version: Option<String>,
312
313    /// Raw `TERM` describing the emulation environment.
314    pub term: Option<String>,
315
316    /// Raw `COLORTERM`, including unrecognized or empty values. It can be inherited.
317    pub colorterm: Option<String>,
318
319    /// Raw `TERM_PROGRAM` if present, otherwise `TERM`.
320    ///
321    /// This convenience label can name something different from the selected kind.
322    pub raw_name: Option<String>,
323
324    /// One selected multiplexer, independently of the terminal match.
325    pub multiplexer: Option<MultiplexerInfo>,
326
327    /// Color support inferred from the hints, with evidence separate from terminal identity.
328    pub color: ColorInfo,
329
330    /// Evidence for the terminal match, empty when the kind is unknown.
331    pub detected_via: Vec<DetectionSource>,
332
333    /// Matching environment key/value pairs, empty for unknown or command-derived matches.
334    pub identifiers: Vec<Identifier>,
335
336    /// Existing variables consulted during detection, when diagnostic capture is enabled.
337    ///
338    /// Absent keys and unrelated variables are omitted. Disabling capture does not redact the
339    /// other fields in this result. Values may contain session identifiers and paths.
340    pub raw_env_subset: BTreeMap<String, String>,
341
342    /// All attempted probes, empty when command execution is disabled or no mux marker matches.
343    pub command_probes: Vec<CommandProbe>,
344}
345
346impl TerminalInfo {
347    /// Start an empty result before assigning environment and probe evidence.
348    pub(crate) fn unknown() -> Self {
349        Self {
350            kind: TerminalKind::Unknown,
351            version: None,
352            term_program: None,
353            term_program_version: None,
354            term: None,
355            colorterm: None,
356            raw_name: None,
357            multiplexer: None,
358            color: ColorInfo::unknown(),
359            detected_via: Vec::new(),
360            identifiers: Vec::new(),
361            raw_env_subset: BTreeMap::new(),
362            command_probes: Vec::new(),
363        }
364    }
365}