mdcat-ng 0.2.1

cat for markdown: show markdown documents in terminals
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// 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 — <https://www.iterm2.com>.
    ITerm2,
    /// Terminology — <http://terminolo.gy>.
    Terminology,
    /// Kitty — <https://sw.kovidgoyal.net/kitty/>.
    Kitty,
    /// WezTerm — <https://wezfurlong.org/wezterm/>.
    WezTerm,
    /// The built-in terminal in VSCode (since 1.80, iTerm2 image protocol).
    VSCode,
    /// Ghostty — <https://mitchellh.com/ghostty>.
    Ghostty,
    /// Alacritty — ANSI + OSC 8 hyperlinks.
    Alacritty,
    /// Foot, Wayland terminal — ANSI + OSC 8 + Sixel (when the feature lands).
    Foot,
    /// KDE Konsole — ANSI + OSC 8.
    Konsole,
    /// Apple's Terminal.app — ANSI only on older macOS; OSC 8 on macOS 15+.
    AppleTerminal,
    /// Warp — <https://warp.dev>.
    Warp,
    /// Rio — <https://raphamorim.io/rio/>. Supports Kitty graphics.
    Rio,
    /// Hyper (Electron-based) — ANSI only.
    Hyper,
    /// Contour — ANSI + OSC 8 (Sixel when the feature lands).
    Contour,
    /// mlterm — ANSI + Sixel (when the feature lands).
    Mlterm,
    /// Windows Terminal — ANSI + OSC 8 (Sixel since 1.22 beta).
    WindowsTerminal,
}

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",
            TerminalProgram::Alacritty => "Alacritty",
            TerminalProgram::Foot => "foot",
            TerminalProgram::Konsole => "Konsole",
            TerminalProgram::AppleTerminal => "Apple Terminal",
            TerminalProgram::Warp => "Warp",
            TerminalProgram::Rio => "Rio",
            TerminalProgram::Hyper => "Hyper",
            TerminalProgram::Contour => "Contour",
            TerminalProgram::Mlterm => "mlterm",
            TerminalProgram::WindowsTerminal => "Windows Terminal",
        };
        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> {
        let term = std::env::var("TERM").ok();
        let t = term.as_deref()?;
        match t {
            "wezterm" => Some(Self::WezTerm),
            "xterm-kitty" => Some(Self::Kitty),
            "xterm-ghostty" => Some(Self::Ghostty),
            "alacritty" | "xterm-alacritty" => Some(Self::Alacritty),
            "foot" | "foot-extra" | "xterm-foot" => Some(Self::Foot),
            "rio" | "xterm-rio" => Some(Self::Rio),
            _ if t.starts_with("mlterm") => Some(Self::Mlterm),
            _ => 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("Apple_Terminal") => Some(Self::AppleTerminal),
            Some("WarpTerminal") => Some(Self::Warp),
            Some("Hyper") => Some(Self::Hyper),
            Some("alacritty") => Some(Self::Alacritty),
            Some("rio") => Some(Self::Rio),
            Some("vscode")
                if get_term_program_major_minor_version()
                    .is_some_and(|version| (1, 80) <= version) =>
            {
                Some(Self::VSCode)
            }
            _ => None,
        }
    }

    /// Look at less-common environment variables terminals set to announce
    /// themselves. Third-tier after `$TERM` and `$TERM_PROGRAM`.
    fn detect_secondary_env() -> Option<Self> {
        if std::env::var_os("WT_SESSION").is_some() {
            return Some(Self::WindowsTerminal);
        }
        if std::env::var_os("KONSOLE_VERSION").is_some() {
            return Some(Self::Konsole);
        }
        if let Ok(value) = std::env::var("TERMINAL_EMULATOR") {
            if value.eq_ignore_ascii_case("contour") {
                return Some(Self::Contour);
            }
        }
        if matches!(std::env::var("TERMINOLOGY").ok().as_deref(), Some("1")) {
            return Some(Self::Terminology);
        }
        None
    }

    /// Attempt to detect the terminal program mdcat is running on.
    ///
    /// Environment variables are consulted in the following priority order:
    ///
    /// 1. `$TERM` (most reliable — it propagates across `sudo`/`ssh`)
    /// 2. `$TERM_PROGRAM`
    /// 3. Terminal-specific markers: `$WT_SESSION` (Windows Terminal),
    ///    `$KONSOLE_VERSION`, `$TERMINAL_EMULATOR` (Contour),
    ///    `$TERMINOLOGY`.
    ///
    /// Falls back to [`TerminalProgram::Ansi`] when no signal is found.
    pub fn detect() -> Self {
        Self::detect_term()
            .or_else(Self::detect_term_program)
            .or_else(Self::detect_secondary_env)
            .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,
        };
        let kitty = || ImageCapability::Kitty(self::kitty::KittyGraphicsProtocol);
        let iterm2 = || ImageCapability::ITerm2(ITerm2Protocol);
        #[cfg(feature = "sixel")]
        let sixel = || ImageCapability::Sixel(self::sixel::SixelProtocol);
        match self {
            TerminalProgram::Dumb => TerminalCapabilities::default(),
            TerminalProgram::Ansi
            | TerminalProgram::Alacritty
            | TerminalProgram::Konsole
            | TerminalProgram::AppleTerminal
            | TerminalProgram::Warp
            | TerminalProgram::Hyper => ansi,
            TerminalProgram::ITerm2 => ansi
                .with_mark_capability(MarkCapability::ITerm2(ITerm2Protocol))
                .with_image_capability(iterm2()),
            TerminalProgram::VSCode => ansi.with_image_capability(iterm2()),
            TerminalProgram::Terminology => {
                ansi.with_image_capability(ImageCapability::Terminology(terminology::Terminology))
            }
            TerminalProgram::Kitty
            | TerminalProgram::WezTerm
            | TerminalProgram::Ghostty
            | TerminalProgram::Rio => ansi.with_image_capability(kitty()),
            // Sixel-capable terminals: get the Sixel protocol when the feature
            // is enabled, otherwise fall back to plain ANSI.
            TerminalProgram::Foot
            | TerminalProgram::Contour
            | TerminalProgram::Mlterm
            | TerminalProgram::WindowsTerminal => {
                #[cfg(feature = "sixel")]
                {
                    ansi.with_image_capability(sixel())
                }
                #[cfg(not(feature = "sixel"))]
                {
                    ansi
                }
            }
        }
    }
}

#[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),
        )
    }

    // ─── terminals added in 3.0 ────────────────────────────────────────────

    fn assert_detects(env: Vec<(&str, Option<&str>)>, expected: TerminalProgram) {
        with_vars(env, || assert_eq!(TerminalProgram::detect(), expected));
    }

    #[test]
    fn detect_alacritty_via_term() {
        assert_detects(
            vec![("TERM", Some("alacritty"))],
            TerminalProgram::Alacritty,
        );
    }

    #[test]
    fn detect_alacritty_via_term_program() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("alacritty")),
            ],
            TerminalProgram::Alacritty,
        );
    }

    #[test]
    fn detect_foot() {
        assert_detects(vec![("TERM", Some("foot"))], TerminalProgram::Foot);
    }

    #[test]
    fn detect_rio_via_term() {
        assert_detects(vec![("TERM", Some("rio"))], TerminalProgram::Rio);
    }

    #[test]
    fn detect_rio_via_term_program() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("rio")),
            ],
            TerminalProgram::Rio,
        );
    }

    #[test]
    fn detect_mlterm() {
        assert_detects(vec![("TERM", Some("mlterm"))], TerminalProgram::Mlterm);
    }

    #[test]
    fn detect_warp() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("WarpTerminal")),
            ],
            TerminalProgram::Warp,
        );
    }

    #[test]
    fn detect_hyper() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("Hyper")),
            ],
            TerminalProgram::Hyper,
        );
    }

    #[test]
    fn detect_apple_terminal() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", Some("Apple_Terminal")),
            ],
            TerminalProgram::AppleTerminal,
        );
    }

    #[test]
    fn detect_windows_terminal() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("WT_SESSION", Some("abc-123")),
            ],
            TerminalProgram::WindowsTerminal,
        );
    }

    #[test]
    fn detect_konsole() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("KONSOLE_VERSION", Some("240100")),
            ],
            TerminalProgram::Konsole,
        );
    }

    #[test]
    fn detect_contour() {
        assert_detects(
            vec![
                ("TERM", Some("xterm-256color")),
                ("TERM_PROGRAM", None),
                ("TERMINAL_EMULATOR", Some("contour")),
            ],
            TerminalProgram::Contour,
        );
    }
}