Skip to main content

ftui_render/
ansi.rs

1#![forbid(unsafe_code)]
2
3//! ANSI escape sequence generation helpers.
4//!
5//! This module provides pure byte-generation functions for ANSI/VT control sequences.
6//! It handles the encoding details so the Presenter can focus on state tracking and diffing.
7//!
8//! # Design Principles
9//!
10//! - **Pure functions**: No state tracking, just byte generation
11//! - **Zero allocation**: Use stack buffers for common sequences
12//! - **Explicit**: Readable helpers over clever formatting
13//!
14//! # Sequence Reference
15//!
16//! | Category | Sequence | Description |
17//! |----------|----------|-------------|
18//! | CSI | `ESC [ n m` | SGR (Select Graphic Rendition) |
19//! | CSI | `ESC [ row ; col H` | CUP (Cursor Position, 1-indexed) |
20//! | CSI | `ESC [ n K` | EL (Erase Line) |
21//! | CSI | `ESC [ n J` | ED (Erase Display) |
22//! | CSI | `ESC [ top ; bottom r` | DECSTBM (Set Scroll Region) |
23//! | CSI | `ESC [ ? 2026 h/l` | Synchronized Output (DEC) |
24//! | OSC | `ESC ] 8 ; ; url ST` | Hyperlink (OSC 8) |
25//! | DEC | `ESC 7` / `ESC 8` | Cursor save/restore (DECSC/DECRC) |
26
27use std::io::{self, Write};
28
29use crate::cell::{PackedRgba, StyleFlags};
30
31const MAX_OSC8_FIELD_BYTES: usize = 4096;
32
33#[inline]
34fn osc8_field_is_safe(value: &str) -> bool {
35    value.len() <= MAX_OSC8_FIELD_BYTES && !value.chars().any(char::is_control)
36}
37
38// =============================================================================
39// SGR (Select Graphic Rendition)
40// =============================================================================
41
42/// SGR reset: `CSI 0 m`
43pub const SGR_RESET: &[u8] = b"\x1b[0m";
44
45/// Write SGR reset sequence.
46#[inline]
47pub fn sgr_reset<W: Write>(w: &mut W) -> io::Result<()> {
48    w.write_all(SGR_RESET)
49}
50
51/// SGR attribute codes for style flags.
52#[derive(Debug, Clone, Copy)]
53pub struct SgrCodes {
54    /// Enable code
55    pub on: u8,
56    /// Disable code
57    pub off: u8,
58}
59
60/// SGR codes for bold (on=1, off=22).
61pub const SGR_BOLD: SgrCodes = SgrCodes { on: 1, off: 22 };
62/// SGR codes for dim (on=2, off=22).
63pub const SGR_DIM: SgrCodes = SgrCodes { on: 2, off: 22 };
64/// SGR codes for italic (on=3, off=23).
65pub const SGR_ITALIC: SgrCodes = SgrCodes { on: 3, off: 23 };
66/// SGR codes for underline (on=4, off=24).
67pub const SGR_UNDERLINE: SgrCodes = SgrCodes { on: 4, off: 24 };
68/// SGR codes for blink (on=5, off=25).
69pub const SGR_BLINK: SgrCodes = SgrCodes { on: 5, off: 25 };
70/// SGR codes for reverse video (on=7, off=27).
71pub const SGR_REVERSE: SgrCodes = SgrCodes { on: 7, off: 27 };
72/// SGR codes for hidden text (on=8, off=28).
73pub const SGR_HIDDEN: SgrCodes = SgrCodes { on: 8, off: 28 };
74/// SGR codes for strikethrough (on=9, off=29).
75pub const SGR_STRIKETHROUGH: SgrCodes = SgrCodes { on: 9, off: 29 };
76
77/// Get SGR codes for a style flag.
78#[must_use]
79pub const fn sgr_codes_for_flag(flag: StyleFlags) -> Option<SgrCodes> {
80    match flag.bits() {
81        0b0000_0001 => Some(SGR_BOLD),
82        0b0000_0010 => Some(SGR_DIM),
83        0b0000_0100 => Some(SGR_ITALIC),
84        0b0000_1000 => Some(SGR_UNDERLINE),
85        0b0001_0000 => Some(SGR_BLINK),
86        0b0010_0000 => Some(SGR_REVERSE),
87        0b1000_0000 => Some(SGR_HIDDEN),
88        0b0100_0000 => Some(SGR_STRIKETHROUGH),
89        _ => None,
90    }
91}
92
93#[inline]
94fn write_u8_dec(buf: &mut [u8], n: u8) -> usize {
95    if n >= 100 {
96        let hundreds = n / 100;
97        let tens = (n / 10) % 10;
98        let ones = n % 10;
99        buf[0] = b'0' + hundreds;
100        buf[1] = b'0' + tens;
101        buf[2] = b'0' + ones;
102        3
103    } else if n >= 10 {
104        let tens = n / 10;
105        let ones = n % 10;
106        buf[0] = b'0' + tens;
107        buf[1] = b'0' + ones;
108        2
109    } else {
110        buf[0] = b'0' + n;
111        1
112    }
113}
114
115#[inline]
116fn write_u32_dec(buf: &mut [u8], mut n: u32) -> usize {
117    let mut rev = [0u8; 10];
118    let mut len = 0usize;
119
120    loop {
121        rev[len] = (n % 10) as u8;
122        len += 1;
123        n /= 10;
124        if n == 0 {
125            break;
126        }
127    }
128
129    for i in 0..len {
130        buf[i] = b'0' + rev[len - 1 - i];
131    }
132
133    len
134}
135
136#[inline]
137fn write_sgr_code<W: Write>(w: &mut W, code: u8) -> io::Result<()> {
138    let mut buf = [0u8; 6];
139    buf[0] = 0x1b;
140    buf[1] = b'[';
141    let len = write_u8_dec(&mut buf[2..], code);
142    buf[2 + len] = b'm';
143    w.write_all(&buf[..2 + len + 1])
144}
145
146/// Write SGR sequence for style flags (all set flags).
147///
148/// Emits `CSI n ; n ; ... m` for each enabled flag.
149/// Does not emit reset first - caller is responsible for state management.
150pub fn sgr_flags<W: Write>(w: &mut W, flags: StyleFlags) -> io::Result<()> {
151    if flags.is_empty() {
152        return Ok(());
153    }
154
155    let bits = flags.bits();
156    if bits.is_power_of_two()
157        && let Some(seq) = sgr_single_flag_seq(bits)
158    {
159        return w.write_all(seq);
160    }
161
162    let mut buf = [0u8; 32];
163    let mut idx = 0usize;
164    buf[idx] = 0x1b;
165    buf[idx + 1] = b'[';
166    idx += 2;
167    let mut first = true;
168
169    for (flag, codes) in FLAG_TABLE {
170        if flags.contains(flag) {
171            if !first {
172                buf[idx] = b';';
173                idx += 1;
174            }
175            idx += write_u8_dec(&mut buf[idx..], codes.on);
176            first = false;
177        }
178    }
179
180    buf[idx] = b'm';
181    idx += 1;
182    w.write_all(&buf[..idx])
183}
184
185/// Ordered table of (flag, on/off codes) for iteration.
186pub const FLAG_TABLE: [(StyleFlags, SgrCodes); 8] = [
187    (StyleFlags::BOLD, SGR_BOLD),
188    (StyleFlags::DIM, SGR_DIM),
189    (StyleFlags::ITALIC, SGR_ITALIC),
190    (StyleFlags::UNDERLINE, SGR_UNDERLINE),
191    (StyleFlags::BLINK, SGR_BLINK),
192    (StyleFlags::REVERSE, SGR_REVERSE),
193    (StyleFlags::HIDDEN, SGR_HIDDEN),
194    (StyleFlags::STRIKETHROUGH, SGR_STRIKETHROUGH),
195];
196
197#[inline]
198fn sgr_single_flag_seq(bits: u8) -> Option<&'static [u8]> {
199    match bits {
200        0b0000_0001 => Some(b"\x1b[1m"), // bold
201        0b0000_0010 => Some(b"\x1b[2m"), // dim
202        0b0000_0100 => Some(b"\x1b[3m"), // italic
203        0b0000_1000 => Some(b"\x1b[4m"), // underline
204        0b0001_0000 => Some(b"\x1b[5m"), // blink
205        0b0010_0000 => Some(b"\x1b[7m"), // reverse
206        0b0100_0000 => Some(b"\x1b[9m"), // strikethrough
207        0b1000_0000 => Some(b"\x1b[8m"), // hidden
208        _ => None,
209    }
210}
211
212#[inline]
213fn sgr_single_flag_off_seq(bits: u8) -> Option<&'static [u8]> {
214    match bits {
215        0b0000_0001 => Some(b"\x1b[22m"), // bold off
216        0b0000_0010 => Some(b"\x1b[22m"), // dim off
217        0b0000_0100 => Some(b"\x1b[23m"), // italic off
218        0b0000_1000 => Some(b"\x1b[24m"), // underline off
219        0b0001_0000 => Some(b"\x1b[25m"), // blink off
220        0b0010_0000 => Some(b"\x1b[27m"), // reverse off
221        0b0100_0000 => Some(b"\x1b[29m"), // strikethrough off
222        0b1000_0000 => Some(b"\x1b[28m"), // hidden off
223        _ => None,
224    }
225}
226
227/// Write SGR sequence to turn off specific style flags.
228///
229/// Emits the individual "off" codes for each flag in `flags_to_disable`.
230/// Handles the Bold/Dim shared off code (22): if only one of Bold/Dim needs
231/// to be disabled while the other must stay on, the caller must re-enable
232/// the survivor separately. This function returns the set of flags that were
233/// collaterally disabled (i.e., flags that share an off code with a disabled flag
234/// but should remain enabled according to `flags_to_keep`).
235///
236/// Returns the set of flags that need to be re-enabled due to shared off codes.
237///
238/// Note: disabling BOLD|DIM together emits the shared off-code 22 twice
239/// (one CSI per flag; 5 redundant bytes). This is deliberate: the
240/// presenter's `sgr_flags_off_len` estimator prices per-flag, and the
241/// reset-vs-delta decision depends on the estimator matching emission
242/// byte-for-byte — deduping here without changing the estimator in
243/// lockstep would skew that decision.
244pub fn sgr_flags_off<W: Write>(
245    w: &mut W,
246    flags_to_disable: StyleFlags,
247    flags_to_keep: StyleFlags,
248) -> io::Result<StyleFlags> {
249    if flags_to_disable.is_empty() {
250        return Ok(StyleFlags::empty());
251    }
252
253    let disable_bits = flags_to_disable.bits();
254    if disable_bits.is_power_of_two()
255        && let Some(seq) = sgr_single_flag_off_seq(disable_bits)
256    {
257        w.write_all(seq)?;
258        if disable_bits == StyleFlags::BOLD.bits() && flags_to_keep.contains(StyleFlags::DIM) {
259            return Ok(StyleFlags::DIM);
260        }
261        if disable_bits == StyleFlags::DIM.bits() && flags_to_keep.contains(StyleFlags::BOLD) {
262            return Ok(StyleFlags::BOLD);
263        }
264        return Ok(StyleFlags::empty());
265    }
266
267    let mut collateral = StyleFlags::empty();
268
269    for (flag, codes) in FLAG_TABLE {
270        if !flags_to_disable.contains(flag) {
271            continue;
272        }
273        // Emit the off code
274        write_sgr_code(w, codes.off)?;
275        // Check for collateral damage: Bold (off=22) and Dim (off=22) share the same off code
276        if codes.off == 22 {
277            // Off code 22 disables both Bold and Dim
278            let other = if flag == StyleFlags::BOLD {
279                StyleFlags::DIM
280            } else {
281                StyleFlags::BOLD
282            };
283            if flags_to_keep.contains(other) && !flags_to_disable.contains(other) {
284                collateral |= other;
285            }
286        }
287    }
288
289    Ok(collateral)
290}
291
292const SGR_FG_RGB_PREFIX: &[u8] = b"\x1b[38;2;";
293const SGR_BG_RGB_PREFIX: &[u8] = b"\x1b[48;2;";
294
295#[inline]
296fn write_sgr_rgb_seq<W: Write>(w: &mut W, prefix: &[u8], r: u8, g: u8, b: u8) -> io::Result<()> {
297    let mut buf = [0u8; 20];
298    let mut idx = 0usize;
299
300    buf[..prefix.len()].copy_from_slice(prefix);
301    idx += prefix.len();
302
303    idx += write_u8_dec(&mut buf[idx..], r);
304    buf[idx] = b';';
305    idx += 1;
306    idx += write_u8_dec(&mut buf[idx..], g);
307    buf[idx] = b';';
308    idx += 1;
309    idx += write_u8_dec(&mut buf[idx..], b);
310    buf[idx] = b'm';
311    idx += 1;
312
313    w.write_all(&buf[..idx])
314}
315
316#[inline]
317fn write_csi_u32_suffix<W: Write>(w: &mut W, value: u32, suffix: u8) -> io::Result<()> {
318    let mut buf = [0u8; 16];
319    buf[0] = 0x1b;
320    buf[1] = b'[';
321    let len = write_u32_dec(&mut buf[2..], value);
322    buf[2 + len] = suffix;
323    w.write_all(&buf[..3 + len])
324}
325
326const ANSI16_RGB: [(u8, u8, u8); 16] = [
327    (0, 0, 0),
328    (205, 0, 0),
329    (0, 205, 0),
330    (205, 205, 0),
331    (0, 0, 238),
332    (205, 0, 205),
333    (0, 205, 205),
334    (229, 229, 229),
335    (127, 127, 127),
336    (255, 0, 0),
337    (0, 255, 0),
338    (255, 255, 0),
339    (92, 92, 255),
340    (255, 0, 255),
341    (0, 255, 255),
342    (255, 255, 255),
343];
344
345#[inline]
346const fn ansi_cube_index(value: u8) -> u8 {
347    if value < 48 {
348        0
349    } else if value < 115 {
350        1
351    } else {
352        (value - 35) / 40
353    }
354}
355
356#[inline]
357const fn ansi256_rgb(index: u8) -> (u8, u8, u8) {
358    if index < 16 {
359        return ANSI16_RGB[index as usize];
360    }
361    if index >= 232 {
362        let gray = 8 + 10 * (index - 232);
363        return (gray, gray, gray);
364    }
365
366    let index = index - 16;
367    let r = index / 36;
368    let g = (index / 6) % 6;
369    let b = index % 6;
370    const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
371    (LEVELS[r as usize], LEVELS[g as usize], LEVELS[b as usize])
372}
373
374#[inline]
375fn color_distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> u64 {
376    let dr = i32::from(a.0) - i32::from(b.0);
377    let dg = i32::from(a.1) - i32::from(b.1);
378    let db = i32::from(a.2) - i32::from(b.2);
379    2126 * (dr * dr) as u64 + 7152 * (dg * dg) as u64 + 722 * (db * db) as u64
380}
381
382/// Convert RGB to a deterministic ANSI 256-color palette index.
383///
384/// Non-gray colors map to the nearest 6x6x6 cube cell in constant time. Exact
385/// grays compare that cube cell with the grayscale ramp and keep the closer
386/// candidate.
387#[must_use]
388pub fn rgb_to_ansi256(r: u8, g: u8, b: u8) -> u8 {
389    let cube = 16 + 36 * ansi_cube_index(r) + 6 * ansi_cube_index(g) + ansi_cube_index(b);
390
391    if r != g || g != b {
392        return cube;
393    }
394    if r < 8 {
395        return if r <= 4 { 16 } else { 232 };
396    }
397    if r > 246 {
398        return 231;
399    }
400
401    let gray = 232 + ((r - 8 + 5) / 10).min(23);
402    let target = (r, g, b);
403    if color_distance(target, ansi256_rgb(cube)) <= color_distance(target, ansi256_rgb(gray)) {
404        cube
405    } else {
406        gray
407    }
408}
409
410/// Convert RGB to the deterministic nearest ANSI 16-color palette index.
411#[must_use]
412pub fn rgb_to_ansi16(r: u8, g: u8, b: u8) -> u8 {
413    let target = (r, g, b);
414    let mut best_index = 0;
415    let mut best_distance = u64::MAX;
416    for (index, candidate) in ANSI16_RGB.iter().copied().enumerate() {
417        let distance = color_distance(target, candidate);
418        if distance < best_distance {
419            best_index = index as u8;
420            best_distance = distance;
421        }
422    }
423    best_index
424}
425
426/// Write SGR sequence for true color foreground: `CSI 38;2;r;g;b m`
427pub fn sgr_fg_rgb<W: Write>(w: &mut W, r: u8, g: u8, b: u8) -> io::Result<()> {
428    write_sgr_rgb_seq(w, SGR_FG_RGB_PREFIX, r, g, b)
429}
430
431/// Write SGR sequence for true color background: `CSI 48;2;r;g;b m`
432pub fn sgr_bg_rgb<W: Write>(w: &mut W, r: u8, g: u8, b: u8) -> io::Result<()> {
433    write_sgr_rgb_seq(w, SGR_BG_RGB_PREFIX, r, g, b)
434}
435
436/// Write SGR sequence for 256-color foreground: `CSI 38;5;n m`
437pub fn sgr_fg_256<W: Write>(w: &mut W, index: u8) -> io::Result<()> {
438    write!(w, "\x1b[38;5;{index}m")
439}
440
441/// Write SGR sequence for 256-color background: `CSI 48;5;n m`
442pub fn sgr_bg_256<W: Write>(w: &mut W, index: u8) -> io::Result<()> {
443    write!(w, "\x1b[48;5;{index}m")
444}
445
446/// Write SGR sequence for 16-color foreground.
447///
448/// Uses codes 30-37 for normal colors, 90-97 for bright colors.
449pub fn sgr_fg_16<W: Write>(w: &mut W, index: u8) -> io::Result<()> {
450    let code = if index < 8 {
451        30 + index
452    } else {
453        90 + index - 8
454    };
455    write!(w, "\x1b[{code}m")
456}
457
458/// Write SGR sequence for 16-color background.
459///
460/// Uses codes 40-47 for normal colors, 100-107 for bright colors.
461pub fn sgr_bg_16<W: Write>(w: &mut W, index: u8) -> io::Result<()> {
462    let code = if index < 8 {
463        40 + index
464    } else {
465        100 + index - 8
466    };
467    write!(w, "\x1b[{code}m")
468}
469
470/// Write SGR default foreground: `CSI 39 m`
471pub fn sgr_fg_default<W: Write>(w: &mut W) -> io::Result<()> {
472    w.write_all(b"\x1b[39m")
473}
474
475/// Write SGR default background: `CSI 49 m`
476pub fn sgr_bg_default<W: Write>(w: &mut W) -> io::Result<()> {
477    w.write_all(b"\x1b[49m")
478}
479
480/// Write SGR for a PackedRgba color as foreground (true color).
481///
482/// Skips if alpha is 0 (transparent).
483pub fn sgr_fg_packed<W: Write>(w: &mut W, color: PackedRgba) -> io::Result<()> {
484    if color.a() == 0 {
485        return sgr_fg_default(w);
486    }
487    sgr_fg_rgb(w, color.r(), color.g(), color.b())
488}
489
490/// Write SGR for a PackedRgba color as background (true color).
491///
492/// Skips if alpha is 0 (transparent).
493pub fn sgr_bg_packed<W: Write>(w: &mut W, color: PackedRgba) -> io::Result<()> {
494    if color.a() == 0 {
495        return sgr_bg_default(w);
496    }
497    sgr_bg_rgb(w, color.r(), color.g(), color.b())
498}
499
500// =============================================================================
501// Cursor Positioning
502// =============================================================================
503
504/// CUP (Cursor Position): `CSI row ; col H` (1-indexed)
505///
506/// Moves cursor to absolute position. Row and col are 0-indexed input,
507/// converted to 1-indexed for ANSI.
508pub fn cup<W: Write>(w: &mut W, row: u16, col: u16) -> io::Result<()> {
509    let mut buf = [0u8; 16];
510    let mut idx = 0usize;
511
512    buf[idx] = 0x1b;
513    buf[idx + 1] = b'[';
514    idx += 2;
515    idx += write_u32_dec(&mut buf[idx..], (row as u32) + 1);
516    buf[idx] = b';';
517    idx += 1;
518    idx += write_u32_dec(&mut buf[idx..], (col as u32) + 1);
519    buf[idx] = b'H';
520    idx += 1;
521
522    w.write_all(&buf[..idx])
523}
524
525/// Row the terminal clamps any larger CUP row to: its last row.
526const BOTTOM_ROW_SENTINEL: u32 = 9999;
527
528/// CUP counted from the terminal's last row: `CSI 9999 ; col H` (every
529/// terminal clamps the row to its last one), then `rows_up` rows of CUU.
530///
531/// `col` is 0-indexed. This reaches the same row of a bottom-anchored
532/// region whatever the terminal's height is when the bytes are read, so it
533/// stays correct when they were written before a resize the writer had not
534/// yet seen (an inline UI under a resizing multiplexer).
535pub fn cup_from_bottom<W: Write>(w: &mut W, rows_up: u16, col: u16) -> io::Result<()> {
536    let mut buf = [0u8; 16];
537    let mut idx = 0usize;
538
539    buf[idx] = 0x1b;
540    buf[idx + 1] = b'[';
541    idx += 2;
542    idx += write_u32_dec(&mut buf[idx..], BOTTOM_ROW_SENTINEL);
543    buf[idx] = b';';
544    idx += 1;
545    idx += write_u32_dec(&mut buf[idx..], (col as u32) + 1);
546    buf[idx] = b'H';
547    idx += 1;
548
549    w.write_all(&buf[..idx])?;
550    cuu(w, rows_up)
551}
552
553/// CUP to column only: `CSI col G` (1-indexed)
554///
555/// Moves cursor to column on current row.
556pub fn cha<W: Write>(w: &mut W, col: u16) -> io::Result<()> {
557    write_csi_u32_suffix(w, (col as u32) + 1, b'G')
558}
559
560/// Move cursor up: `CSI n A`
561pub fn cuu<W: Write>(w: &mut W, n: u16) -> io::Result<()> {
562    if n == 0 {
563        return Ok(());
564    }
565    if n == 1 {
566        w.write_all(b"\x1b[A")
567    } else {
568        write_csi_u32_suffix(w, n as u32, b'A')
569    }
570}
571
572/// Move cursor down: `CSI n B`
573pub fn cud<W: Write>(w: &mut W, n: u16) -> io::Result<()> {
574    if n == 0 {
575        return Ok(());
576    }
577    if n == 1 {
578        w.write_all(b"\x1b[B")
579    } else {
580        write_csi_u32_suffix(w, n as u32, b'B')
581    }
582}
583
584/// Move cursor forward (right): `CSI n C`
585pub fn cuf<W: Write>(w: &mut W, n: u16) -> io::Result<()> {
586    if n == 0 {
587        return Ok(());
588    }
589    if n == 1 {
590        w.write_all(b"\x1b[C")
591    } else {
592        write_csi_u32_suffix(w, n as u32, b'C')
593    }
594}
595
596/// Move cursor back (left): `CSI n D`
597pub fn cub<W: Write>(w: &mut W, n: u16) -> io::Result<()> {
598    if n == 0 {
599        return Ok(());
600    }
601    if n == 1 {
602        w.write_all(b"\x1b[D")
603    } else {
604        write_csi_u32_suffix(w, n as u32, b'D')
605    }
606}
607
608/// Move cursor to start of line: `\r` (CR)
609#[inline]
610pub fn cr<W: Write>(w: &mut W) -> io::Result<()> {
611    w.write_all(b"\r")
612}
613
614/// Move cursor down one line: `\n` (LF)
615///
616/// Note: In raw mode (OPOST disabled), this moves y+1 but preserves x.
617#[inline]
618pub fn lf<W: Write>(w: &mut W) -> io::Result<()> {
619    w.write_all(b"\n")
620}
621
622/// DEC cursor save: `ESC 7` (DECSC)
623pub const CURSOR_SAVE: &[u8] = b"\x1b7";
624
625/// DEC cursor restore: `ESC 8` (DECRC)
626pub const CURSOR_RESTORE: &[u8] = b"\x1b8";
627
628/// Write cursor save (DECSC).
629#[inline]
630pub fn cursor_save<W: Write>(w: &mut W) -> io::Result<()> {
631    w.write_all(CURSOR_SAVE)
632}
633
634/// Write cursor restore (DECRC).
635#[inline]
636pub fn cursor_restore<W: Write>(w: &mut W) -> io::Result<()> {
637    w.write_all(CURSOR_RESTORE)
638}
639
640/// Hide cursor: `CSI ? 25 l`
641pub const CURSOR_HIDE: &[u8] = b"\x1b[?25l";
642
643/// Show cursor: `CSI ? 25 h`
644pub const CURSOR_SHOW: &[u8] = b"\x1b[?25h";
645
646/// Write hide cursor.
647#[inline]
648pub fn cursor_hide<W: Write>(w: &mut W) -> io::Result<()> {
649    w.write_all(CURSOR_HIDE)
650}
651
652/// Write show cursor.
653#[inline]
654pub fn cursor_show<W: Write>(w: &mut W) -> io::Result<()> {
655    w.write_all(CURSOR_SHOW)
656}
657
658// =============================================================================
659// Erase Operations
660// =============================================================================
661
662/// EL (Erase Line) mode.
663#[derive(Debug, Clone, Copy, PartialEq, Eq)]
664pub enum EraseLineMode {
665    /// Erase from cursor to end of line.
666    ToEnd = 0,
667    /// Erase from start of line to cursor.
668    ToStart = 1,
669    /// Erase entire line.
670    All = 2,
671}
672
673/// EL (Erase Line): `CSI n K`
674pub fn erase_line<W: Write>(w: &mut W, mode: EraseLineMode) -> io::Result<()> {
675    match mode {
676        EraseLineMode::ToEnd => w.write_all(b"\x1b[K"),
677        EraseLineMode::ToStart => w.write_all(b"\x1b[1K"),
678        EraseLineMode::All => w.write_all(b"\x1b[2K"),
679    }
680}
681
682/// ED (Erase Display) mode.
683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
684pub enum EraseDisplayMode {
685    /// Erase from cursor to end of screen.
686    ToEnd = 0,
687    /// Erase from start of screen to cursor.
688    ToStart = 1,
689    /// Erase entire screen.
690    All = 2,
691    /// Erase scrollback buffer (xterm extension).
692    Scrollback = 3,
693}
694
695/// ED (Erase Display): `CSI n J`
696pub fn erase_display<W: Write>(w: &mut W, mode: EraseDisplayMode) -> io::Result<()> {
697    match mode {
698        EraseDisplayMode::ToEnd => w.write_all(b"\x1b[J"),
699        EraseDisplayMode::ToStart => w.write_all(b"\x1b[1J"),
700        EraseDisplayMode::All => w.write_all(b"\x1b[2J"),
701        EraseDisplayMode::Scrollback => w.write_all(b"\x1b[3J"),
702    }
703}
704
705// =============================================================================
706// Scroll Region
707// =============================================================================
708
709/// DECSTBM (Set Top and Bottom Margins): `CSI top ; bottom r`
710///
711/// Sets the scroll region. Top and bottom are 0-indexed, converted to 1-indexed.
712pub fn set_scroll_region<W: Write>(w: &mut W, top: u16, bottom: u16) -> io::Result<()> {
713    write!(w, "\x1b[{};{}r", (top as u32) + 1, (bottom as u32) + 1)
714}
715
716/// Reset scroll region to full screen: `CSI r`
717pub const RESET_SCROLL_REGION: &[u8] = b"\x1b[r";
718
719/// Write reset scroll region.
720#[inline]
721pub fn reset_scroll_region<W: Write>(w: &mut W) -> io::Result<()> {
722    w.write_all(RESET_SCROLL_REGION)
723}
724
725// =============================================================================
726// Synchronized Output (DEC 2026)
727// =============================================================================
728
729/// Begin synchronized output: `CSI ? 2026 h`
730pub const SYNC_BEGIN: &[u8] = b"\x1b[?2026h";
731
732/// End synchronized output: `CSI ? 2026 l`
733pub const SYNC_END: &[u8] = b"\x1b[?2026l";
734
735/// Write synchronized output begin.
736#[inline]
737pub fn sync_begin<W: Write>(w: &mut W) -> io::Result<()> {
738    w.write_all(SYNC_BEGIN)
739}
740
741/// Write synchronized output end.
742#[inline]
743pub fn sync_end<W: Write>(w: &mut W) -> io::Result<()> {
744    w.write_all(SYNC_END)
745}
746
747// =============================================================================
748// OSC 8 Hyperlinks
749// =============================================================================
750
751/// Open an OSC 8 hyperlink.
752///
753/// Format: `OSC 8 ; params ; uri BEL`
754/// Terminated with BEL (`\x07`), which terminals accept interchangeably
755/// with ST and which is what this emitter (and `hyperlink_end`) writes.
756pub fn hyperlink_start<W: Write>(w: &mut W, url: &str) -> io::Result<()> {
757    if !osc8_field_is_safe(url) {
758        return Ok(());
759    }
760    write!(w, "\x1b]8;;{url}\x07")
761}
762
763/// Close an OSC 8 hyperlink.
764///
765/// Format: `OSC 8 ; ; ST` (or BEL)
766pub fn hyperlink_end<W: Write>(w: &mut W) -> io::Result<()> {
767    w.write_all(b"\x1b]8;;\x07")
768}
769
770/// Open an OSC 8 hyperlink with an ID parameter.
771///
772/// The ID allows grouping multiple link spans.
773/// Format: `OSC 8 ; id=ID ; uri ST` (or BEL)
774pub fn hyperlink_start_with_id<W: Write>(w: &mut W, id: &str, url: &str) -> io::Result<()> {
775    // The OSC 8 params field is a COLON-separated key=value list, so a `:`
776    // (or `=`) inside the id would inject additional parameters — e.g.
777    // id "a:hover=1" parses as id=a plus hover=1, silently changing the
778    // link-grouping id. Suppress such ids like the other unsafe fields
779    // (no sequence breakout is possible either way; controls are rejected).
780    if !osc8_field_is_safe(url)
781        || !osc8_field_is_safe(id)
782        || id.contains(';')
783        || id.contains(':')
784        || id.contains('=')
785    {
786        return Ok(());
787    }
788    write!(w, "\x1b]8;id={id};{url}\x07")
789}
790
791// =============================================================================
792// Mode Control
793// =============================================================================
794
795/// Enable alternate screen: `CSI ? 1049 h`
796pub const ALT_SCREEN_ENTER: &[u8] = b"\x1b[?1049h";
797
798/// Disable alternate screen: `CSI ? 1049 l`
799pub const ALT_SCREEN_LEAVE: &[u8] = b"\x1b[?1049l";
800
801/// Enable bracketed paste: `CSI ? 2004 h`
802pub const BRACKETED_PASTE_ENABLE: &[u8] = b"\x1b[?2004h";
803
804/// Disable bracketed paste: `CSI ? 2004 l`
805pub const BRACKETED_PASTE_DISABLE: &[u8] = b"\x1b[?2004l";
806
807/// Enable SGR mouse reporting with mode-hygiene pre-reset:
808/// - reset legacy/alternate encodings (`1001/1003/1005/1015/1016`)
809/// - enable canonical SGR modes (`1000 + 1002 + 1006`)
810/// - emit `1016l` before `1006h` so SGR mode remains active on terminals
811///   where trailing `1016l` forces X10 fallback.
812///
813/// Enables:
814/// - 1000: Normal mouse tracking
815/// - 1002: Button event tracking (motion while pressed)
816/// - 1006: SGR extended coordinates (supports > 223)
817// NOTE: Set SGR format (1006) before enabling mouse event modes for better
818// compatibility with terminals that key off "last mode set" ordering.
819pub const MOUSE_ENABLE: &[u8] = b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h";
820
821/// Disable mouse reporting and clear legacy/alternate modes.
822pub const MOUSE_DISABLE: &[u8] = b"\x1b[?1000;1002;1006l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l";
823
824/// Enable focus reporting: `CSI ? 1004 h`
825pub const FOCUS_ENABLE: &[u8] = b"\x1b[?1004h";
826
827/// Disable focus reporting: `CSI ? 1004 l`
828pub const FOCUS_DISABLE: &[u8] = b"\x1b[?1004l";
829
830/// Write alternate screen enter.
831#[inline]
832pub fn alt_screen_enter<W: Write>(w: &mut W) -> io::Result<()> {
833    w.write_all(ALT_SCREEN_ENTER)
834}
835
836/// Write alternate screen leave.
837#[inline]
838pub fn alt_screen_leave<W: Write>(w: &mut W) -> io::Result<()> {
839    w.write_all(ALT_SCREEN_LEAVE)
840}
841
842/// Write bracketed paste enable.
843#[inline]
844pub fn bracketed_paste_enable<W: Write>(w: &mut W) -> io::Result<()> {
845    w.write_all(BRACKETED_PASTE_ENABLE)
846}
847
848/// Write bracketed paste disable.
849#[inline]
850pub fn bracketed_paste_disable<W: Write>(w: &mut W) -> io::Result<()> {
851    w.write_all(BRACKETED_PASTE_DISABLE)
852}
853
854/// Write mouse enable.
855#[inline]
856pub fn mouse_enable<W: Write>(w: &mut W) -> io::Result<()> {
857    w.write_all(MOUSE_ENABLE)
858}
859
860/// Write mouse disable.
861#[inline]
862pub fn mouse_disable<W: Write>(w: &mut W) -> io::Result<()> {
863    w.write_all(MOUSE_DISABLE)
864}
865
866/// Write focus enable.
867#[inline]
868pub fn focus_enable<W: Write>(w: &mut W) -> io::Result<()> {
869    w.write_all(FOCUS_ENABLE)
870}
871
872/// Write focus disable.
873#[inline]
874pub fn focus_disable<W: Write>(w: &mut W) -> io::Result<()> {
875    w.write_all(FOCUS_DISABLE)
876}
877
878// =============================================================================
879// Tests
880// =============================================================================
881
882#[cfg(test)]
883mod tests {
884    use super::*;
885
886    fn to_bytes<F: FnOnce(&mut Vec<u8>) -> io::Result<()>>(f: F) -> Vec<u8> {
887        let mut buf = Vec::new();
888        f(&mut buf).unwrap();
889        buf
890    }
891
892    // SGR Tests
893
894    #[test]
895    fn sgr_reset_bytes() {
896        assert_eq!(to_bytes(sgr_reset), b"\x1b[0m");
897    }
898
899    #[test]
900    fn sgr_flags_bold() {
901        assert_eq!(to_bytes(|w| sgr_flags(w, StyleFlags::BOLD)), b"\x1b[1m");
902    }
903
904    #[test]
905    fn sgr_flags_multiple() {
906        let flags = StyleFlags::BOLD | StyleFlags::ITALIC | StyleFlags::UNDERLINE;
907        assert_eq!(to_bytes(|w| sgr_flags(w, flags)), b"\x1b[1;3;4m");
908    }
909
910    #[test]
911    fn sgr_flags_empty() {
912        assert_eq!(to_bytes(|w| sgr_flags(w, StyleFlags::empty())), b"");
913    }
914
915    #[test]
916    fn sgr_fg_rgb_bytes() {
917        assert_eq!(
918            to_bytes(|w| sgr_fg_rgb(w, 255, 128, 0)),
919            b"\x1b[38;2;255;128;0m"
920        );
921    }
922
923    #[test]
924    fn sgr_bg_rgb_bytes() {
925        assert_eq!(to_bytes(|w| sgr_bg_rgb(w, 0, 0, 0)), b"\x1b[48;2;0;0;0m");
926    }
927
928    #[test]
929    fn dynamic_sgr_rgb_matches_reference_formatting() {
930        for (r, g, b) in [(0, 0, 0), (1, 2, 3), (9, 10, 99), (100, 200, 255)] {
931            assert_eq!(
932                to_bytes(|w| sgr_fg_rgb(w, r, g, b)),
933                format!("\x1b[38;2;{r};{g};{b}m").into_bytes()
934            );
935            assert_eq!(
936                to_bytes(|w| sgr_bg_rgb(w, r, g, b)),
937                format!("\x1b[48;2;{r};{g};{b}m").into_bytes()
938            );
939        }
940    }
941
942    #[test]
943    fn sgr_fg_256_bytes() {
944        assert_eq!(to_bytes(|w| sgr_fg_256(w, 196)), b"\x1b[38;5;196m");
945    }
946
947    #[test]
948    fn sgr_bg_256_bytes() {
949        assert_eq!(to_bytes(|w| sgr_bg_256(w, 232)), b"\x1b[48;5;232m");
950    }
951
952    #[test]
953    fn rgb_palette_downgrade_is_deterministic() {
954        assert_eq!(rgb_to_ansi256(255, 0, 0), 196);
955        assert_eq!(rgb_to_ansi256(0, 0, 255), 21);
956        assert_eq!(rgb_to_ansi256(128, 128, 128), 244);
957        assert_eq!(rgb_to_ansi256(17, 17, 17), 233);
958        assert_eq!(rgb_to_ansi16(255, 0, 0), 9);
959        assert_eq!(rgb_to_ansi16(0, 0, 255), 4);
960    }
961
962    #[test]
963    fn grayscale_downgrade_is_nearest_extended_palette_entry() {
964        for value in 0..=u8::MAX {
965            let target = (value, value, value);
966            let selected = rgb_to_ansi256(value, value, value);
967            let selected_distance = color_distance(target, ansi256_rgb(selected));
968            let nearest_distance = (16..=u8::MAX)
969                .map(|index| color_distance(target, ansi256_rgb(index)))
970                .min()
971                .unwrap();
972
973            assert_eq!(
974                selected_distance, nearest_distance,
975                "gray {value} mapped to index {selected}"
976            );
977        }
978    }
979
980    #[test]
981    fn sgr_fg_16_normal() {
982        assert_eq!(to_bytes(|w| sgr_fg_16(w, 1)), b"\x1b[31m"); // Red
983        assert_eq!(to_bytes(|w| sgr_fg_16(w, 7)), b"\x1b[37m"); // White
984    }
985
986    #[test]
987    fn sgr_fg_16_bright() {
988        assert_eq!(to_bytes(|w| sgr_fg_16(w, 9)), b"\x1b[91m"); // Bright red
989        assert_eq!(to_bytes(|w| sgr_fg_16(w, 15)), b"\x1b[97m"); // Bright white
990    }
991
992    #[test]
993    fn sgr_bg_16_normal() {
994        assert_eq!(to_bytes(|w| sgr_bg_16(w, 0)), b"\x1b[40m"); // Black
995        assert_eq!(to_bytes(|w| sgr_bg_16(w, 4)), b"\x1b[44m"); // Blue
996    }
997
998    #[test]
999    fn sgr_bg_16_bright() {
1000        assert_eq!(to_bytes(|w| sgr_bg_16(w, 8)), b"\x1b[100m"); // Bright black
1001        assert_eq!(to_bytes(|w| sgr_bg_16(w, 12)), b"\x1b[104m"); // Bright blue
1002    }
1003
1004    #[test]
1005    fn sgr_default_colors() {
1006        assert_eq!(to_bytes(sgr_fg_default), b"\x1b[39m");
1007        assert_eq!(to_bytes(sgr_bg_default), b"\x1b[49m");
1008    }
1009
1010    #[test]
1011    fn sgr_packed_transparent_uses_default() {
1012        assert_eq!(
1013            to_bytes(|w| sgr_fg_packed(w, PackedRgba::TRANSPARENT)),
1014            b"\x1b[39m"
1015        );
1016        assert_eq!(
1017            to_bytes(|w| sgr_bg_packed(w, PackedRgba::TRANSPARENT)),
1018            b"\x1b[49m"
1019        );
1020    }
1021
1022    #[test]
1023    fn sgr_packed_opaque() {
1024        let color = PackedRgba::rgb(10, 20, 30);
1025        assert_eq!(
1026            to_bytes(|w| sgr_fg_packed(w, color)),
1027            b"\x1b[38;2;10;20;30m"
1028        );
1029    }
1030
1031    // Cursor Tests
1032
1033    #[test]
1034    fn cup_1_indexed() {
1035        assert_eq!(to_bytes(|w| cup(w, 0, 0)), b"\x1b[1;1H");
1036        assert_eq!(to_bytes(|w| cup(w, 23, 79)), b"\x1b[24;80H");
1037    }
1038
1039    #[test]
1040    fn cup_from_bottom_clamps_to_the_last_row_then_moves_up() {
1041        assert_eq!(to_bytes(|w| cup_from_bottom(w, 0, 0)), b"\x1b[9999;1H");
1042        assert_eq!(
1043            to_bytes(|w| cup_from_bottom(w, 1, 6)),
1044            b"\x1b[9999;7H\x1b[A"
1045        );
1046        assert_eq!(
1047            to_bytes(|w| cup_from_bottom(w, 4, 79)),
1048            b"\x1b[9999;80H\x1b[4A"
1049        );
1050        // The largest column still fits the fixed buffer.
1051        assert_eq!(
1052            to_bytes(|w| cup_from_bottom(w, 2, u16::MAX)),
1053            b"\x1b[9999;65536H\x1b[2A"
1054        );
1055    }
1056
1057    #[test]
1058    fn cha_1_indexed() {
1059        assert_eq!(to_bytes(|w| cha(w, 0)), b"\x1b[1G");
1060        assert_eq!(to_bytes(|w| cha(w, 79)), b"\x1b[80G");
1061    }
1062
1063    #[test]
1064    fn cursor_relative_moves() {
1065        assert_eq!(to_bytes(|w| cuu(w, 1)), b"\x1b[A");
1066        assert_eq!(to_bytes(|w| cuu(w, 5)), b"\x1b[5A");
1067        assert_eq!(to_bytes(|w| cud(w, 1)), b"\x1b[B");
1068        assert_eq!(to_bytes(|w| cud(w, 3)), b"\x1b[3B");
1069        assert_eq!(to_bytes(|w| cuf(w, 1)), b"\x1b[C");
1070        assert_eq!(to_bytes(|w| cuf(w, 10)), b"\x1b[10C");
1071        assert_eq!(to_bytes(|w| cub(w, 1)), b"\x1b[D");
1072        assert_eq!(to_bytes(|w| cub(w, 2)), b"\x1b[2D");
1073    }
1074
1075    #[test]
1076    fn cursor_relative_zero_is_noop() {
1077        assert_eq!(to_bytes(|w| cuu(w, 0)), b"");
1078        assert_eq!(to_bytes(|w| cud(w, 0)), b"");
1079        assert_eq!(to_bytes(|w| cuf(w, 0)), b"");
1080        assert_eq!(to_bytes(|w| cub(w, 0)), b"");
1081    }
1082
1083    #[test]
1084    fn dynamic_cursor_sequences_match_reference_formatting() {
1085        for (row, col) in [(0, 0), (23, 79), (999, 999), (u16::MAX, u16::MAX)] {
1086            assert_eq!(
1087                to_bytes(|w| cup(w, row, col)),
1088                format!("\x1b[{};{}H", (row as u32) + 1, (col as u32) + 1).into_bytes()
1089            );
1090        }
1091
1092        for col in [0, 79, 999, u16::MAX] {
1093            assert_eq!(
1094                to_bytes(|w| cha(w, col)),
1095                format!("\x1b[{}G", (col as u32) + 1).into_bytes()
1096            );
1097        }
1098
1099        for n in [0, 1, 2, 10, 999, u16::MAX] {
1100            let expected_up = if n == 0 {
1101                Vec::new()
1102            } else if n == 1 {
1103                b"\x1b[A".to_vec()
1104            } else {
1105                format!("\x1b[{n}A").into_bytes()
1106            };
1107            let expected_down = if n == 0 {
1108                Vec::new()
1109            } else if n == 1 {
1110                b"\x1b[B".to_vec()
1111            } else {
1112                format!("\x1b[{n}B").into_bytes()
1113            };
1114            let expected_forward = if n == 0 {
1115                Vec::new()
1116            } else if n == 1 {
1117                b"\x1b[C".to_vec()
1118            } else {
1119                format!("\x1b[{n}C").into_bytes()
1120            };
1121            let expected_back = if n == 0 {
1122                Vec::new()
1123            } else if n == 1 {
1124                b"\x1b[D".to_vec()
1125            } else {
1126                format!("\x1b[{n}D").into_bytes()
1127            };
1128
1129            assert_eq!(to_bytes(|w| cuu(w, n)), expected_up);
1130            assert_eq!(to_bytes(|w| cud(w, n)), expected_down);
1131            assert_eq!(to_bytes(|w| cuf(w, n)), expected_forward);
1132            assert_eq!(to_bytes(|w| cub(w, n)), expected_back);
1133        }
1134    }
1135
1136    #[test]
1137    fn cursor_save_restore() {
1138        assert_eq!(to_bytes(cursor_save), b"\x1b7");
1139        assert_eq!(to_bytes(cursor_restore), b"\x1b8");
1140    }
1141
1142    #[test]
1143    fn cursor_visibility() {
1144        assert_eq!(to_bytes(cursor_hide), b"\x1b[?25l");
1145        assert_eq!(to_bytes(cursor_show), b"\x1b[?25h");
1146    }
1147
1148    // Erase Tests
1149
1150    #[test]
1151    fn erase_line_modes() {
1152        assert_eq!(to_bytes(|w| erase_line(w, EraseLineMode::ToEnd)), b"\x1b[K");
1153        assert_eq!(
1154            to_bytes(|w| erase_line(w, EraseLineMode::ToStart)),
1155            b"\x1b[1K"
1156        );
1157        assert_eq!(to_bytes(|w| erase_line(w, EraseLineMode::All)), b"\x1b[2K");
1158    }
1159
1160    #[test]
1161    fn erase_display_modes() {
1162        assert_eq!(
1163            to_bytes(|w| erase_display(w, EraseDisplayMode::ToEnd)),
1164            b"\x1b[J"
1165        );
1166        assert_eq!(
1167            to_bytes(|w| erase_display(w, EraseDisplayMode::ToStart)),
1168            b"\x1b[1J"
1169        );
1170        assert_eq!(
1171            to_bytes(|w| erase_display(w, EraseDisplayMode::All)),
1172            b"\x1b[2J"
1173        );
1174        assert_eq!(
1175            to_bytes(|w| erase_display(w, EraseDisplayMode::Scrollback)),
1176            b"\x1b[3J"
1177        );
1178    }
1179
1180    // Scroll Region Tests
1181
1182    #[test]
1183    fn scroll_region_1_indexed() {
1184        assert_eq!(to_bytes(|w| set_scroll_region(w, 0, 23)), b"\x1b[1;24r");
1185        assert_eq!(to_bytes(|w| set_scroll_region(w, 5, 20)), b"\x1b[6;21r");
1186    }
1187
1188    #[test]
1189    fn scroll_region_reset() {
1190        assert_eq!(to_bytes(reset_scroll_region), b"\x1b[r");
1191    }
1192
1193    // Sync Output Tests
1194
1195    #[test]
1196    fn sync_output() {
1197        assert_eq!(to_bytes(sync_begin), b"\x1b[?2026h");
1198        assert_eq!(to_bytes(sync_end), b"\x1b[?2026l");
1199    }
1200
1201    // OSC 8 Hyperlink Tests
1202
1203    #[test]
1204    fn hyperlink_basic() {
1205        assert_eq!(
1206            to_bytes(|w| hyperlink_start(w, "https://example.com")),
1207            b"\x1b]8;;https://example.com\x07"
1208        );
1209        assert_eq!(to_bytes(hyperlink_end), b"\x1b]8;;\x07");
1210    }
1211
1212    #[test]
1213    fn hyperlink_with_id() {
1214        assert_eq!(
1215            to_bytes(|w| hyperlink_start_with_id(w, "link1", "https://example.com")),
1216            b"\x1b]8;id=link1;https://example.com\x07"
1217        );
1218    }
1219
1220    #[test]
1221    fn hyperlink_rejects_control_chars() {
1222        assert_eq!(
1223            to_bytes(|w| hyperlink_start(w, "https://exa\x1bmple.com")),
1224            b""
1225        );
1226        assert_eq!(
1227            to_bytes(|w| hyperlink_start_with_id(w, "id", "https://exa\u{009d}mple.com")),
1228            b""
1229        );
1230    }
1231
1232    #[test]
1233    fn hyperlink_with_id_rejects_parameter_breakout() {
1234        assert_eq!(
1235            to_bytes(|w| hyperlink_start_with_id(w, "id;malicious=1", "https://example.com")),
1236            b""
1237        );
1238    }
1239
1240    #[test]
1241    fn hyperlink_rejects_overlong_fields() {
1242        let long_url = "x".repeat(MAX_OSC8_FIELD_BYTES + 1);
1243        assert_eq!(to_bytes(|w| hyperlink_start(w, &long_url)), b"");
1244
1245        let long_id = "x".repeat(MAX_OSC8_FIELD_BYTES + 1);
1246        assert_eq!(
1247            to_bytes(|w| hyperlink_start_with_id(w, &long_id, "https://example.com")),
1248            b""
1249        );
1250    }
1251
1252    // Mode Control Tests
1253
1254    #[test]
1255    fn alt_screen() {
1256        assert_eq!(to_bytes(alt_screen_enter), b"\x1b[?1049h");
1257        assert_eq!(to_bytes(alt_screen_leave), b"\x1b[?1049l");
1258    }
1259
1260    #[test]
1261    fn bracketed_paste() {
1262        assert_eq!(to_bytes(bracketed_paste_enable), b"\x1b[?2004h");
1263        assert_eq!(to_bytes(bracketed_paste_disable), b"\x1b[?2004l");
1264    }
1265
1266    #[test]
1267    fn mouse_mode() {
1268        assert_eq!(
1269            to_bytes(mouse_enable),
1270            b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h"
1271        );
1272        assert_eq!(
1273            to_bytes(mouse_disable),
1274            b"\x1b[?1000;1002;1006l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l"
1275        );
1276
1277        let enabled = to_bytes(mouse_enable);
1278        assert!(
1279            !enabled.ends_with(b"\x1b[?1016l"),
1280            "mouse enable should not end with 1016l (can force X10 fallback)"
1281        );
1282        let pos_1016l = enabled
1283            .windows(b"\x1b[?1016l".len())
1284            .position(|w| w == b"\x1b[?1016l")
1285            .expect("mouse enable should clear 1016 before enabling SGR");
1286        let pos_1006h = enabled
1287            .windows(b"\x1b[?1006h".len())
1288            .position(|w| w == b"\x1b[?1006h")
1289            .expect("mouse enable should include 1006h");
1290        assert!(
1291            pos_1016l < pos_1006h,
1292            "1016l must be emitted before 1006h to preserve SGR mode"
1293        );
1294    }
1295
1296    #[test]
1297    fn focus_mode() {
1298        assert_eq!(to_bytes(focus_enable), b"\x1b[?1004h");
1299        assert_eq!(to_bytes(focus_disable), b"\x1b[?1004l");
1300    }
1301
1302    // Property tests
1303
1304    #[test]
1305    fn all_sequences_are_ascii() {
1306        // Verify no high bytes in any constant sequences
1307        for seq in [
1308            SGR_RESET,
1309            CURSOR_SAVE,
1310            CURSOR_RESTORE,
1311            CURSOR_HIDE,
1312            CURSOR_SHOW,
1313            RESET_SCROLL_REGION,
1314            SYNC_BEGIN,
1315            SYNC_END,
1316            ALT_SCREEN_ENTER,
1317            ALT_SCREEN_LEAVE,
1318            BRACKETED_PASTE_ENABLE,
1319            BRACKETED_PASTE_DISABLE,
1320            MOUSE_ENABLE,
1321            MOUSE_DISABLE,
1322            FOCUS_ENABLE,
1323            FOCUS_DISABLE,
1324        ] {
1325            for &byte in seq {
1326                assert!(byte < 128, "Non-ASCII byte {byte:#x} in sequence");
1327            }
1328        }
1329    }
1330
1331    #[test]
1332    fn osc_sequences_are_terminated() {
1333        // All OSC 8 sequences must end with BEL
1334        let link_start = to_bytes(|w| hyperlink_start(w, "test"));
1335        assert!(
1336            link_start.ends_with(b"\x07"),
1337            "hyperlink_start not terminated with BEL"
1338        );
1339
1340        let link_end = to_bytes(hyperlink_end);
1341        assert!(
1342            link_end.ends_with(b"\x07"),
1343            "hyperlink_end not terminated with BEL"
1344        );
1345
1346        let link_id = to_bytes(|w| hyperlink_start_with_id(w, "id", "url"));
1347        assert!(
1348            link_id.ends_with(b"\x07"),
1349            "hyperlink_start_with_id not terminated with BEL"
1350        );
1351    }
1352
1353    #[test]
1354    fn hyperlink_id_with_param_separators_is_suppressed() {
1355        // Regression: the OSC 8 params field is colon-separated key=value;
1356        // ':' or '=' in the id injected extra parameters (id "a:hover=1"
1357        // parsed as id=a + hover=1). Such ids are suppressed like other
1358        // unsafe fields.
1359        for bad_id in ["a:hover=1", "x:y", "k=v"] {
1360            let mut buf = Vec::new();
1361            hyperlink_start_with_id(&mut buf, bad_id, "https://example.com").unwrap();
1362            assert!(buf.is_empty(), "id {bad_id:?} must be suppressed");
1363        }
1364        // Plain ids still emit.
1365        let mut buf = Vec::new();
1366        hyperlink_start_with_id(&mut buf, "group-1", "https://example.com").unwrap();
1367        assert_eq!(buf, b"\x1b]8;id=group-1;https://example.com\x07");
1368    }
1369
1370    // ---- sgr_flags_off tests ----
1371
1372    #[test]
1373    fn sgr_flags_off_empty_is_noop() {
1374        let bytes = to_bytes(|w| {
1375            sgr_flags_off(w, StyleFlags::empty(), StyleFlags::empty()).unwrap();
1376            Ok(())
1377        });
1378        assert!(bytes.is_empty(), "disabling no flags should emit nothing");
1379    }
1380
1381    #[test]
1382    fn sgr_flags_off_single_bold() {
1383        let mut buf = Vec::new();
1384        let collateral = sgr_flags_off(&mut buf, StyleFlags::BOLD, StyleFlags::empty()).unwrap();
1385        assert_eq!(buf, b"\x1b[22m");
1386        assert!(collateral.is_empty(), "no collateral when DIM is not kept");
1387    }
1388
1389    #[test]
1390    fn sgr_flags_off_single_dim() {
1391        let mut buf = Vec::new();
1392        let collateral = sgr_flags_off(&mut buf, StyleFlags::DIM, StyleFlags::empty()).unwrap();
1393        assert_eq!(buf, b"\x1b[22m");
1394        assert!(collateral.is_empty(), "no collateral when BOLD is not kept");
1395    }
1396
1397    #[test]
1398    fn sgr_flags_off_bold_collateral_dim() {
1399        // Disabling BOLD while DIM should stay → collateral = DIM
1400        let mut buf = Vec::new();
1401        let collateral = sgr_flags_off(&mut buf, StyleFlags::BOLD, StyleFlags::DIM).unwrap();
1402        assert_eq!(buf, b"\x1b[22m");
1403        assert_eq!(collateral, StyleFlags::DIM);
1404    }
1405
1406    #[test]
1407    fn sgr_flags_off_dim_collateral_bold() {
1408        // Disabling DIM while BOLD should stay → collateral = BOLD
1409        let mut buf = Vec::new();
1410        let collateral = sgr_flags_off(&mut buf, StyleFlags::DIM, StyleFlags::BOLD).unwrap();
1411        assert_eq!(buf, b"\x1b[22m");
1412        assert_eq!(collateral, StyleFlags::BOLD);
1413    }
1414
1415    #[test]
1416    fn sgr_flags_off_italic() {
1417        let mut buf = Vec::new();
1418        let collateral = sgr_flags_off(&mut buf, StyleFlags::ITALIC, StyleFlags::empty()).unwrap();
1419        assert_eq!(buf, b"\x1b[23m");
1420        assert!(collateral.is_empty());
1421    }
1422
1423    #[test]
1424    fn sgr_flags_off_underline() {
1425        let mut buf = Vec::new();
1426        let collateral =
1427            sgr_flags_off(&mut buf, StyleFlags::UNDERLINE, StyleFlags::empty()).unwrap();
1428        assert_eq!(buf, b"\x1b[24m");
1429        assert!(collateral.is_empty());
1430    }
1431
1432    #[test]
1433    fn sgr_flags_off_blink() {
1434        let mut buf = Vec::new();
1435        let collateral = sgr_flags_off(&mut buf, StyleFlags::BLINK, StyleFlags::empty()).unwrap();
1436        assert_eq!(buf, b"\x1b[25m");
1437        assert!(collateral.is_empty());
1438    }
1439
1440    #[test]
1441    fn sgr_flags_off_reverse() {
1442        let mut buf = Vec::new();
1443        let collateral = sgr_flags_off(&mut buf, StyleFlags::REVERSE, StyleFlags::empty()).unwrap();
1444        assert_eq!(buf, b"\x1b[27m");
1445        assert!(collateral.is_empty());
1446    }
1447
1448    #[test]
1449    fn sgr_flags_off_hidden() {
1450        let mut buf = Vec::new();
1451        let collateral = sgr_flags_off(&mut buf, StyleFlags::HIDDEN, StyleFlags::empty()).unwrap();
1452        assert_eq!(buf, b"\x1b[28m");
1453        assert!(collateral.is_empty());
1454    }
1455
1456    #[test]
1457    fn sgr_flags_off_strikethrough() {
1458        let mut buf = Vec::new();
1459        let collateral =
1460            sgr_flags_off(&mut buf, StyleFlags::STRIKETHROUGH, StyleFlags::empty()).unwrap();
1461        assert_eq!(buf, b"\x1b[29m");
1462        assert!(collateral.is_empty());
1463    }
1464
1465    #[test]
1466    fn sgr_flags_off_multi_no_bold_dim_overlap() {
1467        // Disable ITALIC + UNDERLINE (no shared off codes)
1468        let mut buf = Vec::new();
1469        let collateral = sgr_flags_off(
1470            &mut buf,
1471            StyleFlags::ITALIC | StyleFlags::UNDERLINE,
1472            StyleFlags::empty(),
1473        )
1474        .unwrap();
1475        // Multi-flag path emits individual off codes in FLAG_TABLE order.
1476        assert_eq!(buf, b"\x1b[23m\x1b[24m");
1477        assert!(collateral.is_empty());
1478    }
1479
1480    #[test]
1481    fn sgr_flags_off_bold_and_dim_together() {
1482        // Disabling both BOLD and DIM: off=22 emitted for each, but no collateral
1483        // since both are being disabled (neither needs to stay)
1484        let mut buf = Vec::new();
1485        let collateral = sgr_flags_off(
1486            &mut buf,
1487            StyleFlags::BOLD | StyleFlags::DIM,
1488            StyleFlags::empty(),
1489        )
1490        .unwrap();
1491        assert_eq!(buf, b"\x1b[22m\x1b[22m");
1492        assert!(
1493            collateral.is_empty(),
1494            "no collateral when both are disabled"
1495        );
1496    }
1497
1498    #[test]
1499    fn sgr_flags_off_overlap_keep_and_disable_does_not_report_collateral() {
1500        // Overlapping keep/disable can happen in defensive callers; disabling should win.
1501        let mut buf = Vec::new();
1502        let collateral = sgr_flags_off(
1503            &mut buf,
1504            StyleFlags::BOLD | StyleFlags::DIM,
1505            StyleFlags::DIM,
1506        )
1507        .unwrap();
1508        assert_eq!(buf, b"\x1b[22m\x1b[22m");
1509        assert!(
1510            collateral.is_empty(),
1511            "DIM is explicitly disabled, so it must not be reported as collateral"
1512        );
1513    }
1514
1515    #[test]
1516    fn sgr_flags_off_bold_dim_with_dim_kept() {
1517        // Disabling BOLD + ITALIC while DIM should stay
1518        let mut buf = Vec::new();
1519        let collateral = sgr_flags_off(
1520            &mut buf,
1521            StyleFlags::BOLD | StyleFlags::ITALIC,
1522            StyleFlags::DIM,
1523        )
1524        .unwrap();
1525        assert_eq!(
1526            collateral,
1527            StyleFlags::DIM,
1528            "DIM should be collateral damage from BOLD off (code 22)"
1529        );
1530    }
1531
1532    // ---- sgr_codes_for_flag tests ----
1533
1534    #[test]
1535    fn sgr_codes_for_all_single_flags() {
1536        let cases = [
1537            (StyleFlags::BOLD, 1, 22),
1538            (StyleFlags::DIM, 2, 22),
1539            (StyleFlags::ITALIC, 3, 23),
1540            (StyleFlags::UNDERLINE, 4, 24),
1541            (StyleFlags::BLINK, 5, 25),
1542            (StyleFlags::REVERSE, 7, 27),
1543            (StyleFlags::HIDDEN, 8, 28),
1544            (StyleFlags::STRIKETHROUGH, 9, 29),
1545        ];
1546        for (flag, expected_on, expected_off) in cases {
1547            let codes = sgr_codes_for_flag(flag)
1548                .unwrap_or_else(|| panic!("should return codes for {flag:?}"));
1549            assert_eq!(codes.on, expected_on, "on code for {flag:?}");
1550            assert_eq!(codes.off, expected_off, "off code for {flag:?}");
1551        }
1552    }
1553
1554    #[test]
1555    fn sgr_codes_for_composite_flag_returns_none() {
1556        let composite = StyleFlags::BOLD | StyleFlags::ITALIC;
1557        assert!(
1558            sgr_codes_for_flag(composite).is_none(),
1559            "composite flags should return None"
1560        );
1561    }
1562
1563    #[test]
1564    fn sgr_codes_for_empty_flag_returns_none() {
1565        assert!(
1566            sgr_codes_for_flag(StyleFlags::empty()).is_none(),
1567            "empty flags should return None"
1568        );
1569    }
1570
1571    #[test]
1572    fn sgr_codes_for_flag_matches_flag_table_entries() {
1573        for (flag, expected) in FLAG_TABLE {
1574            let actual = sgr_codes_for_flag(flag).expect("single-bit FLAG_TABLE entry");
1575            assert_eq!(actual.on, expected.on, "{flag:?} on code");
1576            assert_eq!(actual.off, expected.off, "{flag:?} off code");
1577        }
1578    }
1579
1580    // ---- cr / lf tests ----
1581
1582    #[test]
1583    fn cr_emits_carriage_return() {
1584        assert_eq!(to_bytes(cr), b"\r");
1585    }
1586
1587    #[test]
1588    fn lf_emits_line_feed() {
1589        assert_eq!(to_bytes(lf), b"\n");
1590    }
1591
1592    // ---- sgr_flags individual fast-path verification ----
1593
1594    #[test]
1595    fn sgr_flags_each_single_flag_fast_path() {
1596        let cases: &[(StyleFlags, &[u8])] = &[
1597            (StyleFlags::BOLD, b"\x1b[1m"),
1598            (StyleFlags::DIM, b"\x1b[2m"),
1599            (StyleFlags::ITALIC, b"\x1b[3m"),
1600            (StyleFlags::UNDERLINE, b"\x1b[4m"),
1601            (StyleFlags::BLINK, b"\x1b[5m"),
1602            (StyleFlags::REVERSE, b"\x1b[7m"),
1603            (StyleFlags::STRIKETHROUGH, b"\x1b[9m"),
1604            (StyleFlags::HIDDEN, b"\x1b[8m"),
1605        ];
1606        for &(flag, expected) in cases {
1607            assert_eq!(
1608                to_bytes(|w| sgr_flags(w, flag)),
1609                expected,
1610                "single-flag fast path for {flag:?}"
1611            );
1612        }
1613    }
1614
1615    #[test]
1616    fn sgr_flags_all_eight() {
1617        let all = StyleFlags::BOLD
1618            | StyleFlags::DIM
1619            | StyleFlags::ITALIC
1620            | StyleFlags::UNDERLINE
1621            | StyleFlags::BLINK
1622            | StyleFlags::REVERSE
1623            | StyleFlags::HIDDEN
1624            | StyleFlags::STRIKETHROUGH;
1625        let bytes = to_bytes(|w| sgr_flags(w, all));
1626        // Should emit CSI with codes in FLAG_TABLE order: 1;2;3;4;5;7;8;9
1627        assert_eq!(bytes, b"\x1b[1;2;3;4;5;7;8;9m");
1628    }
1629
1630    // ---- write_u8_dec boundary verification (via sgr_code) ----
1631
1632    #[test]
1633    fn sgr_code_single_digit() {
1634        // code=1 → "\x1b[1m" (1 digit)
1635        let mut buf = Vec::new();
1636        write_sgr_code(&mut buf, 1).unwrap();
1637        assert_eq!(buf, b"\x1b[1m");
1638    }
1639
1640    #[test]
1641    fn sgr_code_two_digits() {
1642        // code=22 → "\x1b[22m" (2 digits)
1643        let mut buf = Vec::new();
1644        write_sgr_code(&mut buf, 22).unwrap();
1645        assert_eq!(buf, b"\x1b[22m");
1646    }
1647
1648    #[test]
1649    fn sgr_code_three_digits() {
1650        // code=100 → "\x1b[100m" (3 digits)
1651        let mut buf = Vec::new();
1652        write_sgr_code(&mut buf, 100).unwrap();
1653        assert_eq!(buf, b"\x1b[100m");
1654    }
1655
1656    #[test]
1657    fn sgr_code_max_u8() {
1658        // code=255 → "\x1b[255m"
1659        let mut buf = Vec::new();
1660        write_sgr_code(&mut buf, 255).unwrap();
1661        assert_eq!(buf, b"\x1b[255m");
1662    }
1663
1664    #[test]
1665    fn sgr_code_zero() {
1666        let mut buf = Vec::new();
1667        write_sgr_code(&mut buf, 0).unwrap();
1668        assert_eq!(buf, b"\x1b[0m");
1669    }
1670
1671    // ---- 16-color boundary tests ----
1672
1673    #[test]
1674    fn sgr_fg_16_boundary_7_to_8() {
1675        // Index 7 is the last normal color, 8 is first bright
1676        assert_eq!(to_bytes(|w| sgr_fg_16(w, 7)), b"\x1b[37m");
1677        assert_eq!(to_bytes(|w| sgr_fg_16(w, 8)), b"\x1b[90m");
1678    }
1679
1680    #[test]
1681    fn sgr_bg_16_boundary_7_to_8() {
1682        assert_eq!(to_bytes(|w| sgr_bg_16(w, 7)), b"\x1b[47m");
1683        assert_eq!(to_bytes(|w| sgr_bg_16(w, 8)), b"\x1b[100m");
1684    }
1685
1686    #[test]
1687    fn sgr_fg_16_first_color() {
1688        assert_eq!(to_bytes(|w| sgr_fg_16(w, 0)), b"\x1b[30m"); // Black
1689    }
1690
1691    #[test]
1692    fn sgr_bg_16_last_bright() {
1693        assert_eq!(to_bytes(|w| sgr_bg_16(w, 15)), b"\x1b[107m"); // Bright white
1694    }
1695
1696    // ---- 256-color boundary tests ----
1697
1698    #[test]
1699    fn sgr_fg_256_zero() {
1700        assert_eq!(to_bytes(|w| sgr_fg_256(w, 0)), b"\x1b[38;5;0m");
1701    }
1702
1703    #[test]
1704    fn sgr_fg_256_max() {
1705        assert_eq!(to_bytes(|w| sgr_fg_256(w, 255)), b"\x1b[38;5;255m");
1706    }
1707
1708    #[test]
1709    fn sgr_bg_256_zero() {
1710        assert_eq!(to_bytes(|w| sgr_bg_256(w, 0)), b"\x1b[48;5;0m");
1711    }
1712
1713    #[test]
1714    fn sgr_bg_256_max() {
1715        assert_eq!(to_bytes(|w| sgr_bg_256(w, 255)), b"\x1b[48;5;255m");
1716    }
1717
1718    // ---- cursor positioning edge cases ----
1719
1720    #[test]
1721    fn cup_max_u16() {
1722        // u16::MAX saturating_add(1) wraps correctly
1723        let bytes = to_bytes(|w| cup(w, u16::MAX, u16::MAX));
1724        let s = String::from_utf8(bytes).unwrap();
1725        assert!(s.starts_with("\x1b["));
1726        assert!(s.ends_with("H"));
1727    }
1728
1729    #[test]
1730    fn cha_max_u16() {
1731        let bytes = to_bytes(|w| cha(w, u16::MAX));
1732        let s = String::from_utf8(bytes).unwrap();
1733        assert!(s.starts_with("\x1b["));
1734        assert!(s.ends_with("G"));
1735    }
1736
1737    #[test]
1738    fn cursor_up_max() {
1739        let bytes = to_bytes(|w| cuu(w, u16::MAX));
1740        let s = String::from_utf8(bytes).unwrap();
1741        assert!(s.contains("65535"));
1742        assert!(s.ends_with("A"));
1743    }
1744
1745    // ---- scroll region edge cases ----
1746
1747    #[test]
1748    fn scroll_region_same_top_bottom() {
1749        assert_eq!(to_bytes(|w| set_scroll_region(w, 5, 5)), b"\x1b[6;6r");
1750    }
1751
1752    // ---- sgr_flags_off single-flag off-seq fast path (all 8 flags) ----
1753
1754    #[test]
1755    fn sgr_flags_off_each_single_flag_fast_path() {
1756        let cases: &[(StyleFlags, &[u8])] = &[
1757            (StyleFlags::BOLD, b"\x1b[22m"),
1758            (StyleFlags::DIM, b"\x1b[22m"),
1759            (StyleFlags::ITALIC, b"\x1b[23m"),
1760            (StyleFlags::UNDERLINE, b"\x1b[24m"),
1761            (StyleFlags::BLINK, b"\x1b[25m"),
1762            (StyleFlags::REVERSE, b"\x1b[27m"),
1763            (StyleFlags::STRIKETHROUGH, b"\x1b[29m"),
1764            (StyleFlags::HIDDEN, b"\x1b[28m"),
1765        ];
1766        for &(flag, expected) in cases {
1767            let mut buf = Vec::new();
1768            let collateral = sgr_flags_off(&mut buf, flag, StyleFlags::empty()).unwrap();
1769            assert_eq!(buf, expected, "off sequence for {flag:?}");
1770            assert!(collateral.is_empty(), "no collateral for {flag:?}");
1771        }
1772    }
1773
1774    // ---- sgr_packed with non-zero alpha ----
1775
1776    #[test]
1777    fn sgr_bg_packed_opaque() {
1778        let color = PackedRgba::rgb(100, 200, 50);
1779        assert_eq!(
1780            to_bytes(|w| sgr_bg_packed(w, color)),
1781            b"\x1b[48;2;100;200;50m"
1782        );
1783    }
1784
1785    // ---- hyperlink with empty url/id ----
1786
1787    #[test]
1788    fn hyperlink_empty_url() {
1789        assert_eq!(to_bytes(|w| hyperlink_start(w, "")), b"\x1b]8;;\x07");
1790    }
1791
1792    #[test]
1793    fn hyperlink_with_empty_id() {
1794        assert_eq!(
1795            to_bytes(|w| hyperlink_start_with_id(w, "", "https://x.com")),
1796            b"\x1b]8;id=;https://x.com\x07"
1797        );
1798    }
1799
1800    // ---- all dynamic sequences start with ESC ----
1801
1802    #[test]
1803    fn all_dynamic_sequences_start_with_esc() {
1804        let sequences: Vec<Vec<u8>> = vec![
1805            to_bytes(sgr_reset),
1806            to_bytes(|w| sgr_flags(w, StyleFlags::BOLD)),
1807            to_bytes(|w| sgr_fg_rgb(w, 1, 2, 3)),
1808            to_bytes(|w| sgr_bg_rgb(w, 1, 2, 3)),
1809            to_bytes(|w| sgr_fg_256(w, 42)),
1810            to_bytes(|w| sgr_bg_256(w, 42)),
1811            to_bytes(|w| sgr_fg_16(w, 5)),
1812            to_bytes(|w| sgr_bg_16(w, 5)),
1813            to_bytes(sgr_fg_default),
1814            to_bytes(sgr_bg_default),
1815            to_bytes(|w| cup(w, 0, 0)),
1816            to_bytes(|w| cha(w, 0)),
1817            to_bytes(|w| cuu(w, 1)),
1818            to_bytes(|w| cud(w, 1)),
1819            to_bytes(|w| cuf(w, 1)),
1820            to_bytes(|w| cub(w, 1)),
1821            to_bytes(cursor_save),
1822            to_bytes(cursor_restore),
1823            to_bytes(cursor_hide),
1824            to_bytes(cursor_show),
1825            to_bytes(|w| erase_line(w, EraseLineMode::All)),
1826            to_bytes(|w| erase_display(w, EraseDisplayMode::All)),
1827            to_bytes(|w| set_scroll_region(w, 0, 23)),
1828            to_bytes(reset_scroll_region),
1829            to_bytes(sync_begin),
1830            to_bytes(sync_end),
1831            to_bytes(|w| hyperlink_start(w, "test")),
1832            to_bytes(hyperlink_end),
1833            to_bytes(alt_screen_enter),
1834            to_bytes(alt_screen_leave),
1835            to_bytes(bracketed_paste_enable),
1836            to_bytes(bracketed_paste_disable),
1837            to_bytes(mouse_enable),
1838            to_bytes(mouse_disable),
1839            to_bytes(focus_enable),
1840            to_bytes(focus_disable),
1841        ];
1842        for (i, seq) in sequences.iter().enumerate() {
1843            assert!(
1844                seq.starts_with(b"\x1b"),
1845                "sequence {i} should start with ESC, got {seq:?}"
1846            );
1847        }
1848    }
1849}