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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! 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, Event, Parser, Screen, Style, Utf8Decoder};
mod checkpoint;
pub use checkpoint::RestoreError;
/// Mouse events a program asked its terminal to send, from the xterm
/// tracking modes. Each includes the ones above it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MouseTracking {
/// None: the terminal uses the mouse itself (selection, scrolling).
#[default]
Off,
/// Button presses and releases, and the wheel (`?1000h`).
Click,
/// Also motion while a button is held (`?1002h`).
Drag,
/// Also motion with no button held (`?1003h`).
Motion,
}
/// A minimal VT100/ECMA-48 terminal emulator over an [`ansi::Screen`].
pub struct Term {
/// The primary (normal) screen buffer. It carries the scrollback, if any
/// ([`Term::with_history`]).
primary: Screen,
/// Scrollback capacity in lines (0: none).
history: usize,
/// Scrollback capacity in bytes as stored (0: no cap beyond the lines).
history_bytes: usize,
/// 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`), for the host to draw or
/// not; the screen cursor position is always synced regardless.
cursor_visible: bool,
/// Bracketed paste (`?2004h`/`?2004l`): the program wants pasted text
/// wrapped in `ESC [200~` ... `ESC [201~`. The host does the wrapping.
pub(crate) bracketed_paste: bool,
/// Mouse reporting the program asked for (`?1000`/`?1002`/`?1003`), and
/// in which encoding (`?1006`, SGR). The host reports the mouse.
mouse_tracking: MouseTracking,
mouse_sgr: bool,
/// Line feed / new line mode (LNM, ANSI mode 20, `CSI 20 h`/`l`): while
/// set, LF, VT and FF also return the cursor to column 0. A host that
/// feeds output from plain pipes (no tty to turn LF into CR LF) sets it
/// instead of rewriting every byte.
pub(crate) newline_mode: bool,
/// The parser driving `feed`; one per stream so mid-sequence chunk splits
/// are handled by `ansi`.
parser: Parser,
/// Decodes text runs, which `ansi::Event` hands over as raw bytes, and
/// carries a character split across chunks. Allocates nothing.
decoder: Utf8Decoder,
/// 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 {
Term::with_history(rows, cols, 0)
}
/// Like [`Term::new`], keeping up to `lines` lines that scroll off the
/// top of the primary screen, readable through [`Term::scrollback`].
/// Each line is stored compactly as it leaves (`ansi::Screen::with_history`:
/// its text plus runs of style, not a row of cells), so memory follows
/// the text held rather than `lines x cols`.
/// The alternate screen, and scroll regions, keep no history.
pub fn with_history(rows: usize, cols: usize, lines: usize) -> Self {
let rows = rows.max(1);
let cols = cols.max(1);
Term {
primary: Screen::with_history(rows, cols, lines),
history: lines,
history_bytes: 0,
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,
bracketed_paste: false,
mouse_tracking: MouseTracking::Off,
mouse_sgr: false,
newline_mode: false,
parser: Parser::new(),
decoder: Utf8Decoder::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;
// The parser and decoder are lifted out for the call so the callback
// can borrow the rest of `self`; both are restored before returning.
let mut parser = std::mem::take(&mut self.parser);
let mut decoder = std::mem::take(&mut self.decoder);
parser.feed_with(bytes, |event| self.apply(event, &mut decoder));
self.parser = parser;
self.decoder = decoder;
}
/// 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(),
}
}
/// The primary screen, whose history ([`ansi::Screen::history_len`],
/// [`ansi::Screen::history_row`]) holds the lines scrolled off its top.
/// Empty unless made with [`Term::with_history`].
pub fn scrollback(&self) -> &Screen {
&self.primary
}
/// Cap the scrollback at `max` bytes as stored (0: no cap), dropping the
/// oldest lines past it (`ansi::Screen::set_history_bytes`): a memory
/// bound however wide or colourful lines are. Kept across resizes.
pub fn set_history_bytes(&mut self, max: usize) {
self.history_bytes = max;
self.primary.set_history_bytes(max);
}
/// True while the alternate screen is active (full-screen programs), where
/// scrolling back through history does not apply.
pub fn in_alternate_screen(&self) -> bool {
self.in_alt
}
/// Whether the program has the cursor shown (`?25h`, the default) or
/// hidden (`?25l`), for the host to draw it or not.
pub fn cursor_visible(&self) -> bool {
self.cursor_visible
}
/// Whether the program asked for bracketed paste (`?2004h`): the host
/// then wraps what it pastes in `ESC [200~` and `ESC [201~`.
pub fn bracketed_paste(&self) -> bool {
self.bracketed_paste
}
/// Which mouse events the program asked to be sent (`?1000h` clicks,
/// `?1002h` also drags, `?1003h` also any motion); the host reports
/// them instead of using the mouse itself.
pub fn mouse_tracking(&self) -> MouseTracking {
self.mouse_tracking
}
/// Whether mouse reports use the SGR encoding (`?1006h`,
/// `ESC [< b ; x ; y M`), else the original one (`ESC [M` and three
/// bytes, for positions up to 223).
pub fn mouse_sgr(&self) -> bool {
self.mouse_sgr
}
/// 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 mut primary = Screen::with_history(rows, cols, self.history);
primary.set_history_bytes(self.history_bytes);
let old_primary = std::mem::replace(&mut self.primary, primary);
let old_alt = std::mem::replace(&mut self.alt, Screen::new(rows, cols));
self.primary.copy_history_from(&old_primary);
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, event: Event<'_>, decoder: &mut Utf8Decoder) {
if let Event::Text(bytes) = event {
// Most output is plain ASCII: with no character half-received, it
// needs no decoding at all (a word-wide `is_ascii` decides).
if decoder.is_idle() && bytes.is_ascii() {
self.print_run(bytes);
} else {
decoder.decode(bytes, |s| self.print_run(s.as_bytes()));
}
return;
}
// Anything but text ends a run, so a half-finished character can never
// be completed: render it as U+FFFD, exactly as `ansi::Parser::feed`
// would have.
decoder.flush_incomplete(|s| self.print_run(s.as_bytes()));
match event {
Event::Control(b) => self.control(b),
Event::Csi {
private,
params,
final_byte,
..
} => self.csi(private.map(char::from), params, char::from(final_byte)),
Event::Esc { final_byte, .. } => self.esc(final_byte),
// Titles, DCS/SOS/PM/APC strings: nothing to render.
Event::Text(_) | Event::Osc(_) | Event::Other { .. } => {}
}
}
/// Write a run of text at the cursor.
///
/// Terminal output is overwhelmingly plain ASCII, and going through
/// [`Term::print`] for each character re-reads the cursor, re-borrows the
/// active buffer, looks up a width and bounds-checks a cell — per character.
/// So a run of ordinary single-width ASCII that fits on the current row is
/// written in one [`Screen::write_ascii`] with the cursor moved once.
///
/// The fast path is deliberately narrow, and anything it does not cover
/// falls through to `print` unchanged: no wrap is pending, the characters
/// are printable ASCII (never control, never wide, never zero-width), and
/// the run stops one column short of the edge so the pending-wrap latch is
/// still decided by `print`.
///
/// `text` is valid UTF-8: either decoded, or plain ASCII passed through.
fn print_run(&mut self, text: &[u8]) {
let mut rest = text;
while !rest.is_empty() {
let n = self.plain_run(rest);
if n == 0 {
// Not the fast path: one character the careful way.
let len = utf8_len(rest[0]).min(rest.len());
let ch = std::str::from_utf8(&rest[..len])
.ok()
.and_then(|s| s.chars().next())
.unwrap_or(char::REPLACEMENT_CHARACTER);
self.print(ch);
rest = &rest[len..];
continue;
}
let style = self.style;
let screen = if self.in_alt {
&mut self.alt
} else {
&mut self.primary
};
let Cursor { row, col } = screen.cursor();
screen.write_ascii(row, col, &rest[..n], style);
screen.set_cursor(Cursor { row, col: col + n });
rest = &rest[n..];
}
}
/// How many leading bytes of `s` the fast path in [`Term::print_run`] can
/// write: printable ASCII, stopping before the last column of the row.
fn plain_run(&self, s: &[u8]) -> usize {
if self.wrap_pending {
return 0;
}
let screen = if self.in_alt {
&self.alt
} else {
&self.primary
};
let col = screen.cursor().col;
// Leave the final column to `print`, which owns the pending-wrap latch.
let room = screen.cols().saturating_sub(col + 1);
let head = &s[..room.min(s.len())];
// Text reaches here from the parser, which never passes C0 controls or
// DEL in a text run, so "printable ASCII" is just "ASCII": checked a
// word at a time by `is_ascii`, byte by byte only when it fails.
debug_assert!(!head.iter().any(|&b| b < 0x20 || b == 0x7F));
if head.is_ascii() {
head.len()
} else {
head.iter()
.take_while(|&&b| (0x20..0x7f).contains(&b))
.count()
}
}
/// 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.autowrap_line();
}
// 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.autowrap_line();
}
// 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;
}
}
/// Autowrap: the row is marked as continuing onto the next (so a host
/// copies them as one line), then the cursor moves to the next row's
/// start. Marked before the line feed, so a row the feed scrolls into the
/// history takes the mark with it.
fn autowrap_line(&mut self) {
let row = self.cursor().row;
self.active_mut().set_row_wrapped(row, true);
self.set_col(0);
self.line_feed();
self.wrap_pending = false;
}
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
// (and to column 0 in new line mode).
self.line_feed();
if self.newline_mode {
self.set_col(0);
}
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),
// SM / RM: of the ANSI modes only LNM (20) changes rendering.
'h' | 'l' if params.contains(&20) => self.newline_mode = final_byte == 'h',
'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,
2004 => self.bracketed_paste = set,
// The tracking modes replace one another; resetting the one
// in force (or any, as programs send all three) turns it off.
1000 | 1002 | 1003 => {
self.mouse_tracking = match (set, p) {
(true, 1000) => MouseTracking::Click,
(true, 1002) => MouseTracking::Drag,
(true, _) => MouseTracking::Motion,
(false, _) => MouseTracking::Off,
}
}
1006 => self.mouse_sgr = 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 {
// The visible rows only: never a copy of the scrollback.
self.sync_frame = Some(self.active().visible());
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);
}
}
}
// ED 3: erase the scrollback (xterm), leaving the screen.
3 => self.primary.clear_history(),
_ => {}
}
}
/// 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);
}
// Its end erased, the row no longer runs on into the next.
if mode != 1 {
self.active_mut().set_row_wrapped(cr, false);
}
}
/// 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));
}
}
}
/// Length of the UTF-8 sequence a lead byte starts (1 for ASCII and for bytes
/// that cannot lead, which valid input never has here).
fn utf8_len(lead: u8) -> usize {
match lead {
0xC0..=0xDF => 2,
0xE0..=0xEF => 3,
0xF0..=0xF7 => 4,
_ => 1,
}
}