nativelite-vterm 0.5.4

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
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
//! Integration tests for `vterm`.
//!
//! Spec-anchored: each vector is a hand-authored `(input_bytes, expected)`
//! pair traced against VT100/ECMA-48 behavior. We assert cell contents, cursor
//! position, style-on-write, scroll confinement, alt-screen swap, and
//! chunk-split invariance (feeding the same bytes split at every boundary must
//! yield an identical final screen). Zero dev-dependencies; the built-in
//! `#[test]` harness only.

use ansi::{CellWidth, Cursor};
use vterm::Term;

/// Collect a row's characters into a `String` for readable assertions.
fn row_text(t: &Term, row: usize) -> String {
    let s = t.screen();
    (0..s.cols()).map(|c| s.cell(row, c).ch).collect()
}

/// Build a `Term`, feed the bytes in one shot.
fn run(rows: usize, cols: usize, bytes: &[u8]) -> Term {
    let mut t = Term::new(rows, cols);
    t.feed(bytes);
    t
}

// --- basic printing + cursor ------------------------------------------------

#[test]
fn prints_text_and_advances_cursor() {
    let t = run(4, 10, b"hi");
    assert_eq!(t.screen().cell(0, 0).ch, 'h');
    assert_eq!(t.screen().cell(0, 1).ch, 'i');
    assert_eq!(t.screen().cursor(), Cursor::new(0, 2));
}

#[test]
fn cup_and_erase_then_print() {
    // The spec's anchor vector.
    let t = run(24, 80, b"\x1b[2J\x1b[3;5HX");
    assert_eq!(t.screen().cell(2, 4).ch, 'X');
    assert_eq!(t.screen().cursor(), Cursor::new(2, 5));
}

#[test]
fn hvp_f_is_same_as_cup() {
    let t = run(10, 10, b"\x1b[2;3fZ");
    assert_eq!(t.screen().cell(1, 2).ch, 'Z');
    assert_eq!(t.screen().cursor(), Cursor::new(1, 3));
}

#[test]
fn cup_defaults_and_clamps() {
    // Bare CUP homes the cursor; out-of-range clamps to the last cell.
    assert_eq!(run(5, 5, b"\x1b[H").screen().cursor(), Cursor::new(0, 0));
    assert_eq!(
        run(5, 5, b"\x1b[99;99H").screen().cursor(),
        Cursor::new(4, 4)
    );
}

// --- CR / LF / BS / TAB motion ---------------------------------------------

#[test]
fn carriage_return_to_col0() {
    let t = run(4, 10, b"abc\rX");
    assert_eq!(t.screen().cell(0, 0).ch, 'X');
    assert_eq!(t.screen().cell(0, 1).ch, 'b');
    assert_eq!(t.screen().cursor(), Cursor::new(0, 1));
}

#[test]
fn line_feed_moves_down_same_column() {
    let t = run(4, 10, b"ab\nc");
    assert_eq!(t.screen().cell(0, 0).ch, 'a');
    assert_eq!(t.screen().cell(1, 2).ch, 'c');
    assert_eq!(t.screen().cursor(), Cursor::new(1, 3));
}

#[test]
fn vt_and_ff_behave_like_lf() {
    assert_eq!(run(4, 5, b"a\x0bb").screen().cursor(), Cursor::new(1, 2));
    assert_eq!(run(4, 5, b"a\x0cb").screen().cursor(), Cursor::new(1, 2));
}

#[test]
fn backspace_moves_left_and_clamps() {
    let t = run(4, 10, b"abc\x08\x08");
    assert_eq!(t.screen().cursor(), Cursor::new(0, 1));
    assert_eq!(run(4, 10, b"\x08").screen().cursor(), Cursor::new(0, 0)); // clamps at 0
}

#[test]
fn tab_advances_to_next_stop() {
    let t = run(4, 40, b"\tX");
    assert_eq!(t.screen().cell(0, 8).ch, 'X');
    assert_eq!(t.screen().cursor(), Cursor::new(0, 9));
    // A tab from mid-cell jumps to the next multiple of 8.
    let t2 = run(4, 40, b"abc\tY");
    assert_eq!(t2.screen().cell(0, 8).ch, 'Y');
}

// --- cursor motion CSI ------------------------------------------------------

#[test]
fn cursor_up_down_left_right() {
    // Home, down 2, right 3, up 1, left 1 → (1, 2).
    let t = run(10, 10, b"\x1b[H\x1b[2B\x1b[3C\x1b[A\x1b[D");
    assert_eq!(t.screen().cursor(), Cursor::new(1, 2));
}

#[test]
fn cnl_and_cpl_go_to_col0() {
    let t = run(10, 10, b"\x1b[5;5H\x1b[2EX");
    assert_eq!(t.screen().cursor(), Cursor::new(6, 1)); // down 2 lines, col 0, printed X
    assert_eq!(t.screen().cell(6, 0).ch, 'X');
    let t2 = run(10, 10, b"\x1b[5;5H\x1b[2F");
    assert_eq!(t2.screen().cursor(), Cursor::new(2, 0));
}

#[test]
fn cha_and_vpa_absolute() {
    let t = run(10, 10, b"\x1b[5;5H\x1b[3G"); // CHA col 3
    assert_eq!(t.screen().cursor(), Cursor::new(4, 2));
    let t2 = run(10, 10, b"\x1b[5;5H\x1b[2d"); // VPA row 2
    assert_eq!(t2.screen().cursor(), Cursor::new(1, 4));
}

// --- autowrap ---------------------------------------------------------------

#[test]
fn autowrap_at_right_edge() {
    // 3 cols: "abc" fills the row, "d" wraps to the next line col 0.
    let t = run(4, 3, b"abcd");
    assert_eq!(row_text(&t, 0), "abc");
    assert_eq!(t.screen().cell(1, 0).ch, 'd');
    assert_eq!(t.screen().cursor(), Cursor::new(1, 1));
}

#[test]
fn pending_wrap_is_deferred() {
    // After "abc" the cursor is latched at col 2 (pending), not yet wrapped.
    let t = run(4, 3, b"abc");
    assert_eq!(t.screen().cursor(), Cursor::new(0, 2));
    assert_eq!(row_text(&t, 0), "abc");
}

#[test]
fn autowrap_off_overwrites_last_column() {
    // DECAWM off (?7l): writes past the edge overwrite the last cell.
    let t = run(4, 3, b"\x1b[?7labcd");
    assert_eq!(row_text(&t, 0), "abd");
    assert_eq!(t.screen().cursor(), Cursor::new(0, 2));
}

// --- scroll on LF at bottom margin -----------------------------------------

#[test]
fn scroll_when_lf_at_bottom() {
    // 2 rows: fill row0="A", row1="B", then LF scrolls: row0="B", row1 blank.
    // Use CR+LF so each line starts at col 0.
    let t = run(2, 3, b"A\r\nB\r\n");
    assert_eq!(t.screen().cell(0, 0).ch, 'B');
    assert_eq!(t.screen().cell(1, 0).ch, ' ');
    assert_eq!(t.screen().cursor(), Cursor::new(1, 0));
}

#[test]
fn scroll_loses_top_line() {
    let t = run(3, 3, b"1\r\n2\r\n3\r\n4");
    assert_eq!(t.screen().cell(0, 0).ch, '2');
    assert_eq!(t.screen().cell(1, 0).ch, '3');
    assert_eq!(t.screen().cell(2, 0).ch, '4');
}

// --- ED / EL ----------------------------------------------------------------

#[test]
fn erase_display_variants() {
    // ED 0: cursor to end. Fill 2x3 with X, home+down, ED0 clears from (1,0).
    let t = run(2, 3, b"XXX\rXXX"); // note: no newline scroll; simple fill
    let mut t = t;
    t.feed(b"\x1b[1;2H\x1b[0J"); // cursor (0,1), erase to end
    assert_eq!(t.screen().cell(0, 0).ch, 'X');
    assert_eq!(t.screen().cell(0, 1).ch, ' ');
    assert_eq!(t.screen().cell(0, 2).ch, ' ');

    // ED 1: start to cursor.
    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;3H\x1b[1J"); // cursor (0,2)
    assert_eq!(row_text(&t, 0), "   DE");

    // ED 2: whole screen.
    let mut t = run(2, 3, b"abcdef");
    t.feed(b"\x1b[2J");
    assert_eq!(row_text(&t, 0), "   ");
    assert_eq!(row_text(&t, 1), "   ");
}

#[test]
fn erase_line_variants() {
    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;3H\x1b[0K"); // erase cursor to end from col 2
    assert_eq!(row_text(&t, 0), "AB   ");

    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;3H\x1b[1K"); // erase start to cursor (inclusive)
    assert_eq!(row_text(&t, 0), "   DE");

    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;3H\x1b[2K"); // erase whole line
    assert_eq!(row_text(&t, 0), "     ");
}

// --- SGR --------------------------------------------------------------------

#[test]
fn sgr_sets_style_on_written_cells() {
    let t = run(2, 10, b"\x1b[1;31mR\x1b[0mN");
    let r = t.screen().cell(0, 0);
    assert!(r.style.bold);
    assert_eq!(r.style.fg, ansi::Color::Indexed(1));
    let n = t.screen().cell(0, 1);
    assert!(!n.style.bold);
    assert_eq!(n.style.fg, ansi::Color::Default);
}

#[test]
fn bare_sgr_m_resets() {
    let t = run(2, 10, b"\x1b[1m\x1b[mX"); // empty params ⇒ reset
    assert!(!t.screen().cell(0, 0).style.bold);
}

// --- DECSTBM scroll region --------------------------------------------------

#[test]
fn scroll_region_confines_scrolling() {
    // Region rows 1..2 (1-based 2;3). LFs scroll only within it; row0 fixed.
    let mut t = run(4, 3, b"top");
    t.feed(b"\x1b[2;3r"); // region rows 2..3, cursor homes to (0,0)
                          // Move into the region bottom and force scrolls (CR+LF for col 0).
    t.feed(b"\x1b[3;1HA\r\nB\r\nC");
    assert_eq!(row_text(&t, 0), "top"); // untouched, above region
                                        // Region scrolled: last two written lines survive at rows 1 and 2.
    assert_eq!(t.screen().cell(1, 0).ch, 'B');
    assert_eq!(t.screen().cell(2, 0).ch, 'C');
}

#[test]
fn scroll_region_resets_cursor_to_origin() {
    let mut t = run(6, 6, b"\x1b[3;4H");
    t.feed(b"\x1b[2;5r");
    assert_eq!(t.screen().cursor(), Cursor::new(0, 0));
}

// --- IL / DL ----------------------------------------------------------------

#[test]
fn insert_lines_shifts_down() {
    // rows: 0=A 1=B 2=C. IL 1 at row 1 → 0=A 1=blank 2=B (C falls off).
    let mut t = run(3, 3, b"A\r\nB\r\nC");
    t.feed(b"\x1b[2;1H\x1b[L");
    assert_eq!(t.screen().cell(0, 0).ch, 'A');
    assert_eq!(t.screen().cell(1, 0).ch, ' ');
    assert_eq!(t.screen().cell(2, 0).ch, 'B');
}

#[test]
fn delete_lines_shifts_up() {
    // rows: 0=A 1=B 2=C. DL 1 at row 1 → 0=A 1=C 2=blank.
    let mut t = run(3, 3, b"A\r\nB\r\nC");
    t.feed(b"\x1b[2;1H\x1b[M");
    assert_eq!(t.screen().cell(0, 0).ch, 'A');
    assert_eq!(t.screen().cell(1, 0).ch, 'C');
    assert_eq!(t.screen().cell(2, 0).ch, ' ');
}

// --- ICH / DCH --------------------------------------------------------------

#[test]
fn insert_chars_shifts_right() {
    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;2H\x1b[2@"); // insert 2 blanks at col 1
    assert_eq!(row_text(&t, 0), "A  BC");
}

#[test]
fn delete_chars_shifts_left() {
    let mut t = run(1, 5, b"ABCDE");
    t.feed(b"\x1b[1;2H\x1b[2P"); // delete 2 chars at col 1
    assert_eq!(row_text(&t, 0), "ADE  ");
}

// --- save / restore cursor --------------------------------------------------

#[test]
fn csi_save_restore_cursor() {
    let t = run(10, 10, b"\x1b[3;4H\x1b[s\x1b[8;8H\x1b[u");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3));
}

#[test]
fn esc_decsc_decrc() {
    let t = run(10, 10, b"\x1b[3;4H\x1b7\x1b[8;8H\x1b8");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3));
}

#[test]
fn restore_also_restores_style() {
    let t = run(2, 10, b"\x1b[1m\x1b7\x1b[0m\x1b8X");
    assert!(t.screen().cell(0, 0).style.bold); // style restored to bold
}

// --- alt screen -------------------------------------------------------------

#[test]
fn alt_screen_hides_and_restores_primary() {
    let mut t = run(4, 5, b"PRIME");
    assert_eq!(t.screen().cell(0, 0).ch, 'P');
    t.feed(b"\x1b[?1049h"); // enter alt: cleared buffer
    assert_eq!(t.screen().cell(0, 0).ch, ' ');
    t.feed(b"\x1b[HALT");
    assert_eq!(t.screen().cell(0, 0).ch, 'A');
    t.feed(b"\x1b[?1049l"); // leave alt: primary restored
    assert_eq!(t.screen().cell(0, 0).ch, 'P');
}

#[test]
fn the_cursor_moves_with_an_alt_screen_switch_in_both_directions() {
    let mut t = run(6, 10, b"\x1b[3;4H");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3));
    t.feed(b"\x1b[?1049h");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3), "entering keeps it");
    t.feed(b"\x1b[5;7H");
    t.feed(b"\x1b[?1049l");
    assert_eq!(
        t.screen().cursor(),
        Cursor::new(4, 6),
        "leaving brings the alt position back to the primary"
    );
}

#[test]
fn a_saved_cursor_restores_across_buffers_and_a_resize_clamps_it_in_alt() {
    let mut t = run(6, 10, b"\x1b[2;2H\x1b7\x1b[?1049h\x1b[5;5H\x1b8");
    assert_eq!(t.screen().cursor(), Cursor::new(1, 1));
    t.feed(b"\x1b[6;10H");
    t.resize(3, 3);
    assert_eq!(t.screen().cursor(), Cursor::new(2, 2));
    t.feed(b"\x1b[?1049l");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 2));
}

#[test]
fn a_synchronized_update_shows_the_cursor_of_the_last_whole_frame() {
    let mut t = run(6, 10, b"\x1b[2;3H\x1b[?2026h\x1b[4;4HX");
    assert_eq!(t.screen().cursor(), Cursor::new(1, 2));
    t.feed(b"\x1b[?2026l");
    assert_eq!(t.screen().cursor(), Cursor::new(3, 4));
}

#[test]
fn entering_alt_and_opening_a_sync_update_in_one_sequence_snapshots_the_live_cursor() {
    // `?1049;2026h` switches buffers and then snapshots, mid-token. The cursor
    // used to be mirrored into the screen only at the end of each token, so the
    // snapshot caught the fresh alt buffer's (0,0) while the emulator was at
    // (2,3) — a host parked the terminal cursor at the origin for that frame.
    let mut t = run(10, 20, b"\x1b[3;4H\x1b[?1049;2026h");
    assert!(t.in_sync());
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3));
    t.feed(b"\x1b[?2026l");
    assert_eq!(t.screen().cursor(), Cursor::new(2, 3));
}

#[test]
fn alt_screen_47_and_1047_also_work() {
    let mut t = run(4, 5, b"X");
    t.feed(b"\x1b[?47h");
    assert_eq!(t.screen().cell(0, 0).ch, ' ');
    t.feed(b"\x1b[?47l");
    assert_eq!(t.screen().cell(0, 0).ch, 'X');
}

// --- cursor visibility (tracked, non-fatal) --------------------------------

#[test]
fn cursor_hide_show_is_accepted() {
    // Just assert these don't corrupt the screen; visibility is host-side.
    let t = run(4, 5, b"\x1b[?25lAB\x1b[?25h");
    assert_eq!(t.screen().cell(0, 0).ch, 'A');
    assert_eq!(t.screen().cursor(), Cursor::new(0, 2));
}

// --- resize -----------------------------------------------------------------

#[test]
fn resize_preserves_top_left_and_clamps_cursor() {
    let mut t = run(4, 4, b"\x1b[4;4Hxy"); // content near old bottom-right
    t.feed(b"\x1b[1;1HAB"); // top-left content
    t.resize(2, 2);
    assert_eq!(t.screen().rows(), 2);
    assert_eq!(t.screen().cols(), 2);
    assert_eq!(t.screen().cell(0, 0).ch, 'A');
    assert_eq!(t.screen().cell(0, 1).ch, 'B');
    // Cursor was at (0,2) after "AB"; clamps into 2x2.
    let Cursor { row, col } = t.screen().cursor();
    assert!(row < 2 && col < 2);
}

// --- chunk-split invariance -------------------------------------------------

#[test]
fn chunk_split_yields_identical_screen() {
    let script = b"\x1b[2J\x1b[3;5m\x1b[1;1mHello\r\n\x1b[1;31mWorld\x1b[0m\x1b[2;3r\nmore\ttext\x1b[?1049h\x1b[HALT\x1b[?1049l";
    let oneshot = run(8, 20, script);

    // Feed the same bytes one byte at a time.
    let mut split = Term::new(8, 20);
    for &b in script.iter() {
        split.feed(&[b]);
    }
    // Compare full grids and cursor.
    let (a, b) = (oneshot.screen(), split.screen());
    assert_eq!(a.rows(), b.rows());
    assert_eq!(a.cols(), b.cols());
    assert_eq!(a.cursor(), b.cursor());
    for r in 0..a.rows() {
        for c in 0..a.cols() {
            assert_eq!(a.cell(r, c), b.cell(r, c), "mismatch at ({r},{c})");
        }
    }

    // And split at a different, arbitrary boundary (chunks of 3).
    let mut split3 = Term::new(8, 20);
    for chunk in script.chunks(3) {
        split3.feed(chunk);
    }
    let c = split3.screen();
    assert_eq!(a.cursor(), c.cursor());
    for r in 0..a.rows() {
        for col in 0..a.cols() {
            assert_eq!(a.cell(r, col), c.cell(r, col));
        }
    }
}

// --- synchronized output (DEC mode 2026) ------------------------------------

#[test]
fn sync_hides_partial_frame_until_close() {
    // A frame drawn inside ?2026h..?2026l must not be visible mid-update: the
    // host samples screen() and would otherwise composite a half-drawn frame.
    let mut t = run(2, 5, b"OLD");
    assert_eq!(row_text(&t, 0), "OLD  ");
    assert!(!t.in_sync());

    // Open the update, wipe the screen, start drawing the new frame.
    t.feed(b"\x1b[?2026h");
    assert!(t.in_sync());
    t.feed(b"\x1b[2J\x1b[HNE"); // clear + begin writing "NEW"
                                // Mid-update: readers still see the last complete frame.
    assert_eq!(row_text(&t, 0), "OLD  ", "partial frame leaked during sync");

    t.feed(b"W"); // finish drawing
    assert_eq!(row_text(&t, 0), "OLD  ", "still mid-update");

    // Close the update: the complete new frame is revealed atomically.
    t.feed(b"\x1b[?2026l");
    assert!(!t.in_sync());
    assert_eq!(row_text(&t, 0), "NEW  ");
}

#[test]
fn sync_nested_open_keeps_first_snapshot() {
    // A second ?2026h before the close must not re-snapshot a half-drawn frame.
    let mut t = run(1, 5, b"AAA");
    t.feed(b"\x1b[?2026h");
    t.feed(b"\x1b[2J\x1b[HB"); // partial
    t.feed(b"\x1b[?2026h"); // nested open, keep the "AAA" snapshot
    t.feed(b"BB");
    assert_eq!(row_text(&t, 0), "AAA  ");
    t.feed(b"\x1b[?2026l");
    assert_eq!(row_text(&t, 0), "BBB  ");
}

#[test]
fn resize_during_sync_reveals_live_buffer() {
    // A resize mid-sync drops the stale snapshot rather than serving a
    // wrong-sized frame from screen().
    let mut t = run(2, 5, b"OLD");
    t.feed(b"\x1b[?2026h");
    t.feed(b"\x1b[2J\x1b[HNEW");
    assert!(t.in_sync());
    t.resize(3, 8);
    assert!(!t.in_sync());
    assert_eq!(t.screen().cols(), 8);
    assert_eq!(row_text(&t, 0), "NEW     ");
}

// --- ECH (erase character) and SU/SD (scroll) -------------------------------

#[test]
fn ech_blanks_cells_without_shifting() {
    // ECH (CSI X) erases n cells from the cursor; the rest of the line does NOT
    // shift left (that would be DCH). "ABCDE", cursor to col 1, CSI 2 X → "A  DE".
    // Its absence is a classic "stale text left behind" bug.
    let t = run(1, 5, b"ABCDE\x1b[1;2H\x1b[2X");
    assert_eq!(row_text(&t, 0), "A  DE");
    assert_eq!(t.screen().cursor(), Cursor::new(0, 1)); // cursor unmoved
}

#[test]
fn ech_defaults_to_one_and_clamps() {
    // No param = 1 cell; a huge count clamps to the row's right edge.
    assert_eq!(row_text(&run(1, 4, b"WXYZ\x1b[1;1H\x1b[X"), 0), " XYZ");
    assert_eq!(row_text(&run(1, 4, b"WXYZ\x1b[1;2H\x1b[99X"), 0), "W   ");
}

#[test]
fn su_scrolls_the_screen_up() {
    // CSI S scrolls the (default full-screen) region up one line: top line lost,
    // blank in at the bottom.
    let t = run(3, 3, b"AAA\r\nBBB\r\nCCC\x1b[S");
    assert_eq!(row_text(&t, 0), "BBB");
    assert_eq!(row_text(&t, 1), "CCC");
    assert_eq!(row_text(&t, 2), "   ");
}

#[test]
fn sd_scrolls_the_screen_down() {
    // CSI T scrolls down one line: blank in at the top, bottom line lost.
    let t = run(3, 3, b"AAA\r\nBBB\r\nCCC\x1b[T");
    assert_eq!(row_text(&t, 0), "   ");
    assert_eq!(row_text(&t, 1), "AAA");
    assert_eq!(row_text(&t, 2), "BBB");
}

// --- take_dirty ---------------------------------------------------------------

#[test]
fn take_dirty_is_false_on_a_fresh_term() {
    let mut t = Term::new(4, 10);
    assert!(!t.take_dirty(), "new term must not be dirty");
}

#[test]
fn take_dirty_is_true_after_feed_and_resets_on_second_call() {
    let mut t = Term::new(4, 10);
    t.feed(b"hello");
    assert!(t.take_dirty(), "dirty after feed");
    assert!(!t.take_dirty(), "dirty resets on second take_dirty");
}

#[test]
fn take_dirty_is_false_after_empty_feed() {
    let mut t = Term::new(4, 10);
    t.feed(b"");
    assert!(!t.take_dirty(), "empty feed must not set dirty");
}

#[test]
fn take_dirty_is_true_after_resize() {
    let mut t = Term::new(4, 10);
    t.take_dirty(); // clear any residual
    t.resize(6, 20);
    assert!(t.take_dirty(), "resize must set dirty");
    assert!(!t.take_dirty(), "dirty resets after resize take");
}

#[test]
fn take_dirty_accumulates_across_multiple_feeds_before_reset() {
    let mut t = Term::new(4, 10);
    t.feed(b"A");
    t.feed(b"B");
    assert!(t.take_dirty(), "dirty after two feeds");
    assert!(!t.take_dirty(), "dirty resets after single take");
}

// --- East Asian double-width (atrium-dev-r8 item 3) -------------------------

#[test]
fn wide_glyph_occupies_two_cells_and_advances_by_two() {
    // A CJK ideograph is a width-2 lead cell + a width-0 continuation, and the
    // cursor advances by two columns.
    let t = run(4, 10, "世".as_bytes());
    let s = t.screen();
    assert_eq!(s.cell(0, 0).ch, '世');
    assert_eq!(s.cell(0, 0).width, CellWidth::Wide, "lead cell is width 2");
    assert_eq!(
        s.cell(0, 1).width,
        CellWidth::Continuation,
        "right half is a width-0 continuation"
    );
    assert_eq!(s.cursor(), Cursor::new(0, 2));
}

#[test]
fn wide_glyphs_pack_without_drift() {
    // 世界 lays out as lead,cont,lead,cont across four columns; the cursor ends
    // at column 4 (not 2), so following ASCII lands aligned.
    let t = run(4, 10, "世界X".as_bytes());
    let s = t.screen();
    assert_eq!(s.cell(0, 0).ch, '世');
    assert_eq!(s.cell(0, 1).width, CellWidth::Continuation);
    assert_eq!(s.cell(0, 2).ch, '界');
    assert_eq!(s.cell(0, 3).width, CellWidth::Continuation);
    assert_eq!(s.cell(0, 4).ch, 'X');
    assert_eq!(s.cursor(), Cursor::new(0, 5));
}

#[test]
fn emoji_is_width_two() {
    let t = run(4, 10, "🚀".as_bytes());
    let s = t.screen();
    assert_eq!(s.cell(0, 0).ch, '🚀');
    assert_eq!(s.cell(0, 0).width, CellWidth::Wide);
    assert_eq!(s.cell(0, 1).width, CellWidth::Continuation);
    assert_eq!(s.cursor(), Cursor::new(0, 2));
}

#[test]
fn wide_glyph_at_right_edge_wraps_whole_not_split() {
    // Cursor at the last column (col 4 of a 5-wide term) with a wide glyph: it
    // cannot be split, so the WHOLE glyph wraps to the next line. The last
    // column of the first row stays blank (never a half glyph), and borders in
    // a compositor stay aligned.
    let t = run(3, 5, b"ABCD\xe4\xb8\x96"); // "ABCD" then 世
    let s = t.screen();
    assert_eq!(
        row_text(&t, 0),
        "ABCD ",
        "row 0 keeps its blank last column"
    );
    assert_eq!(
        s.cell(0, 4).width,
        CellWidth::Single,
        "last column is a blank, not a half glyph"
    );
    assert_eq!(
        s.cell(1, 0).ch,
        '世',
        "wide glyph wrapped whole to next line"
    );
    assert_eq!(s.cell(1, 0).width, CellWidth::Wide);
    assert_eq!(s.cell(1, 1).width, CellWidth::Continuation);
    assert_eq!(s.cursor(), Cursor::new(1, 2));
}

#[test]
fn cup_then_wide_lands_at_target_and_advances() {
    // CUP to (row 2, col 3) then a wide glyph: it lands exactly there and the
    // cursor advances by two.
    let t = run(6, 12, b"\x1b[3;4H\xe4\xb8\x96"); // CUP 3;4 then 世
    let s = t.screen();
    assert_eq!(s.cell(2, 3).ch, '世');
    assert_eq!(s.cell(2, 3).width, CellWidth::Wide);
    assert_eq!(s.cell(2, 4).width, CellWidth::Continuation);
    assert_eq!(s.cursor(), Cursor::new(2, 5));
}

#[test]
fn zero_width_combining_mark_is_dropped_no_drift() {
    // A base letter followed by a combining acute accent (U+0301): the mark
    // takes no cell and does not move the cursor, so text after it stays put.
    let t = run(4, 10, "e\u{0301}x".as_bytes());
    let s = t.screen();
    assert_eq!(s.cell(0, 0).ch, 'e');
    assert_eq!(s.cell(0, 1).ch, 'x', "combining mark consumed no column");
    assert_eq!(s.cursor(), Cursor::new(0, 2));
}

#[test]
fn wide_glyph_wrap_is_chunk_split_invariant() {
    // The wide glyph's bytes split across feeds must still wrap whole. Feed
    // "ABCD" then 世 one byte at a time.
    let mut t = Term::new(3, 5);
    for b in b"ABCD\xe4\xb8\x96" {
        t.feed(&[*b]);
    }
    let s = t.screen();
    assert_eq!(s.cell(1, 0).ch, '世');
    assert_eq!(s.cursor(), Cursor::new(1, 2));
}

#[test]
fn wide_glyph_at_right_edge_with_autowrap_off_is_dropped_not_split() {
    // atrium-dev-r8 item-5 edge test (reviewer-flagged). DECAWM off (?7l): a
    // wide glyph that cannot fit in the last column is dropped whole — never
    // split, never wrapped. The last column keeps its content and the cursor
    // does not move.
    let mut t = Term::new(2, 4);
    t.feed(b"\x1b[?7l"); // autowrap off
    t.feed(b"\x1b[1;4H"); // cursor to row 1, col 4 → 0-based (0,3), the last column
    t.feed("世".as_bytes()); // wide glyph: no room, autowrap off → dropped
    let s = t.screen();
    assert_ne!(
        s.cell(0, 3).ch,
        '世',
        "wide glyph must not be written at the edge"
    );
    assert_eq!(
        s.cell(0, 3).width,
        CellWidth::Single,
        "no half-glyph lead left behind"
    );
    assert_eq!(
        s.cursor(),
        Cursor::new(0, 3),
        "cursor stays put when the glyph is dropped"
    );
    assert_eq!(s.cell(1, 0).ch, ' ', "nothing wrapped to the next line");
}

// --- the ASCII blit fast path ----------------------------------------------

/// A run of plain ASCII is blitted in one go rather than a character at a time,
/// and that shortcut must be invisible: the same text, split differently or
/// mixed with anything the fast path does not handle, lands in the same cells.
#[test]
fn a_blitted_ascii_run_lands_exactly_where_one_by_one_printing_would() {
    // Whole-row run, then a wrap, then more text — across a chunk split that
    // falls inside the run.
    let mut split = Term::new(3, 10);
    split.feed(b"abcde");
    split.feed(b"fghijklm");
    let whole = run(3, 10, b"abcdefghijklm");
    assert_eq!(row_text(&whole, 0), "abcdefghij");
    assert_eq!(row_text(&whole, 1), "klm       ");
    assert_eq!(
        row_text(&split, 0),
        row_text(&whole, 0),
        "chunking changes nothing"
    );
    assert_eq!(row_text(&split, 1), row_text(&whole, 1));
    assert_eq!(split.screen().cursor(), whole.screen().cursor());

    // Exactly filling a row latches the pending wrap instead of moving off it:
    // the fast path stops one short of the edge and leaves that to `print`.
    let t = run(3, 10, b"0123456789");
    assert_eq!(row_text(&t, 0), "0123456789");
    assert_eq!(
        t.screen().cursor(),
        Cursor::new(0, 9),
        "cursor waits on the last column (deferred wrap)"
    );

    // A wide glyph between two ASCII runs: the fast path hands that character
    // to `print` and picks up again after it.
    let t = run(3, 10, "ab世cd".as_bytes());
    let s = t.screen();
    assert_eq!((s.cell(0, 0).ch, s.cell(0, 1).ch), ('a', 'b'));
    assert_eq!(s.cell(0, 2).ch, '世');
    assert_eq!(s.cell(0, 3).width, CellWidth::Continuation);
    assert_eq!((s.cell(0, 4).ch, s.cell(0, 5).ch), ('c', 'd'));
    assert_eq!(s.cursor(), Cursor::new(0, 6));

    // A control byte ends a run: `\r` returns to column 0 and the text after it
    // overwrites, including the lead half of the wide glyph — which leaves that
    // glyph's continuation cell behind, as it always has.
    let t = run(3, 10, "ab世cd\refg".as_bytes());
    assert_eq!(row_text(&t, 0), "efg cd    ");
}

#[test]
fn new_line_mode_makes_lf_return_to_column_zero() {
    let mut t = Term::new(4, 10);
    t.feed(b"ab\ncd");
    assert_eq!(t.screen().cell(1, 2).ch, 'c', "plain LF keeps the column");
    let mut t = Term::new(4, 10);
    t.feed(b"\x1b[20hab\ncd\x0bef");
    assert_eq!(t.screen().cell(1, 0).ch, 'c', "LNM: LF also returns");
    assert_eq!(t.screen().cell(2, 0).ch, 'e', "VT too");
    t.feed(b"\x1b[20l\ngh");
    assert_eq!(t.screen().cell(3, 2).ch, 'g', "reset: plain LF again");
    // Other ANSI modes are ignored, and do not touch LNM.
    let mut t = Term::new(4, 10);
    t.feed(b"\x1b[20h\x1b[4lx\ny");
    assert_eq!(t.screen().cell(1, 0).ch, 'y');
}

#[test]
fn a_character_split_across_chunks_is_not_skipped_by_the_ascii_path() {
    // The é arrives in two feeds; the ASCII after it must not overtake it.
    let mut t = Term::new(2, 10);
    t.feed(b"caf\xC3");
    t.feed(b"\xA9 ok");
    let row: String = (0..7).map(|c| t.screen().cell(0, c).ch).collect();
    assert_eq!(row, "café ok");
    // The case the guard exists for: a half-received character followed by a
    // chunk that is PURE ASCII. Without the `decoder.is_idle()` check the fast
    // path would write " ok" first and lose the C3 (the screen read "caf ok ").
    let mut t = Term::new(2, 10);
    t.feed(b"caf\xC3");
    t.feed(b" ok");
    let row: String = (0..7).map(|c| t.screen().cell(0, c).ch).collect();
    assert_eq!(row, "caf\u{FFFD} ok");
    let mut t = Term::new(2, 10);
    t.feed(b"a\xE2\x82");
    t.feed(b"bc\r");
    let row: String = (0..3).map(|c| t.screen().cell(0, c).ch).collect();
    assert_eq!(row, "a\u{FFFD}b");
    // A truncated character before a control still renders as U+FFFD.
    let mut t = Term::new(2, 10);
    t.feed(b"a\xE2\x82\rb");
    assert_eq!(t.screen().cell(0, 0).ch, 'b');
    assert_eq!(t.screen().cell(0, 1).ch, '\u{FFFD}');
}

#[test]
fn history_holds_what_scrolls_off_and_survives_a_resize() {
    let mut t = Term::with_history(3, 12, 100);
    for k in 0..10 {
        t.feed(format!("line {k}\r\n").as_bytes());
    }
    // On screen: line 8, line 9, and the empty line the cursor sits on.
    let sb = t.scrollback();
    assert_eq!(sb.history_len(), 8);
    let text =
        |s: &ansi::Screen, age| -> String { (0..6).map(|c| s.history_cell(age, c).ch).collect() };
    assert_eq!(text(sb, 0), "line 7");
    assert_eq!(text(sb, 7), "line 0");
    t.resize(4, 20);
    assert_eq!(
        t.scrollback().history_len(),
        8,
        "a resize keeps the history"
    );
    assert_eq!(text(t.scrollback(), 0), "line 7");
    // ED 3 erases it; the alternate screen never adds to it.
    t.feed(b"\x1b[3J");
    assert_eq!(t.scrollback().history_len(), 0);
    t.feed(b"\x1b[?1049h");
    assert!(t.in_alternate_screen());
    for k in 0..10 {
        t.feed(format!("alt {k}\r\n").as_bytes());
    }
    t.feed(b"\x1b[?1049l");
    assert_eq!(t.scrollback().history_len(), 0);
    // Without history nothing is kept.
    let mut plain = Term::new(3, 12);
    plain.feed(b"a\r\nb\r\nc\r\nd\r\n");
    assert_eq!(plain.scrollback().history_len(), 0);
}

#[test]
fn a_history_byte_cap_bounds_wide_coloured_scrollback_across_a_resize() {
    let mut t = Term::with_history(4, 200, 100_000);
    t.set_history_bytes(200 * 1024);
    // 200 columns, a colour change on every cell: a few KB a line stored.
    let mut line = Vec::new();
    for c in 0..200u32 {
        line.extend_from_slice(format!("\x1b[38;5;{}m{}", c % 200, c % 10).as_bytes());
    }
    line.extend_from_slice(b"\x1b[0m\r\n");
    for _ in 0..2_000 {
        t.feed(&line);
    }
    let cap = 200 * 1024 + 2 * 96 * 1024;
    let h = t.scrollback();
    assert!(h.history_bytes() <= cap, "{} bytes", h.history_bytes());
    assert!(h.history_len() < 2_000, "the oldest went");
    // A resize keeps the cap.
    t.resize(6, 150);
    for _ in 0..2_000 {
        t.feed(&line);
    }
    let h = t.scrollback();
    assert!(
        h.history_bytes() <= cap,
        "{} bytes after a resize",
        h.history_bytes()
    );
}

#[test]
fn mouse_tracking_modes_follow_the_program() {
    use vterm::MouseTracking;
    let mut t = Term::new(24, 80);
    assert_eq!(t.mouse_tracking(), MouseTracking::Off);
    assert!(!t.mouse_sgr());
    // As atrium turns its mouse on: all three, then SGR.
    t.feed(b"\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h");
    assert_eq!(
        t.mouse_tracking(),
        MouseTracking::Motion,
        "the last one set"
    );
    assert!(t.mouse_sgr());
    t.feed(b"\x1b[?1000;1006l");
    assert_eq!(
        t.mouse_tracking(),
        MouseTracking::Off,
        "any reset turns it off"
    );
    assert!(!t.mouse_sgr());
    t.feed(b"\x1b[?1002h");
    assert_eq!(t.mouse_tracking(), MouseTracking::Drag);
    t.feed(b"\x1b[?1000h");
    assert_eq!(
        t.mouse_tracking(),
        MouseTracking::Click,
        "one replaces another"
    );
}

/// A synchronized-output snapshot (`?2026h`) is the visible rows only: while
/// it is open `screen()` reads no scrollback, and the history is intact once
/// it closes. RED-when-broken: snapshotting with `.clone()` copies the
/// history too, and `history_len()` is non-zero inside the frame.
#[test]
fn a_sync_snapshot_carries_no_scrollback() {
    let mut t = Term::with_history(2, 10, 100);
    for i in 0..20 {
        t.feed(format!("line{i}\r\n").as_bytes());
    }
    let before = t.screen().history_len();
    assert!(before > 0, "the history filled: {before}");
    t.feed(b"\x1b[?2026h");
    assert!(t.in_sync());
    assert_eq!(
        t.screen().history_len(),
        0,
        "the frame is the visible rows only"
    );
    t.feed(b"\x1b[?2026l");
    assert!(!t.in_sync());
    assert_eq!(t.screen().history_len(), before, "the history is untouched");
}