Skip to main content

uncurses/ansi/
mode.rs

1//! ANSI and DEC private terminal mode management.
2//!
3//! ## Category
4//!
5//! This module encodes SM/RM, DECSET/DECRST, DECRQM, and report responses for
6//! terminal modes. It also names commonly used modes such as alternate screen,
7//! mouse tracking, bracketed paste, synchronized output, and in-band resize.
8//!
9//! ## CSI anatomy
10//!
11//! Standard ANSI modes omit a private prefix; DEC private modes insert `?` after
12//! CSI. Final byte `h` sets a mode, `l` resets it, `$p` requests state, and `$y`
13//! reports state.
14//!
15//! ```text
16//! ESC [  ?  2 0 4 8  h        CSI ? 2048 h  (enable mode 2048)
17//! ──┬── ─┬─ ───┬──── ┬
18//!  CSI  priv  params final
19//! ```
20//!
21//! ## Batching conventions
22//!
23//! [`write_set_mode`] and [`write_reset_mode`] split mixed mode slices into DEC
24//! and ANSI sequences because the prefixes differ. An empty slice emits nothing.
25
26use std::io::{self, Write};
27
28/// A terminal mode addressable by ANSI SM/RM or DECSET/DECRST.
29///
30/// [`Mode::Ansi`] writes ordinary CSI mode numbers such as `ESC [ 4 h`;
31/// [`Mode::Dec`] writes private mode numbers with `?`, such as
32/// `ESC [ ? 1049 h`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub enum Mode {
35    /// Standard ANSI mode number.
36    ///
37    /// Set/reset/request forms use `ESC [ <number> h`, `ESC [ <number> l`, and `ESC [ <number> $ p`.
38    Ansi(u16),
39    /// DEC private mode number.
40    ///
41    /// Set/reset/request forms use `ESC [ ? <number> h`, `ESC [ ? <number> l`, and `ESC [ ? <number> $ p`.
42    Dec(u16),
43}
44
45// Well-known DEC private modes
46impl Mode {
47    /// DEC private mode 1 (DECCKM): cursor keys send application sequences when set and normal cursor sequences when reset.
48    pub const CURSOR_KEYS: Mode = Mode::Dec(1);
49    /// DEC private mode 2 (DECANM): selects ANSI mode when set and VT52 mode when reset on terminals that implement it.
50    pub const ANSI_VT52: Mode = Mode::Dec(2);
51    /// DEC private mode 3 (DECCOLM): 132-column mode when set; commonly resets margins and clears display on supporting terminals.
52    pub const COLUMN_132: Mode = Mode::Dec(3);
53    /// DEC private mode 4 (DECSCLM): smooth scrolling when set, jump scrolling when reset.
54    pub const SMOOTH_SCROLL: Mode = Mode::Dec(4);
55    /// DEC private mode 5 (DECSCNM): reverse-video screen mode.
56    pub const REVERSE_VIDEO: Mode = Mode::Dec(5);
57    /// DEC private mode 6 (DECOM): absolute cursor positions are relative to the scroll region when set.
58    pub const ORIGIN: Mode = Mode::Dec(6);
59    /// DEC private mode 7 (DECAWM): automatically wrap at the right margin when set.
60    pub const AUTO_WRAP: Mode = Mode::Dec(7);
61    /// DEC private mode 8 (DECARM): key auto-repeat enabled when set.
62    pub const AUTO_REPEAT: Mode = Mode::Dec(8);
63    /// DEC private mode 9: X10 mouse reporting.
64    pub const MOUSE_X10: Mode = Mode::Dec(9);
65    /// DEC private mode 18 (DECPFF): print form-feed mode.
66    pub const PRINT_FORM_FEED: Mode = Mode::Dec(18);
67    /// DEC private mode 19 (DECPEX): print extent mode.
68    pub const PRINT_EXTENT: Mode = Mode::Dec(19);
69    /// DEC private mode 25 (DECTCEM): cursor visible when set, hidden when reset.
70    pub const CURSOR_VISIBLE: Mode = Mode::Dec(25);
71    /// DEC private mode 40 (DECNCSM): allow column-mode changes without clearing on supporting terminals.
72    pub const NO_CLEAR_COLUMN: Mode = Mode::Dec(40);
73    /// DEC private mode 66 (DECNKM): keypad application/numeric behavior; see [`crate::ansi::keypad`].
74    pub const NUMERIC_KEYPAD: Mode = Mode::Dec(66);
75    /// DEC private mode 67 (DECBKM): backarrow key sends backspace/delete according to set/reset state.
76    pub const BACKARROW_KEY: Mode = Mode::Dec(67);
77    /// DEC private mode 69 (DECLRMM): enables left/right margin interpretation for DECSLRM.
78    pub const LEFT_RIGHT_MARGIN: Mode = Mode::Dec(69);
79    /// DEC private mode 80 (DECSDM): Sixel display mode. When set, Sixel
80    /// images are drawn at the top-left corner and the cursor stays in place.
81    /// When reset, Sixel scrolling is on: images start at the cursor.
82    /// Terminals can interpret this mode differently.
83    pub const SIXEL_DISPLAY: Mode = Mode::Dec(80);
84    /// DEC private mode 47: legacy alternate screen buffer.
85    pub const ALT_SCREEN_LEGACY: Mode = Mode::Dec(47);
86    /// DEC private mode 1000: report mouse button press/release events.
87    pub const MOUSE_NORMAL: Mode = Mode::Dec(1000);
88    /// DEC private mode 1001: highlight mouse tracking.
89    pub const MOUSE_HIGHLIGHT: Mode = Mode::Dec(1001);
90    /// DEC private mode 1002: report button-motion mouse events.
91    pub const MOUSE_BUTTON: Mode = Mode::Dec(1002);
92    /// DEC private mode 1003: report any-motion mouse events.
93    pub const MOUSE_ANY: Mode = Mode::Dec(1003);
94    /// DEC private mode 1004: enable focus in/out reports (`ESC [ I` / `ESC [ O`).
95    pub const FOCUS: Mode = Mode::Dec(1004);
96    /// DEC private mode 1005: UTF-8 mouse coordinate encoding.
97    pub const MOUSE_UTF8: Mode = Mode::Dec(1005);
98    /// DEC private mode 1006: SGR mouse coordinate encoding.
99    pub const MOUSE_SGR: Mode = Mode::Dec(1006);
100    /// DEC private mode 1015: alternate mouse coordinate encoding.
101    pub const MOUSE_URXVT: Mode = Mode::Dec(1015);
102    /// DEC private mode 1016: SGR-pixel mouse coordinate encoding.
103    pub const MOUSE_SGR_PIXEL: Mode = Mode::Dec(1016);
104    /// Alternate screen buffer (1047).
105    pub const ALT_SCREEN: Mode = Mode::Dec(1047);
106    /// DEC private mode 1048: save/restore cursor around mode set/reset.
107    pub const SAVE_CURSOR: Mode = Mode::Dec(1048);
108    /// DEC private mode 1049: alternate screen buffer with cursor save/restore and clear semantics.
109    pub const ALT_SCREEN_SAVE_CURSOR: Mode = Mode::Dec(1049);
110    /// DEC private mode 2004: wrap pasted data in bracketed-paste delimiters.
111    pub const BRACKETED_PASTE: Mode = Mode::Dec(2004);
112    /// DEC private mode 2026: synchronized output batching.
113    pub const SYNCHRONIZED_OUTPUT: Mode = Mode::Dec(2026);
114    /// DEC private mode 2027: Unicode core keyboard/input behavior on supporting terminals.
115    pub const UNICODE_CORE: Mode = Mode::Dec(2027);
116    /// DEC private mode 2031: light/dark color-scheme notifications.
117    pub const LIGHT_DARK: Mode = Mode::Dec(2031);
118    /// DEC private mode 2033: terminal visibility reports.
119    pub const VISIBILITY_REPORTS: Mode = Mode::Dec(2033);
120    /// DEC private mode 2048: in-band resize reports.
121    pub const IN_BAND_RESIZE: Mode = Mode::Dec(2048);
122    /// DEC private mode 8452: after a Sixel image, the cursor goes to the
123    /// right of the image's last row instead of the line below it.
124    pub const SIXEL_CURSOR_RIGHT: Mode = Mode::Dec(8452);
125    /// DEC private mode 9001: Win32-input reporting on supporting terminals.
126    pub const WIN32_INPUT: Mode = Mode::Dec(9001);
127}
128
129// Well-known ANSI modes
130impl Mode {
131    /// ANSI mode 2 (KAM): keyboard action mode.
132    pub const KEYBOARD_ACTION: Mode = Mode::Ansi(2);
133    /// ANSI mode 4 (IRM): insert mode when set, replace mode when reset.
134    pub const INSERT: Mode = Mode::Ansi(4);
135    /// ANSI mode 8 (BDSM): bidirectional-support mode.
136    pub const BIDI_SUPPORT: Mode = Mode::Ansi(8);
137    /// ANSI mode 12 (SRM): send/receive mode, often associated with local echo behavior.
138    pub const SEND_RECEIVE: Mode = Mode::Ansi(12);
139    /// ANSI mode 20 (LNM): line-feed/new-line handling mode.
140    pub const LINE_FEED_NEW_LINE: Mode = Mode::Ansi(20);
141}
142
143/// Decoded state value from a mode report response (`DECRPM` or ANSI report).
144///
145/// The numeric values are the `Ps` status field in `ESC [ ? mode ; Ps $ y` or
146/// `ESC [ mode ; Ps $ y`.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148pub enum ModeSetting {
149    /// Report value `0`: the terminal does not recognize the requested mode.
150    NotRecognized,
151    /// Report value `1`: the mode is currently set.
152    Set,
153    /// Report value `2`: the mode is currently reset.
154    Reset,
155    /// Report value `3`: the mode is permanently set and cannot be reset.
156    PermanentlySet,
157    /// Report value `4`: the mode is permanently reset and cannot be set.
158    PermanentlyReset,
159}
160
161impl ModeSetting {
162    /// Convert a numeric mode-report status value into [`ModeSetting`].
163    ///
164    /// Values `1..=4` map to their defined states; every other value maps to [`ModeSetting::NotRecognized`].
165    pub fn from_value(v: u16) -> Self {
166        match v {
167            1 => ModeSetting::Set,
168            2 => ModeSetting::Reset,
169            3 => ModeSetting::PermanentlySet,
170            4 => ModeSetting::PermanentlyReset,
171            _ => ModeSetting::NotRecognized,
172        }
173    }
174
175    /// Return the numeric status value used in mode-report responses.
176    pub fn value(self) -> u16 {
177        match self {
178            ModeSetting::NotRecognized => 0,
179            ModeSetting::Set => 1,
180            ModeSetting::Reset => 2,
181            ModeSetting::PermanentlySet => 3,
182            ModeSetting::PermanentlyReset => 4,
183        }
184    }
185
186    /// Return `true` for [`ModeSetting::Set`] and [`ModeSetting::PermanentlySet`].
187    pub fn is_set(self) -> bool {
188        matches!(self, ModeSetting::Set | ModeSetting::PermanentlySet)
189    }
190
191    /// Return `true` for [`ModeSetting::Reset`] and [`ModeSetting::PermanentlyReset`].
192    pub fn is_reset(self) -> bool {
193        matches!(self, ModeSetting::Reset | ModeSetting::PermanentlyReset)
194    }
195
196    /// Return whether the terminal recognized the mode.
197    ///
198    /// Only [`ModeSetting::NotRecognized`] is considered unrecognized.
199    pub fn is_recognized(self) -> bool {
200        !matches!(self, ModeSetting::NotRecognized)
201    }
202
203    /// Return whether the mode is permanently fixed and cannot be toggled.
204    ///
205    /// Both [`ModeSetting::PermanentlySet`] and [`ModeSetting::PermanentlyReset`]
206    /// report a state the host cannot change.
207    pub fn is_permanent(self) -> bool {
208        matches!(
209            self,
210            ModeSetting::PermanentlySet | ModeSetting::PermanentlyReset
211        )
212    }
213
214    /// Return whether the mode can actually be used by the host.
215    ///
216    /// This is `true` for every recognized state except
217    /// [`ModeSetting::PermanentlyReset`]: a permanently reset mode is
218    /// recognized but the terminal will never allow it to be set, so the
219    /// feature it gates is effectively unavailable. Use this (rather than
220    /// [`is_recognized`](Self::is_recognized)) when deciding whether a
221    /// capability can be relied upon.
222    pub fn is_available(self) -> bool {
223        matches!(
224            self,
225            ModeSetting::Set | ModeSetting::Reset | ModeSetting::PermanentlySet
226        )
227    }
228}
229
230impl std::fmt::Display for ModeSetting {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        let label = match self {
233            ModeSetting::NotRecognized => "not recognized",
234            ModeSetting::Set => "set",
235            ModeSetting::Reset => "reset",
236            ModeSetting::PermanentlySet => "permanently set",
237            ModeSetting::PermanentlyReset => "permanently reset",
238        };
239        f.write_str(label)
240    }
241}
242
243/// Set one or more modes.
244///
245/// DEC private modes emit `ESC [ ? ... h`; ANSI modes emit `ESC [ ... h`. If `modes` contains both kinds, this function writes one DEC sequence and one ANSI sequence. An empty slice emits nothing.
246pub fn write_set_mode<W: Write>(w: &mut W, modes: &[Mode]) -> io::Result<()> {
247    write_mode_seq(w, modes, b'h')
248}
249
250/// Reset one or more modes.
251///
252/// DEC private modes emit `ESC [ ? ... l`; ANSI modes emit `ESC [ ... l`. Mixed slices are split by mode kind. An empty slice emits nothing.
253pub fn write_reset_mode<W: Write>(w: &mut W, modes: &[Mode]) -> io::Result<()> {
254    write_mode_seq(w, modes, b'l')
255}
256
257impl Mode {
258    /// Write the set-mode sequence for this single mode.
259    ///
260    /// This is a convenience wrapper around [`write_set_mode`].
261    pub fn set<W: Write>(self, w: &mut W) -> io::Result<()> {
262        write_set_mode(w, &[self])
263    }
264
265    /// Write the reset-mode sequence for this single mode.
266    ///
267    /// This is a convenience wrapper around [`write_reset_mode`].
268    pub fn reset<W: Write>(self, w: &mut W) -> io::Result<()> {
269        write_reset_mode(w, &[self])
270    }
271
272    /// Request this mode's current state with DECRQM/RQM.
273    ///
274    /// DEC modes emit `ESC [ ? <mode> $ p`; ANSI modes emit `ESC [ <mode> $ p`.
275    pub fn request<W: Write>(self, w: &mut W) -> io::Result<()> {
276        write_request_mode(w, self)
277    }
278}
279
280fn write_mode_seq<W: Write>(w: &mut W, modes: &[Mode], final_byte: u8) -> io::Result<()> {
281    if modes.is_empty() {
282        return Ok(());
283    }
284
285    // Separate ANSI and DEC modes — they use different CSI prefixes
286    let mut ansi_modes = Vec::new();
287    let mut dec_modes = Vec::new();
288
289    for &mode in modes {
290        match mode {
291            Mode::Ansi(n) => ansi_modes.push(n),
292            Mode::Dec(n) => dec_modes.push(n),
293        }
294    }
295
296    if !dec_modes.is_empty() {
297        w.write_all(b"\x1b[?")?;
298        for (i, &n) in dec_modes.iter().enumerate() {
299            if i > 0 {
300                w.write_all(b";")?;
301            }
302            write!(w, "{n}")?;
303        }
304        w.write_all(&[final_byte])?;
305    }
306
307    if !ansi_modes.is_empty() {
308        w.write_all(b"\x1b[")?;
309        for (i, &n) in ansi_modes.iter().enumerate() {
310            if i > 0 {
311                w.write_all(b";")?;
312            }
313            write!(w, "{n}")?;
314        }
315        w.write_all(&[final_byte])?;
316    }
317
318    Ok(())
319}
320
321/// Request mode status.
322///
323/// DEC modes emit `ESC [ ? <mode> $ p`; ANSI modes emit `ESC [ <mode> $ p`. The terminal response can be represented by [`ModeSetting`].
324pub fn write_request_mode<W: Write>(w: &mut W, mode: Mode) -> io::Result<()> {
325    match mode {
326        Mode::Dec(n) => write!(w, "\x1b[?{n}$p"),
327        Mode::Ansi(n) => write!(w, "\x1b[{n}$p"),
328    }
329}
330
331/// Write a mode-report response.
332///
333/// DEC modes emit `ESC [ ? <mode> ; <setting> $ y`; ANSI modes emit `ESC [ <mode> ; <setting> $ y`. Use when synthesizing input reports or testing parsers.
334pub fn write_report_mode<W: Write>(w: &mut W, mode: Mode, setting: ModeSetting) -> io::Result<()> {
335    let v = setting.value();
336    match mode {
337        Mode::Dec(n) => write!(w, "\x1b[?{n};{v}$y"),
338        Mode::Ansi(n) => write!(w, "\x1b[{n};{v}$y"),
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[test]
347    fn test_set_dec_mode() {
348        let mut buf = Vec::new();
349        write_set_mode(&mut buf, &[Mode::ALT_SCREEN_SAVE_CURSOR]).unwrap();
350        assert_eq!(buf, b"\x1b[?1049h");
351    }
352
353    #[test]
354    fn test_reset_dec_mode() {
355        let mut buf = Vec::new();
356        write_reset_mode(&mut buf, &[Mode::ALT_SCREEN_SAVE_CURSOR]).unwrap();
357        assert_eq!(buf, b"\x1b[?1049l");
358    }
359
360    #[test]
361    fn test_set_multiple_dec_modes() {
362        let mut buf = Vec::new();
363        write_set_mode(&mut buf, &[Mode::MOUSE_ANY, Mode::MOUSE_SGR]).unwrap();
364        assert_eq!(buf, b"\x1b[?1003;1006h");
365    }
366
367    #[test]
368    fn test_mode_setting_roundtrip() {
369        for s in [
370            ModeSetting::NotRecognized,
371            ModeSetting::Set,
372            ModeSetting::Reset,
373            ModeSetting::PermanentlySet,
374            ModeSetting::PermanentlyReset,
375        ] {
376            assert_eq!(ModeSetting::from_value(s.value()), s);
377        }
378        assert!(ModeSetting::Set.is_set());
379        assert!(ModeSetting::PermanentlySet.is_set());
380        assert!(!ModeSetting::Reset.is_set());
381        assert!(ModeSetting::Reset.is_reset());
382        assert!(ModeSetting::PermanentlyReset.is_reset());
383        // A recognized mode is anything other than NotRecognized.
384        assert!(!ModeSetting::NotRecognized.is_recognized());
385        for s in [
386            ModeSetting::Set,
387            ModeSetting::Reset,
388            ModeSetting::PermanentlySet,
389            ModeSetting::PermanentlyReset,
390        ] {
391            assert!(s.is_recognized());
392        }
393        // Permanent states are the two that cannot be toggled.
394        assert!(ModeSetting::PermanentlySet.is_permanent());
395        assert!(ModeSetting::PermanentlyReset.is_permanent());
396        assert!(!ModeSetting::Set.is_permanent());
397        assert!(!ModeSetting::Reset.is_permanent());
398        assert!(!ModeSetting::NotRecognized.is_permanent());
399        // A mode is usable unless it is unrecognized or permanently reset.
400        assert!(ModeSetting::Set.is_available());
401        assert!(ModeSetting::Reset.is_available());
402        assert!(ModeSetting::PermanentlySet.is_available());
403        assert!(!ModeSetting::PermanentlyReset.is_available());
404        assert!(!ModeSetting::NotRecognized.is_available());
405    }
406
407    #[test]
408    fn test_mode_setting_display() {
409        assert_eq!(ModeSetting::NotRecognized.to_string(), "not recognized");
410        assert_eq!(ModeSetting::Set.to_string(), "set");
411        assert_eq!(ModeSetting::Reset.to_string(), "reset");
412        assert_eq!(ModeSetting::PermanentlySet.to_string(), "permanently set");
413        assert_eq!(
414            ModeSetting::PermanentlyReset.to_string(),
415            "permanently reset"
416        );
417    }
418
419    #[test]
420    fn test_write_report_mode_dec() {
421        let mut buf = Vec::new();
422        write_report_mode(&mut buf, Mode::ALT_SCREEN_SAVE_CURSOR, ModeSetting::Set).unwrap();
423        assert_eq!(buf, b"\x1b[?1049;1$y");
424    }
425
426    #[test]
427    fn test_write_report_mode_ansi() {
428        let mut buf = Vec::new();
429        write_report_mode(&mut buf, Mode::INSERT, ModeSetting::Reset).unwrap();
430        assert_eq!(buf, b"\x1b[4;2$y");
431    }
432
433    #[test]
434    fn test_request_mode_dec() {
435        let mut buf = Vec::new();
436        write_request_mode(&mut buf, Mode::ALT_SCREEN_SAVE_CURSOR).unwrap();
437        assert_eq!(buf, b"\x1b[?1049$p");
438    }
439
440    #[test]
441    fn test_new_mode_constants() {
442        assert_eq!(Mode::KEYBOARD_ACTION, Mode::Ansi(2));
443        assert_eq!(Mode::BIDI_SUPPORT, Mode::Ansi(8));
444        assert_eq!(Mode::SEND_RECEIVE, Mode::Ansi(12));
445        assert_eq!(Mode::LINE_FEED_NEW_LINE, Mode::Ansi(20));
446        assert_eq!(Mode::MOUSE_UTF8, Mode::Dec(1005));
447        assert_eq!(Mode::MOUSE_URXVT, Mode::Dec(1015));
448        assert_eq!(Mode::WIN32_INPUT, Mode::Dec(9001));
449        assert_eq!(Mode::ALT_SCREEN_LEGACY, Mode::Dec(47));
450        assert_eq!(Mode::LIGHT_DARK, Mode::Dec(2031));
451        assert_eq!(Mode::VISIBILITY_REPORTS, Mode::Dec(2033));
452    }
453}