pulldown_cmark_mdcat/terminal/
detect.rs

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
// Copyright 2018-2020 Sebastian Wiesner <sebastian@swsnr.de>

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Detect the terminal application mdcat is running on.

use crate::terminal::capabilities::iterm2::ITerm2Protocol;
use crate::terminal::capabilities::*;
use std::fmt::{Display, Formatter};

/// A terminal application.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TerminalProgram {
    /// A dumb terminal which does not support any formatting.
    Dumb,
    /// A plain ANSI terminal which supports only standard ANSI formatting.
    Ansi,
    /// iTerm2.
    ///
    /// iTerm2 is a powerful macOS terminal emulator with many formatting features, including images
    /// and inline links.
    ///
    /// See <https://www.iterm2.com> for more information.
    ITerm2,
    /// Terminology.
    ///
    /// See <http://terminolo.gy> for more information.
    Terminology,
    /// Kitty.
    ///
    /// kitty is a fast, featureful, GPU-based terminal emulator with a lot of extensions to the
    /// terminal protocol.
    ///
    /// See <https://sw.kovidgoyal.net/kitty/> for more information.
    Kitty,
    /// WezTerm
    ///
    /// WezTerm is a GPU-accelerated cross-platform terminal emulator and multiplexer.  It's highly
    /// customizable and supports some terminal extensions.
    ///
    /// See <https://wezfurlong.org/wezterm/> for more information.
    WezTerm,
    /// The built-in terminal in VSCode.
    ///
    /// Since version 1.80 it supports images with the iTerm2 protocol.
    VSCode,
    /// Ghostty.
    ///
    /// See <https://mitchellh.com/ghostty> for more information.
    Ghostty,
}

impl Display for TerminalProgram {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let name = match *self {
            TerminalProgram::Dumb => "dumb",
            TerminalProgram::Ansi => "ansi",
            TerminalProgram::ITerm2 => "iTerm2",
            TerminalProgram::Terminology => "Terminology",
            TerminalProgram::Kitty => "kitty",
            TerminalProgram::WezTerm => "WezTerm",
            TerminalProgram::VSCode => "vscode",
            TerminalProgram::Ghostty => "ghostty",
        };
        write!(f, "{name}")
    }
}

/// Extract major and minor version from `$TERM_PROGRAM_VERSION`.
///
/// Return `None` if the variable doesn't exist, or has invalid contents, such as
/// non-numeric parts, insufficient parts for a major.minor version, etc.
fn get_term_program_major_minor_version() -> Option<(u16, u16)> {
    let value = std::env::var("TERM_PROGRAM_VERSION").ok()?;
    let mut parts = value.split('.').take(2);
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    Some((major, minor))
}

impl TerminalProgram {
    fn detect_term() -> Option<Self> {
        match std::env::var("TERM").ok().as_deref() {
            Some("wezterm") => Some(Self::WezTerm),
            Some("xterm-kitty") => Some(Self::Kitty),
            Some("xterm-ghostty") => Some(Self::Ghostty),
            _ => None,
        }
    }

    fn detect_term_program() -> Option<Self> {
        match std::env::var("TERM_PROGRAM").ok().as_deref() {
            Some("WezTerm") => Some(Self::WezTerm),
            Some("iTerm.app") => Some(Self::ITerm2),
            Some("ghostty") => Some(Self::Ghostty),
            Some("vscode")
                if get_term_program_major_minor_version()
                    .map_or(false, |version| (1, 80) <= version) =>
            {
                Some(Self::VSCode)
            }
            _ => None,
        }
    }

    /// Attempt to detect the terminal program mdcat is running on.
    ///
    /// This function looks at various environment variables to identify the terminal program.
    ///
    /// It first looks at `$TERM` to determine the terminal program, then at `$TERM_PROGRAM`, and
    /// finally at `$TERMINOLOGY`.
    ///
    /// If `$TERM` is set to anything other than `xterm-256colors` it's definitely accurate, since
    /// it points to the terminfo entry to use.  `$TERM` also propagates across most boundaries
    /// (e.g. `sudo`, `ssh`), and thus the most reliable place to check.
    ///
    /// However, `$TERM` only works if the terminal has a dedicated entry in terminfo database. Many
    /// terminal programs avoid this complexity (even WezTerm only sets `$TERM` if explicitly
    /// configured to do so), so `mdcat` proceeds to look at other variables.  However, these are
    /// generally not as reliable as `$TERM`, because they often do not propagate across SSH or
    /// sudo, and may leak if one terminal program is started from another one.
    ///
    /// # Returns
    ///
    /// - [`TerminalProgram::Kitty`] if `$TERM` is `xterm-kitty`.
    /// - [`TerminalProgram::WezTerm`] if `$TERM` is `wezterm`.
    /// - [`TerminalProgram::WezTerm`] if `$TERM_PROGRAM` is `WezTerm`.
    /// - [`TerminalProgram::ITerm2`] if `$TERM_PROGRAM` is `iTerm.app`.
    /// - [`TerminalProgram::Ghostty`] if `$TERM` is `xterm-ghostty`.
    /// - [`TerminalProgram::Ghostty`] if `$TERM_PROGRAM` is `ghostty`.
    /// - [`TerminalProgram::Terminology`] if `$TERMINOLOGY` is `1`.
    /// - [`TerminalProgram::Ansi`] otherwise.
    pub fn detect() -> Self {
        Self::detect_term()
            .or_else(Self::detect_term_program)
            .or_else(|| match std::env::var("TERMINOLOGY").ok().as_deref() {
                Some("1") => Some(Self::Terminology),
                _ => None,
            })
            .unwrap_or(Self::Ansi)
    }

    /// Get the capabilities of this terminal emulator.
    pub fn capabilities(self) -> TerminalCapabilities {
        let ansi = TerminalCapabilities {
            style: Some(StyleCapability::Ansi),
            image: None,
            marks: None,
        };
        match self {
            TerminalProgram::Dumb => TerminalCapabilities::default(),
            TerminalProgram::Ansi => ansi,
            TerminalProgram::ITerm2 => ansi
                .with_mark_capability(MarkCapability::ITerm2(ITerm2Protocol))
                .with_image_capability(ImageCapability::ITerm2(ITerm2Protocol)),
            TerminalProgram::Terminology => {
                ansi.with_image_capability(ImageCapability::Terminology(terminology::Terminology))
            }
            TerminalProgram::Kitty => ansi
                .with_image_capability(ImageCapability::Kitty(self::kitty::KittyGraphicsProtocol)),
            TerminalProgram::WezTerm => ansi
                .with_image_capability(ImageCapability::Kitty(self::kitty::KittyGraphicsProtocol)),
            TerminalProgram::VSCode => {
                ansi.with_image_capability(ImageCapability::ITerm2(ITerm2Protocol))
            }
            TerminalProgram::Ghostty => ansi
                .with_image_capability(ImageCapability::Kitty(self::kitty::KittyGraphicsProtocol)),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::terminal::TerminalProgram;

    use temp_env::with_vars;

    #[test]
    pub fn detect_term_kitty() {
        with_vars(vec![("TERM", Some("xterm-kitty"))], || {
            assert_eq!(TerminalProgram::detect(), TerminalProgram::Kitty)
        })
    }

    #[test]
    pub fn detect_term_wezterm() {
        with_vars(vec![("TERM", Some("wezterm"))], || {
            assert_eq!(TerminalProgram::detect(), TerminalProgram::WezTerm)
        })
    }

    #[test]
    pub fn detect_term_program_wezterm() {
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("WezTerm")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::WezTerm),
        )
    }

    #[test]
    pub fn detect_term_program_iterm2() {
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("iTerm.app")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::ITerm2),
        )
    }

    #[test]
    pub fn detect_terminology() {
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("TERMINOLOGY", Some("1")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::Terminology),
        );
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("TERMINOLOGY", Some("0")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::Ansi),
        );
    }

    #[test]
    pub fn detect_term_ghostty() {
        with_vars(vec![("TERM", Some("xterm-ghostty"))], || {
            assert_eq!(TerminalProgram::detect(), TerminalProgram::Ghostty)
        })
    }

    #[test]
    pub fn detect_term_program_ghostty() {
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("ghostty")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::Ghostty),
        )
    }

    #[test]
    pub fn detect_ansi() {
        with_vars(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("TERMINOLOGY", None),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::Ansi),
        )
    }

    /// Regression test for <https://github.com/swsnr/mdcat/issues/230>
    #[test]
    #[allow(non_snake_case)]
    pub fn GH_230_detect_nested_kitty_from_iterm2() {
        with_vars(
            vec![
                ("TERM_PROGRAM", Some("iTerm.app")),
                ("TERM", Some("xterm-kitty")),
            ],
            || assert_eq!(TerminalProgram::detect(), TerminalProgram::Kitty),
        )
    }
}