nativelite-vterm 0.5.1

A minimal terminal-emulator core: child VT output bytes in, a live ansi::Screen out. Zero third-party dependencies; depends only on the nativelite ansi and uwidth crates.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! The terminal emulator: bytes in, a live [`ansi::Screen`] out.
//!
//! [`Term`] holds a primary and an alternate [`ansi::Screen`] (the active one
//! owns the cursor — there is no second copy to keep in sync), the
//! current SGR [`ansi::Style`], a scroll region, tab stops, a saved-cursor
//! slot, and the flags a VT100 tracks (autowrap, cursor visibility, and the
//! pending-wrap latch at the right edge). [`Term::feed`] runs the child's
//! output through an internal [`ansi::Parser`] and applies each token.
//!
//! Coordinates are 0-based internally; CSI parameters are 1-based on the wire
//! and converted on the way in. Where VT defaults a missing parameter to 1
//! (cursor motion, CUP), we treat a 0 from the parser as that default; where
//! it defaults to 0 (erase/SGR selectors), 0 is used directly.

use ansi::{Cell, Cursor, Parser, Screen, Style, Token};

/// A minimal VT100/ECMA-48 terminal emulator over an [`ansi::Screen`].
pub struct Term {
    /// The primary (normal) screen buffer.
    primary: Screen,
    /// The alternate screen buffer, used while an app enters alt-screen mode
    /// (`?1049h`/`?47h`/`?1047h`). Kept the same size as `primary`.
    alt: Screen,
    /// True while the alternate buffer is active.
    in_alt: bool,
    /// Current SGR style applied to newly written cells.
    style: Style,
    /// Scroll region, 0-based inclusive `[top, bottom]` (DECSTBM).
    scroll_top: usize,
    scroll_bottom: usize,
    /// Saved cursor state (DECSC/`ESC 7` and CSI `s`): position and style.
    saved: Option<(Cursor, Style)>,
    /// Tab stops: `tabs[c]` true means a tab stop at column `c`.
    tabs: Vec<bool>,
    /// Pending-wrap latch: set after writing the last column so the *next*
    /// printable wraps to the next line first (DECAWM deferred-wrap).
    wrap_pending: bool,
    /// Autowrap mode (DECAWM). Default on.
    autowrap: bool,
    /// Cursor visibility (DECTCEM, `?25h`/`?25l`). Tracked for the host; the
    /// screen cursor position is always synced regardless.
    cursor_visible: bool,
    /// The parser driving `feed`; one per stream so mid-sequence chunk splits
    /// are handled by `ansi`.
    parser: Parser,
    /// Set to `true` by `feed` (non-empty bytes) and `resize`; reset and
    /// returned by `take_dirty`. Lets callers skip a composite when nothing
    /// has changed since the last rendered frame.
    dirty: bool,
    /// Synchronized-output depth (DEC private mode 2026, `?2026h`/`?2026l`).
    /// While an app is inside a synchronized update it is redrawing the frame;
    /// a compositor that samples the screen mid-update sees a half-drawn frame
    /// (leftover/overlapping text). While `in_sync`, [`Term::screen`] hands back
    /// `sync_frame`, a clone of the last *complete* frame captured when the
    /// update opened, so external readers only ever see whole frames. Writes
    /// still land on the live buffer; the new frame is revealed on `?2026l`.
    in_sync: bool,
    /// The last complete frame, snapshotted when a synchronized update opens.
    /// `Some` exactly while `in_sync`; `None` otherwise.
    sync_frame: Option<Screen>,
}

impl Term {
    /// A blank emulator of `rows x cols` (both clamped to at least 1), cursor
    /// at the origin, full-height scroll region, default tab stops every 8
    /// columns, autowrap on, cursor visible.
    pub fn new(rows: usize, cols: usize) -> Self {
        let rows = rows.max(1);
        let cols = cols.max(1);
        Term {
            primary: Screen::new(rows, cols),
            alt: Screen::new(rows, cols),
            in_alt: false,
            style: Style::default(),
            scroll_top: 0,
            scroll_bottom: rows - 1,
            saved: None,
            tabs: default_tabs(cols),
            wrap_pending: false,
            autowrap: true,
            cursor_visible: true,
            parser: Parser::new(),
            dirty: false,
            in_sync: false,
            sync_frame: None,
        }
    }

    /// Feed a chunk of child output. Chunks may split at any byte boundary
    /// (mid-escape, mid-UTF-8); the internal parser holds partial state across
    /// calls, so the final screen is independent of how bytes were chunked.
    pub fn feed(&mut self, bytes: &[u8]) {
        if bytes.is_empty() {
            return;
        }
        self.dirty = true;
        let tokens = self.parser.feed(bytes);
        for tok in tokens {
            self.apply(&tok);
        }
    }

    /// Returns `true` if any bytes have been fed (or a resize has occurred)
    /// since the last call to `take_dirty`, and resets the flag. Call once
    /// per frame decision to avoid redundant compositing.
    pub fn take_dirty(&mut self) -> bool {
        std::mem::replace(&mut self.dirty, false)
    }

    /// The active buffer (alternate while in alt-screen, else primary). Its
    /// cursor is the emulator's cursor, so a compositor / `Screen::diff` parks
    /// the terminal cursor correctly.
    pub fn screen(&self) -> &Screen {
        // The active buffer owns the cursor, so it is always current. While a
        // synchronized update (`?2026h`) is open we hand back the last complete
        // frame instead of the live, half-drawn buffer (double-buffering).
        match &self.sync_frame {
            Some(frame) => frame,
            None => self.active(),
        }
    }

    /// True while the child is inside a synchronized update (DEC mode 2026):
    /// it has emitted `?2026h` and not yet the matching `?2026l`. During this
    /// window [`Term::screen`] returns the last complete frame. Exposed so a
    /// host can also gate its own compositing on it if desired.
    pub fn in_sync(&self) -> bool {
        self.in_sync
    }

    /// Resize to `rows x cols` (clamped to at least 1). For 0.1 this rebuilds
    /// fresh buffers of the new size (the caller repaints); the cursor and
    /// scroll region are clamped, tab stops rebuilt, and pending wrap cleared.
    pub fn resize(&mut self, rows: usize, cols: usize) {
        let rows = rows.max(1);
        let cols = cols.max(1);
        let cursor = self.cursor();
        let old_primary = std::mem::replace(&mut self.primary, Screen::new(rows, cols));
        let old_alt = std::mem::replace(&mut self.alt, Screen::new(rows, cols));
        copy_top_left(&old_primary, &mut self.primary);
        copy_top_left(&old_alt, &mut self.alt);
        self.scroll_top = self.scroll_top.min(rows - 1);
        self.scroll_bottom = rows - 1;
        // The fresh active buffer takes the cursor, clamped onto the new size.
        self.active_mut().set_cursor(cursor);
        self.tabs = default_tabs(cols);
        self.wrap_pending = false;
        // A resize rebuilds the buffers; any held sync frame is now the wrong
        // size and stale. Drop it and reveal the freshly-sized live buffer.
        self.in_sync = false;
        self.sync_frame = None;
        self.dirty = true;
    }

    // --- internals --------------------------------------------------------

    fn active(&self) -> &Screen {
        if self.in_alt {
            &self.alt
        } else {
            &self.primary
        }
    }

    fn active_mut(&mut self) -> &mut Screen {
        if self.in_alt {
            &mut self.alt
        } else {
            &mut self.primary
        }
    }

    fn rows(&self) -> usize {
        self.active().rows()
    }

    fn cols(&self) -> usize {
        self.active().cols()
    }

    /// The emulator cursor: the active buffer's.
    fn cursor(&self) -> Cursor {
        self.active().cursor()
    }

    fn set_row(&mut self, row: usize) {
        let col = self.cursor().col;
        self.active_mut().set_cursor(Cursor { row, col });
    }

    fn set_col(&mut self, col: usize) {
        let row = self.cursor().row;
        self.active_mut().set_cursor(Cursor { row, col });
    }

    fn apply(&mut self, tok: &Token) {
        match tok {
            Token::Text(s) => {
                for ch in s.chars() {
                    self.print(ch);
                }
            }
            Token::Control(b) => self.control(*b),
            Token::Csi {
                private,
                params,
                final_byte,
                ..
            } => self.csi(*private, params, *final_byte),
            Token::Esc { final_byte, .. } => self.esc(*final_byte),
            // Titles, DCS/SOS/PM/APC strings: nothing to render.
            Token::Osc(_) | Token::Other { .. } => {}
        }
    }

    /// Write one printable character at the cursor, honoring autowrap via the
    /// pending-wrap latch and East Asian double-width via [`uwidth`].
    ///
    /// A width-2 glyph (CJK, fullwidth, emoji) occupies two columns: its left
    /// half is a [`Cell::wide`] carrying the character, its right half a
    /// [`Cell::continuation`] carrying no glyph. The cursor advances by two. A
    /// wide glyph that would straddle the right edge is not split — the whole
    /// glyph wraps to the next line (autowrap on) or is dropped (autowrap off),
    /// matching real terminals. Zero-width characters (combining marks, joiners,
    /// variation selectors) are dropped: this grid stores one character per
    /// cell and cannot compose them, and dropping avoids the column drift that
    /// giving them a cell of their own would cause.
    fn print(&mut self, ch: char) {
        let w = uwidth::char_width(ch) as usize;

        // Zero-width: no cell, no cursor movement (see doc comment).
        if w == 0 {
            return;
        }

        if self.wrap_pending && self.autowrap {
            // The previous write filled the last column; wrap now.
            self.set_col(0);
            self.line_feed();
            self.wrap_pending = false;
        }

        // A double-width glyph needs two columns; if only one remains it cannot
        // be split. Wrap the whole glyph to the next line (or drop it when
        // autowrap is off, rather than overwrite half a cell at the edge).
        if w == 2 && self.cursor().col + 1 >= self.cols() {
            if !self.autowrap {
                return;
            }
            self.set_col(0);
            self.line_feed();
            self.wrap_pending = false;
        }

        // The per-character hot path borrows the active buffer once for the
        // cells and the cursor together (field-disjoint, so `self.wrap_pending`
        // stays writable below).
        let (autowrap, style) = (self.autowrap, self.style);
        let screen = if self.in_alt {
            &mut self.alt
        } else {
            &mut self.primary
        };
        let cols = screen.cols();
        let Cursor { row: r, col: c } = screen.cursor();
        if w == 2 {
            screen.set(r, c, Cell::wide(ch, style));
            screen.set(r, c + 1, Cell::continuation(style));
        } else {
            screen.set(r, c, Cell::new(ch, style));
        }
        // Advance by the glyph's width. If that lands at or past the last
        // column, stay at the last column and latch a pending wrap (deferred to
        // the next printable), matching real terminals and the `ansi` diff's
        // pending-wrap comment. A width-1 glyph advances exactly as before.
        let at_edge = c + w >= cols;
        let next = if at_edge { cols - 1 } else { c + w };
        screen.set_cursor(Cursor { row: r, col: next });
        if at_edge && autowrap {
            self.wrap_pending = true;
        }
    }

    fn control(&mut self, b: u8) {
        match b {
            b'\r' => {
                self.set_col(0);
                self.wrap_pending = false;
            }
            b'\n' | 0x0b | 0x0c => {
                // LF, VT, FF: move down one line, scrolling at the margin.
                self.line_feed();
                self.wrap_pending = false;
            }
            0x08 => {
                // BS: cursor left one column, clamped at column 0.
                if self.cursor().col > 0 {
                    self.set_col(self.cursor().col - 1);
                }
                self.wrap_pending = false;
            }
            b'\t' => {
                self.set_col(self.next_tab_stop());
                self.wrap_pending = false;
            }
            _ => {} // BEL and other C0 controls: nothing to render.
        }
    }

    /// Move the cursor down one line; if it is at the bottom margin, scroll the
    /// scroll region up by one instead.
    fn line_feed(&mut self) {
        if self.cursor().row == self.scroll_bottom {
            self.scroll_up(1);
        } else if self.cursor().row + 1 < self.rows() {
            self.set_row(self.cursor().row + 1);
        }
    }

    /// Next tab stop strictly right of the cursor, or the last column.
    fn next_tab_stop(&self) -> usize {
        let cols = self.cols();
        let mut c = self.cursor().col + 1;
        while c < cols {
            if self.tabs.get(c).copied().unwrap_or(false) {
                return c;
            }
            c += 1;
        }
        cols - 1
    }

    // --- CSI dispatch -----------------------------------------------------

    fn csi(&mut self, private: Option<char>, params: &[u16], final_byte: char) {
        // Private-marker sequences (`?...`) are the mode toggles.
        if private == Some('?') {
            match final_byte {
                'h' => self.set_mode(params, true),
                'l' => self.set_mode(params, false),
                _ => {} // other private CSI: ignore quietly
            }
            return;
        }
        if private.is_some() {
            return; // `>`/`<`/`=` device sequences: ignore quietly
        }

        // Helpers: VT motion params default to 1 (0 from the parser means the
        // param was absent → use 1). Erase/line selectors default to 0.
        let n1 = |i: usize| -> usize { at1(params, i) };

        match final_byte {
            // Cursor absolute position: CUP / HVP (row;col, 1-based).
            'H' | 'f' => {
                let r = n1(0).saturating_sub(1);
                let c = n1(1).saturating_sub(1);
                self.move_to(r, c);
            }
            'A' => self.move_up(n1(0)),
            'B' => self.move_down(n1(0)),
            'C' => self.move_right(n1(0)),
            'D' => self.move_left(n1(0)),
            'E' => {
                // CNL: cursor next line, column 0.
                self.move_down(n1(0));
                self.set_col(0);
                self.wrap_pending = false;
            }
            'F' => {
                // CPL: cursor previous line, column 0.
                self.move_up(n1(0));
                self.set_col(0);
                self.wrap_pending = false;
            }
            'G' => {
                // CHA: cursor to absolute column (1-based).
                let c = n1(0).saturating_sub(1);
                self.set_col(c.min(self.cols() - 1));
                self.wrap_pending = false;
            }
            'd' => {
                // VPA: cursor to absolute row (1-based).
                let r = n1(0).saturating_sub(1);
                self.set_row(r.min(self.rows() - 1));
                self.wrap_pending = false;
            }
            'J' => self.erase_display(at0(params, 0)),
            'K' => self.erase_line(at0(params, 0)),
            'X' => self.erase_chars(n1(0)),
            'm' => self.style.apply_sgr(params),
            'r' => self.set_scroll_region(params),
            'L' => self.insert_lines(n1(0)),
            'M' => self.delete_lines(n1(0)),
            'S' => self.scroll_up(n1(0)),
            'T' => self.scroll_down(n1(0)),
            '@' => self.insert_chars(n1(0)),
            'P' => self.delete_chars(n1(0)),
            's' => self.save_cursor(),
            'u' => self.restore_cursor(),
            _ => {} // unimplemented CSI: ignore quietly
        }
    }

    fn set_mode(&mut self, params: &[u16], set: bool) {
        for &p in params {
            match p {
                25 => self.cursor_visible = set,
                7 => self.autowrap = set, // DECAWM
                47 | 1047 | 1049 => self.set_alt(set),
                2026 => self.set_sync(set), // synchronized output
                _ => {}                     // other private modes: ignore quietly
            }
        }
    }

    fn set_alt(&mut self, enter: bool) {
        // One logical cursor across both buffers: it moves with the switch.
        let cursor = self.cursor();
        if enter && !self.in_alt {
            // Entering: switch to a cleared alternate buffer.
            self.alt = Screen::new(self.rows(), self.cols());
            self.in_alt = true;
        } else if !enter && self.in_alt {
            // Leaving: restore the primary buffer as-is.
            self.in_alt = false;
        }
        self.active_mut().set_cursor(cursor);
        self.wrap_pending = false;
    }

    /// Enter/leave a synchronized update (DEC mode 2026). On open we snapshot
    /// the current active buffer as the last complete frame and serve that from
    /// `screen()` until close, so a mid-redraw frame is never exposed. Nested
    /// opens keep the first (good) snapshot rather than capturing a half-drawn
    /// one. On close we drop the snapshot, revealing the now-complete buffer.
    fn set_sync(&mut self, open: bool) {
        if open {
            if !self.in_sync {
                self.sync_frame = Some(self.active().clone());
                self.in_sync = true;
            }
        } else {
            self.in_sync = false;
            self.sync_frame = None;
        }
    }

    // --- cursor motion (clamped) -----------------------------------------

    fn move_to(&mut self, r: usize, c: usize) {
        self.active_mut().set_cursor(Cursor { row: r, col: c });
        self.wrap_pending = false;
    }

    fn move_up(&mut self, n: usize) {
        self.set_row(self.cursor().row.saturating_sub(n));
        self.wrap_pending = false;
    }

    fn move_down(&mut self, n: usize) {
        self.set_row((self.cursor().row + n).min(self.rows() - 1));
        self.wrap_pending = false;
    }

    fn move_right(&mut self, n: usize) {
        self.set_col((self.cursor().col + n).min(self.cols() - 1));
        self.wrap_pending = false;
    }

    fn move_left(&mut self, n: usize) {
        self.set_col(self.cursor().col.saturating_sub(n));
        self.wrap_pending = false;
    }

    // --- erase ------------------------------------------------------------

    /// ED: 0 = cursor to end of screen, 1 = start of screen to cursor, 2 = all.
    fn erase_display(&mut self, mode: u16) {
        let (rows, cols) = (self.rows(), self.cols());
        let Cursor { row: cr, col: cc } = self.cursor();
        let blank = Cell::default();
        match mode {
            0 => {
                for c in cc..cols {
                    self.active_mut().set(cr, c, blank);
                }
                for r in (cr + 1)..rows {
                    for c in 0..cols {
                        self.active_mut().set(r, c, blank);
                    }
                }
            }
            1 => {
                for r in 0..cr {
                    for c in 0..cols {
                        self.active_mut().set(r, c, blank);
                    }
                }
                for c in 0..=cc {
                    self.active_mut().set(cr, c, blank);
                }
            }
            2 => {
                for r in 0..rows {
                    for c in 0..cols {
                        self.active_mut().set(r, c, blank);
                    }
                }
            }
            _ => {}
        }
    }

    /// EL: 0 = cursor to end of line, 1 = start of line to cursor, 2 = whole line.
    fn erase_line(&mut self, mode: u16) {
        let cols = self.cols();
        let Cursor { row: cr, col: cc } = self.cursor();
        let blank = Cell::default();
        let range = match mode {
            0 => cc..cols,
            1 => 0..(cc + 1).min(cols),
            2 => 0..cols,
            _ => return,
        };
        for c in range {
            self.active_mut().set(cr, c, blank);
        }
    }

    /// ECH: erase (blank) `n` cells from the cursor rightward, **without** moving
    /// the cursor or shifting the rest of the line (unlike DCH, which closes the
    /// gap). This is a common way to clear a run of cells (e.g. a status line or
    /// trailing content), so dropping it leaves stale text behind. Clamped to the
    /// row's right edge.
    fn erase_chars(&mut self, n: usize) {
        let cols = self.cols();
        let Cursor { row: cr, col: cc } = self.cursor();
        let end = (cc + n.max(1)).min(cols);
        let blank = Cell::default();
        for c in cc..end {
            self.active_mut().set(cr, c, blank);
        }
        self.wrap_pending = false;
    }

    // --- scroll region + line/char insert/delete --------------------------

    /// DECSTBM: set scroll region `top;bottom` (1-based, clamped); resets the
    /// cursor to the origin. An empty/`0` bottom means the last row.
    fn set_scroll_region(&mut self, params: &[u16]) {
        let rows = self.rows();
        let top = at1(params, 0).saturating_sub(1);
        let bottom = match at0(params, 1) {
            0 => rows - 1,
            b => (b as usize - 1).min(rows - 1),
        };
        // Ignore an inverted/empty region, as VT100 does.
        if top < bottom {
            self.scroll_top = top;
            self.scroll_bottom = bottom;
        }
        self.active_mut().set_cursor(Cursor::default());
        self.wrap_pending = false;
    }

    /// Scroll the scroll region up by `n` lines: top lines lost, blanks in at
    /// the bottom margin.
    ///
    /// One block move in the screen ([`Screen::scroll_rows_up`]), not a copy per
    /// cell: this runs on every line of output, and the per-cell loop held the
    /// emulator to ~11 MB/s on a 40x160 grid.
    fn scroll_up(&mut self, n: usize) {
        let (top, bottom) = (self.scroll_top, self.scroll_bottom);
        self.active_mut()
            .scroll_rows_up(top, bottom, n, Cell::default());
    }

    /// Scroll the scroll region down by `n` lines: bottom lines lost, blanks in
    /// at the top margin.
    fn scroll_down(&mut self, n: usize) {
        let (top, bottom) = (self.scroll_top, self.scroll_bottom);
        self.active_mut()
            .scroll_rows_down(top, bottom, n, Cell::default());
    }

    /// IL: insert `n` blank lines at the cursor row, within the scroll region;
    /// lines below shift down and fall off the bottom margin. No-op outside the
    /// region.
    fn insert_lines(&mut self, n: usize) {
        if self.cursor().row < self.scroll_top || self.cursor().row > self.scroll_bottom {
            return;
        }
        let saved_top = self.scroll_top;
        self.scroll_top = self.cursor().row;
        self.scroll_down(n);
        self.scroll_top = saved_top;
        self.set_col(0);
        self.wrap_pending = false;
    }

    /// DL: delete `n` lines at the cursor row, within the scroll region; lines
    /// below shift up and blanks fill the bottom margin. No-op outside region.
    fn delete_lines(&mut self, n: usize) {
        if self.cursor().row < self.scroll_top || self.cursor().row > self.scroll_bottom {
            return;
        }
        let saved_top = self.scroll_top;
        self.scroll_top = self.cursor().row;
        self.scroll_up(n);
        self.scroll_top = saved_top;
        self.set_col(0);
        self.wrap_pending = false;
    }

    /// ICH: insert `n` blank cells at the cursor, shifting the rest of the line
    /// right off the edge.
    fn insert_chars(&mut self, n: usize) {
        let cols = self.cols();
        let Cursor { row: r, col: start } = self.cursor();
        let n = n.min(cols - start);
        for c in (start..cols).rev() {
            let cell = if c >= start + n {
                self.active().cell(r, c - n)
            } else {
                Cell::default()
            };
            self.active_mut().set(r, c, cell);
        }
        self.wrap_pending = false;
    }

    /// DCH: delete `n` cells at the cursor, shifting the rest of the line left
    /// and filling the tail with blanks.
    fn delete_chars(&mut self, n: usize) {
        let cols = self.cols();
        let Cursor { row: r, col: start } = self.cursor();
        let n = n.min(cols - start);
        for c in start..cols {
            let cell = if c + n < cols {
                self.active().cell(r, c + n)
            } else {
                Cell::default()
            };
            self.active_mut().set(r, c, cell);
        }
        self.wrap_pending = false;
    }

    // --- save / restore + ESC --------------------------------------------

    fn save_cursor(&mut self) {
        self.saved = Some((self.cursor(), self.style));
    }

    fn restore_cursor(&mut self) {
        if let Some((cursor, style)) = self.saved {
            self.active_mut().set_cursor(cursor);
            self.style = style;
        }
        self.wrap_pending = false;
    }

    fn esc(&mut self, final_byte: u8) {
        match final_byte {
            b'7' => self.save_cursor(),    // DECSC
            b'8' => self.restore_cursor(), // DECRC
            _ => {}                        // charset selection etc.: ignore quietly
        }
    }
}

/// Tab stops every 8 columns (VT default), with a stop at column 0.
fn default_tabs(cols: usize) -> Vec<bool> {
    (0..cols).map(|c| c % 8 == 0).collect()
}

/// Read a param defaulting a missing/zero value to 1 (VT motion default).
fn at1(params: &[u16], i: usize) -> usize {
    match params.get(i).copied().unwrap_or(0) {
        0 => 1,
        v => v as usize,
    }
}

/// Read a param defaulting a missing value to 0 (erase/selector default).
fn at0(params: &[u16], i: usize) -> u16 {
    params.get(i).copied().unwrap_or(0)
}

/// Copy the overlapping top-left region of `src` into `dst` (for resize).
fn copy_top_left(src: &Screen, dst: &mut Screen) {
    let rows = src.rows().min(dst.rows());
    let cols = src.cols().min(dst.cols());
    for r in 0..rows {
        for c in 0..cols {
            dst.set(r, c, src.cell(r, c));
        }
    }
}