termlens 0.11.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
//! The rendered screen grid: [`Screen`], [`Cell`], [`Style`], [`Color`].
//!
//! A [`Screen`] is an immutable snapshot of the emulated terminal at one
//! moment. It is a cheap-to-clone value type (the grid is behind an [`Arc`]),
//! so errors and assertions can carry whole screens around freely.

use std::fmt;
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;

use unicode_normalization::UnicodeNormalization;

use crate::graphics::GraphicsSeen;

mod diff;
mod parse;
mod render;
#[cfg(feature = "serde")]
mod serde_impl;

pub use diff::ScreenDiff;

/// A terminal color, as reported by the emulator.
///
/// Deliberately *not* `#[non_exhaustive]`, unlike [`Key`](crate::Key) and
/// [`Signal`](crate::Signal). The terminal colour model is closed —
/// default, a palette index, or 24-bit RGB, which is also exactly what
/// every VT emulator reports — so there is no fourth variant waiting to be
/// added, and `Color` is the one enum here that downstream code really
/// does `match` on. Leaving it exhaustive keeps those matches complete;
/// equality (`cell.style().fg == Color::Indexed(1)`) is unaffected either
/// way.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum Color {
    /// The terminal's default foreground/background.
    #[default]
    Default,
    /// A palette color (0–255).
    Indexed(u8),
    /// A 24-bit RGB color.
    Rgb(u8, u8, u8),
}

impl fmt::Display for Color {
    /// The token the `styles:` block of the snapshot format writes
    /// (`docs/DESIGN.md` §3): a palette index as decimal (`4`), an RGB
    /// colour as `#rrggbb` (`#1e1e2e`). [`Color::Default`] renders as
    /// `default`, which the block itself never writes — a default-styled
    /// span is omitted, so absence means default — but a message that
    /// prints a cell's colour needs a word for it.
    ///
    /// `Screen::parse` reads the indexed and RGB forms back, so a colour
    /// printed this way round-trips through a saved screen.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Color::Default => f.write_str("default"),
            Color::Indexed(i) => write!(f, "{i}"),
            Color::Rgb(r, g, b) => write!(f, "#{r:02x}{g:02x}{b:02x}"),
        }
    }
}

/// Visual attributes of a [`Cell`].
///
/// Inspect them per cell via [`Cell::style`], or snapshot them wholesale
/// with [`Screen::with_styles`] (plain snapshots stay text-only).
/// More terminal attributes may be added in future releases. To construct a
/// style for comparison, start from `Style::default()` and assign the fields
/// relevant to the assertion rather than using a struct literal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Style {
    /// Foreground color.
    pub fg: Color,
    /// Background color.
    pub bg: Color,
    /// Bold / increased intensity (`SGR 1`).
    ///
    /// `bold` and `dim` are two fields over **one** intensity state: the
    /// last of `SGR 1` and `SGR 2` written wins, so a cell never reports
    /// both, and `ESC[1;2m` reads as dim only. `SGR 22` clears whichever
    /// is set.
    pub bold: bool,
    /// Dim / decreased intensity (`SGR 2`). Shares one intensity state with
    /// [`bold`](Self::bold): last write wins, never both.
    pub dim: bool,
    /// Italic.
    pub italic: bool,
    /// Underline.
    pub underline: bool,
    /// Reverse video (foreground and background swapped).
    pub reverse: bool,
    /// Blinking (`SGR 5`/`6`; the two rates are not distinguished).
    pub blink: bool,
    /// Concealed: the cell holds text the terminal does not display
    /// (`SGR 8`) — a masked password field, typically.
    ///
    /// This is the attribute worth checking explicitly. Without it, a test
    /// asserting that a field is masked passes just as happily against an
    /// application that printed the secret in clear, because the two
    /// renderings are identical in the grid. [`Screen::cell`] still reports
    /// the underlying text, exactly as a real terminal holds it — what
    /// changes is that you can now tell the difference.
    pub conceal: bool,
    /// Struck through (`SGR 9`).
    pub strikethrough: bool,
}

/// Which mouse events the application asked its terminal to report.
///
/// Read it from a snapshot via [`Screen::mouse_mode`];
/// [`Terminal::click`](crate::Terminal::click) and
/// [`Terminal::scroll`](crate::Terminal::scroll) consult the same state to
/// encode exactly what the application expects.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum MouseMode {
    /// No mouse tracking enabled.
    #[default]
    None,
    /// X10 mode (`CSI ?9 h`): presses only.
    Press,
    /// VT200 mode (`CSI ?1000 h`): presses and releases.
    PressRelease,
    /// Button-event tracking (`CSI ?1002 h`): presses, releases, and motion
    /// while a button is held down.
    ButtonMotion,
    /// Any-event tracking (`CSI ?1003 h`): presses, releases, and all
    /// motion.
    AnyMotion,
}

impl MouseMode {
    /// The bit this mode occupies in a [`MouseModes`] set; `None` has none.
    fn bit(self) -> u8 {
        match self {
            MouseMode::None => 0,
            MouseMode::Press => 1,
            MouseMode::PressRelease => 2,
            MouseMode::ButtonMotion => 4,
            MouseMode::AnyMotion => 8,
        }
    }

    /// Every tracking mode, in the order of the private modes that enable
    /// them: `?9`, `?1000`, `?1002`, `?1003`.
    const TRACKING: [MouseMode; 4] = [
        MouseMode::Press,
        MouseMode::PressRelease,
        MouseMode::ButtonMotion,
        MouseMode::AnyMotion,
    ];
}

/// The set of mouse tracking modes an application has enabled and not yet
/// disabled — what it *asked for*, as distinct from the one protocol the
/// terminal reports in, which is [`Screen::mouse_mode`].
///
/// A terminal reports mouse events in exactly one protocol, so the four
/// tracking modes collapse into one value on the input path: enabling
/// `?1003` after `?1002` upgrades the reports, disabling either turns them
/// off. But an application enables them as a set — crossterm's
/// `EnableMouseCapture` sends `?1000`, `?1002` and `?1003` together — and
/// "did it ask for any-motion tracking, or only button-motion?" is a
/// question about that set. Whether hovering does anything at all hangs on
/// it, and a regression from `?1003` to `?1002` passes every test that
/// only reads the collapsed value while the last mode sent stays the same.
///
/// Read it from a snapshot via [`Screen::mouse_modes`]:
///
/// ```no_run
/// # fn main() -> termlens::Result<()> {
/// # let mut t = termlens::Terminal::builder().spawn("true")?;
/// use termlens::MouseMode;
/// t.wait_until(|s| s.mouse_modes().contains(MouseMode::AnyMotion))?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MouseModes(u8);

impl MouseModes {
    pub(crate) fn from_bits(bits: u8) -> Self {
        Self(bits)
    }

    /// Whether the application currently has `mode` enabled.
    ///
    /// [`MouseMode::None`] is not a tracking mode; asking for it answers
    /// whether the set is empty, so `contains(MouseMode::None)` reads as
    /// "the application asked for no tracking at all".
    #[must_use]
    pub fn contains(self, mode: MouseMode) -> bool {
        match mode {
            MouseMode::None => self.is_empty(),
            tracking => self.0 & tracking.bit() != 0,
        }
    }

    /// True while no tracking mode is enabled.
    #[must_use]
    pub fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// How many tracking modes are enabled.
    #[must_use]
    pub fn len(self) -> usize {
        self.0.count_ones() as usize
    }

    /// The enabled modes, in the order of the private modes that enable
    /// them (`?9`, `?1000`, `?1002`, `?1003`).
    pub fn iter(self) -> impl Iterator<Item = MouseMode> {
        MouseMode::TRACKING
            .into_iter()
            .filter(move |mode| self.0 & mode.bit() != 0)
    }
}

impl fmt::Debug for MouseModes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

/// The shape of the cursor an application asked its terminal for with
/// `DECSCUSR` (`CSI Ps SP q`).
///
/// Read it from a snapshot via [`Screen::cursor_shape`], and whether it
/// blinks via [`Screen::cursor_blink`] — one parameter carries both, but
/// they are two facts and a test usually wants only one of them.
///
/// The shape is load-bearing behaviour rather than decoration: a modal
/// editor switches to a bar for insert and back to a block for normal, and
/// "the mode indicator says INSERT" and "the terminal was actually put into
/// insert" are different claims. It also makes the *restore* assertable — a
/// program that changes the cursor and never changes it back leaves the
/// user's terminal wrong after exit, the same class of defect
/// [`Screen::alternate_screen`] already catches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum CursorShape {
    /// The application never sent `DECSCUSR`, so the cursor is whatever the
    /// terminal draws by default.
    ///
    /// Deliberately not folded into [`Block`](CursorShape::Block): a
    /// terminal's default usually *is* a block, but "never asked" and
    /// "asked for a block" are different claims about the program, and only
    /// one of them survives a refactor that drops the escape.
    #[default]
    Default,
    /// A filled block — `DECSCUSR` 0 and 1 (blinking) or 2 (steady).
    Block,
    /// An underline — `DECSCUSR` 3 (blinking) or 4 (steady).
    Underline,
    /// A vertical bar — `DECSCUSR` 5 (blinking) or 6 (steady).
    Bar,
}

/// What an application copied with `OSC 52`, as observed at one snapshot.
///
/// What the emulator did not implement while producing a [`Screen`] — the
/// view [`Screen::unsupported`] returns.
///
/// Distinct sequence shapes, first seen first, in the form the timeout
/// messages use (`^[[20h` for `CSI 20 h`), at most 32 retained;
/// [`overflow`](Self::overflow) counts the distinct shapes beyond those, so
/// a stream that invents thousands cannot grow a snapshot and "nothing was
/// dropped" is one check, [`is_empty`](Self::is_empty).
///
/// A view rather than a slice, so how the screen stores the list — cheap to
/// clone, today — is not part of the public API. `Copy`, borrowing the
/// screen; compares equal to an array or slice of `&str` when the retained
/// shapes match in order and nothing overflowed, so a pin reads
/// `assert_eq!(s.unsupported(), ["^[[59m"])`.
#[derive(Clone, Copy)]
pub struct Unsupported<'a> {
    retained: &'a [Arc<str>],
    overflow: u64,
}

impl<'a> Unsupported<'a> {
    /// True when nothing unsupported was seen at all — no retained shape
    /// and no overflow.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.retained.is_empty() && self.overflow == 0
    }

    /// Distinct shapes retained (at most 32). Not the total: add
    /// [`overflow`](Self::overflow) for that.
    #[must_use]
    pub fn len(&self) -> usize {
        self.retained.len()
    }

    /// The retained shapes, first seen first.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a str> + 'a {
        self.retained.iter().map(|shape| &**shape)
    }

    /// Whether `sequence` — in the same form, e.g. `"^[[5m"` — is among the
    /// retained shapes. A shape past the retention bound is counted in
    /// [`overflow`](Self::overflow) and cannot be found here.
    #[must_use]
    pub fn contains(&self, sequence: &str) -> bool {
        self.retained.iter().any(|shape| &**shape == sequence)
    }

    /// Distinct shapes seen beyond the 32 retained, counted only.
    #[must_use]
    pub fn overflow(&self) -> u64 {
        self.overflow
    }
}

impl<'a> IntoIterator for Unsupported<'a> {
    type Item = &'a str;
    type IntoIter = UnsupportedIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        UnsupportedIter(self.retained.iter())
    }
}

/// The iterator over an [`Unsupported`] view's retained shapes.
#[derive(Debug, Clone)]
pub struct UnsupportedIter<'a>(std::slice::Iter<'a, Arc<str>>);

impl<'a> Iterator for UnsupportedIter<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<&'a str> {
        self.0.next().map(|shape| &**shape)
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for UnsupportedIter<'_> {}

impl fmt::Debug for Unsupported<'_> {
    /// `["^[[59m"]`, or `["^[[20h", …] (+8 more)` when shapes overflowed.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()?;
        if self.overflow > 0 {
            write!(f, " (+{} more)", self.overflow)?;
        }
        Ok(())
    }
}

impl PartialEq for Unsupported<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.overflow == other.overflow && self.iter().eq(other.iter())
    }
}

impl Eq for Unsupported<'_> {}

/// Equal to a slice of shapes when the retained shapes match in order and
/// nothing overflowed — so `assert_eq!(s.unsupported(), ["^[[59m"])` pins
/// the whole record, and an empty array pins "nothing unsupported".
impl PartialEq<[&str]> for Unsupported<'_> {
    fn eq(&self, other: &[&str]) -> bool {
        self.overflow == 0 && self.iter().eq(other.iter().copied())
    }
}

impl<const N: usize> PartialEq<[&str; N]> for Unsupported<'_> {
    fn eq(&self, other: &[&str; N]) -> bool {
        *self == other[..]
    }
}

impl PartialEq<&[&str]> for Unsupported<'_> {
    fn eq(&self, other: &&[&str]) -> bool {
        *self == **other
    }
}

/// Read it from a snapshot via [`Screen::clipboard`]. A toast on screen
/// proves the copy path ran; this proves the payload, which is usually the
/// behaviour actually under test.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Clipboard {
    targets: Arc<str>,
    text: Option<Arc<str>>,
}

impl Clipboard {
    pub(crate) fn new(targets: &str, text: Option<String>) -> Self {
        Self {
            targets: Arc::from(targets),
            text: text.map(Arc::from),
        }
    }

    /// The copied text, or `None` when the payload was not usable text.
    ///
    /// `None` means the application sent something termlens could not
    /// decode: base64 with invalid characters or a broken length, bytes
    /// that are not valid UTF-8, or a payload past the capture bound. It is
    /// deliberately distinct from `Some("")`, which is a real write of
    /// nothing — the way an application clears the clipboard.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        self.text.as_deref()
    }

    /// The selections written to, exactly as the application named them:
    /// `c` (clipboard), `p` (primary), `q`, `s`, or `0`–`7`, in any
    /// combination — an application writing to the wrong one is a real bug
    /// worth catching.
    ///
    /// Empty means the application named none, in which case a real
    /// terminal picks its default (xterm: clipboard *and* primary).
    #[must_use]
    pub fn targets(&self) -> &str {
        &self.targets
    }
}

/// A hyperlink an application emitted with `OSC 8`, as observed at one
/// snapshot.
///
/// Read them from a snapshot via [`Screen::links`]. A hyperlink changes no
/// cell — the label is drawn exactly as unlinked text would be — so without
/// this a test asserting that a TUI linked an issue, a file or a doc page
/// **passes identically against an application that emitted no link at all,
/// or linked the wrong URL**. That is the failure
/// [`Screen::clipboard`] exists to prevent for `OSC 52`, in the same shape.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Link {
    uri: Arc<str>,
    id: Option<Arc<str>>,
    label: Option<Arc<str>>,
    closed: bool,
}

impl Link {
    pub(crate) fn open(uri: &str, id: Option<&str>) -> Self {
        Self {
            uri: Arc::from(uri),
            id: id.map(Arc::from),
            label: None,
            closed: false,
        }
    }

    pub(crate) fn close(&mut self, label: Option<String>) {
        self.label = label.map(Arc::from);
        self.closed = true;
    }

    /// The URI the application linked to, as it wrote it.
    ///
    /// Bytes that are not valid UTF-8 are replaced rather than refused: an
    /// `OSC 8` target is percent-encoded ASCII by construction, so a URI
    /// that is not text is already malformed, and a replacement character
    /// makes it compare unequal to whatever the test expected — which is
    /// the right outcome — while still showing what arrived.
    #[must_use]
    pub fn uri(&self) -> &str {
        &self.uri
    }

    /// The `id=` parameter, if the application gave one.
    ///
    /// Spans sharing an id are one logical link — the way a terminal knows
    /// that a path broken across two lines highlights as a single target —
    /// so grouping by this is how a multi-span link is asserted as one.
    #[must_use]
    pub fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }

    /// The text the link wrapped: what a reader sees and clicks.
    ///
    /// `None` means the label is not knowable, which is two situations that
    /// [`closed`](Self::closed) tells apart: the span is still open and has
    /// no final text yet, or the application wrote more while it was open
    /// than termlens keeps, so what was captured is a prefix and returning
    /// it as *the* label would be a lie. `Some("")` is a real link around
    /// no text at all.
    ///
    /// Control characters are not part of a label: a newline inside a span
    /// moves the cursor, it does not spell anything.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Whether the application closed the span (`OSC 8 ; ; ST`).
    ///
    /// False is worth asserting against. A link left open is not a
    /// cosmetic slip: in a real terminal every character written afterwards
    /// joins it, so a whole screen becomes clickable and points at the
    /// wrong place.
    #[must_use]
    pub fn closed(&self) -> bool {
        self.closed
    }
}

/// Out-of-band terminal state captured with each snapshot. Deliberately
/// invisible in the text rendering (existing snapshot files stay valid);
/// exposed through the accessors on [`Screen`].
///
/// Held behind a single [`Arc`] on [`Screen`], for two reasons that pull the
/// same way. `Screen` is embedded in every [`Error`](crate::Error), so its
/// size is load-bearing — enough scalars here and `Result<T>` grows past
/// what clippy's `result_large_err` will accept. And a `Screen` clone then
/// bumps one refcount instead of copying every field, which matters because
/// a clone happens on each wait evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct TermState {
    pub(crate) title: Arc<str>,
    pub(crate) alternate_screen: bool,
    pub(crate) bracketed_paste: bool,
    pub(crate) application_cursor: bool,
    /// The one protocol the terminal reports in — the backend's collapsed
    /// value, which is also what `click` and `scroll` encode for.
    pub(crate) mouse: MouseMode,
    /// The tracking modes the application has asked for and not yet
    /// released, kept by the sequence tracker (#151).
    pub(crate) mouse_modes: MouseModes,
    /// Behind an `Arc` deliberately: `Screen` is embedded in every
    /// `Error` and cloned on every wait, so its size is load-bearing.
    pub(crate) clipboard: Option<Arc<Clipboard>>,
    /// Bells rung in ground state (a `BEL` terminating an OSC string is a
    /// terminator, not a bell).
    pub(crate) bells: u64,
    /// Whether the application enabled focus reporting (mode 1004).
    pub(crate) focus_events: bool,
    /// The raw `DECSCUSR` parameter last requested; `None` until the
    /// application asks. One `Option<u8>` rather than a shape and a blink
    /// flag, because the parameter is what the application actually said.
    pub(crate) cursor_style: Option<u8>,
    /// `OSC 8` hyperlinks emitted, oldest first, behind an `Arc` so a
    /// snapshot costs one refcount rather than a copy of every link.
    pub(crate) links: Arc<Vec<Link>>,
    /// Inline graphics payloads transmitted.
    pub(crate) graphics: GraphicsSeen,
    /// Completed synchronized updates. Filled in by the terminal rather
    /// than the emulator, which does not own the frame count.
    pub(crate) repaints: u64,
    /// Rows that have scrolled off the top, oldest first, as text.
    ///
    /// Text rather than cells, deliberately: a thousand rows of styled
    /// cells per snapshot would dominate the cost of every wait, and
    /// history is asserted on for its content. The rows are shared, so a
    /// snapshot pays one `Arc` clone each.
    pub(crate) scrollback: Arc<[Arc<str>]>,
    /// The scrolled-off rows as cells, when the terminal retains styled
    /// history; `None` when it does not. In lockstep with `scrollback`.
    pub(crate) scrollback_cells: Option<Arc<[Arc<[Cell]>]>>,
    /// Per row, whether it ended in a soft wrap rather than a line end —
    /// the backend's own record, never asked for before #265.
    pub(crate) wrapped: Arc<[bool]>,
    /// `IRM` is set: the application left the terminal in insert mode.
    pub(crate) insert_mode: bool,
    /// Escape sequences nobody honoured, distinct, first seen first (#266).
    pub(crate) unsupported: Arc<[Arc<str>]>,
    /// Distinct unsupported shapes beyond the bound, counted only.
    pub(crate) unsupported_overflow: u64,
    /// `ESC g` seen: a flash rather than a beep.
    pub(crate) visual_bells: u64,
}

impl Default for TermState {
    fn default() -> Self {
        Self {
            title: Arc::from(""),
            alternate_screen: false,
            bracketed_paste: false,
            application_cursor: false,
            mouse: MouseMode::None,
            mouse_modes: MouseModes::default(),
            clipboard: None,
            bells: 0,
            focus_events: false,
            cursor_style: None,
            links: Arc::new(Vec::new()),
            graphics: GraphicsSeen::default(),
            repaints: 0,
            scrollback: Arc::from([] as [Arc<str>; 0]),
            scrollback_cells: None,
            wrapped: Arc::from([] as [bool; 0]),
            insert_mode: false,
            unsupported: Arc::from([] as [Arc<str>; 0]),
            unsupported_overflow: 0,
            visual_bells: 0,
        }
    }
}

/// One cell of the screen grid.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Cell {
    contents: String,
    style: Style,
    wide: bool,
    wide_continuation: bool,
}

impl Cell {
    pub(crate) fn new(contents: String, style: Style, wide: bool, wide_continuation: bool) -> Self {
        Self {
            contents,
            style,
            wide,
            wide_continuation,
        }
    }

    /// The cell's text: usually a single grapheme (possibly with combining
    /// characters). Empty for blank cells and for wide-continuation cells.
    #[must_use]
    pub fn contents(&self) -> &str {
        &self.contents
    }

    /// The cell's visual attributes.
    #[must_use]
    pub fn style(&self) -> &Style {
        &self.style
    }

    /// True if the cell holds a double-width character (CJK, most emoji).
    /// The following cell is then a wide-continuation placeholder.
    #[must_use]
    pub fn is_wide(&self) -> bool {
        self.wide
    }

    /// True if this cell is the placeholder occupying the second column of a
    /// double-width character.
    #[must_use]
    pub fn is_wide_continuation(&self) -> bool {
        self.wide_continuation
    }
}

/// Whether two cursors look the same on screen.
///
/// A hidden cursor draws nothing, so *where* it sits is not part of the
/// picture — and the snapshot text format does not record it, which is what
/// made a parsed snapshot report a difference against its own original that
/// no one could see (#298). A visible cursor's position is part of the
/// picture, and so is the visibility itself.
pub(crate) fn same_cursor(a: (u16, u16, bool), b: (u16, u16, bool)) -> bool {
    match (a.2, b.2) {
        (false, false) => true,
        (true, true) => (a.0, a.1) == (b.0, b.1),
        _ => false,
    }
}

/// Where [`Screen::locate`] found a needle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Location {
    /// On the visible grid, at this `(row, col)` — the same coordinates
    /// [`Screen::find`] reports.
    Screen {
        /// Grid row, zero-based from the top.
        row: u16,
        /// Grid column, zero-based, a real terminal column.
        col: u16,
    },
    /// In the retained history, in row `row` counting from the oldest
    /// retained row, at display column `col` of that row as it was
    /// captured. Not a grid coordinate, and not stable across a resize.
    History {
        /// History row, oldest first.
        row: usize,
        /// Display column within that row, as captured.
        col: u16,
    },
}

impl Location {
    /// True when the needle is on the visible grid.
    ///
    /// ```text
    /// assert!(s.locate("total").is_some_and(Location::is_on_screen));
    /// ```
    #[must_use]
    pub fn is_on_screen(self) -> bool {
        matches!(self, Location::Screen { .. })
    }

    /// True when the needle has scrolled off into the retained history.
    #[must_use]
    pub fn is_in_history(self) -> bool {
        matches!(self, Location::History { .. })
    }

    /// The column, in either region: a real terminal column on the grid,
    /// the display column of the row *as it was captured* in history.
    /// Both are zero-based and both answer "how far along the row".
    ///
    /// There is deliberately no `row()`. The two rows are different
    /// things — a grid row counted from the top of the screen, a history
    /// row counted from the oldest retained line — and one accessor
    /// returning either would invite exactly the confusion this enum
    /// exists to prevent. Match on the variant when the row matters.
    #[must_use]
    pub fn col(self) -> u16 {
        match self {
            Location::Screen { col, .. } | Location::History { col, .. } => col,
        }
    }
}

/// An immutable snapshot of the terminal screen.
///
/// Cheap to clone (the grid is shared behind an [`Arc`]); every clone
/// observes the same instant. Coordinates are `(row, col)`, zero-based,
/// with `(0, 0)` at the top left. [`Screen::size`] follows the terminal
/// convention of *columns × rows* instead — the same order as
/// [`TerminalBuilder::size`](crate::TerminalBuilder::size).
///
/// The [`Display`](fmt::Display) rendering is the snapshot format documented
/// in `docs/DESIGN.md`: a header line, then the grid with trailing
/// whitespace stripped per line. Trailing blanks are *preserved* inside the
/// grid itself, so coordinate queries like [`Screen::cell`] and
/// [`Screen::find`] are unaffected by the trimming.
///
/// # Equality
///
/// `==` means **the same observation**: every cell, the cursor, the size,
/// and all the out-of-band state — title, modes, clipboard, links,
/// graphics, retained history, and the cumulative
/// [`repaints`](Self::repaints) and [`bells`](Self::bells) counters — agree.
/// That is deliberately stricter than "looks the same": two visually
/// identical snapshots taken either side of a bell compare unequal, because
/// they *are* different moments, and a test asking "did anything change?"
/// usually wants to hear about the bell. For "looks the same", compare
/// [`with_styles`](Self::with_styles) renderings, which cover text and
/// style and nothing invisible. Comparing plain `to_string()` output is the
/// trap to avoid: [`Display`](fmt::Display) is text only, so two screens
/// that differ only in a highlight, a colour or a concealed field compare
/// equal that way.
#[derive(Clone, PartialEq, Eq)]
pub struct Screen {
    cols: u16,
    rows: u16,
    cursor_row: u16,
    cursor_col: u16,
    cursor_visible: bool,
    cells: Arc<[Cell]>,
    state: Arc<TermState>,
}

impl Screen {
    pub(crate) fn from_parts(
        cols: u16,
        rows: u16,
        cursor_row: u16,
        cursor_col: u16,
        cursor_visible: bool,
        cells: Vec<Cell>,
        state: TermState,
    ) -> Self {
        debug_assert_eq!(cells.len(), usize::from(cols) * usize::from(rows));
        Self {
            cols,
            rows,
            cursor_row,
            cursor_col,
            cursor_visible,
            cells: cells.into(),
            state: Arc::new(state),
        }
    }

    /// Whether two snapshots show the same picture: size, cursor and every
    /// cell. Deliberately not `==`, which also compares the out-of-band
    /// state — bells, repaints, the title — none of which is a picture.
    /// This is what `wait_stable` watches.
    pub(crate) fn same_picture(&self, other: &Screen) -> bool {
        self.cols == other.cols
            && self.rows == other.rows
            && same_cursor(self.cursor(), other.cursor())
            && (Arc::ptr_eq(&self.cells, &other.cells) || self.cells == other.cells)
    }

    /// Stamp the repaint count onto a freshly built snapshot.
    ///
    /// The count lives on the terminal, not the emulator: it is the same
    /// counter `wait_frame`'s cursor is built on, and a second one in the
    /// emulator could drift from it.
    pub(crate) fn with_repaints(mut self, repaints: u64) -> Self {
        // Called on a snapshot nobody else holds yet, so `make_mut` mutates
        // in place rather than cloning.
        Arc::make_mut(&mut self.state).repaints = repaints;
        self
    }

    /// Number of columns (the screen's width).
    #[must_use]
    pub fn cols(&self) -> u16 {
        self.cols
    }

    /// Number of rows (the screen's height).
    #[must_use]
    pub fn rows(&self) -> u16 {
        self.rows
    }

    /// Screen size as `([cols](Self::cols), [rows](Self::rows))` — width ×
    /// height, matching [`TerminalBuilder::size`](crate::TerminalBuilder::size).
    /// Note the order differs from cell addressing, which is `(row, col)`;
    /// prefer the named accessors when in doubt.
    #[must_use]
    pub fn size(&self) -> (u16, u16) {
        (self.cols, self.rows)
    }

    /// Cursor position and visibility: `(row, col, visible)`.
    ///
    /// The position is what most callers want; for the visibility alone,
    /// [`cursor_visible`](Self::cursor_visible) says so at the call site
    /// instead of `.2`.
    #[must_use]
    pub fn cursor(&self) -> (u16, u16, bool) {
        (self.cursor_row, self.cursor_col, self.cursor_visible)
    }

    /// Whether the cursor is shown (`DECTCEM`, `CSI ? 25 h`/`l`) — the
    /// third element of [`cursor`](Self::cursor), on its own, so an
    /// assertion reads as what it checks:
    ///
    /// ```text
    /// assert!(!s.cursor_visible(), "a list view hides the cursor: {s}");
    /// ```
    ///
    /// The snapshot header renders this as `cursor: hidden`; a hidden
    /// cursor's position is still reported by `cursor()` but is not part
    /// of the picture [`diff`](Self::diff) compares.
    #[must_use]
    pub fn cursor_visible(&self) -> bool {
        self.cursor_visible
    }

    /// The cursor shape the application asked for with `DECSCUSR`
    /// (`CSI Ps SP q`), or [`CursorShape::Default`] while it has never
    /// asked — which is a real state, and not the same as asking for a
    /// block.
    ///
    /// Like all out-of-band state this is invisible in the
    /// [`Display`](fmt::Display) rendering, so assert on it directly:
    ///
    /// ```text
    /// t.wait_until(|s| s.cursor_shape() == CursorShape::Bar)?;   // insert mode
    /// t.send(Key::Esc)?;
    /// t.wait_until(|s| s.cursor_shape() == CursorShape::Block)?; // and back
    /// ```
    ///
    /// A hard reset (`RIS`, `ESC c`) returns this to
    /// [`CursorShape::Default`] — a program that restores the cursor that
    /// way really has handed the terminal back its own default, and
    /// reporting the last `DECSCUSR` would claim otherwise.
    #[must_use]
    pub fn cursor_shape(&self) -> CursorShape {
        match self.state.cursor_style {
            None => CursorShape::Default,
            Some(0..=2) => CursorShape::Block,
            Some(3..=4) => CursorShape::Underline,
            Some(5..=6) => CursorShape::Bar,
            // The tracker only ever stores 0..=6; anything else would be a
            // value it declined to interpret, and guessing a shape here is
            // the one thing this accessor must not do.
            Some(_) => CursorShape::Default,
        }
    }

    /// Whether the cursor the application asked for blinks.
    ///
    /// `None` while [`cursor_shape`](Self::cursor_shape) is
    /// [`CursorShape::Default`]: the application never said, and the
    /// terminal's own default rate is not ours to claim. Shape and blink
    /// travel in one `DECSCUSR` parameter but are two independent facts —
    /// an editor that wants a steady bar and gets a blinking one has a real
    /// bug, and it is invisible in the grid.
    #[must_use]
    pub fn cursor_blink(&self) -> Option<bool> {
        match self.state.cursor_style {
            Some(0 | 1 | 3 | 5) => Some(true),
            Some(2 | 4 | 6) => Some(false),
            _ => None,
        }
    }

    /// The `OSC 8` hyperlinks the application emitted, oldest first.
    ///
    /// A hyperlink leaves the grid identical, so this is the only place the
    /// URL exists — the label renders as ordinary text and
    /// [`row_text`](Self::row_text) never sees the target:
    ///
    /// ```text
    /// $ printf 'see \033]8;;https://example.invalid/a\033\\docs\033]8;;\033\\ here\n'
    /// s.row_text(0)                      == "see docs here"
    /// s.links()[0].label()               == Some("docs")
    /// s.links()[0].uri()                 == "https://example.invalid/a"
    /// ```
    ///
    /// One entry per span *emitted*, not per distinct target: an
    /// application that redraws its links on every repaint appends them
    /// again each time. The log is bounded at the most recent 64 spans and
    /// evicts oldest-first, so the current frame's links are always present
    /// and an application that leaks links cannot grow this without limit.
    /// Assert with `.iter().any(…)` rather than on the length.
    ///
    /// Like all out-of-band state, links are invisible in the
    /// [`Display`](fmt::Display) rendering.
    #[must_use]
    pub fn links(&self) -> &[Link] {
        &self.state.links
    }

    /// The window title, as the application most recently set it (`OSC 0`
    /// or `OSC 2` — crossterm's `SetTitle`). Empty until the application
    /// sets one; `OSC 1` (icon name only) is ignored. termlens tracks the
    /// title itself, so it works regardless of the emulator backend.
    ///
    /// Like all out-of-band state, the title is not part of the
    /// [`Display`](fmt::Display) rendering — assert on it directly:
    /// `wait_until(|s| s.title() == "editor — draft.txt")`.
    #[must_use]
    pub fn title(&self) -> &str {
        &self.state.title
    }

    /// True while the application has the alternate screen active (modes
    /// 47/1049) — the buffer full-screen TUIs switch to on startup and
    /// leave on exit, restoring the shell's scrollback.
    #[must_use]
    pub fn alternate_screen(&self) -> bool {
        self.state.alternate_screen
    }

    /// True while bracketed paste (mode 2004) is enabled.
    /// [`Terminal::paste`](crate::Terminal::paste) consults this: the text
    /// then arrives as one paste event instead of a burst of key presses.
    #[must_use]
    pub fn bracketed_paste(&self) -> bool {
        self.state.bracketed_paste
    }

    /// True while application cursor mode (DECCKM) is set.
    /// [`Terminal::send`](crate::Terminal::send) consults this: arrow keys
    /// then use their `ESC O` application forms.
    #[must_use]
    pub fn application_cursor(&self) -> bool {
        self.state.application_cursor
    }

    /// True while the application has focus reporting (mode 1004) enabled.
    /// [`Terminal::focus_in`](crate::Terminal::focus_in) and
    /// [`Terminal::focus_out`](crate::Terminal::focus_out) consult the same
    /// state, so a test can assert the application asked for focus events
    /// before trying to deliver one.
    #[must_use]
    pub fn focus_events(&self) -> bool {
        self.state.focus_events
    }

    /// The protocol mouse events are reported in — [`MouseMode::None`]
    /// until the application enables a tracking mode.
    /// [`Terminal::click`](crate::Terminal::click) and
    /// [`Terminal::scroll`](crate::Terminal::scroll) consult the same
    /// state, so their reports always match what the application expects.
    ///
    /// One value, because a terminal reports in one protocol: the four
    /// tracking modes are mutually exclusive on the wire, the last one
    /// enabled wins, and disabling any of them turns reporting off. For the
    /// *set* the application asked for — which distinguishes an
    /// application that enabled `?1002` and `?1003` from one that enabled
    /// `?1003` alone — see [`mouse_modes`](Self::mouse_modes).
    #[must_use]
    pub fn mouse_mode(&self) -> MouseMode {
        self.state.mouse
    }

    /// Every mouse tracking mode the application has enabled and not yet
    /// disabled, as a set — see [`MouseModes`] for why the set and the
    /// reporting protocol are two different facts.
    ///
    /// `DECRQM` answers each tracking mode from this same set, so an
    /// application that probes `?1002` while `?1003` is also on is told
    /// "set" rather than "not recognized".
    #[must_use]
    pub fn mouse_modes(&self) -> MouseModes {
        self.state.mouse_modes
    }

    /// The most recent `OSC 52` clipboard write observed at this snapshot,
    /// or `None` if the application has not copied anything yet.
    ///
    /// Snapshot state, so it follows snapshot rules: the value is what the
    /// clipboard held at this observation, which makes a
    /// [`wait_frame`](crate::Terminal::wait_frame) or
    /// [`wait_until`](crate::Terminal::wait_until) predicate over a
    /// clipboard write well-defined.
    ///
    /// ```no_run
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder().spawn("true")?;
    /// t.wait_until(|s| s.clipboard().is_some_and(|c| c.text() == Some("the title")))?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Clipboard *reads* (`OSC 52 ; c ; ?`) are a different sequence and
    /// are not answered: they stay named in timeout errors, so an
    /// application blocked on one is diagnosed rather than left hanging.
    #[must_use]
    pub fn clipboard(&self) -> Option<&Clipboard> {
        self.state.clipboard.as_deref()
    }

    /// How many times the application has **completed a repaint** — a DEC
    /// 2026 synchronized update begun and ended — as of this observation.
    ///
    /// Monotonic, so the natural use is a delta around an action:
    ///
    /// ```no_run
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder().spawn("true")?;
    /// let before = t.screen().repaints();
    /// t.scroll(0, 0, termlens::Scroll::Down)?;
    /// let frame = t.wait_frame(|s| s.contains("row 2"))?;
    /// // One wheel notch must not become five repaints.
    /// assert_eq!(frame.repaints() - before, 1);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// **It counts repaints, not changes.** A Begin/End pair that altered no
    /// cell still counts, exactly as [`wait_frame`](crate::Terminal::wait_frame)
    /// treats it — and that is the property an amplification test depends
    /// on. "One input produced four repaints" is invisible to any content
    /// predicate, because every intermediate frame shows correct content.
    /// Only the count sees it.
    ///
    /// Zero for an application that never emits synchronized updates; there
    /// is nothing to count, not even its redraws.
    ///
    /// On a frame that [`wait_frame`](crate::Terminal::wait_frame) handed
    /// back, this is also the staleness check: the frame's count against
    /// `screen().repaints()` says how many repaints the live screen is
    /// ahead of the one you are asserting on.
    #[must_use]
    pub fn repaints(&self) -> u64 {
        self.state.repaints
    }

    /// How many times the application has rung the bell (`BEL`, `0x07`) as
    /// of this observation.
    ///
    /// A count rather than a flag, so "rang twice" is distinguishable from
    /// "rang once", and monotonic like [`repaints`](Self::repaints) so a test
    /// can take a delta around one action.
    ///
    /// The bell is often the *only* feedback a rejected input produces:
    /// "pressing an invalid key does nothing" and "pressing an invalid key is
    /// refused with a bell" are different behaviours, and without this they
    /// are the same screen.
    ///
    /// Only a `BEL` in ground state counts. The one that terminates an
    /// `OSC` string is punctuation, not a bell, and a `BEL` inside a
    /// DCS-class string is payload.
    #[must_use]
    pub fn bells(&self) -> u64 {
        self.state.bells
    }

    /// Inline graphics payloads the application has transmitted — kitty
    /// (`APC G … ST`) and sixel (`DCS q … ST`) — as of this observation.
    ///
    /// ```no_run
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder().spawn("true")?;
    /// t.wait_until(|s| s.contains("diagram"))?;
    /// // A diagram must render as box art in every terminal, so it must
    /// // never go out as an image.
    /// assert!(t.screen().graphics().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Observing is not rendering, and not a claim of support: DA1 goes on
    /// declining both protocols, which is precisely why an application that
    /// transmits one anyway is worth catching.
    ///
    /// The payloads themselves — placement, declared size, format, and with
    /// the `decode` feature the pixels — are on
    /// [`GraphicsSeen::payloads`](crate::GraphicsSeen::payloads).
    #[must_use]
    pub fn graphics(&self) -> GraphicsSeen {
        self.state.graphics.clone()
    }

    /// Escape sequences the emulator did not implement, so the grid below
    /// them is not what a terminal would show — as an [`Unsupported`] view:
    /// distinct shapes, first seen first, in the form the timeout messages
    /// use (`^[[20h` for `CSI 20 h`), at most 32 retained, with
    /// [`overflow`](Unsupported::overflow) counting the rest.
    ///
    /// Empty for an application that uses only what the emulator renders,
    /// which is what makes it worth asserting: the failure this catches is
    /// the one where a test passes against a plausible-looking wrong screen
    /// because the sequence that would have made it right was dropped.
    /// Sequences termlens handles itself — the character sets, tab stops,
    /// insert mode, the queries it answers or names, the modes it tracks,
    /// the SGR attributes the shadow parser recovers — are not listed,
    /// since the screen does show their effect. A request to resize the
    /// window (`CSI 8 ; rows ; cols t`) *is* listed: the grid's size is the
    /// test's to set, so the request is recorded rather than honoured.
    ///
    /// ```no_run
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder()
    /// #     .args(["-c", "printf '\\033[20htext'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.contains("text"))?;
    /// let s = t.screen();
    /// assert_eq!(s.unsupported(), ["^[[20h"]);
    /// assert!(s.unsupported().contains("^[[20h"));
    /// assert_eq!(s.unsupported().overflow(), 0);
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    ///
    /// (`no_run` because the doctest suite also runs on Windows, where
    /// ConPTY drops the sequence before termlens sees it and the record is
    /// the console's — the behaviour is pinned in `tests/unsupported.rs`,
    /// which is `ignore`d there with that reason.)
    #[must_use]
    pub fn unsupported(&self) -> Unsupported<'_> {
        Unsupported {
            retained: &self.state.unsupported,
            overflow: self.state.unsupported_overflow,
        }
    }

    /// Visual bells (`ESC g`) the application requested — a flash rather
    /// than a beep, and a different event from [`bells`](Self::bells), so an
    /// application that flashes on an invalid key is assertable as such.
    #[must_use]
    pub fn visual_bells(&self) -> u64 {
        self.state.visual_bells
    }

    /// Whether the application has the terminal in insert mode (`IRM`,
    /// `CSI 4 h`): a printed character pushes the rest of its row right
    /// rather than overwriting. The same shape of assertion as
    /// [`alternate_screen`](Self::alternate_screen) — "the application set
    /// a mode and left it there" — and cleared by `RIS` and `DECSTR`.
    #[must_use]
    pub fn insert_mode(&self) -> bool {
        self.state.insert_mode
    }

    /// Whether `row` ended in a **soft wrap** — the application wrote past
    /// the right margin and the terminal continued on the next row — rather
    /// than in a line end. The backend's own record; `false` for a row
    /// outside the screen.
    ///
    /// This is the fact [`logical_text`](Self::logical_text) joins rows on.
    #[must_use]
    pub fn row_wrapped(&self, row: u16) -> bool {
        self.state
            .wrapped
            .get(usize::from(row))
            .copied()
            .unwrap_or(false)
    }

    /// The grid as the application wrote it: soft-wrapped rows joined with
    /// nothing, every other row ending in `\n`, trailing whitespace stripped
    /// per logical line — [`text`](Self::text) with the wraps undone, blank
    /// rows below the content included as blank lines just as there.
    ///
    /// A line long enough to wrap is two rows on the grid, and a needle
    /// spanning the wrap is not found by [`contains`](Self::contains) or
    /// [`find`](Self::find), which read the grid row by row. This is the
    /// accessor for that assertion: on a 20-column screen showing
    /// `the quick brown fox` over `jumps`,
    /// `logical_text().contains("brown fox jumps")` is true. It is `str`
    /// matching from here on — byte-exact, no NFC fold — like
    /// [`full_text`](Self::full_text).
    #[must_use]
    pub fn logical_text(&self) -> String {
        let mut out = String::new();
        let mut line = String::new();
        for row in 0..self.rows {
            line.push_str(&self.row_text(row));
            if self.row_wrapped(row) {
                continue;
            }
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(line.trim_end());
            line.clear();
        }
        if !line.is_empty() {
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(line.trim_end());
        }
        out
    }

    /// The cell at `(row, col)`, or `None` when out of bounds.
    #[must_use]
    pub fn cell(&self, row: u16, col: u16) -> Option<&Cell> {
        if row >= self.rows || col >= self.cols {
            return None;
        }
        self.cells
            .get(usize::from(row) * usize::from(self.cols) + usize::from(col))
    }

    /// The text of one row, blank cells rendered as spaces, trailing
    /// whitespace **included**.
    ///
    /// Wide characters contribute their character once; their continuation
    /// cell contributes nothing (so the string's *display width* matches the
    /// row, not its `char` count).
    ///
    /// # Panics
    ///
    /// Panics when `row` is outside the screen. Unlike the clamped ranges
    /// accepted by [`rect_text`](Self::rect_text), a single invalid index is
    /// a caller mistake; returning an empty string would make it
    /// indistinguishable from a blank row. Use [`cell`](Self::cell) when an
    /// out-of-bounds result is expected and should be represented by `None`.
    #[must_use]
    pub fn row_text(&self, row: u16) -> String {
        assert!(
            row < self.rows,
            "row_text: row {row} is outside the {}-row screen",
            self.rows
        );
        let mut out = String::with_capacity(usize::from(self.cols));
        for col in 0..self.cols {
            let cell = self.cell(row, col).expect("row and column are in bounds");
            if cell.is_wide_continuation() {
                continue;
            }
            if cell.contents().is_empty() {
                out.push(' ');
            } else {
                out.push_str(cell.contents());
            }
        }
        out
    }

    /// The whole grid as text: one line per row, trailing whitespace
    /// stripped per line, rows joined with `\n`. This is exactly the body of
    /// the [`Display`](fmt::Display) rendering, without the header.
    #[must_use]
    pub fn text(&self) -> String {
        let mut out = String::new();
        for row in 0..self.rows {
            if row > 0 {
                out.push('\n');
            }
            let line = self.row_text(row);
            out.push_str(line.trim_end());
        }
        out
    }

    /// How many rows have scrolled off the top and are still retained.
    ///
    /// Zero when nothing has scrolled — or when the terminal was built with
    /// [`scrollback(0)`](crate::TerminalBuilder::scrollback). Caps at the
    /// configured length: past that, the oldest rows are dropped, and this
    /// stops growing rather than reporting everything the application ever
    /// wrote.
    #[must_use]
    pub fn scrollback_rows(&self) -> usize {
        self.state.scrollback.len()
    }

    /// The retained history as text: one line per scrolled-off row, oldest
    /// first, trailing whitespace stripped, joined with `\n`.
    ///
    /// Empty when nothing has scrolled. History is text only — a scrolled
    /// row has no [`Style`] and no [`cell`](Self::cell) addressing, which
    /// is what keeps a snapshot cheap enough to take on every wait.
    ///
    /// Each row keeps the width it was captured at. A
    /// [`resize`](crate::Terminal::resize) does not reflow history, so
    /// after a narrowing resize the rows captured before it are wider than
    /// the rows captured after — see there for why that is the chosen
    /// behaviour.
    #[must_use]
    pub fn scrollback_text(&self) -> String {
        let mut out = String::new();
        for (i, row) in self.state.scrollback.iter().enumerate() {
            if i > 0 {
                out.push('\n');
            }
            out.push_str(row);
        }
        out
    }

    /// Whether this terminal retains **styles** in history —
    /// [`TerminalBuilder::scrollback_styles`](crate::TerminalBuilder::scrollback_styles)
    /// — so [`scrollback_cell`](Self::scrollback_cell) answers.
    #[must_use]
    pub fn styled_scrollback(&self) -> bool {
        self.state.scrollback_cells.is_some()
    }

    /// The cell at `(row, col)` of the retained history, row 0 the oldest,
    /// or `None` out of range — and `None` for every cell unless the
    /// terminal was built with
    /// [`scrollback_styles(true)`](crate::TerminalBuilder::scrollback_styles).
    ///
    /// This is what keeps the masked-password assertion alive once the line
    /// scrolls: `scrollback_cell(row, col).unwrap().style().conceal` is the
    /// same question [`cell`](Self::cell) answers on the grid. The column is
    /// the one the row was captured at — history is not reflowed, so after a
    /// narrowing resize the rows captured before it are wider than the grid
    /// is now.
    #[must_use]
    pub fn scrollback_cell(&self, row: usize, col: u16) -> Option<&Cell> {
        self.state
            .scrollback_cells
            .as_ref()?
            .get(row)?
            .get(usize::from(col))
    }

    /// Where `needle` is, on the visible screen or in the retained history
    /// — the search that spans both and says which region it found the
    /// needle in, so a wait can be written that does not depend on where a
    /// block currently sits.
    ///
    /// The grid is searched first, with [`find`](Self::find)'s semantics
    /// (NFC on both sides, trailing whitespace trimmed, real columns); then
    /// history, oldest row first, with the same folding. A history column is
    /// a display column of the row **as it was captured**: history is not
    /// reflowed, so it does not survive a narrowing resize, and it is not a
    /// grid coordinate — nothing here promises one. Multi-row needles are
    /// searched on the grid only.
    ///
    /// ```
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder().size(20, 3)
    /// #     .args(["-c", "printf 'SECRET\na\nb\nc\nd\n'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.scrollback_rows() > 0)?;
    /// use termlens::Location;
    /// match t.screen().locate("SECRET") {
    ///     Some(Location::History { row, col }) => assert_eq!((row, col), (0, 0)),
    ///     other => panic!("scrolled off, so it is in history: {other:?}"),
    /// }
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn locate(&self, needle: &str) -> Option<Location> {
        if let Some((row, col)) = self.find(needle) {
            return Some(Location::Screen { row, col });
        }
        if needle.is_empty() || needle.contains('\n') {
            return None;
        }
        let needle = nfc(needle);
        for (row, line) in self.state.scrollback.iter().enumerate() {
            let folded = nfc(line);
            let Some(byte_off) = folded.find(needle.as_str()) else {
                continue;
            };
            let col = unicode_width::UnicodeWidthStr::width(&folded[..byte_off]);
            return Some(Location::History {
                row,
                col: u16::try_from(col).unwrap_or(u16::MAX),
            });
        }
        None
    }

    /// History **and** visible screen, as one text block: the retained
    /// scrolled-off rows followed by [`text`](Self::text).
    ///
    /// This is the accessor for the assertion an author actually writes —
    /// "this block reached the terminal, wherever it currently sits". An
    /// application that commits finished output into scrollback and keeps a
    /// small live region moves content between the two regions as it goes,
    /// so a test that has to know which region to look in is a test that
    /// breaks when the application scrolls one line further.
    #[must_use]
    pub fn full_text(&self) -> String {
        let mut out = self.scrollback_text();
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&self.text());
        out
    }

    /// True if `needle` occurs in the rendered text ([`Screen::text`]).
    ///
    /// Because rows are joined with `\n`, multi-line needles match across
    /// consecutive rows (with trailing whitespace stripped per row).
    ///
    /// The **visible screen only** — like every other query on this type.
    /// For content that may already have scrolled off, use
    /// [`full_text`](Self::full_text) (history and screen) or
    /// [`scrollback_text`](Self::scrollback_text) (history alone). This is
    /// the trap in the most-copied line in these docs: a
    /// `wait_until(|s| s.contains("done"))` on text the application printed
    /// and then scrolled away in the same burst can never succeed, and the
    /// screen embedded in the timeout will not show the text either. The
    /// timeout therefore says how many rows have scrolled off whenever any
    /// have.
    ///
    /// The same trap one row lower: a line long enough to **wrap** is two
    /// rows here, and a needle spanning the wrap is not found even though a
    /// reader plainly sees it. [`logical_text`](Self::logical_text) joins
    /// soft-wrapped rows back together, using the wrap record the backend
    /// keeps ([`row_wrapped`](Self::row_wrapped)).
    ///
    /// # Normalization
    ///
    /// Both sides are folded to **NFC** before comparing, so a needle finds
    /// text the application normalized the other way. A terminal draws
    /// `caf\u{e9}` and `cafe\u{301}` identically, and so does the failure
    /// output and the diff — which is what made the mismatch a trap rather
    /// than a limitation. A test author types NFC (that is what editors
    /// produce); text from a filesystem path, a git author name, or macOS
    /// input is frequently NFD.
    ///
    /// Folding is unconditional here and needs no escape hatch, because the
    /// raw form is never taken away: [`text`](Self::text),
    /// [`row_text`](Self::row_text), [`rect_text`](Self::rect_text),
    /// [`cell`](Self::cell) and [`title`](Self::title) all return exactly
    /// the codepoints the application sent, so a test that means to assert
    /// on normalization compares those directly. A snapshot is an
    /// observation; only the search over it is forgiving.
    ///
    /// Note that this makes matching grapheme-shaped rather than
    /// byte-shaped: on a screen showing `caf\u{e9}`, `contains("cafe")` is
    /// **false**, because the screen does not show `cafe`.
    ///
    /// Text pulled out as a `String` and matched with `str` methods —
    /// `full_text().contains(..)` — is byte-exact, since the comparison is
    /// then `std`'s and not ours.
    ///
    /// Trailing whitespace is trimmed per row first, so the blank padding
    /// past a row's last glyph is never matched — and neither is a trailing
    /// U+00A0 or U+3000 the application drew, which the trim cannot tell
    /// from padding. [`find`](Self::find) trims identically, so the two
    /// never disagree; [`cell`](Self::cell) still reports the character.
    #[must_use]
    pub fn contains(&self, needle: &str) -> bool {
        if self.is_ascii() && needle.is_ascii() {
            return self.text().contains(needle);
        }
        self.nfc_text().contains(&nfc(needle))
    }

    /// Locate the first occurrence of `needle` scanning rows top to bottom;
    /// returns the `(row, col)` of its first character.
    /// Mouse methods such as [`Terminal::drag`](crate::Terminal::drag) take
    /// columns first, so destructure this pair before using it as mouse input.
    ///
    /// The **visible screen only**, like [`contains`](Self::contains): a
    /// needle that has scrolled into history is not found here, however
    /// recently it left. [`full_text`](Self::full_text) spans history and
    /// screen, [`scrollback_text`](Self::scrollback_text) the history alone.
    /// A needle spanning a soft wrap is not found either — a match across a
    /// wrap has no single row and column to report — and
    /// [`logical_text`](Self::logical_text) is the accessor for that.
    ///
    /// Needles containing `\n` match across consecutive rows with exactly
    /// the semantics of [`Screen::contains`] (trailing whitespace stripped
    /// per row): a multi-row needle is found wherever `contains` would be
    /// true. A needle that *begins* with `\n` reports the position of its
    /// first character after those newlines.
    ///
    /// Columns account for double-width characters: a match after a CJK
    /// character reports the real terminal column.
    ///
    /// Matching folds both sides to NFC, exactly as
    /// [`contains`](Self::contains) does and for the same reasons — a needle
    /// is found here precisely when `contains` is true. The reported column
    /// is the real one: folding happens per cell, so the byte-to-column map
    /// stays exact even where a composition shortened the text.
    ///
    /// Trailing whitespace is trimmed per row before either searches, so
    /// the blank padding past a row's last glyph is never matched: on a
    /// row reading `Total:`, `find("Total: ")` is `None`, as `contains`
    /// says. The same trim treats a trailing U+00A0 or U+3000 the
    /// application genuinely drew as padding — a decision, so that the two
    /// searches agree; [`cell`](Self::cell) still reports the character.
    #[must_use]
    pub fn find(&self, needle: &str) -> Option<(u16, u16)> {
        let mut first = None;
        self.for_each_match(needle, |at| {
            first = Some(at);
            false
        });
        first
    }

    /// Every occurrence of `needle`, in reading order — the `(row, col)` of
    /// each match's first character. Matching is identical to
    /// [`find`](Self::find), which is the first element of this same scan:
    /// NFC on both sides, trailing whitespace trimmed per row, real columns
    /// across double-width characters, the visible screen only.
    ///
    /// Two decisions, written down so they need not be discovered:
    ///
    /// - **Matches do not overlap.** `find_all("aa")` on a row reading
    ///   `aaaa` is two matches, not three — each match advances past its
    ///   own end, as `str::matches` does.
    /// - **Multi-row needles are supported**, with exactly the semantics of
    ///   `find`: a needle containing `\n` matches across consecutive rows,
    ///   and the scan resumes below the rows a match consumed.
    ///
    /// A `Vec` rather than an iterator: a screen holds at most a few
    /// thousand cells, so allocation is not the concern, and a `Vec` is what
    /// `.len()` — "this warning appears exactly once" — and indexing —
    /// "click the second item" — want. There is deliberately no count
    /// method; `find_all(x).len()` reads fine and one scan is easier to keep
    /// honest than two.
    ///
    /// ```
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder()
    /// #     .args(["-c", r"printf 'item\nitem\nitem'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.find_all("item").len() == 3)?;
    /// let s = t.screen();
    /// assert_eq!(s.find_all("item"), [(0, 0), (1, 0), (2, 0)]);
    /// let (row, col) = s.find_all("item")[1];   // the second one, for a click
    /// # assert_eq!((row, col), (1, 0));
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn find_all(&self, needle: &str) -> Vec<(u16, u16)> {
        let mut all = Vec::new();
        self.for_each_match(needle, |at| {
            all.push(at);
            true
        });
        all
    }

    /// The one scan behind [`find`](Self::find) and [`find_all`](Self::find_all):
    /// every non-overlapping match of `needle` in reading order, handed to
    /// `visit` until it returns `false`. One implementation, so the two can
    /// never disagree about what matches — `find`'s rustdoc promises it
    /// agrees with `contains`, and a second scan would be a second thing to
    /// keep in agreement.
    fn for_each_match(&self, needle: &str, mut visit: impl FnMut((u16, u16)) -> bool) {
        if needle.is_empty() {
            visit((0, 0));
            return;
        }
        let needle = &self.fold(needle);
        if !needle.contains('\n') {
            for row in 0..self.rows {
                let (text, cols) = self.searchable_row(row);
                // Search the row as `contains` sees it — trailing whitespace
                // trimmed — not the grid padded out to `cols`. The trimmed
                // string is a prefix, so the byte-to-column map is unchanged
                // and an interior space still matches (#212).
                for (byte_off, _) in text.trim_end().match_indices(needle.as_str()) {
                    let Some(&col) = cols.get(byte_off) else {
                        return;
                    };
                    if !visit((row, col)) {
                        return;
                    }
                }
            }
            return;
        }

        // Multi-row: the needle is a substring of `text()` — its first
        // segment ends a row (after the trailing-whitespace trim), the
        // middle segments equal whole rows, the last starts one.
        let segments: Vec<&str> = needle.split('\n').collect();
        let Ok(extra) = u16::try_from(segments.len() - 1) else {
            return;
        };
        self.for_each_multirow_match(&segments, |row| {
            let (first_line, cols) = self.searchable_row(row);
            let first = first_line.trim_end();
            // The needle's first character: on this row for a non-empty
            // first segment, else the first character after the leading
            // newlines (start of a following row).
            let at = match segments.iter().position(|s| !s.is_empty()) {
                Some(0) => {
                    let byte_off = first.len() - segments[0].len();
                    match cols.get(byte_off) {
                        Some(&col) => (row, col),
                        None => return false,
                    }
                }
                Some(k) => match u16::try_from(k) {
                    Ok(k) => (row + k, 0),
                    Err(_) => return false,
                },
                None => (row + extra, 0),
            };
            visit(at)
        });
    }

    /// Every non-overlapping multi-row match of `segments`, reported as the
    /// row its **first** segment sits on. The shape such a needle has to
    /// have: the first segment ends a row (after the trailing-whitespace
    /// trim), the middle segments are whole rows, the last starts one.
    ///
    /// One engine, two callers — [`find_all`](Self::find_all) and
    /// [`mask_matching`](Self::mask_matching) — so they cannot disagree
    /// about what matched, which is exactly how a mask came to leave a
    /// needle `find_all` reported (#300).
    fn for_each_multirow_match(&self, segments: &[&str], mut visit: impl FnMut(u16) -> bool) {
        let Ok(extra) = u16::try_from(segments.len().saturating_sub(1)) else {
            return;
        };
        let Some(last_start) = self.rows.checked_sub(extra) else {
            return;
        };
        let mut row = 0;
        while row < last_start {
            let (first_line, _) = self.searchable_row(row);
            let first = first_line.trim_end();
            let tail_matches = || {
                segments[1..].iter().enumerate().all(|(i, seg)| {
                    let (line, _) = self.searchable_row(row + 1 + i as u16);
                    let line = line.trim_end();
                    if i as u16 == extra - 1 {
                        line.starts_with(seg) // last segment: prefix
                    } else {
                        line == *seg // middle segments: whole rows
                    }
                })
            };
            if !first.ends_with(segments[0]) || !tail_matches() {
                row += 1;
                continue;
            }
            if !visit(row) {
                return;
            }
            // Non-overlapping: the rows this match spanned are spent.
            row += extra;
        }
    }

    /// A copy of this screen with every cell in the rectangle blanked —
    /// the given columns of the given rows, the same range arguments and
    /// clamping as [`rect_text`](Self::rect_text), **columns first**.
    ///
    /// # Masks change contents and nothing else
    ///
    /// Mask the grid, not the text, because width is meaning in a terminal.
    /// A snapshot of a screen with a clock in the title bar fails on every
    /// run, and a text filter over the rendering — insta's — turns an
    /// eight-column `12:34:56` into a six-column `[time]` and moves every
    /// cell after it, while the `styles:` block still names the original
    /// columns. These three methods replace cell *contents* and keep the
    /// size, the cursor, every style and the wide-character structure, so
    /// the masked screen is an ordinary [`Screen`]: it snapshots, `find`s
    /// and compares like any other, and a colour regression stays visible
    /// through the redaction. A masked cell renders as its fill.
    ///
    /// # Panics
    ///
    /// If either range runs backwards, as [`rect_text`](Self::rect_text)
    /// does and for the same reason.
    #[must_use]
    pub fn mask_rect(&self, cols: impl RangeBounds<u16>, rows: impl RangeBounds<u16>) -> Screen {
        let (col_start, col_end) = clamp_range(&cols, self.cols, "column");
        let (row_start, row_end) = clamp_range(&rows, self.rows, "row");
        self.masked(
            |row, col, _| {
                (row_start..row_end).contains(&row) && (col_start..col_end).contains(&col)
            },
            None,
        )
    }

    /// A copy of this screen with the cells covered by every match of
    /// `pattern` — a literal, matched the way [`find_all`](Self::find_all)
    /// matches — replaced by `fill`, one per column, so an eight-column
    /// time stays eight columns of `▒`. A wide character under a match
    /// becomes two fill cells. See [`mask_rect`](Self::mask_rect) for what
    /// a mask keeps.
    ///
    /// With the `regex` feature, `mask_matches` takes a pattern instead; the
    /// two share one engine.
    ///
    /// # Panics
    ///
    /// If `fill` is not one column wide: a wide fill would change the
    /// row's width, which is the one thing a mask exists not to do.
    #[must_use]
    pub fn mask_matching(&self, pattern: &str, fill: char) -> Screen {
        let pattern = self.fold(pattern);
        if pattern.contains('\n') {
            // A needle that spans rows is matched by the engine `find_all`
            // uses. The per-row scan below is handed one row at a time and
            // never sees a newline, so it matched nothing and masked
            // nothing — while `find_all` reported the hit (#300).
            return self.masked_multiline(&pattern, fill);
        }
        self.masked_spans(
            |hay| {
                hay.match_indices(pattern.as_str())
                    .map(|(start, _)| (start, start + pattern.len()))
                    .collect()
            },
            fill,
        )
    }

    /// The multi-row half of [`mask_matching`](Self::mask_matching): every
    /// cell a row-spanning needle covers. `needle` is already folded.
    fn masked_multiline(&self, needle: &str, fill: char) -> Screen {
        let segments: Vec<&str> = needle.split('\n').collect();
        let Ok(extra) = u16::try_from(segments.len().saturating_sub(1)) else {
            return self.clone();
        };
        let width = usize::from(self.cols);
        let mut hits = vec![false; self.cells.len()];
        self.for_each_multirow_match(&segments, |row| {
            for (index, segment) in segments.iter().enumerate() {
                let at = row + index as u16;
                let (text, cols) = self.searchable_row(at);
                let line = text.trim_end();
                // The same shape the matcher just checked: the first segment
                // ends its row, the last starts one, the rest are whole rows.
                let (start, end) = if index == 0 {
                    (line.len().saturating_sub(segment.len()), line.len())
                } else if index as u16 == extra {
                    (0, segment.len())
                } else {
                    (0, line.len())
                };
                for byte in start..end {
                    if let Some(&col) = cols.get(byte) {
                        hits[usize::from(at) * width + usize::from(col)] = true;
                    }
                }
            }
            true
        });
        self.apply_mask(hits, Some(fill))
    }

    /// A copy of this screen with every cell for which `predicate` holds
    /// blanked — everything dim, say, or everything in a given colour. See
    /// [`mask_rect`](Self::mask_rect) for what a mask keeps.
    #[must_use]
    pub fn mask_cells(&self, mut predicate: impl FnMut(&Cell) -> bool) -> Screen {
        self.masked(|_, _, cell| predicate(cell), None)
    }

    /// The masks' shared core: `hit(row, col, cell)` decides, `fill` is the
    /// replacement (`None` for a blank cell).
    fn masked(&self, mut hit: impl FnMut(u16, u16, &Cell) -> bool, fill: Option<char>) -> Screen {
        let width = usize::from(self.cols);
        let hits: Vec<bool> = self
            .cells
            .iter()
            .enumerate()
            .map(|(i, cell)| {
                let row = u16::try_from(i / width).unwrap_or(u16::MAX);
                let col = u16::try_from(i % width).unwrap_or(u16::MAX);
                hit(row, col, cell)
            })
            .collect();
        self.apply_mask(hits, fill)
    }

    /// Mask by byte ranges of each row's searchable text — what a literal
    /// or a pattern match produces — mapped back to columns through the
    /// same map `find` reports columns with.
    fn masked_spans(
        &self,
        mut spans: impl FnMut(&str) -> Vec<(usize, usize)>,
        fill: char,
    ) -> Screen {
        let width = usize::from(self.cols);
        let mut hits = vec![false; self.cells.len()];
        for row in 0..self.rows {
            let (text, cols) = self.searchable_row(row);
            for (start, end) in spans(text.trim_end()) {
                for byte in start..end {
                    if let Some(&col) = cols.get(byte) {
                        hits[usize::from(row) * width + usize::from(col)] = true;
                    }
                }
            }
        }
        self.apply_mask(hits, Some(fill))
    }

    fn apply_mask(&self, mut hits: Vec<bool>, fill: Option<char>) -> Screen {
        if let Some(fill) = fill {
            assert_eq!(
                unicode_width::UnicodeWidthChar::width(fill),
                Some(1),
                "a mask fill must be one column wide, and {fill:?} is not"
            );
        }
        // A masked wide character masks both of its columns, whichever of
        // the two was hit, so the row keeps its width.
        let width = usize::from(self.cols);
        for i in 0..hits.len() {
            if !hits[i] {
                continue;
            }
            if self.cells[i].is_wide() && (i + 1) % width != 0 && i + 1 < hits.len() {
                hits[i + 1] = true;
            }
            if self.cells[i].is_wide_continuation() && i % width != 0 {
                hits[i - 1] = true;
            }
        }
        let contents = fill.map_or_else(String::new, String::from);
        let cells: Vec<Cell> = self
            .cells
            .iter()
            .zip(&hits)
            .map(|(cell, &hit)| {
                if hit {
                    Cell::new(contents.clone(), *cell.style(), false, false)
                } else {
                    cell.clone()
                }
            })
            .collect();
        Screen {
            cols: self.cols,
            rows: self.rows,
            cursor_row: self.cursor_row,
            cursor_col: self.cursor_col,
            cursor_visible: self.cursor_visible,
            cells: cells.into(),
            state: Arc::clone(&self.state),
        }
    }

    /// The text within a rectangle: the given columns of the given rows,
    /// one line per row, trailing whitespace stripped per line (the same
    /// rule as [`Screen::text`]). Ranges take any range expression and are
    /// clamped to the screen:
    ///
    /// ```
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder()
    /// #     .args(["-c", "printf 'left | right'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.contains("right"))?;
    /// let s = t.screen();
    /// let right_pane = s.rect_text(7.., ..);   // columns 7 → end, all rows
    /// assert!(right_pane.contains("right"));
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    ///
    /// Cells contribute as in [`Screen::row_text`]: blanks render as
    /// spaces, and a wide character contributes where its leading cell
    /// sits — even when the rectangle cuts it in half.
    ///
    /// # Panics
    ///
    /// If either range runs backwards (`3..0`). Note the argument order:
    /// **columns first**, like every API here that speaks of terminal
    /// geometry or a mouse position —
    /// [`TerminalBuilder::size`](crate::TerminalBuilder::size),
    /// [`Terminal::resize`](crate::Terminal::resize),
    /// [`Terminal::click`](crate::Terminal::click) and its `click_with`,
    /// `drag`, `scroll` and `scroll_with` siblings, and [`size`](Self::size).
    /// Everything that addresses a cell in the grid is row-first:
    /// [`cell`](Self::cell), [`row_text`](Self::row_text), and the
    /// `(row, col)` that [`find`](Self::find), [`find_by`](Self::find_by)
    /// and [`cursor`](Self::cursor) return. Swapping the two is therefore
    /// the mistake to expect, and a swap can invert a range.
    ///
    /// A panic rather than an error, deliberately, and for the same reason
    /// `&slice[3..0]` panics: a backwards range is not a fact about the
    /// terminal discovered at runtime, it is a mistake in the calling
    /// source. Returned quietly it read as `""` — "this pane is empty",
    /// a perfectly plausible assertion outcome — so a mis-ordered call
    /// passed for the wrong reason and kept passing. Clippy's
    /// `reversed_empty_ranges` already refuses a written-out `3..0`; this
    /// covers the computed bounds it cannot see. Out-of-*range* bounds are
    /// different and stay clamped: asking for more screen than exists is a
    /// reasonable thing to do.
    #[must_use]
    pub fn rect_text(&self, cols: impl RangeBounds<u16>, rows: impl RangeBounds<u16>) -> String {
        let (col_start, col_end) = clamp_range(&cols, self.cols, "column");
        let (row_start, row_end) = clamp_range(&rows, self.rows, "row");
        let mut out = String::new();
        for row in row_start..row_end {
            if row > row_start {
                out.push('\n');
            }
            let mut line = String::new();
            for col in col_start..col_end {
                let Some(cell) = self.cell(row, col) else {
                    break;
                };
                if cell.is_wide_continuation() {
                    continue;
                }
                if cell.contents().is_empty() {
                    line.push(' ');
                } else {
                    line.push_str(cell.contents());
                }
            }
            out.push_str(line.trim_end());
        }
        out
    }

    /// The first cell satisfying `predicate` (scanning rows top to bottom,
    /// columns left to right), as `(row, col)`.
    ///
    /// This is the tool for "where did the highlight go":
    ///
    /// ```
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder()
    /// #     .args(["-c", r"printf 'a \033[7mchoice\033[0m'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.contains("choice"))?;
    /// let s = t.screen();
    /// assert_eq!(s.find_by(|c| c.style().reverse), Some((0, 2)));
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    ///
    /// Every cell is scanned, including blanks and wide-character
    /// continuation cells (they carry their character's style).
    #[must_use]
    pub fn find_by(&self, mut predicate: impl FnMut(&Cell) -> bool) -> Option<(u16, u16)> {
        for row in 0..self.rows {
            for col in 0..self.cols {
                if predicate(self.cell(row, col)?) {
                    return Some((row, col));
                }
            }
        }
        None
    }

    /// True when every cell holds only ASCII, so normalization is the
    /// identity and the search helpers can skip it. This is the shape of
    /// virtually every screen, which is what keeps `contains` — evaluated
    /// on every wait wake-up — as cheap as it was.
    fn is_ascii(&self) -> bool {
        self.cells.iter().all(|c| c.contents().is_ascii())
    }

    /// `needle` in the form the search helpers compare against.
    fn fold(&self, needle: &str) -> String {
        if self.is_ascii() && needle.is_ascii() {
            needle.to_owned()
        } else {
            nfc(needle)
        }
    }

    /// The whole grid in searchable form: rows joined with `\n`, trailing
    /// whitespace stripped per row, each row folded the same way
    /// [`searchable_row`](Self::searchable_row) folds it — so `contains` and
    /// `find` can never disagree about what matches.
    fn nfc_text(&self) -> String {
        let mut out = String::new();
        for row in 0..self.rows {
            if row > 0 {
                out.push('\n');
            }
            let (line, _) = self.searchable_row(row);
            out.push_str(line.trim_end());
        }
        out
    }

    /// One row in searchable form, plus the column that produced each byte.
    ///
    /// Folding is **per cell**, not over the joined string, and that is the
    /// load-bearing detail: a cell holds a base character together with its
    /// combining marks (vt100 appends them to the cell being written), so
    /// folding cell by cell composes exactly what the terminal draws in one
    /// cell and can never compose across a cell boundary. It also keeps the
    /// byte-to-column map exact, which is what [`find`](Self::find) reports.
    fn searchable_row(&self, row: u16) -> (String, Vec<u16>) {
        let ascii = self.is_ascii();
        let mut text = String::with_capacity(usize::from(self.cols));
        let mut cols = Vec::with_capacity(usize::from(self.cols));
        for col in 0..self.cols {
            let Some(cell) = self.cell(row, col) else {
                break;
            };
            if cell.is_wide_continuation() {
                continue;
            }
            let before = text.len();
            if cell.contents().is_empty() {
                text.push(' ');
            } else if ascii {
                text.push_str(cell.contents());
            } else {
                text.extend(cell.contents().nfc());
            }
            cols.resize(text.len(), col);
            debug_assert!(text.len() > before || cell.is_wide_continuation());
        }
        // One extra entry, so a match at the very end of the row maps to
        // the last column instead of falling off the map.
        cols.push(self.cols.saturating_sub(1));
        (text, cols)
    }

    /// This screen rendered **with its styles**: the normal
    /// [`Display`](fmt::Display) output followed by a `styles:` block
    /// listing every non-default span (format specified in
    /// `docs/DESIGN.md` §3). Style-only regressions — a highlight moving
    /// to another row, a color changing — become visible snapshot diffs:
    ///
    /// ```no_run
    /// # fn main() -> termlens::Result<()> {
    /// # let t = termlens::Terminal::builder().spawn("true")?;
    /// insta::assert_snapshot!(t.screen().with_styles());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Plain snapshots stay text-only; this is the opt-in.
    #[must_use]
    pub fn with_styles(&self) -> ScreenWithStyles<'_> {
        ScreenWithStyles { screen: self }
    }
}

/// Pattern matching over the rows of the screen (feature `regex`).
///
/// The crate's position — assert on the rendered screen, not the byte
/// stream — is not weakened by matching a pattern against a *row of that
/// screen*: the match still lands on cells with coordinates. Matching is
/// per row over the row's text as [`contains`](Self::contains) sees it —
/// NFC-folded, trailing whitespace trimmed — so a pattern never spans rows
/// (a terminal has no row boundary a user reads across), and the column
/// reported is a cell column, mapped back through wide characters exactly
/// as [`find`](Self::find) does.
#[cfg(feature = "regex")]
#[cfg_attr(docsrs, doc(cfg(feature = "regex")))]
impl Screen {
    /// The first match of `re` in reading order: `(row, col, matched text)`,
    /// the column being that of the match's first character.
    ///
    /// ```
    /// # fn main() -> termlens::Result<()> {
    /// # let mut t = termlens::Terminal::builder()
    /// #     .args(["-c", r"printf 'myapp v1.42.0 ready'; read q"]).spawn("sh")?;
    /// # t.wait_until(|s| s.contains("ready"))?;
    /// let version = regex::Regex::new(r"v\d+\.\d+\.\d+").unwrap();
    /// let (row, col, text) = t.screen().find_match(&version).expect("a version");
    /// assert_eq!((row, col, text.as_str()), (0, 6, "v1.42.0"));
    /// # t.send(termlens::Key::Enter); t.wait_exit()?; Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn find_match(&self, re: &regex::Regex) -> Option<(u16, u16, String)> {
        let mut first = None;
        self.for_each_regex_match(re, |m| {
            first = Some(m);
            false
        });
        first
    }

    /// Every match of `re`, in reading order, non-overlapping within a row
    /// as [`regex::Regex::find_iter`] is: `(row, col, matched text)` each.
    #[must_use]
    pub fn find_all_matches(&self, re: &regex::Regex) -> Vec<(u16, u16, String)> {
        let mut all = Vec::new();
        self.for_each_regex_match(re, |m| {
            all.push(m);
            true
        });
        all
    }

    /// True if some row matches `re` — the pattern-shaped
    /// [`contains`](Self::contains), and what
    /// [`Terminal::wait_until_matches`](crate::Terminal::wait_until_matches)
    /// waits on.
    #[must_use]
    pub fn matches(&self, re: &regex::Regex) -> bool {
        self.find_match(re).is_some()
    }

    /// [`mask_matching`](Self::mask_matching) with a pattern: the cells
    /// covered by every match of `re` in every row become `fill`, one per
    /// column, so a `\d{2}:\d{2}:\d{2}` clock stays eight columns wide.
    ///
    /// # Panics
    ///
    /// If `fill` is not one column wide, as `mask_matching` does.
    #[must_use]
    pub fn mask_matches(&self, re: &regex::Regex, fill: char) -> Screen {
        self.masked_spans(
            |hay| re.find_iter(hay).map(|m| (m.start(), m.end())).collect(),
            fill,
        )
    }

    fn for_each_regex_match(
        &self,
        re: &regex::Regex,
        mut visit: impl FnMut((u16, u16, String)) -> bool,
    ) {
        for row in 0..self.rows {
            let (text, cols) = self.searchable_row(row);
            for m in re.find_iter(text.trim_end()) {
                let Some(&col) = cols.get(m.start()) else {
                    return;
                };
                if !visit((row, col, m.as_str().to_owned())) {
                    return;
                }
            }
        }
    }
}

/// `s` folded to NFC.
fn nfc(s: &str) -> String {
    s.nfc().collect()
}

/// Clamp any range expression to `0..len`, as `(start, end)` exclusive.
///
/// # Panics
///
/// If the range runs backwards, naming the axis. See [`Screen::rect_text`]
/// for why this is a panic and not an error.
fn clamp_range(range: &impl RangeBounds<u16>, len: u16, axis: &str) -> (u16, u16) {
    let start = match range.start_bound() {
        Bound::Included(&s) => s,
        Bound::Excluded(&s) => s.saturating_add(1),
        Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        Bound::Included(&e) => e.saturating_add(1),
        Bound::Excluded(&e) => e,
        Bound::Unbounded => len,
    };
    // Checked on what the caller wrote, before clamping, so the message
    // quotes their numbers. Clamping cannot create an inversion: both
    // bounds are clamped to the same `len`.
    assert!(
        start <= end,
        "rect_text: {axis} range starts at {start} but ends at {end}"
    );
    (start.min(len), end.min(len))
}

impl Style {
    /// True when every attribute is at its default.
    pub(crate) fn is_default(&self) -> bool {
        *self == Style::default()
    }

    /// Fixed-order tokens for the `styles:` block (see `docs/DESIGN.md` §3).
    pub(crate) fn tokens(&self) -> String {
        // `Display for Color` is the token; the block only ever writes a
        // non-default one, since absence means default.
        fn color(prefix: &str, color: Color, out: &mut Vec<String>) {
            if color != Color::Default {
                out.push(format!("{prefix}={color}"));
            }
        }
        let mut tokens = Vec::new();
        color("fg", self.fg, &mut tokens);
        color("bg", self.bg, &mut tokens);
        // SGR order, which is the order the existing tokens were already
        // in — so a cell's tokens are unchanged unless it carries one of
        // the new attributes.
        for (on, name) in [
            (self.bold, "bold"),
            (self.dim, "dim"),
            (self.italic, "italic"),
            (self.underline, "underline"),
            (self.blink, "blink"),
            (self.reverse, "reverse"),
            (self.conceal, "conceal"),
            (self.strikethrough, "strikethrough"),
        ] {
            if on {
                tokens.push(name.to_owned());
            }
        }
        tokens.join(" ")
    }
}

/// [`Screen`] rendered with its styles — see [`Screen::with_styles`].
///
/// Nameable, so it can be stored, returned from a helper or taken as a
/// parameter rather than only passed straight to a snapshot macro:
///
/// ```
/// use termlens::{Screen, ScreenWithStyles};
///
/// fn styled(screen: &Screen) -> ScreenWithStyles<'_> {
///     screen.with_styles()
/// }
///
/// let screen = Screen::parse("size: 4x1  cursor: 0,0\nhi")?;
/// assert!(styled(&screen).to_string().ends_with("styles:\n(none)"));
/// # Ok::<(), termlens::Error>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ScreenWithStyles<'a> {
    screen: &'a Screen,
}

impl fmt::Display for ScreenWithStyles<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let screen = self.screen;
        write!(f, "{screen}\n\nstyles:")?;
        let mut any = false;
        for row in 0..screen.rows() {
            let mut spans: Vec<String> = Vec::new();
            let mut run: Option<(u16, u16, Style)> = None;
            for col in 0..screen.cols() {
                let style = screen
                    .cell(row, col)
                    .map_or_else(Style::default, |cell| *cell.style());
                match &mut run {
                    Some((_, end, current)) if *current == style => *end = col,
                    _ => {
                        if let Some(span) = flush(run.take()) {
                            spans.push(span);
                        }
                        run = Some((col, col, style));
                    }
                }
            }
            if let Some(span) = flush(run) {
                spans.push(span);
            }
            if !spans.is_empty() {
                any = true;
                write!(f, "\n{row}: {}", spans.join("; "))?;
            }
        }
        if !any {
            write!(f, "\n(none)")?;
        }
        return Ok(());

        /// Render one run, or `None` for default-styled runs (absence
        /// means default).
        fn flush(run: Option<(u16, u16, Style)>) -> Option<String> {
            let (start, end, style) = run?;
            if style.is_default() {
                return None;
            }
            let range = if start == end {
                format!("{start}")
            } else {
                format!("{start}-{end}")
            };
            Some(format!("{range} {}", style.tokens()))
        }
    }
}

impl fmt::Debug for Screen {
    /// Deliberately compact: the header plus the rendered text, exactly like
    /// [`Display`](fmt::Display). The derived alternative — thousands of
    /// [`Cell`]s on one line — makes `Err(Error::Timeout { .. })` in a
    /// `Result`-returning test unreadable (and long enough that CI log
    /// pipelines drop the line entirely). Use [`Screen::cell`] to inspect
    /// individual cells.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Screen({self})")
    }
}

impl fmt::Display for Screen {
    /// The snapshot text format: `size: <cols>x<rows>  cursor: <row>,<col>`
    /// (or `cursor: hidden`), then the grid verbatim, one terminal row per
    /// line with trailing whitespace stripped.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "size: {}x{}  cursor: ", self.cols, self.rows)?;
        if self.cursor_visible {
            write!(f, "{},{}", self.cursor_row, self.cursor_col)?;
        } else {
            write!(f, "hidden")?;
        }
        write!(f, "\n{}", self.text())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a screen from rows of text; `'*'` becomes a styled bold cell,
    /// wide characters get a proper continuation cell.
    fn screen(cols: u16, rows: u16, lines: &[&str]) -> Screen {
        use unicode_width::UnicodeWidthChar;

        let mut cells: Vec<Cell> = Vec::new();
        for r in 0..usize::from(rows) {
            let mut row_cells: Vec<Cell> = Vec::new();
            if let Some(line) = lines.get(r) {
                for ch in line.chars() {
                    // A zero-width combining mark joins the cell it modifies,
                    // which is what vt100 does: it appends combining
                    // characters to the cell currently being written rather
                    // than advancing. Modelling that here matters, because
                    // needle folding is per cell.
                    if ch.width().unwrap_or(1) == 0 {
                        if let Some(last) = row_cells.last_mut() {
                            let joined = format!("{}{ch}", last.contents());
                            *last = Cell::new(joined, *last.style(), last.is_wide(), false);
                            continue;
                        }
                    }
                    let wide = ch.width().unwrap_or(1) == 2;
                    let style = Style {
                        bold: ch == '*',
                        ..Style::default()
                    };
                    row_cells.push(Cell::new(ch.to_string(), style, wide, false));
                    if wide {
                        // As the emulator builds it: the continuation carries
                        // the leading cell's style (#218).
                        row_cells.push(Cell::new(String::new(), style, false, true));
                    }
                }
            }
            assert!(row_cells.len() <= usize::from(cols), "test line too long");
            while row_cells.len() < usize::from(cols) {
                row_cells.push(Cell::new(String::new(), Style::default(), false, false));
            }
            cells.extend(row_cells);
        }
        Screen::from_parts(cols, rows, 1, 2, true, cells, TermState::default())
    }

    #[test]
    fn row_text_pads_blanks_and_skips_continuations() {
        let s = screen(10, 2, &["ab", "汉x"]);
        assert_eq!(s.row_text(0), "ab        ");
        // 汉 is wide: one char + continuation, then x, then 7 blanks.
        assert_eq!(s.row_text(1), "汉x       ");
    }

    #[test]
    #[should_panic(expected = "row_text: row 9 is outside the 2-row screen")]
    fn row_text_rejects_out_of_bounds_rows() {
        let _ = screen(10, 2, &["ab", "汉x"]).row_text(9);
    }

    #[test]
    fn text_strips_trailing_whitespace_per_line() {
        let s = screen(10, 3, &["ab", "", "c"]);
        assert_eq!(s.text(), "ab\n\nc");
    }

    #[test]
    fn contains_matches_across_rows() {
        let s = screen(10, 2, &["hello", "world"]);
        assert!(s.contains("hello"));
        assert!(s.contains("hello\nworld"));
        assert!(!s.contains("hello world"));
    }

    /// The trap: NFC and NFD render identically, so a needle that misses
    /// looks like content that is absent. Both directions, because the
    /// author's needle and the application's output can each be either.
    #[test]
    fn needles_match_across_normalization_forms() {
        let nfc = "caf\u{e9}";
        let nfd = "cafe\u{301}";

        let on_nfd = screen(10, 1, &[nfd]);
        assert!(on_nfd.contains(nfc), "NFC needle must find NFD text");
        assert!(on_nfd.contains(nfd));
        assert_eq!(on_nfd.find(nfc), Some((0, 0)));
        assert_eq!(on_nfd.find(nfd), Some((0, 0)));

        let on_nfc = screen(10, 1, &[nfc]);
        assert!(on_nfc.contains(nfd), "NFD needle must find NFC text");
        assert!(on_nfc.contains(nfc));
        assert_eq!(on_nfc.find(nfd), Some((0, 0)));

        // The grid still holds what the application sent: an observation is
        // not rewritten, and a test that means to assert on the form can.
        assert_eq!(on_nfd.text(), nfd);
        assert_eq!(on_nfc.text(), nfc);
        assert_ne!(on_nfd.text(), on_nfc.text());
    }

    /// Matching is grapheme-shaped once folding applies: the screen shows
    /// `caf\u{e9}`, so it does not show `cafe`.
    #[test]
    fn a_folded_match_does_not_split_a_composed_character() {
        let on_nfd = screen(10, 1, &["cafe\u{301}"]);
        assert!(!on_nfd.contains("cafe"), "the screen shows caf\u{e9}");
        assert!(on_nfd.contains("caf"));
    }

    /// Columns must survive folding: NFD text is longer in bytes than its
    /// NFC form, so a naive offset would land in the wrong cell.
    #[test]
    fn folded_matches_still_report_real_columns() {
        // "e" + combining acute in cell 0, then a marker further along.
        let s = screen(10, 1, &["e\u{301}xyMARK"]);
        assert_eq!(s.find("MARK"), Some((0, 3)));
        assert_eq!(s.find("x"), Some((0, 1)));
        // Wide characters and folding together.
        let wide = screen(10, 1, &["\u{6c49}e\u{301}Z"]);
        assert_eq!(wide.find("Z"), Some((0, 3)));
    }

    #[test]
    fn find_reports_wide_aware_columns() {
        let s = screen(10, 2, &["abc", "汉字x"]);
        assert_eq!(s.find("bc"), Some((0, 1)));
        // 汉 occupies cols 0-1, 字 occupies 2-3, x sits at col 4.
        assert_eq!(s.find("x"), Some((1, 4)));
        assert_eq!(s.find(""), Some((1, 2)));
        assert_eq!(s.find("missing"), None);
    }

    #[test]
    fn find_locates_multi_row_needles_like_contains() {
        let s = screen(10, 3, &["hello", "world", "again"]);
        assert_eq!(s.find("hello\nworld"), Some((0, 0)));
        assert_eq!(s.find("llo\nwor"), Some((0, 2)));
        assert_eq!(s.find("world\nagain"), Some((1, 0)));
        assert_eq!(s.find("o\nworld\nag"), Some((0, 4)));
        assert_eq!(s.find("hello\nagain"), None); // rows aren't consecutive
        assert_eq!(s.find("hell\nworld"), None); // "hell" doesn't end row 0
        assert_eq!(s.find("hello\nworl\nagain"), None); // middle must be whole
        assert_eq!(s.find("again\nmore"), None); // would run off the screen
                                                 // Trailing whitespace is trimmed per row, exactly like `contains`.
        assert_eq!(s.find("hello \nworld"), None);
        // A needle starting with '\n' reports its first real character.
        assert_eq!(s.find("\nworld"), Some((1, 0)));
        assert_eq!(s.find("\n"), Some((1, 0)));
        // Property: multi-row find agrees with contains.
        for needle in ["hello\nworld", "llo\nwor", "x\nworld", "\nagain"] {
            assert_eq!(s.find(needle).is_some(), s.contains(needle), "{needle:?}");
        }
    }

    #[test]
    fn single_row_find_agrees_with_contains_about_trailing_padding() {
        // `find` searched the row padded to the terminal width while
        // `contains` searched the trimmed text (#212), so a needle ending in
        // a space was found on a row where nothing followed the word.
        let s = screen(10, 2, &["Total:", "a b"]);
        for needle in [
            "Total:", "Total: ", "Total:  ", " ", "   ", "otal: ", "a b", "a b ", "b ",
        ] {
            assert_eq!(s.find(needle).is_some(), s.contains(needle), "{needle:?}");
        }
        assert_eq!(s.find("Total:"), Some((0, 0)));
        assert_eq!(s.find("Total: "), None);
        assert_eq!(s.find("a b"), Some((1, 0))); // an interior space still matches
        assert_eq!(s.find(" "), Some((1, 1))); // …and is the only space that does
    }

    #[test]
    fn multi_row_find_reports_wide_aware_columns() {
        let s = screen(10, 2, &["汉字x", "next"]);
        // 汉 = cols 0-1, 字 = cols 2-3, x = col 4.
        assert_eq!(s.find("字x\nnext"), Some((0, 2)));
        assert_eq!(s.find("x\nnext"), Some((0, 4)));
    }

    #[test]
    fn rect_text_slices_columns_and_rows() {
        let s = screen(10, 3, &["0123456789", "abcdefghij", "xyz"]);
        assert_eq!(s.rect_text(2..5, 0..2), "234\ncde");
        assert_eq!(s.rect_text(2..=4, 0..=1), "234\ncde"); // inclusive forms
        assert_eq!(s.rect_text(.., 2..), "xyz"); // trailing blanks trimmed
        assert_eq!(s.rect_text(8.., ..2), "89\nij");
        assert_eq!(s.rect_text(0..3, 5..9), ""); // rows clamp to nothing
        assert_eq!(s.rect_text(20..30, ..1), ""); // cols clamp to nothing
        assert_eq!(s.rect_text(.., ..), s.text()); // the whole screen
    }

    /// Both axes, because they used to disagree: a reversed column range
    /// returned a bare "\n" and a reversed row range returned "", and
    /// neither said anything was wrong.
    ///
    /// The bounds come from variables on purpose. A *literal* `3..0` is
    /// already caught by clippy's `reversed_empty_ranges`, so the case that
    /// reaches a running test is the computed one — which is also the shape
    /// a swapped-argument mistake actually takes.
    #[test]
    #[should_panic(expected = "column range starts at 3 but ends at 0")]
    fn a_reversed_column_range_panics() {
        let s = screen(10, 3, &["0123456789", "abcdefghij", "xyz"]);
        let (from, to) = (3, 0);
        let _ = s.rect_text(from..to, 0..2);
    }

    #[test]
    #[should_panic(expected = "row range starts at 2 but ends at 0")]
    fn a_reversed_row_range_panics() {
        let s = screen(10, 3, &["0123456789", "abcdefghij", "xyz"]);
        let (from, to) = (2, 0);
        let _ = s.rect_text(0..3, from..to);
    }

    /// Out-of-range is not the same mistake and stays clamped: asking for
    /// more screen than exists is reasonable, asking backwards is not.
    #[test]
    fn out_of_range_bounds_still_clamp() {
        let s = screen(10, 3, &["0123456789", "abcdefghij", "xyz"]);
        assert_eq!(s.rect_text(8..99, ..1), "89");
        assert_eq!(s.rect_text(.., 1..99), "abcdefghij\nxyz");
        assert_eq!(s.rect_text(5..5, ..), "\n\n"); // empty but not inverted
    }

    #[test]
    fn rect_text_wide_characters_count_where_they_start() {
        let s = screen(10, 1, &["汉字x"]);
        assert_eq!(s.rect_text(0..2, ..), "");
        // Slicing in from the continuation side drops the cut character
        // (its leading cell is outside) and keeps the next one whole.
        assert_eq!(s.rect_text(1..3, ..), "");
        assert_eq!(s.rect_text(4.., ..), "x");
    }

    #[test]
    fn find_by_scans_row_major_and_sees_styles() {
        let s = screen(10, 2, &["ab*", "c"]);
        assert_eq!(s.find_by(|c| c.style().bold), Some((0, 2)));
        assert_eq!(s.find_by(|c| c.contents() == "c"), Some((1, 0)));
        assert_eq!(s.find_by(|c| c.style().reverse), None);
    }

    #[test]
    fn cell_and_cursor_accessors() {
        let s = screen(10, 2, &["a*"]);
        assert_eq!(s.cell(0, 0).unwrap().contents(), "a");
        assert!(s.cell(0, 1).unwrap().style().bold);
        assert!(s.cell(2, 0).is_none());
        assert!(s.cell(0, 10).is_none());
        assert_eq!(s.cursor(), (1, 2, true));
        assert_eq!(s.size(), (10, 2));
        assert_eq!((s.cols(), s.rows()), (10, 2));
    }

    #[test]
    fn with_styles_renders_runs_in_fixed_token_order() {
        use unicode_width::UnicodeWidthChar as _;
        let mut cells: Vec<Cell> = Vec::new();
        let styled = Style {
            fg: Color::Indexed(4),
            bold: true,
            ..Style::default()
        };
        // Row 0: "hi" styled, rest default. Row 1: all default text.
        // Row 2: one reverse blank cell at col 3 (highlight past text).
        for ch in ['h', 'i'] {
            assert_eq!(ch.width(), Some(1));
            cells.push(Cell::new(ch.to_string(), styled, false, false));
        }
        for _ in 2..6 {
            cells.push(Cell::new(String::new(), Style::default(), false, false));
        }
        for ch in "plain ".chars() {
            cells.push(Cell::new(ch.to_string(), Style::default(), false, false));
        }
        for col in 0..6 {
            let style = if col == 3 {
                Style {
                    reverse: true,
                    ..Style::default()
                }
            } else {
                Style::default()
            };
            cells.push(Cell::new(String::new(), style, false, false));
        }
        let screen = Screen::from_parts(6, 3, 0, 0, true, cells, TermState::default());

        let rendered = screen.with_styles().to_string();
        let styles_block = rendered.split("\n\nstyles:\n").nth(1).unwrap();
        assert_eq!(styles_block, "0: 0-1 fg=4 bold\n2: 3 reverse");
        // The plain rendering is a strict prefix.
        assert!(rendered.starts_with(&screen.to_string()));
    }

    #[test]
    fn with_styles_on_a_default_screen_says_none() {
        let s = screen(10, 2, &["hello"]);
        let rendered = s.with_styles().to_string();
        assert!(rendered.ends_with("\n\nstyles:\n(none)"), "{rendered}");
    }

    #[test]
    fn with_styles_renders_rgb_and_merges_adjacent_runs() {
        let style = Style {
            bg: Color::Rgb(0x1e, 0x1e, 0x2e),
            ..Style::default()
        };
        let mut cells: Vec<Cell> = Vec::new();
        for ch in ['a', 'b', 'c'] {
            cells.push(Cell::new(ch.to_string(), style, false, false));
        }
        cells.push(Cell::new(String::new(), Style::default(), false, false));
        let screen = Screen::from_parts(4, 1, 0, 0, true, cells, TermState::default());
        let rendered = screen.with_styles().to_string();
        assert!(
            rendered.ends_with("styles:\n0: 0-2 bg=#1e1e2e"),
            "{rendered}"
        );
    }

    /// `==` is the same observation, counters included — stricter than the
    /// text rendering, which is the trap the doc names.
    #[test]
    fn equality_is_the_same_observation_not_the_same_rendering() {
        let a = screen(10, 2, &["hello"]);
        assert_eq!(a, a.clone(), "a clone observes the same instant");
        assert_eq!(a, screen(10, 2, &["hello"]), "built alike, equal");
        assert_ne!(a, screen(10, 2, &["hullo"]));

        // A bell changes no cell: the renderings agree, the screens do not.
        let cells = vec![Cell::new("x".into(), Style::default(), false, false)];
        let quiet = Screen::from_parts(1, 1, 0, 0, true, cells.clone(), TermState::default());
        let rung = Screen::from_parts(
            1,
            1,
            0,
            0,
            true,
            cells,
            TermState {
                bells: 1,
                ..TermState::default()
            },
        );
        assert_eq!(quiet.to_string(), rung.to_string());
        assert_ne!(quiet, rung);

        // A style is invisible to `to_string()` and visible to `==` — and to
        // the styled rendering, which is the comparison the doc points at.
        let bold = vec![Cell::new(
            "x".into(),
            Style {
                bold: true,
                ..Style::default()
            },
            false,
            false,
        )];
        let styled = Screen::from_parts(1, 1, 0, 0, true, bold, TermState::default());
        assert_eq!(quiet.to_string(), styled.to_string());
        assert_ne!(quiet, styled);
        assert_ne!(
            quiet.with_styles().to_string(),
            styled.with_styles().to_string()
        );
    }

    #[test]
    fn display_format_matches_spec() {
        let s = screen(10, 2, &["hi"]);
        assert_eq!(format!("{s}"), "size: 10x2  cursor: 1,2\nhi\n");
    }

    /// The whole point of `TermState` is that it is invisible in the text
    /// rendering, so a release adding a fact to it cannot invalidate a
    /// checked-in snapshot. Asserted exactly, on two screens that differ in
    /// nothing else — the integration test cannot make this claim, because
    /// driving a shell to the second state also echoes a newline.
    #[test]
    fn the_cursor_shape_is_invisible_in_the_rendering() {
        let render = |cursor_style| {
            let state = TermState {
                cursor_style,
                ..TermState::default()
            };
            let cells = vec![Cell::new("x".into(), Style::default(), false, false)];
            Screen::from_parts(1, 1, 0, 0, true, cells, state).to_string()
        };
        let plain = render(None);
        for ps in 0u8..=6 {
            assert_eq!(
                render(Some(ps)),
                plain,
                "DECSCUSR {ps} changed the rendering"
            );
        }
        // The same claim for the other fact this release captures.
        let linked = TermState {
            links: Arc::new(vec![Link::open("https://example.invalid/a", Some("7"))]),
            ..TermState::default()
        };
        let cells = vec![Cell::new("x".into(), Style::default(), false, false)];
        assert_eq!(
            Screen::from_parts(1, 1, 0, 0, true, cells, linked).to_string(),
            plain,
            "a hyperlink changed the rendering"
        );
        // …and the fact itself is still there to assert on.
        let state = TermState {
            cursor_style: Some(5),
            ..TermState::default()
        };
        let cells = vec![Cell::new("x".into(), Style::default(), false, false)];
        let s = Screen::from_parts(1, 1, 0, 0, true, cells, state);
        assert_eq!(s.cursor_shape(), CursorShape::Bar);
        assert_eq!(s.cursor_blink(), Some(true));
    }

    #[test]
    fn state_accessors_report_the_captured_state_and_stay_out_of_display() {
        let default = screen(4, 1, &["x"]);
        assert_eq!(default.title(), "");
        assert!(!default.alternate_screen());
        assert!(!default.bracketed_paste());
        assert!(!default.application_cursor());
        assert_eq!(default.mouse_mode(), MouseMode::None);
        assert!(default.clipboard().is_none());
        assert_eq!(default.cursor_shape(), CursorShape::Default);
        assert_eq!(default.cursor_blink(), None);
        assert!(default.links().is_empty());

        let state = TermState {
            title: Arc::from("my app"),
            alternate_screen: true,
            bracketed_paste: true,
            application_cursor: true,
            mouse: MouseMode::AnyMotion,
            mouse_modes: MouseModes::from_bits(0b1110),
            clipboard: Some(Arc::new(Clipboard::new("c", Some("copied".into())))),
            bells: 3,
            focus_events: true,
            cursor_style: Some(6),
            links: Arc::new(vec![{
                let mut l = Link::open("https://example.invalid/a", Some("7"));
                l.close(Some("docs".into()));
                l
            }]),
            graphics: GraphicsSeen::for_test(1, 1, 2, 160),
            repaints: 9,
            scrollback: Arc::from([Arc::from("scrolled away")]),
            ..TermState::default()
        };
        let cells = vec![Cell::new("x".into(), Style::default(), false, false)];
        let s = Screen::from_parts(1, 1, 0, 0, true, cells, state);
        assert_eq!(s.title(), "my app");
        assert!(s.alternate_screen() && s.bracketed_paste() && s.application_cursor());
        assert_eq!(s.mouse_mode(), MouseMode::AnyMotion);
        let modes = s.mouse_modes();
        assert_eq!(
            modes.iter().collect::<Vec<_>>(),
            [
                MouseMode::PressRelease,
                MouseMode::ButtonMotion,
                MouseMode::AnyMotion
            ]
        );
        assert!(modes.contains(MouseMode::ButtonMotion) && !modes.contains(MouseMode::Press));
        assert!(!modes.contains(MouseMode::None) && !modes.is_empty() && modes.len() == 3);
        assert_eq!(
            format!("{modes:?}"),
            "{PressRelease, ButtonMotion, AnyMotion}"
        );
        assert!(
            default.mouse_modes().is_empty() && default.mouse_modes().contains(MouseMode::None)
        );
        let clip = s.clipboard().expect("captured");
        assert_eq!((clip.targets(), clip.text()), ("c", Some("copied")));
        assert_eq!(s.scrollback_rows(), 1);
        assert_eq!(s.bells(), 3);
        // 6 is a steady bar: the shape and the blink are read apart.
        assert_eq!(s.cursor_shape(), CursorShape::Bar);
        assert_eq!(s.cursor_blink(), Some(false));
        let link = &s.links()[0];
        assert_eq!(link.uri(), "https://example.invalid/a");
        assert_eq!(
            (link.id(), link.label(), link.closed()),
            (Some("7"), Some("docs"), true)
        );
        assert!(s.focus_events());
        assert_eq!(s.repaints(), 9);
        assert_eq!(s.graphics().kitty(), 1);
        assert_eq!(s.graphics().sixel(), 1);
        assert_eq!(s.graphics().total(), 2);
        assert_eq!(s.graphics().deletes(), 2);
        assert_eq!(s.graphics().bytes(), 160);
        assert!(!s.graphics().is_empty());
        assert!(GraphicsSeen::default().is_empty());
        assert_eq!(s.scrollback_text(), "scrolled away");
        assert_eq!(s.full_text(), "scrolled away\nx");
        // Out-of-band state never leaks into the text format — including
        // history, so existing snapshot files stay valid now that
        // retention is on by default.
        assert_eq!(format!("{s}"), "size: 1x1  cursor: 0,0\nx");
    }
}