summaryrefslogtreecommitdiffstatshomepage
path: root/test/functional/terminal/tui_spec.lua
blob: b1e22ef191216fe81b4f906b01bd4a353303418a (plain)
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
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
-- TUI acceptance tests.
-- Uses :terminal as a way to send keys and assert screen state.
--
-- "bracketed paste" terminal feature:
-- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Bracketed-Paste-Mode

local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local Screen = require('test.functional.ui.screen')
local tt = require('test.functional.testterm')

local eq = t.eq
local feed_data = tt.feed_data
local clear = n.clear
local command = n.command
local exec = n.exec
local exec_lua = n.exec_lua
local testprg = n.testprg
local retry = t.retry
local nvim_prog = n.nvim_prog
local nvim_set = n.nvim_set
local ok = t.ok
local read_file = t.read_file
local fn = n.fn
local api = n.api
local is_os = t.is_os
local new_pipename = n.new_pipename
local set_session = n.set_session
local write_file = t.write_file
local eval = n.eval
local assert_log = t.assert_log

local testlog = 'Xtest-tui-log'

-- Using this to have 'notermguicolors' in Nvim instances without starting a timer
-- that causes delay on exit with ASAN/TSAN.
local env_notermguicolors = { COLORTERM = 'xterm-256color' }

describe('TUI', function()
  it('exit status 1 and error message with server --listen error #34365', function()
    clear()
    local addr_in_use = api.nvim_get_vvar('servername')
    local screen = tt.setup_child_nvim(
      { '--listen', addr_in_use, '-u', 'NONE', '-i', 'NONE' },
      { extra_rows = 10, cols = 60, env = { NVIM_LOG_FILE = testlog } }
    )
    finally(function()
      os.remove(testlog)
    end)

    screen:expect({ any = vim.pesc('[Process exited 1]') })

    -- When the address is very long, the error message may be only partly visible.
    if #addr_in_use <= 600 then
      screen:expect({
        any = vim.pesc(
          ('%s: Failed to --listen: address already in use:'):format(
            fn.fnamemodify(nvim_prog, ':t')
          )
        ),
        unchanged = true,
      })
    end

    -- Always assert the log for the error message.
    assert_log(
      vim.pesc('Failed to start server: address already in use: ' .. addr_in_use),
      testlog,
      100
    )
  end)

  it('suspending does not crash or hang', function()
    clear()
    local screen = tt.setup_child_nvim({ '--clean' }, { env = env_notermguicolors })
    local s0 = [[
      ^                                                  |
      ~                                                 |*3
      {2:[No Name]                       0,0-1          All}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(s0)
    feed_data(':')
    local s1 = [[
                                                        |
      ~                                                 |*3
      {2:[No Name]                       0,0-1          All}|
      :^                                                 |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(s1)
    feed_data('suspend\r')
    if is_os('win') then -- no-op on Windows
      screen:expect([[
        ^                                                  |
        ~                                                 |*3
        {2:[No Name]                       0,0-1          All}|
        :suspend                                          |
        {5:-- TERMINAL --}                                    |
      ]])
    else -- resuming works on other platforms
      screen:expect([[
                                                          |*5
        ^[Process suspended]                               |
        {5:-- TERMINAL --}                                    |
      ]])
      n.feed('<Space>')
      screen:expect(s0)
    end
    feed_data(':')
    screen:expect(s1)
  end)
end)

describe('TUI :detach', function()
  it('does not stop server', function()
    local job_opts = { env = t.shallowcopy(env_notermguicolors) }

    n.clear()
    finally(function()
      n.check_close()
    end)

    local child_server = new_pipename()
    local screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      nvim_set .. ' laststatus=2 background=dark',
    }, job_opts)
    tt.override_screen_expect_for_conpty(screen)

    tt.feed_data('iHello, World')
    screen:expect([[
      Hello, World^                                      |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])

    local child_session = n.connect(child_server)
    finally(function()
      -- Avoid a dangling process after :detach.
      child_session:request('nvim_command', 'qall!')
    end)
    local status, child_uis = child_session:request('nvim_list_uis')
    assert(status)
    eq(1, #child_uis)

    eq(
      { false, { 0, 'Vim(detach):E477: No ! allowed: detach!' } },
      { child_session:request('nvim_command', 'detach!') }
    )
    eq(
      { false, { 0, 'Vim(detach):E481: No range allowed: 1detach' } },
      { child_session:request('nvim_command', '1detach') }
    )
    eq(
      { false, { 0, 'Vim(detach):E488: Trailing characters: foo: detach foo' } },
      { child_session:request('nvim_command', 'detach foo') }
    )

    tt.feed_data('\027\027:detach\013')
    -- Note: "Process exited" message is misleading; tt.setup_child_nvim() sees the foreground
    -- process (client) exited, and doesn't know the server is still running?
    screen:expect {
      any = [[Process exited 0]],
    }

    child_uis --[[@type any[] ]] = ({ child_session:request('nvim_list_uis') })[2]
    eq(0, #child_uis)

    -- NOTE: The tt.setup_child_nvim() screen just wraps :terminal, it's not connected to the child.
    -- To use it again, we need to detach the old one.
    screen:detach()

    -- Edit some text on the headless server.
    status = (child_session:request('nvim_input', 'ddiWe did it, pooky.<Esc><Esc>'))
    assert(status)

    -- Test reattach by connecting a new TUI.
    local screen_reattached = tt.setup_child_nvim({
      '--remote-ui',
      '--server',
      child_server,
    }, job_opts)

    screen_reattached:expect([[
      We did it, pooky^.                                 |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)
end)

describe('TUI :restart', function()
  before_each(n.clear)
  after_each(n.check_close)

  ---@param exp boolean Restart expected
  ---@param sess table Session
  ---@param addr string
  local function assert_restarted(exp, sess, addr)
    local s = sess
    retry(nil, 5000, function()
      if exp then
        s:close()
        s = n.connect(addr)
      end

      -- Cheesy but reliable: :restart drops "-- [files…]", so empty v:argf means restart happened.
      -- TODO(justinmk): add `v:startreason`, `v:starttime`
      local _, argf = s:request('nvim_eval', 'v:argf')
      ok(vim.tbl_count(argf) == (exp and 0 or 1), exp and 'empty v:argf' or 'nonempty v:argf', argf)
    end)
  end

  it('validation', function()
    eq('Vim(restart):E481: No range allowed: :1restart', t.pcall_err(n.command, ':1restart'))
  end)

  it('ZR', function()
    -- Just exercise ZR, don't need to test all :restart functionality here.
    t.skip(is_os('win'), 'FIXME: --listen not preserved by :restart on Windows #38539')
    local server_pipe = new_pipename()
    local server_session
    finally(function()
      if server_session and not server_session.closed then
        server_session:close()
      end
    end)
    local screen = tt.setup_child_nvim({
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--listen',
      server_pipe,
      '--cmd',
      'set notermguicolors',
      '--',
      'file1.txt', -- XXX: see comment in assert_restarted()
    }, {
      env = vim.tbl_extend('force', env_notermguicolors, {
        -- Ignore logs, because assert_restarted may log "connection refused" while it retries.
        NVIM_LOG_FILE = testlog,
      }),
    })
    finally(function()
      os.remove(testlog)
    end)
    screen:expect({ any = 'file1%.txt' })

    server_session = n.connect(server_pipe)
    assert_restarted(false, server_session, server_pipe)

    -- ZR on modified buffer fails with E37.
    tt.feed_data('ifoo\027')
    tt.feed_data('ZR')
    screen:expect({ any = 'E37:' })

    -- [count]ZR discards unsaved changes.
    tt.feed_data('1ZR')
    screen:expect({ any = vim.pesc('[No Name]') })
    assert_restarted(true, server_session, server_pipe)
  end)

  it('works', function()
    local server_pipe = new_pipename()
    local screen = tt.setup_child_nvim({
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--listen',
      server_pipe,
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set laststatus=2 background=dark noruler noshowcmd',
      -- XXX: New server starts before the UI connects to it.
      -- So checking screen state for this pid is not possible.
      -- '--cmd',
      -- 'echo getpid()',
    }, { env = { COLORTERM = 'truecolor' } })
    screen:set_option('rgb', true)

    -- 'termguicolors' support should be detected properly after :restart.
    -- The value of has("gui_running") should be 0 before and after :restart.
    local function assert_termguicolors_and_no_gui_running()
      tt.feed_data(':echo "&termguicolors: " .. &termguicolors\013')
      screen:expect({ any = '&termguicolors: 1' })
      tt.feed_data(':echo "GUI Running: " .. has("gui_running")\013')
      screen:expect({ any = 'GUI Running: 0' })
    end

    local s0 = [[
      ^                                                  |
      {1:~}{18:                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(s0)
    assert_termguicolors_and_no_gui_running()

    local server_session = n.connect(server_pipe)
    local _, server_pid = server_session:request('nvim_call_function', 'getpid', {})
    local function assert_new_pid()
      server_session:close()
      -- On Windows, --listen address is restored async (after old server exits).
      if is_os('win') then
        retry(nil, 5000, function()
          server_session = n.connect(server_pipe)
        end)
      else
        server_session = n.connect(server_pipe)
      end
      local _, new_pid = server_session:request('nvim_call_function', 'getpid', {})
      t.neq(server_pid, new_pid)
      server_pid = new_pid
    end

    --- XXX: No longer using -c <command> during new server startup.
    --- Gets the last `argn` items in v:argv as a joined string.
    -- local function get_argv(argn)
    --   local argv = ({ server_session:request('nvim_eval', 'v:argv') })[2] --[[@type table]]
    --   return table.concat(argv, ' ', #argv - argn, #argv)
    -- end

    local s1 = [[
                                                        |
      ^Hello1                                            |
      {1:~}{18:                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]

    tt.feed_data(':set nomodified\013')
    -- Command is run on new server.
    tt.feed_data(":restart put ='Hello1'\013")
    screen:expect(s1)
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- Complex command following +cmd.
    tt.feed_data(":restart +qall! put ='Hello2' | put ='World2'\013")
    screen:expect([[
                                                        |
      Hello2                                            |
      ^World2                                            |
      {1:~}{18:                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- Check ":restart" on an unmodified buffer.
    tt.feed_data(':set nomodified\013')
    tt.feed_data(':restart\013')
    screen:expect(s0)
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- Check ":restart +qall!" on an unmodified buffer.
    tt.feed_data(':restart +qall!\013')
    screen:expect(s0)
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- Check ":restart +echo" cannot restart server.
    -- Check the full screen state to ensure this doesn't pollute the current UI.
    tt.feed_data(':restart +echo\013')
    screen:expect([[
      ^                                                  |
      {1:~}{18:                                                 }|*3
      {3:[No Name]                                         }|
      {9:restart failed: +cmd did not quit the server}      |
      {5:-- TERMINAL --}                                    |
    ]])

    tt.feed_data('ithis will be removed\027')
    screen:expect({ any = vim.pesc('this will be remove^d') })

    -- Check ":confirm restart" on a modified buffer.
    tt.feed_data(':confirm restart\013')
    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })

    -- Cancel the operation (abandons restart).
    tt.feed_data('C\013')
    screen:expect({ any = vim.pesc('[No Name]') })

    -- Check :restart respects 'confirm' option.
    tt.feed_data(':set confirm\013')
    tt.feed_data(':restart\013')
    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })
    tt.feed_data('C\013')
    screen:expect({ any = vim.pesc('[No Name]') })
    tt.feed_data(':set noconfirm\013')

    -- Check ":confirm restart <cmd>" on a modified buffer.
    tt.feed_data(":confirm restart put ='Hello3'\013")
    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })
    tt.feed_data('N\013')
    screen:expect({ any = '%^Hello3' })
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- Check ":confirm restart +echo" correctly ignores ":confirm"
    tt.feed_data(':confirm restart +echo\013')
    screen:expect({ any = vim.pesc('+cmd did not quit the server') })

    -- Check ":restart" on a modified buffer.
    tt.feed_data('ithis will be removed\027')
    tt.feed_data(':restart\013')
    screen:expect({ any = vim.pesc('Vim(qall):E37: No write since last change') })

    -- Check ":restart +qall!" on a modified buffer.
    tt.feed_data('ithis will be removed\027')
    tt.feed_data(':restart +qall!\013')
    screen:expect(s0)
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    if not is_os('win') then
      -- No --listen conflict when server exit is delayed.
      feed_data(':lua vim.schedule(function() vim.wait(100) end); vim.cmd.restart()\n')
      screen:expect(s0)
      assert_new_pid()
      assert_termguicolors_and_no_gui_running()
    end

    screen:try_resize(60, 6)
    screen:expect([[
      ^                                                            |
      {1:~}{18:                                                           }|*2
      {3:[No Name]                                                   }|
                                                                  |
      {5:-- TERMINAL --}                                              |
    ]])

    --- Check that ":restart" uses the updated size after terminal resize.
    tt.feed_data(':restart echo "restarted"\013')
    screen:expect([[
      ^                                                            |
      {1:~}{18:                                                           }|*2
      {3:[No Name]                                                   }|
      restarted                                                   |
      {5:-- TERMINAL --}                                              |
    ]])
    assert_new_pid()
    assert_termguicolors_and_no_gui_running()

    -- The server is now detached and needs to be quit explicitly.
    feed_data(':qall!\r')
    screen:expect({ any = vim.pesc('[Process exited 0]') })
  end)

  it('drops "-" and "-- [files…]" from v:argv #34417', function()
    t.skip(is_os('win'), 'stdin behavior differs on Windows')
    local server_session
    finally(function()
      if server_session then
        server_session:close()
      end
    end)
    local server_pipe = new_pipename()
    local screen = tt.setup_child_nvim({
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--listen',
      server_pipe,
      '--cmd',
      'set notermguicolors',
      '-s',
      '-',
      '-',
      '--',
      'Xtest-file1',
      'Xtest-file2',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      ~                                                 |*3
      {2:Xtest-file1                     0,0-1          All}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    server_session = n.connect(server_pipe)
    local expr = 'index(v:argv, "-") >= 0 || index(v:argv, "--") >= 0 ? v:true : v:false'
    local has_s = 'index(v:argv, "-s") >= 0 ? v:true : v:false'
    eq({ true, true }, { server_session:request('nvim_eval', expr) })
    eq({ true, true }, { server_session:request('nvim_eval', has_s) })

    tt.feed_data(":restart put='foo'\013")
    screen:expect([[
                                                        |
      ^foo                                               |
      ~                                                 |*2
      {2:[No Name] [+]                   2,1            All}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    server_session:close()
    server_session = n.connect(server_pipe)

    eq({ true, false }, { server_session:request('nvim_eval', expr) })
    eq({ true, false }, { server_session:request('nvim_eval', has_s) })

    -- local argv = ({ server_session:request('nvim_eval', 'v:argv') })[2] --[[@type table]]
    -- eq(13, #argv)
    -- eq("-c put='foo'", table.concat(argv, ' ', #argv - 1, #argv))

    -- The server is now detached and needs to be quit explicitly.
    feed_data(':qall!\r')
    screen:expect({ any = vim.pesc('[Process exited 0]') })
  end)

  it('[command] triggers autocommands properly #38549', function()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'autocmd FileType text echomsg "TRIGGERED: " .. bufnr()',
      '--cmd',
      'set notermguicolors noswapfile laststatus=0',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      ~                                                 |*4
                                      0,0-1         All |
      {5:-- TERMINAL --}                                    |
    ]])

    -- 'laststatus' should be 0 in the new Nvim and FileType event should be triggered.
    feed_data(':restart set nowrap | edit test/functional/fixtures/bigfile.txt\r')
    screen:expect([[
      ^0000;<control>;Cc;0;BN;;;;;N;NULL;;;;             |
      0001;<control>;Cc;0;BN;;;;;N;START OF HEADING;;;; |
      0002;<control>;Cc;0;BN;;;;;N;START OF TEXT;;;;    |
      0003;<control>;Cc;0;BN;;;;;N;END OF TEXT;;;;      |
      0004;<control>;Cc;0;BN;;;;;N;END OF TRANSMISSION;;|
      TRIGGERED: 1                    1,1           Top |
      {5:-- TERMINAL --}                                    |
    ]])

    -- The server is now detached and needs to be quit explicitly.
    feed_data(':qall!\r')
    screen:expect({ any = vim.pesc('[Process exited 0]') })
  end)

  it('new server loads user config after old server exits #38569', function()
    local config_file = 'Xrestart_session_config.lua'
    local session_file = 'Xrestart_session.vim'
    write_file(
      config_file,
      ([[
        vim.api.nvim_create_autocmd("VimLeavePre", {
          callback = function()
            vim.cmd('mksession! %s')
          end,
        })

        if vim.v.vim_did_enter and vim.uv.fs_stat('%s') then
          vim.cmd('source %s')
        end
      ]]):format(session_file, session_file, session_file)
    )
    finally(function()
      os.remove(config_file)
      os.remove(session_file)
    end)

    local screen = tt.setup_child_nvim({
      '--clean',
      '-u',
      config_file,
      '--cmd',
      'set notermguicolors noswapfile laststatus=0 nowrap noruler noshowcmd',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      ~                                                 |*4
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':rightbelow 28vsplit test/functional/fixtures/bigfile.txt\r')
    screen:expect([[
                           │^0000;<control>;Cc;0;BN;;;;;N|
      ~                    │0001;<control>;Cc;0;BN;;;;;N|
      ~                    │0002;<control>;Cc;0;BN;;;;;N|
      ~                    │0003;<control>;Cc;0;BN;;;;;N|
      ~                    │0004;<control>;Cc;0;BN;;;;;N|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':restart echo "restarted"\r')
    screen:expect([[
      ^                     │0000;<control>;Cc;0;BN;;;;;N|
      ~                    │0001;<control>;Cc;0;BN;;;;;N|
      ~                    │0002;<control>;Cc;0;BN;;;;;N|
      ~                    │0003;<control>;Cc;0;BN;;;;;N|
      ~                    │0004;<control>;Cc;0;BN;;;;;N|
      restarted                                         |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':set sessionoptions-=winsize | restart\r')
    screen:expect([[
      ^                         │0000;<control>;Cc;0;BN;;|
      ~                        │0001;<control>;Cc;0;BN;;|
      ~                        │0002;<control>;Cc;0;BN;;|
      ~                        │0003;<control>;Cc;0;BN;;|
      ~                        │0004;<control>;Cc;0;BN;;|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    -- The server is now detached and needs to be quit explicitly.
    feed_data(':qall!\r')
    screen:expect({ any = vim.pesc('[Process exited 0]') })
  end)
end)

describe('TUI :connect', function()
  before_each(n.clear)
  after_each(n.check_close)

  local screen_empty = [[
    ^                                                  |
    {100:~                                                 }|*5
                                                      |
  ]]

  it('leaves the current server running', function()
    local server1 = new_pipename()
    local screen1 = tt.setup_child_nvim({ '--listen', server1, '--clean' })
    screen1:expect({ any = vim.pesc('[No Name]') })

    tt.feed_data(':connect\013')
    screen1:expect({ any = 'E471: Argument required' })

    tt.feed_data('iThis is server 1.\027')
    screen1:expect({ any = vim.pesc('This is server 1^.') })

    -- Prevent screen2 from receiving the old terminal state.
    command('enew')
    screen1:expect(screen_empty)
    screen1:detach()

    local server2 = new_pipename()
    local screen2 = tt.setup_child_nvim({ '--listen', server2, '--clean' })
    screen2:expect({ any = vim.pesc('[No Name]') })

    tt.feed_data('iThis is server 2.\027')
    screen2:expect({ any = vim.pesc('This is server 2^.') })

    tt.feed_data(':connect ' .. server1 .. '\013')
    screen2:expect({ any = vim.pesc('This is server 1^.') })

    local server1_session = n.connect(server1)
    server1_session:request('nvim_command', 'qall!')
    screen2:expect({ any = vim.pesc('[Process exited 0]') })

    screen2:detach()

    local server2_session = n.connect(server2)

    local screen3 = tt.setup_child_nvim({ '--remote-ui', '--server', server2 })
    screen3:expect({ any = vim.pesc('This is server 2^.') })

    screen3:detach()
    server2_session:request('nvim_command', 'qall!')
  end)

  it('! stops the current server', function()
    local server1 = new_pipename()
    local screen1 = tt.setup_child_nvim({ '--listen', server1, '--clean' })
    screen1:expect({ any = vim.pesc('[No Name]') })

    tt.feed_data('iThis is server 1.\027')
    screen1:expect({ any = vim.pesc('This is server 1^.') })

    -- Prevent screen2 from receiving the old terminal state.
    command('enew')
    screen1:expect(screen_empty)
    screen1:detach()

    local server2 = new_pipename()
    local screen2 = tt.setup_child_nvim({ '--listen', server2, '--clean' })
    screen2:expect({ any = vim.pesc('[No Name]') })

    tt.feed_data(':connect! ' .. server1 .. '\013')
    screen2:expect({ any = vim.pesc('This is server 1^.') })

    retry(nil, nil, function()
      eq(nil, vim.uv.fs_stat(server2))
    end)

    local server1_session = n.connect(server1)
    server1_session:request('nvim_command', 'qall!')
    screen2:expect({ any = vim.pesc('[Process exited 0]') })

    screen2:detach()
  end)
end)

describe('TUI', function()
  local screen --[[@type test.functional.ui.screen]]
  local child_session --[[@type test.Session]]
  local child_exec_lua --[[@type fun(code: string, ...):any]]

  before_each(function()
    clear()
    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '--clean',
      '--cmd',
      nvim_set .. ' laststatus=2 background=dark',
      '--cmd',
      'colorscheme vim',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session = n.connect(child_server)
    child_exec_lua = tt.make_lua_executor(child_session)
  end)

  -- Wait for mode in the child Nvim (avoid "typeahead race" #10826).
  local function wait_for_mode(mode)
    retry(nil, nil, function()
      local _, m = child_session:request('nvim_get_mode')
      eq(mode, m.mode)
    end)
  end

  -- Assert buffer contents in the child Nvim.
  local function expect_child_buf_lines(expected)
    assert(type({}) == type(expected))
    retry(nil, nil, function()
      local _, buflines = child_session:request('nvim_buf_get_lines', 0, 0, -1, false)
      eq(expected, buflines)
    end)
  end

  -- Ensure both child client and child server have processed pending events.
  local function poke_both_eventloop()
    child_exec_lua([[
      _G.termresponse = nil
      vim.api.nvim_create_autocmd('TermResponse', {
        once = true,
        callback = function(ev) _G.termresponse = ev.data.sequence end,
      })
    ]])
    feed_data('\027P0$r\027\\')
    retry(nil, nil, function()
      eq('\027P0$r', child_exec_lua('return _G.termresponse'))
    end)
  end

  it('rapid resize #7572 #7628', function()
    -- Need buffer rows to provoke the behavior.
    feed_data(':edit test/functional/fixtures/bigfile.txt\n')
    screen:expect([[
      ^0000;<control>;Cc;0;BN;;;;;N;NULL;;;;             |
      0001;<control>;Cc;0;BN;;;;;N;START OF HEADING;;;; |
      0002;<control>;Cc;0;BN;;;;;N;START OF TEXT;;;;    |
      0003;<control>;Cc;0;BN;;;;;N;END OF TEXT;;;;      |
      {3:test/functional/fixtures/bigfile.txt              }|
      :edit test/functional/fixtures/bigfile.txt        |
      {5:-- TERMINAL --}                                    |
    ]])
    command('call jobresize(b:terminal_job_id, 58, 9)')
    command('call jobresize(b:terminal_job_id, 62, 13)')
    command('call jobresize(b:terminal_job_id, 100, 42)')
    command('call jobresize(b:terminal_job_id, 37, 1000)')
    -- Resize to <5 columns.
    screen:try_resize(4, 44)
    command('call jobresize(b:terminal_job_id, 4, 1000)')
    -- Resize to 1 row, then to 1 column, then increase rows to 4.
    screen:try_resize(44, 1)
    command('call jobresize(b:terminal_job_id, 44, 1)')
    screen:try_resize(1, 1)
    command('call jobresize(b:terminal_job_id, 1, 1)')
    screen:try_resize(1, 4)
    command('call jobresize(b:terminal_job_id, 1, 4)')
    screen:try_resize(57, 17)
    command('call jobresize(b:terminal_job_id, 57, 17)')
    retry(nil, nil, function()
      eq({ true, 57 }, { child_session:request('nvim_win_get_width', 0) })
    end)
  end)

  it('accepts resize while pager is active', function()
    tt.override_screen_expect_for_conpty(screen)
    child_session:request(
      'nvim_exec2',
      [[
      set more
      func! ManyErr()
        for i in range(20)
          echoerr "FAIL ".i
        endfor
      endfunc
    ]],
      {}
    )
    feed_data(':call ManyErr()\r')
    screen:expect([[
      {101:Error in function ManyErr:}                        |
      {103:line    2:}                                        |
      {101:FAIL 0}                                            |
      {101:FAIL 1}                                            |
      {101:FAIL 2}                                            |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    screen:try_resize(50, 10)
    screen:expect([[
      :call ManyErr()                                   |
      {101:Error in function ManyErr:}                        |
      {103:line    2:}                                        |
      {101:FAIL 0}                                            |
      {101:FAIL 1}                                            |
      {101:FAIL 2}                                            |
                                                        |*2
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data('j')
    screen:expect([[
      {101:Error in function ManyErr:}                        |
      {103:line    2:}                                        |
      {101:FAIL 0}                                            |
      {101:FAIL 1}                                            |
      {101:FAIL 2}                                            |
      {101:FAIL 3}                                            |
      {101:FAIL 4}                                            |
      {101:FAIL 5}                                            |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    screen:try_resize(50, 7)
    screen:expect([[
      {101:FAIL 1}                                            |
      {101:FAIL 2}                                            |
      {101:FAIL 3}                                            |
      {101:FAIL 4}                                            |
      {101:FAIL 5}                                            |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    screen:try_resize(50, 5)
    screen:expect([[
      {101:FAIL 3}                                            |
      {101:FAIL 4}                                            |
      {101:FAIL 5}                                            |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data('g')
    screen:expect([[
      :call ManyErr()                                   |
      {101:Error in function ManyErr:}                        |
      {103:line    2:}                                        |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    screen:try_resize(50, 10)
    screen:expect([[
      :call ManyErr()                                   |
      {101:Error in function ManyErr:}                        |
      {103:line    2:}                                        |
      {101:FAIL 0}                                            |
      {101:FAIL 1}                                            |
      {101:FAIL 2}                                            |
      {101:FAIL 3}                                            |
      {101:FAIL 4}                                            |
      {102:-- More --}^                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data('\003')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*6
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('accepts basic utf-8 input', function()
    feed_data('iabc\ntest1\ntest2')
    screen:expect([[
      abc                                               |
      test1                                             |
      test2^                                             |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027')
    screen:expect([[
      abc                                               |
      test1                                             |
      test^2                                             |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('interprets leading <Esc> byte as ALT modifier in normal-mode', function()
    local keys = 'dfghjkl'
    for c in keys:gmatch('.') do
      feed_data(':nnoremap <a-' .. c .. '> ialt-' .. c .. '<cr><esc>\r')
      feed_data('\027' .. c)
    end
    screen:expect([[
      alt-j                                             |
      alt-k                                             |
      alt-l                                             |
      ^                                                  |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('gg')
    screen:expect([[
      ^alt-d                                             |
      alt-f                                             |
      alt-g                                             |
      alt-h                                             |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('interprets ESC+key as ALT chord in i_CTRL-V', function()
    -- Vim represents ALT/META by setting the "high bit" of the modified key:
    -- ALT+j inserts "ê". Nvim does not (#3982).
    feed_data('i\022\027j')
    screen:expect([[
      <M-j>^                                             |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('interprets <Esc> encoded with kitty keyboard protocol', function()
    child_session:request(
      'nvim_exec2',
      [[
      nnoremap <M-;> <Nop>
      nnoremap <Esc> AESC<Esc>
      nnoremap <C-Esc> ACtrlEsc<Esc>
      nnoremap <D-Esc> ASuperEsc<Esc>
      nnoremap ; Asemicolon<Esc>
    ]],
      {}
    )
    -- Works with no modifier
    feed_data('\027[27u;')
    expect_child_buf_lines({ 'ESCsemicolon' })
    -- Works with Ctrl modifier
    feed_data('\027[27;5u')
    expect_child_buf_lines({ 'ESCsemicolonCtrlEsc' })
    -- Works with Super modifier
    feed_data('\027[27;9u')
    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEsc' })
    -- Works with NumLock modifier (which should be the same as no modifier) #33799
    feed_data('\027[27;129u')
    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEscESC' })
    screen:expect([[
      ESCsemicolonCtrlEscSuperEscES^C                    |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <Esc>; should be recognized as <M-;> when <M-;> is mapped
    feed_data('\027;')
    screen:expect_unchanged()
    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEscESC' })
  end)

  it('interprets <Esc><Nul> as <M-C-Space> #17198', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    feed_data('i\022\027\000')
    screen:expect([[
      <M-C-Space>^                                       |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it("split sequences work within 'ttimeoutlen' time", function()
    poke_both_eventloop() -- Make sure startup requests have finished.
    child_session:request('nvim_set_option_value', 'ttimeoutlen', 250, {})
    feed_data('i')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Split UTF-8 '⌂' character
    feed_data('\226')
    screen:expect_unchanged(false, 25)
    feed_data('\140')
    screen:expect_unchanged(false, 25)
    feed_data('\130')
    screen:expect([[
      ⌂^                                                 |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Split CSI u escape sequence for Ctrl-X
    feed_data('\027')
    screen:expect_unchanged(false, 25)
    feed_data('[')
    screen:expect_unchanged(false, 25)
    feed_data('120;')
    screen:expect_unchanged(false, 25)
    feed_data('5u')
    screen:expect([[
      ⌂^                                                 |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)}        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <Esc> is sent after 'ttimeoutlen' exceeds.
    feed_data('\027')
    screen:expect_unchanged(false, 25)
    vim.uv.sleep(225)
    screen:expect([[
      ^⌂                                                 |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('accepts ASCII control sequences', function()
    feed_data('i')
    feed_data('\022\007') -- ctrl+g
    feed_data('\022\022') -- ctrl+v
    feed_data('\022\013') -- ctrl+m
    screen:expect([[
      {104:^G^V^M}^                                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session:request('nvim_set_keymap', 'i', '\031', '!!!', {})
    feed_data('\031')
    screen:expect([[
      {104:^G^V^M}!!!^                                         |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session:request('nvim_buf_delete', 0, { force = true })
    child_session:request('nvim_set_option_value', 'laststatus', 0, {})
    child_session:request(
      'nvim_call_function',
      'jobstart',
      { { testprg('shell-test'), 'INTERACT' }, { term = true } }
    )
    screen:expect([[
      interact $ ^                                       |
                                                        |*4
      {5:-- TERMINAL --}                                    |*2
    ]])
    -- mappings for C0 control codes should work in Terminal mode #33750
    child_session:request('nvim_set_keymap', 't', '\031', '<Cmd>new<CR>', {})
    feed_data('\031')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|
      {3:[No Name]                                         }|
      interact $                                        |
                                                        |*2
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  local function test_mouse_wheel(esc)
    t.skip(is_os('win'), 'FIXME: some spaces have wrong attrs on Windows')
    child_session:request(
      'nvim_exec2',
      [[
      set number nostartofline nowrap mousescroll=hor:1,ver:1
      call setline(1, repeat([join(range(10), '----')], 10))
      vsplit
    ]],
      {}
    )
    screen:expect([[
      {103:  1 }^0----1----2----3----4│{103:  1 }0----1----2----3----|
      {103:  2 }0----1----2----3----4│{103:  2 }0----1----2----3----|
      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
      {103:  4 }0----1----2----3----4│{103:  4 }0----1----2----3----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelDown> in active window
    if esc then
      feed_data('\027[<65;8;1M')
    else
      api.nvim_input_mouse('wheel', 'down', '', 0, 0, 7)
    end
    screen:expect([[
      {103:  2 }^0----1----2----3----4│{103:  1 }0----1----2----3----|
      {103:  3 }0----1----2----3----4│{103:  2 }0----1----2----3----|
      {103:  4 }0----1----2----3----4│{103:  3 }0----1----2----3----|
      {103:  5 }0----1----2----3----4│{103:  4 }0----1----2----3----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelDown> in inactive window
    if esc then
      feed_data('\027[<65;48;1M')
    else
      api.nvim_input_mouse('wheel', 'down', '', 0, 0, 47)
    end
    screen:expect([[
      {103:  2 }^0----1----2----3----4│{103:  2 }0----1----2----3----|
      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
      {103:  4 }0----1----2----3----4│{103:  4 }0----1----2----3----|
      {103:  5 }0----1----2----3----4│{103:  5 }0----1----2----3----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelRight> in active window
    if esc then
      feed_data('\027[<67;8;1M')
    else
      api.nvim_input_mouse('wheel', 'right', '', 0, 0, 7)
    end
    screen:expect([[
      {103:  2 }^----1----2----3----4-│{103:  2 }0----1----2----3----|
      {103:  3 }----1----2----3----4-│{103:  3 }0----1----2----3----|
      {103:  4 }----1----2----3----4-│{103:  4 }0----1----2----3----|
      {103:  5 }----1----2----3----4-│{103:  5 }0----1----2----3----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelRight> in inactive window
    if esc then
      feed_data('\027[<67;48;1M')
    else
      api.nvim_input_mouse('wheel', 'right', '', 0, 0, 47)
    end
    screen:expect([[
      {103:  2 }^----1----2----3----4-│{103:  2 }----1----2----3----4|
      {103:  3 }----1----2----3----4-│{103:  3 }----1----2----3----4|
      {103:  4 }----1----2----3----4-│{103:  4 }----1----2----3----4|
      {103:  5 }----1----2----3----4-│{103:  5 }----1----2----3----4|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelDown> in active window
    if esc then
      feed_data('\027[<69;8;1M')
    else
      api.nvim_input_mouse('wheel', 'down', 'S', 0, 0, 7)
    end
    screen:expect([[
      {103:  5 }^----1----2----3----4-│{103:  2 }----1----2----3----4|
      {103:  6 }----1----2----3----4-│{103:  3 }----1----2----3----4|
      {103:  7 }----1----2----3----4-│{103:  4 }----1----2----3----4|
      {103:  8 }----1----2----3----4-│{103:  5 }----1----2----3----4|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelDown> in inactive window
    if esc then
      feed_data('\027[<69;48;1M')
    else
      api.nvim_input_mouse('wheel', 'down', 'S', 0, 0, 47)
    end
    screen:expect([[
      {103:  5 }^----1----2----3----4-│{103:  5 }----1----2----3----4|
      {103:  6 }----1----2----3----4-│{103:  6 }----1----2----3----4|
      {103:  7 }----1----2----3----4-│{103:  7 }----1----2----3----4|
      {103:  8 }----1----2----3----4-│{103:  8 }----1----2----3----4|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelRight> in active window
    if esc then
      feed_data('\027[<71;8;1M')
    else
      api.nvim_input_mouse('wheel', 'right', 'S', 0, 0, 7)
    end
    screen:expect([[
      {103:  5 }^----6----7----8----9 │{103:  5 }----1----2----3----4|
      {103:  6 }----6----7----8----9 │{103:  6 }----1----2----3----4|
      {103:  7 }----6----7----8----9 │{103:  7 }----1----2----3----4|
      {103:  8 }----6----7----8----9 │{103:  8 }----1----2----3----4|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelRight> in inactive window
    if esc then
      feed_data('\027[<71;48;1M')
    else
      api.nvim_input_mouse('wheel', 'right', 'S', 0, 0, 47)
    end
    screen:expect([[
      {103:  5 }^----6----7----8----9 │{103:  5 }5----6----7----8----|
      {103:  6 }----6----7----8----9 │{103:  6 }5----6----7----8----|
      {103:  7 }----6----7----8----9 │{103:  7 }5----6----7----8----|
      {103:  8 }----6----7----8----9 │{103:  8 }5----6----7----8----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelUp> in active window
    if esc then
      feed_data('\027[<64;8;1M')
    else
      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 7)
    end
    screen:expect([[
      {103:  4 }----6----7----8----9 │{103:  5 }5----6----7----8----|
      {103:  5 }^----6----7----8----9 │{103:  6 }5----6----7----8----|
      {103:  6 }----6----7----8----9 │{103:  7 }5----6----7----8----|
      {103:  7 }----6----7----8----9 │{103:  8 }5----6----7----8----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelUp> in inactive window
    if esc then
      feed_data('\027[<64;48;1M')
    else
      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 47)
    end
    screen:expect([[
      {103:  4 }----6----7----8----9 │{103:  4 }5----6----7----8----|
      {103:  5 }^----6----7----8----9 │{103:  5 }5----6----7----8----|
      {103:  6 }----6----7----8----9 │{103:  6 }5----6----7----8----|
      {103:  7 }----6----7----8----9 │{103:  7 }5----6----7----8----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelLeft> in active window
    if esc then
      feed_data('\027[<66;8;1M')
    else
      api.nvim_input_mouse('wheel', 'left', '', 0, 0, 7)
    end
    screen:expect([[
      {103:  4 }5----6----7----8----9│{103:  4 }5----6----7----8----|
      {103:  5 }5^----6----7----8----9│{103:  5 }5----6----7----8----|
      {103:  6 }5----6----7----8----9│{103:  6 }5----6----7----8----|
      {103:  7 }5----6----7----8----9│{103:  7 }5----6----7----8----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <ScrollWheelLeft> in inactive window
    if esc then
      feed_data('\027[<66;48;1M')
    else
      api.nvim_input_mouse('wheel', 'left', '', 0, 0, 47)
    end
    screen:expect([[
      {103:  4 }5----6----7----8----9│{103:  4 }-5----6----7----8---|
      {103:  5 }5^----6----7----8----9│{103:  5 }-5----6----7----8---|
      {103:  6 }5----6----7----8----9│{103:  6 }-5----6----7----8---|
      {103:  7 }5----6----7----8----9│{103:  7 }-5----6----7----8---|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelUp> in active window
    if esc then
      feed_data('\027[<68;8;1M')
    else
      api.nvim_input_mouse('wheel', 'up', 'S', 0, 0, 7)
    end
    screen:expect([[
      {103:  1 }5----6----7----8----9│{103:  4 }-5----6----7----8---|
      {103:  2 }5----6----7----8----9│{103:  5 }-5----6----7----8---|
      {103:  3 }5----6----7----8----9│{103:  6 }-5----6----7----8---|
      {103:  4 }5^----6----7----8----9│{103:  7 }-5----6----7----8---|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelUp> in inactive window
    if esc then
      feed_data('\027[<68;48;1M')
    else
      api.nvim_input_mouse('wheel', 'up', 'S', 0, 0, 47)
    end
    screen:expect([[
      {103:  1 }5----6----7----8----9│{103:  1 }-5----6----7----8---|
      {103:  2 }5----6----7----8----9│{103:  2 }-5----6----7----8---|
      {103:  3 }5----6----7----8----9│{103:  3 }-5----6----7----8---|
      {103:  4 }5^----6----7----8----9│{103:  4 }-5----6----7----8---|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelLeft> in active window
    if esc then
      feed_data('\027[<70;8;1M')
    else
      api.nvim_input_mouse('wheel', 'left', 'S', 0, 0, 7)
    end
    screen:expect([[
      {103:  1 }0----1----2----3----4│{103:  1 }-5----6----7----8---|
      {103:  2 }0----1----2----3----4│{103:  2 }-5----6----7----8---|
      {103:  3 }0----1----2----3----4│{103:  3 }-5----6----7----8---|
      {103:  4 }0----1----2----3----^4│{103:  4 }-5----6----7----8---|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- <S-ScrollWheelLeft> in inactive window
    if esc then
      feed_data('\027[<70;48;1M')
    else
      api.nvim_input_mouse('wheel', 'left', 'S', 0, 0, 47)
    end
    screen:expect([[
      {103:  1 }0----1----2----3----4│{103:  1 }0----1----2----3----|
      {103:  2 }0----1----2----3----4│{103:  2 }0----1----2----3----|
      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
      {103:  4 }0----1----2----3----^4│{103:  4 }0----1----2----3----|
      {3:[No Name] [+]             }{2:[No Name] [+]           }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end

  describe('accepts mouse wheel events', function()
    it('(mouse events sent to host)', function()
      test_mouse_wheel(false)
    end)

    it('(escape sequences sent to child)', function()
      test_mouse_wheel(true)
    end)
  end)

  local function test_mouse_popup(esc)
    child_session:request(
      'nvim_exec2',
      [[
      call setline(1, 'popup menu test')
      set mouse=a mousemodel=popup

      aunmenu PopUp
      " Delete the default MenuPopup event handler.
      autocmd! nvim.popupmenu
      menu PopUp.foo :let g:menustr = 'foo'<CR>
      menu PopUp.bar :let g:menustr = 'bar'<CR>
      menu PopUp.baz :let g:menustr = 'baz'<CR>
      highlight Pmenu ctermbg=NONE ctermfg=NONE cterm=underline,reverse
      highlight PmenuSel ctermbg=NONE ctermfg=NONE cterm=underline,reverse,bold
    ]],
      {}
    )
    if esc then
      feed_data('\027[<2;5;1M')
    else
      api.nvim_input_mouse('right', 'press', '', 0, 0, 4)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~  }{105: foo }{100:                                          }|
      {100:~  }{105: bar }{100:                                          }|
      {100:~  }{105: baz }{100:                                          }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<2;5;1m')
    else
      api.nvim_input_mouse('right', 'release', '', 0, 0, 4)
    end
    screen:expect_unchanged()
    if esc then
      feed_data('\027[<64;5;1M')
    else
      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 4)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~  }{106: foo }{100:                                          }|
      {100:~  }{105: bar }{100:                                          }|
      {100:~  }{105: baz }{100:                                          }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<35;7;4M')
    else
      api.nvim_input_mouse('move', '', '', 0, 3, 6)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~  }{105: foo }{100:                                          }|
      {100:~  }{105: bar }{100:                                          }|
      {100:~  }{106: baz }{100:                                          }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<65;7;4M')
    else
      api.nvim_input_mouse('wheel', 'down', '', 0, 3, 6)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~  }{105: foo }{100:                                          }|
      {100:~  }{106: bar }{100:                                          }|
      {100:~  }{105: baz }{100:                                          }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<0;7;3M')
    else
      api.nvim_input_mouse('left', 'press', '', 0, 2, 6)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      :let g:menustr = 'bar'                            |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<0;7;3m')
    else
      api.nvim_input_mouse('left', 'release', '', 0, 2, 6)
    end
    screen:expect_unchanged()
    if esc then
      feed_data('\027[<2;45;3M')
    else
      api.nvim_input_mouse('right', 'press', '', 0, 2, 44)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~                                                 }|*2
      {100:~                                          }{105: foo }{100:  }|
      {3:[No Name] [+]                              }{105: bar }{3:  }|
      :let g:menustr = 'bar'                     {105: baz }  |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<34;48;6M')
    else
      api.nvim_input_mouse('right', 'drag', '', 0, 5, 47)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~                                                 }|*2
      {100:~                                          }{105: foo }{100:  }|
      {3:[No Name] [+]                              }{105: bar }{3:  }|
      :let g:menustr = 'bar'                     {106: baz }  |
      {5:-- TERMINAL --}                                    |
    ]])
    if esc then
      feed_data('\027[<2;48;6m')
    else
      api.nvim_input_mouse('right', 'release', '', 0, 5, 47)
    end
    screen:expect([[
      ^popup menu test                                   |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      :let g:menustr = 'baz'                            |
      {5:-- TERMINAL --}                                    |
    ]])
  end

  describe('mouse events work with right-click menu', function()
    it('(mouse events sent to host)', function()
      test_mouse_popup(false)
    end)

    it('(escape sequences sent to child)', function()
      test_mouse_popup(true)
    end)
  end)

  it('accepts keypad keys from kitty keyboard protocol #19180', function()
    feed_data('i')
    feed_data(fn.nr2char(57399)) -- KP_0
    feed_data(fn.nr2char(57400)) -- KP_1
    feed_data(fn.nr2char(57401)) -- KP_2
    feed_data(fn.nr2char(57402)) -- KP_3
    feed_data(fn.nr2char(57403)) -- KP_4
    feed_data(fn.nr2char(57404)) -- KP_5
    feed_data(fn.nr2char(57405)) -- KP_6
    feed_data(fn.nr2char(57406)) -- KP_7
    feed_data(fn.nr2char(57407)) -- KP_8
    feed_data(fn.nr2char(57408)) -- KP_9
    feed_data(fn.nr2char(57409)) -- KP_DECIMAL
    feed_data(fn.nr2char(57410)) -- KP_DIVIDE
    feed_data(fn.nr2char(57411)) -- KP_MULTIPLY
    feed_data(fn.nr2char(57412)) -- KP_SUBTRACT
    feed_data(fn.nr2char(57413)) -- KP_ADD
    feed_data(fn.nr2char(57414)) -- KP_ENTER
    feed_data(fn.nr2char(57415)) -- KP_EQUAL
    screen:expect([[
      0123456789./*-+                                   |
      =^                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57417)) -- KP_LEFT
    screen:expect([[
      0123456789./*-+                                   |
      ^=                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57418)) -- KP_RIGHT
    screen:expect([[
      0123456789./*-+                                   |
      =^                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57419)) -- KP_UP
    screen:expect([[
      0^123456789./*-+                                   |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57420)) -- KP_DOWN
    screen:expect([[
      0123456789./*-+                                   |
      =^                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57425)) -- KP_INSERT
    screen:expect([[
      0123456789./*-+                                   |
      =^                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- REPLACE --}                                     |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[27u') -- ESC
    screen:expect([[
      0123456789./*-+                                   |
      ^=                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[57417;5u') -- CTRL + KP_LEFT
    screen:expect([[
      ^0123456789./*-+                                   |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[57418;2u') -- SHIFT + KP_RIGHT
    screen:expect([[
      0123456789^./*-+                                   |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57426)) -- KP_DELETE
    screen:expect([[
      0123456789^/*-+                                    |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57423)) -- KP_HOME
    screen:expect([[
      ^0123456789/*-+                                    |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(fn.nr2char(57424)) -- KP_END
    screen:expect([[
      0123456789/*-^+                                    |
      =                                                 |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session:request(
      'nvim_exec2',
      [[
      tab split
      tabnew
      highlight Tabline ctermbg=NONE ctermfg=NONE cterm=underline
    ]],
      {}
    )
    screen:expect([[
      {107: + [No Name]  + [No Name] }{5: [No Name] }{2:            }{107:X}|
      ^                                                  |
      {100:~                                                 }|*2
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[57421;5u') -- CTRL + KP_PAGE_UP
    screen:expect([[
      {107: + [No Name] }{5: + [No Name] }{107: [No Name] }{2:            }{107:X}|
      0123456789/*-^+                                    |
      =                                                 |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[57422;5u') -- CTRL + KP_PAGE_DOWN
    screen:expect([[
      {107: + [No Name]  + [No Name] }{5: [No Name] }{2:            }{107:X}|
      ^                                                  |
      {100:~                                                 }|*2
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('supports Super and Meta modifiers', function()
    feed_data('i')
    feed_data('\022\027[106;9u') -- Super + j
    feed_data('\022\027[107;33u') -- Meta + k
    feed_data('\022\027[13;41u') -- Super + Meta + Enter
    feed_data('\022\027[127;48u') -- Shift + Alt + Ctrl + Super + Meta + Backspace
    feed_data('\n')
    feed_data('\022\027[57376;9u') -- Super + F13
    feed_data('\022\027[57377;33u') -- Meta + F14
    feed_data('\022\027[57378;41u') -- Super + Meta + F15
    feed_data('\022\027[57379;48u') -- Shift + Alt + Ctrl + Super + Meta + F16
    screen:expect([[
      <D-j><T-k><T-D-CR><M-T-C-S-D-BS>                  |
      <D-F13><T-F14><T-D-F15><M-T-C-S-D-F16>^            |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: Insert mode', function()
    -- "bracketed paste"
    feed_data('i""\027i\027[200~')
    screen:expect([[
      "^"                                                |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('pasted from terminal')
    expect_child_buf_lines({ '"pasted from terminal"' })
    screen:expect([[
      "pasted from terminal^"                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[201~') -- End paste.
    poke_both_eventloop()
    screen:expect_unchanged()
    feed_data('\027[27u') -- ESC: go to Normal mode.
    wait_for_mode('n')
    screen:expect([[
      "pasted from termina^l"                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Dot-repeat/redo.
    feed_data('2.')
    expect_child_buf_lines({ '"pasted from terminapasted from terminalpasted from terminall"' })
    screen:expect([[
      "pasted from terminapasted from terminalpasted fro|
      m termina^ll"                                      |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Undo.
    feed_data('u')
    expect_child_buf_lines({ '"pasted from terminal"' })
    feed_data('u')
    expect_child_buf_lines({ '""' })
    feed_data('u')
    expect_child_buf_lines({ '' })
  end)

  it('paste: select-mode', function()
    feed_data('ithis is line 1\nthis is line 2\nline 3 is here\n\027')
    wait_for_mode('n')
    screen:expect([[
      this is line 1                                    |
      this is line 2                                    |
      line 3 is here                                    |
      ^                                                  |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Select-mode. Use <C-n> to move down.
    feed_data('gg04lgh\14\14')
    screen:expect([[
      this{108: is line 1}                                    |
      {108:this is line 2}                                    |
      {108:line}^ 3 is here                                    |
                                                        |
      {3:[No Name] [+]                                     }|
      {5:-- SELECT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[200~')
    feed_data('just paste it™')
    feed_data('\027[201~')
    screen:expect([[
      thisjust paste it^™3 is here                       |
                                                        |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Undo.
    feed_data('u')
    expect_child_buf_lines {
      'this is line 1',
      'this is line 2',
      'line 3 is here',
      '',
    }
    -- Redo.
    feed_data('\18') -- <C-r>
    expect_child_buf_lines {
      'thisjust paste it™3 is here',
      '',
    }
  end)

  it('paste: terminal mode', function()
    child_exec_lua('vim.o.statusline="^^^^^^^"')
    child_exec_lua('vim.fn.jobstart({ ... }, { term = true })', testprg('tty-test'))
    feed_data('i')
    screen:expect([[
      tty ready                                         |
      ^                                                  |
                                                        |*2
      {109:^^^^^^^                                           }|
      {5:-- TERMINAL --}                                    |*2
    ]])
    feed_data('\027[200~')
    feed_data('hallo')
    feed_data('\027[201~')
    screen:expect([[
      tty ready                                         |
      hallo^                                             |
                                                        |*2
      {109:^^^^^^^                                           }|
      {5:-- TERMINAL --}                                    |*2
    ]])
  end)

  it('paste: normal-mode (+CRLF #10872)', function()
    t.skip(is_os('win'), 'FIXME: some spaces have wrong attrs on Windows')
    feed_data(':set ruler | echo')
    wait_for_mode('c')
    feed_data('\n')
    wait_for_mode('n')
    local expected_lf = { 'line 1', 'ESC:\027 / CR: \rx' }
    local expected_crlf = { 'line 1', 'ESC:\027 / CR: ', 'x' }
    local expected_grid1 = [[
      line 1                                            |
      ESC:{104:^[} / CR:                                      |
      ^x                                                 |
      {100:~                                                 }|
      {3:[No Name] [+]                   3,1            All}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    -- "bracketed paste"
    feed_data('\027[200~' .. table.concat(expected_lf, '\n') .. '\027[201~')
    screen:expect(expected_grid1)
    -- Dot-repeat/redo.
    feed_data('.')
    local expected_grid2 = [[
      ESC:{104:^[} / CR:                                      |
      xline 1                                           |
      ESC:{104:^[} / CR:                                      |
      ^x                                                 |
      {3:[No Name] [+]                   5,1            Bot}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(expected_grid2)
    -- Undo.
    feed_data('u')
    expect_child_buf_lines(expected_crlf)
    feed_data('u')
    expect_child_buf_lines({ '' })
    feed_data(':echo')
    wait_for_mode('c')
    feed_data('\n')
    wait_for_mode('n')
    -- CRLF input
    feed_data('\027[200~' .. table.concat(expected_lf, '\r\n') .. '\027[201~')
    screen:expect(expected_grid1)
    expect_child_buf_lines(expected_crlf)
    -- Dot-repeat/redo.
    feed_data('.')
    screen:expect(expected_grid2)
    -- Undo.
    feed_data('u')
    expect_child_buf_lines(expected_crlf)
    feed_data('u')
    expect_child_buf_lines({ '' })
  end)

  it('paste: cmdline-mode inserts 1 line', function()
    feed_data('ifoo\n') -- Insert some text (for dot-repeat later).
    feed_data('\027:""') -- Enter Cmdline-mode.
    feed_data('\027[D') -- <Left> to place cursor between quotes.
    wait_for_mode('c')
    screen:expect([[
      foo                                               |
                                                        |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      :"^"                                               |
      {5:-- TERMINAL --}                                    |
    ]])
    -- "bracketed paste"
    feed_data('\027[200~line 1\nline 2\n')
    wait_for_mode('c')
    feed_data('line 3\nline 4\n\027[201~')
    poke_both_eventloop()
    wait_for_mode('c')
    screen:expect([[
      foo                                               |
                                                        |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      :"line 1^"                                         |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Dot-repeat/redo.
    feed_data('\027[27u')
    wait_for_mode('n')
    feed_data('.')
    screen:expect([[
      foo                                               |*2
      ^                                                  |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: cmdline-mode collects chunks of unfinished line', function()
    local function expect_cmdline(expected)
      retry(nil, nil, function()
        local _, cmdline = child_session:request('nvim_call_function', 'getcmdline', {})
        eq(expected, cmdline)
        local _, pos = child_session:request('nvim_call_function', 'getcmdpos', {})
        eq(#expected, pos) -- Cursor is just before the last char.
      end)
    end
    feed_data('\027:""') -- Enter Cmdline-mode.
    feed_data('\027[D') -- <Left> to place cursor between quotes.
    expect_cmdline('""')
    feed_data('\027[200~stuff 1 ')
    expect_cmdline('"stuff 1 "')
    -- Discards everything after the first line.
    feed_data('more\nstuff 2\nstuff 3\n')
    expect_cmdline('"stuff 1 more"')
    feed_data('stuff 3')
    expect_cmdline('"stuff 1 more"')
    -- End the paste sequence.
    feed_data('\027[201~')
    poke_both_eventloop()
    expect_cmdline('"stuff 1 more"')
    feed_data(' typed')
    expect_cmdline('"stuff 1 more typed"')
  end)

  it('paste: recovers from vim.paste() failure', function()
    child_exec_lua([[
      _G.save_paste_fn = vim.paste
      -- Stack traces for this test are non-deterministic, so disable them
      _G.debug.traceback = function(msg) return msg end
      vim.paste = function(lines, phase) error("fake fail") end
    ]])
    -- Prepare something for dot-repeat/redo.
    feed_data('ifoo\n\027[27u')
    wait_for_mode('n')
    screen:expect([[
      foo                                               |
      ^                                                  |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Start pasting...
    feed_data('\027[200~line 1\nline 2\n')
    screen:expect([[
      foo                                               |
      ^                                                  |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {101:paste: Lua: [string "<nvim>"]:4: fake fail}        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Remaining chunks are discarded after vim.paste() failure.
    feed_data('line 3\nline 4\n')
    feed_data('line 5\nline 6\n')
    feed_data('line 7\nline 8\n')
    -- Stop paste.
    feed_data('\027[201~')
    screen:expect_unchanged()
    feed_data('\n') -- <CR> to dismiss hit-enter prompt
    expect_child_buf_lines({ 'foo', '' })
    -- Dot-repeat/redo is not modified by failed paste.
    feed_data('.')
    screen:expect([[
      foo                                               |*2
      ^                                                  |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Editor should still work after failed/drained paste.
    feed_data('ityped input...\027[27u')
    screen:expect([[
      foo                                               |*2
      typed input..^.                                    |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Paste works if vim.paste() succeeds.
    child_exec_lua([[vim.paste = _G.save_paste_fn]])
    feed_data('\027[200~line A\nline B\n\027[201~')
    screen:expect([[
      foo                                               |
      typed input...line A                              |
      line B                                            |
      ^                                                  |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: vim.paste() cancel (retval=false) #10865', function()
    -- This test only exercises the "cancel" case.  Use-case would be "dangling
    -- paste", but that is not implemented yet. #10865
    child_exec_lua([[
      vim.paste = function(lines, phase) return false end
    ]])
    feed_data('\027[200~line A\nline B\n\027[201~')
    expect_child_buf_lines({ '' })
    feed_data('ifoo\n\027[27u')
    expect_child_buf_lines({ 'foo', '' })
  end)

  it('paste: vim.paste() cancel (retval=false) with streaming #30462', function()
    child_exec_lua([[
      vim.paste = (function(overridden)
        return function(lines, phase)
          for i, line in ipairs(lines) do
            if line:find('!') then
              return false
            end
          end
          return overridden(lines, phase)
        end
      end)(vim.paste)
    ]])
    feed_data('A')
    wait_for_mode('i')
    feed_data('\027[200~aaa')
    expect_child_buf_lines({ 'aaa' })
    feed_data('bbb')
    expect_child_buf_lines({ 'aaabbb' })
    feed_data('ccc!') -- This chunk is cancelled.
    expect_child_buf_lines({ 'aaabbb' })
    feed_data('ddd\027[201~') -- This chunk is ignored.
    poke_both_eventloop()
    expect_child_buf_lines({ 'aaabbb' })
    feed_data('\027[27u')
    wait_for_mode('n')
    feed_data('.') -- Dot-repeat only includes chunks actually pasted.
    expect_child_buf_lines({ 'aaabbbaaabbb' })
    feed_data('$\027[200~eee\027[201~') -- A following paste works normally.
    expect_child_buf_lines({ 'aaabbbaaabbbeee' })
  end)

  it("paste: 'nomodifiable' buffer", function()
    tt.override_screen_expect_for_conpty(screen)
    child_exec_lua([[
      vim.bo.modifiable = false
      -- Truncate the error message to hide the line number
      _G.debug.traceback = function(msg) return msg:sub(-49) end
    ]])
    feed_data('\027[200~fail 1\nfail 2\n\027[201~')
    screen:expect([[
                                                        |
      {100:~                                                 }|
      {3:                                                  }|
      {101:paste: Lua: Vim:E21: Cannot make changes, 'modifia}|
      {101:ble' is off}                                       |
      {102:Press ENTER or type command to continue}^           |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\n') -- <Enter> to dismiss hit-enter prompt
    child_exec_lua('vim.bo.modifiable = true')
    feed_data('\027[200~success 1\nsuccess 2\n\027[201~')
    screen:expect([[
      success 1                                         |
      success 2                                         |
      ^                                                  |
      {100:~                                                 }|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: exactly 64 bytes #10311', function()
    local expected = string.rep('z', 64)
    feed_data('i')
    wait_for_mode('i')
    -- "bracketed paste"
    feed_data('\027[200~' .. expected .. '\027[201~')
    expect_child_buf_lines({ expected })
    feed_data(' end')
    expected = expected .. ' end'
    screen:expect([[
      zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz|
      zzzzzzzzzzzzzz end^                                |
      {100:~                                                 }|*2
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    expect_child_buf_lines({ expected })
  end)

  it('paste: less-than sign in cmdline #11088', function()
    local expected = '<'
    feed_data(':')
    wait_for_mode('c')
    -- "bracketed paste"
    feed_data('\027[200~' .. expected .. '\027[201~')
    screen:expect([[
                                                        |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      :<^                                                |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: big burst of input', function()
    feed_data(':set ruler\n')
    local q = {}
    for i = 1, 3000 do
      q[i] = 'item ' .. tostring(i)
    end
    feed_data('i')
    wait_for_mode('i')
    -- "bracketed paste"
    feed_data('\027[200~' .. table.concat(q, '\n') .. '\027[201~')
    expect_child_buf_lines(q)
    feed_data(' end')
    screen:expect([[
      item 2997                                         |
      item 2998                                         |
      item 2999                                         |
      item 3000 end^                                     |
      {3:[No Name] [+]                   3000,14        Bot}|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[27u') -- ESC: go to Normal mode.
    wait_for_mode('n')
    -- Dot-repeat/redo.
    feed_data('.')
    screen:expect([[
      item 2997                                         |
      item 2998                                         |
      item 2999                                         |
      item 3000 en^dd                                    |
      {3:[No Name] [+]                   5999,13        Bot}|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: forwards spurious "start paste" code', function()
    -- If multiple "start paste" sequences are sent without a corresponding
    -- "stop paste" sequence, only the first occurrence should be consumed.
    feed_data('i')
    wait_for_mode('i')
    -- Send the "start paste" sequence.
    feed_data('\027[200~')
    feed_data('\npasted from terminal (1)\n')
    -- Send spurious "start paste" sequence.
    feed_data('\027[200~')
    feed_data('\n')
    -- Send the "stop paste" sequence.
    feed_data('\027[201~')
    screen:expect([[
                                                        |
      pasted from terminal (1)                          |
      {104:^[}[200~                                           |
      ^                                                  |
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: ignores spurious "stop paste" code', function()
    -- If "stop paste" sequence is received without a preceding "start paste"
    -- sequence, it should be ignored.
    feed_data('i')
    wait_for_mode('i')
    -- Send "stop paste" sequence.
    feed_data('\027[201~')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: split "start paste" code', function()
    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
    feed_data('i')
    wait_for_mode('i')
    -- Send split "start paste" sequence.
    feed_data('\027[2')
    feed_data('00~pasted from terminal\027[201~')
    screen:expect([[
      pasted from terminal^                              |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: split "stop paste" code', function()
    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
    feed_data('i')
    wait_for_mode('i')
    -- Send split "stop paste" sequence.
    feed_data('\027[200~pasted from terminal\027[20')
    feed_data('1~')
    screen:expect([[
      pasted from terminal^                              |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('paste: streamed paste with isolated "stop paste" code', function()
    child_exec_lua([[
      _G.paste_phases = {}
      vim.paste = (function(overridden)
        return function(lines, phase)
          table.insert(_G.paste_phases, phase)
          overridden(lines, phase)
        end
      end)(vim.paste)
    ]])
    feed_data('i')
    wait_for_mode('i')
    feed_data('\027[200~pasted') -- phase 1
    screen:expect([[
      pasted^                                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(' from terminal') -- phase 2
    screen:expect([[
      pasted from terminal^                              |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    -- Send isolated "stop paste" sequence.
    feed_data('\027[201~') -- phase 3
    poke_both_eventloop()
    screen:expect_unchanged()
    local rv = child_exec_lua('return _G.paste_phases')
    -- In rare cases there may be multiple chunks of phase 2 because of timing.
    eq({ 1, 2, 3 }, { rv[1], rv[2], rv[#rv] })
  end)

  it('allows termguicolors to be set at runtime', function()
    tt.override_screen_expect_for_conpty(screen)
    screen:set_option('rgb', true)
    feed_data(':hi SpecialKey ctermfg=3 guifg=SeaGreen\n')
    feed_data('i')
    feed_data('\022\007') -- ctrl+g
    feed_data('\028\014') -- crtl+\ ctrl+N
    feed_data(':set termguicolors?\n')
    screen:expect([[
      {110:^^G}                                                |
      {111:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      notermguicolors                                   |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':set termguicolors\n')
    screen:expect([[
      {113:^^G}                                                |
      {1:~}{18:                                                 }|*3
      {3:[No Name] [+]                                     }|
      :set termguicolors                                |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':set notermguicolors\n')
    screen:expect([[
      {110:^^G}                                                |
      {111:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      :set notermguicolors                              |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('forwards :term palette colors with termguicolors', function()
    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
    screen:set_rgb_cterm(true)
    screen:set_default_attr_ids({
      [1] = { { reverse = true }, { reverse = true } },
      [2] = {
        { bold = true, background = Screen.colors.LightGreen, foreground = Screen.colors.Black },
        { bold = true },
      },
      [3] = { { bold = true }, { bold = true } },
      [4] = { { fg_indexed = true, foreground = tonumber('0xe0e000') }, { foreground = 3 } },
      [5] = { { foreground = tonumber('0xff8000') }, {} },
      [6] = {
        {
          fg_indexed = true,
          bg_indexed = true,
          bold = true,
          background = tonumber('0x66ff99'),
          foreground = Screen.colors.Black,
        },
        { bold = true, background = 121, foreground = 0 },
      },
      [7] = {
        {
          fg_indexed = true,
          bg_indexed = true,
          background = tonumber('0x66ff99'),
          foreground = Screen.colors.Black,
        },
        { background = 121, foreground = 0 },
      },
    })

    child_exec_lua('vim.o.statusline="^^^^^^^"')
    child_exec_lua('vim.o.termguicolors=true')
    child_exec_lua('vim.fn.jobstart({ ... }, { term = true })', testprg('tty-test'))
    screen:expect([[
      ^tty ready                                         |
                                                        |*3
      {2:^^^^^^^                                           }|
                                                        |
      {3:-- TERMINAL --}                                    |
    ]])
    feed_data(
      ':call chansend(&channel, "\\033[38;5;3mtext\\033[38:2:255:128:0mcolor\\033[0;10mtext")\n'
    )
    screen:expect([[
      ^tty ready                                         |
      {4:text}{5:color}text                                     |
                                                        |*2
      {2:^^^^^^^                                           }|
                                                        |
      {3:-- TERMINAL --}                                    |
    ]])

    feed_data(':set notermguicolors\n')
    screen:expect([[
      ^tty ready                                         |
      {4:text}colortext                                     |
                                                        |*2
      {6:^^^^^^^}{7:                                           }|
      :set notermguicolors                              |
      {3:-- TERMINAL --}                                    |
    ]])
  end)

  -- Note: libvterm doesn't support colored underline or undercurl.
  it('supports undercurl and underdouble when run in :terminal', function()
    child_session:request('nvim_set_hl', 0, 'Visual', { undercurl = true })
    feed_data('ifoobar\027V')
    screen:expect([[
      {114:fooba}^r                                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- VISUAL LINE --}                                 |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session:request('nvim_set_hl', 0, 'Visual', { underdouble = true })
    screen:expect([[
      {115:fooba}^r                                            |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- VISUAL LINE --}                                 |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('in nvim_list_uis(), sets nvim_set_client_info()', function()
    -- $TERM in :terminal.
    local exp_term = (is_os('bsd') or is_os('win')) and 'xterm' or 'xterm-256color'
    local ui_chan = 1
    local expected = {
      {
        chan = ui_chan,
        ext_cmdline = false,
        ext_hlstate = false,
        ext_linegrid = true,
        ext_messages = false,
        ext_multigrid = false,
        ext_popupmenu = false,
        ext_tabline = false,
        ext_termcolors = true,
        ext_wildmenu = false,
        height = 6,
        override = false,
        rgb = false,
        stdin_tty = true,
        stdout_tty = true,
        term_background = '',
        term_colors = 256,
        term_name = exp_term,
        width = 50,
      },
    }
    local _, rv = child_session:request('nvim_list_uis')
    eq(expected, rv)

    ---@type table
    local expected_version = child_exec_lua('return vim.version()')
    -- vim.version() returns `prerelease` string. Coerce it to boolean.
    expected_version.prerelease = not not expected_version.prerelease

    local expected_chan_info = {
      client = {
        attributes = {
          license = 'Apache 2',
          -- pid = 5371,
          website = 'https://neovim.io',
        },
        methods = {},
        name = 'nvim-tui',
        type = 'ui',
        version = expected_version,
      },
      id = ui_chan,
      mode = 'rpc',
      stream = 'stdio',
    }

    local status, chan_info = child_session:request('nvim_get_chan_info', ui_chan)
    ok(status)
    local info = chan_info.client
    ok(info.attributes.pid and info.attributes.pid > 0, 'PID', info.attributes.pid or 'nil')
    ok(info.version.major >= 0)
    ok(info.version.minor >= 0)
    ok(info.version.patch >= 0)

    -- Delete variable fields so we can deep-compare.
    info.attributes.pid = nil

    eq(expected_chan_info, chan_info)
  end)

  it('allows grid to assume wider ambiwidth chars than host terminal', function()
    tt.override_screen_expect_for_conpty(screen)
    child_session:request(
      'nvim_buf_set_lines',
      0,
      0,
      -1,
      true,
      { ('℃'):rep(60), ('℃'):rep(60) }
    )
    child_session:request('nvim_set_option_value', 'cursorline', true, {})
    child_session:request('nvim_set_option_value', 'list', true, {})
    child_session:request('nvim_set_option_value', 'listchars', 'eol:$', { win = 0 })
    feed_data('gg')
    local singlewidth_screen = [[
      {107:^℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃}|
      {107:℃℃℃℃℃℃℃℃℃℃}{116:$}{107:                                       }|
      ℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃|
      ℃℃℃℃℃℃℃℃℃℃{100:$}                                       |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    -- When grid assumes "℃" to be double-width but host terminal assumes it to be single-width,
    -- the second cell of "℃" is a space and the attributes of the "℃" are applied to it.
    local doublewidth_screen = [[
      {107:^℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }|
      {107:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }|
      {107:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }{116:$}{107:                             }|
      ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ {100:@@@@}|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(singlewidth_screen)
    child_session:request('nvim_set_option_value', 'ambiwidth', 'double', {})
    screen:expect(doublewidth_screen)
    child_session:request('nvim_set_option_value', 'ambiwidth', 'single', {})
    screen:expect(singlewidth_screen)
    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2103, 0x2103, 2 } } })
    screen:expect(doublewidth_screen)
    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2103, 0x2103, 1 } } })
    screen:expect(singlewidth_screen)
  end)

  it('allows grid to assume wider non-ambiwidth chars than host terminal', function()
    tt.override_screen_expect_for_conpty(screen)
    child_session:request(
      'nvim_buf_set_lines',
      0,
      0,
      -1,
      true,
      { ('✓'):rep(60), ('✓'):rep(60) }
    )
    child_session:request('nvim_set_option_value', 'cursorline', true, {})
    child_session:request('nvim_set_option_value', 'list', true, {})
    child_session:request('nvim_set_option_value', 'listchars', 'eol:$', { win = 0 })
    feed_data('gg')
    local singlewidth_screen = [[
      {107:^✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓}|
      {107:✓✓✓✓✓✓✓✓✓✓}{116:$}{107:                                       }|
      ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓|
      ✓✓✓✓✓✓✓✓✓✓{100:$}                                       |
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    -- When grid assumes "✓" to be double-width but host terminal assumes it to be single-width,
    -- the second cell of "✓" is a space and the attributes of the "✓" are applied to it.
    local doublewidth_screen = [[
      {107:^✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }|
      {107:✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }|
      {107:✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }{116:$}{107:                             }|
      ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ {100:@@@@}|
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen:expect(singlewidth_screen)
    child_session:request('nvim_set_option_value', 'ambiwidth', 'double', {})
    screen:expect_unchanged()
    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2713, 0x2713, 2 } } })
    screen:expect(doublewidth_screen)
    child_session:request('nvim_set_option_value', 'ambiwidth', 'single', {})
    screen:expect_unchanged()
    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2713, 0x2713, 1 } } })
    screen:expect(singlewidth_screen)
  end)

  it('draws correctly when cursor_address overflows #21643', function()
    screen:try_resize(70, 333)
    retry(nil, nil, function()
      eq({ true, 330 }, { child_session:request('nvim_win_get_height', 0) })
    end)
    child_session:request('nvim_set_option_value', 'cursorline', true, {})
    -- Use full screen message so that redrawing afterwards is more deterministic.
    child_session:notify('nvim_command', 'intro')
    screen:expect({ any = 'Nvim is open source and freely distributable' })
    -- Going to top-left corner needs 3 bytes.
    -- Setting underline attribute needs 9 bytes.
    -- A Ꝩ character takes 3 bytes.
    -- The whole line needs 3 + 9 + 3 * 21838 + 3 = 65529 bytes.
    -- The cursor_address that comes after will overflow the 65535-byte buffer.
    local line = ('Ꝩ'):rep(21838) .. '℃'
    child_session:notify('nvim_buf_set_lines', 0, 0, -1, true, { line, 'b' })
    -- Close the :intro message and redraw the lines.
    feed_data('\n')
    screen:expect([[
      {107:^ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ}|
      {107:ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ}|*310
      {107:ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ℃ }|
      b                                                                     |
      {100:~                                                                     }|*17
      {3:[No Name] [+]                                                         }|
                                                                            |
      {5:-- TERMINAL --}                                                        |
    ]])
  end)

  it('draws correctly when setting title overflows #30793', function()
    screen:try_resize(67, 327)
    retry(nil, nil, function()
      eq({ true, 324 }, { child_session:request('nvim_win_get_height', 0) })
    end)
    child_exec_lua([[
      vim.o.cmdheight = 0
      vim.o.laststatus = 0
      vim.o.ruler = false
      vim.o.showcmd = false
      vim.o.termsync = false
      vim.o.titlestring = '%t%( %M%) - Nvim'
      vim.o.title = true
    ]])
    retry(nil, nil, function()
      eq('[No Name] - Nvim', api.nvim_buf_get_var(0, 'term_title'))
      eq({ true, 326 }, { child_session:request('nvim_win_get_height', 0) })
    end)
    -- Use full screen message so that redrawing afterwards is more deterministic.
    child_session:notify('nvim_command', 'intro')
    screen:expect({ any = 'Nvim is open source and freely distributable' })
    -- Going to top-left corner needs 3 bytes.
    -- A Ꝩ character takes 3 bytes.
    -- The whole line needs 3 + 3 * 21842 = 65529 bytes.
    -- The title will be updated because the buffer is now modified.
    -- The start of the OSC 0 sequence to set title can fit in the 65535-byte buffer,
    -- but the title string cannot.
    local line = ('Ꝩ'):rep(21842)
    child_session:notify('nvim_buf_set_lines', 0, 0, -1, true, { line })
    -- Close the :intro message and redraw the lines.
    feed_data('\n')
    screen:expect([[
      ^ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ|
      ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ|*325
      {5:-- TERMINAL --}                                                     |
    ]])
    retry(nil, nil, function()
      eq('[No Name] + - Nvim', api.nvim_buf_get_var(0, 'term_title'))
    end)
  end)

  it('visual bell (padding) does not crash #21610', function()
    feed_data ':set visualbell\n'
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      :set visualbell                                   |
      {5:-- TERMINAL --}                                    |
    ]])

    -- move left is enough to invoke the bell
    feed_data 'h'
    -- visual change to show we process events after this
    feed_data 'i'
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('no assert failure on deadly signal #21896', function()
    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigterm')]])
    screen:expect(is_os('win') and { any = '%[Process exited 1%]' } or [[
      Nvim: Caught deadly signal 'SIGTERM'              |
      ^                                                  |
      [Process exited 1]                                |
                                                        |*3
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('exit status 1 and error message with deadly signal sent to server', function()
    local _, server_pid = child_session:request('nvim_call_function', 'getpid', {})
    exec_lua([[vim.uv.kill(..., 'sigterm')]], server_pid)
    if not is_os('win') then
      screen:expect({ any = vim.pesc([[Nvim: Caught deadly signal 'SIGTERM']]) })
    end
    screen:expect({ any = vim.pesc('[Process exited 1]') })
  end)

  it('exits immediately when stdin is closed #35744', function()
    local chan = api.nvim_get_option_value('channel', { buf = 0 })
    local pid = fn.jobpid(chan)
    fn.chanclose(chan)
    retry(nil, 50, function()
      eq(vim.NIL, api.nvim_get_proc(pid))
    end)
    -- FIXME: SIGHUP sometimes isn't caught with ASAN.
    screen:expect({ any = t.is_asan() and '%[Process exited %d+%]' or '%[Process exited 1%]' })
  end)

  it('exits properly when :quit non-last window in event handler #14379', function()
    local code = [[
      vim.defer_fn(function()
        vim.cmd('vsplit | quit')
      end, 0)
      vim.cmd('quit')
    ]]
    child_session:notify('nvim_exec_lua', code, {})
    screen:expect([[
      ^                                                  |
      [Process exited 0]                                |
                                                        |*4
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('no stack-use-after-scope with cursor color #22432', function()
    screen:set_option('rgb', true)
    command('set termguicolors')
    child_session:request(
      'nvim_exec2',
      [[
      set tgc
      hi Cursor guifg=Red guibg=Green
      set guicursor=n:block-Cursor/lCursor
    ]],
      {}
    )
    screen:expect([[
      ^                                                  |
      {1:~}{18:                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('i')
    screen:expect([[
      ^                                                  |
      {1:~}{18:                                                 }|*3
      {3:[No Name]                                         }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('redraws on SIGWINCH even if terminal size is unchanged #23411', function()
    -- On Windows, SIGWINCH cannot be sent as a signal with uv_kill(), while
    -- SIGWINCH handlers are only called on terminal resize.
    t.skip(is_os('win'), 'N/A for Windows')
    child_session:request('nvim_echo', { { 'foo' } }, false, {})
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      foo                                               |
      {5:-- TERMINAL --}                                    |
    ]])
    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigwinch')]])
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('supports hiding cursor', function()
    child_session:request(
      'nvim_command',
      "let g:id = jobstart([v:progpath, '--clean', '--headless'])"
    )
    feed_data(':call jobwait([g:id])\n')
    screen:expect([[
                                                        |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      :call jobwait([g:id])                             |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\003')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      Type  :qa  and press <Enter> to exit Nvim         |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('cursor is not hidden on incsearch with no match', function()
    feed_data('ifoo\027')
    feed_data('/foo')
    screen:expect([[
      {2:foo}                                               |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      /foo^                                              |
      {5:-- TERMINAL --}                                    |
    ]])
    screen:sleep(10)
    feed_data('b')
    screen:expect([[
      foo                                               |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      /foob^                                             |
      {5:-- TERMINAL --}                                    |
    ]])
    screen:sleep(10)
    feed_data('a')
    screen:expect([[
      foo                                               |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      /fooba^                                            |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('emits hyperlinks with OSC 8', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    exec_lua([[
      local buf = vim.api.nvim_get_current_buf()
      _G.urls = {}
      vim.api.nvim_create_autocmd('TermRequest', {
        buf = buf,
        callback = function(ev)
          local req = ev.data.sequence
          if not req then
            return
          end
          local id, url = req:match('\027]8;id=(%d+);(.*)$')
          if id ~= nil and url ~= nil then
            table.insert(_G.urls, { id = tonumber(id), url = url })
          end
        end,
      })
    ]])
    child_exec_lua([[
      vim.api.nvim_buf_set_lines(0, 0, 0, true, {'Hello'})
      _G.NS = vim.api.nvim_create_namespace('test')
      vim.api.nvim_buf_set_extmark(0, _G.NS, 0, 1, {
        end_col = 3,
        url = 'https://example.com',
      })
    ]])
    retry(nil, 1000, function()
      eq({ { id = 0xE1EA0000, url = 'https://example.com' } }, exec_lua([[return _G.urls]]))
    end)
    -- No crash with very long URL #30794
    child_exec_lua([[
      vim.api.nvim_buf_set_extmark(0, _G.NS, 0, 3, {
        end_col = 5,
        url = 'https://example.com/' .. ('a'):rep(65536),
      })
    ]])
    retry(nil, nil, function()
      eq({
        { id = 0xE1EA0000, url = 'https://example.com' },
        { id = 0xE1EA0001, url = 'https://example.com/' .. ('a'):rep(65536) },
      }, exec_lua([[return _G.urls]]))
    end)
  end)

  it('TermResponse works with vim.wait() from another autocommand #32706', function()
    child_exec_lua([[
      _G.termresponse = nil
      vim.api.nvim_create_autocmd('TermResponse', {
        callback = function(ev)
          _G.sequence = ev.data.sequence
          _G.v_termresponse = vim.v.termresponse
        end,
      })
      vim.api.nvim_create_autocmd('InsertEnter', {
        buf = 0,
        callback = function()
          _G.result = vim.wait(3000, function()
            local expected = '\027P1+r5463'
            return _G.sequence == expected and _G.v_termresponse == expected
          end)
        end,
      })
    ]])
    feed_data('i')
    feed_data('\027P1+r5463\027\\')
    retry(nil, 4000, function()
      eq(true, child_exec_lua('return _G.result'))
    end)
  end)

  it('TermResponse from unblock_autocmds() sets "data"', function()
    if not child_exec_lua('return pcall(require, "ffi")') then
      pending('N/A: missing LuaJIT FFI')
    end
    child_exec_lua([[
      local ffi = require('ffi')
      ffi.cdef[=[
        void block_autocmds(void);
        void unblock_autocmds(void);
      ]=]
      ffi.C.block_autocmds()
      vim.api.nvim_create_autocmd('TermResponse', {
        once = true,
        callback = function(ev)
          _G.data = ev.data
        end,
      })
    ]])
    feed_data('\027P0$r\027\\')
    retry(nil, 4000, function()
      eq('\027P0$r', child_exec_lua('return vim.v.termresponse'))
    end)
    eq(vim.NIL, child_exec_lua('return _G.data'))
    child_exec_lua('require("ffi").C.unblock_autocmds()')
    eq({ sequence = '\027P0$r' }, child_exec_lua('return _G.data'))

    -- If TermResponse during TermResponse changes v:termresponse, data.sequence contains the actual
    -- response that triggered the autocommand.
    -- The second autocommand below forces a use-after-free when v:termresponse's value changes
    -- during TermResponse if data.sequence didn't allocate its own copy.
    child_exec_lua([[
      require('ffi').C.block_autocmds()
      vim.api.nvim_create_autocmd('TermResponse', {
        once = true,
        callback = function(ev)
          _G.au1_termresponse1 = vim.v.termresponse
          _G.au1_sequence1 = ev.data.sequence
          local chan = vim.fn.sockconnect('pipe', vim.v.servername, { rpc = true })
          vim.rpcrequest(chan, 'nvim_ui_term_event', 'termresponse', 'baz')
          _G.au1_termresponse2 = vim.v.termresponse
          _G.au1_sequence2 = ev.data.sequence
        end,
      })
      _G.au2_sequences = {}
      vim.api.nvim_create_autocmd('TermResponse', {
        callback = function(ev)
          table.insert(_G.au2_sequences, ev.data.sequence)
        end,
      })
    ]])
    child_session:request('nvim_ui_term_event', 'termresponse', 'foobar')
    eq('foobar', child_exec_lua('return vim.v.termresponse'))
    -- For good measure, check deferred TermResponse doesn't try to fire if autocmds are still
    -- blocked after unblock_autocmds.
    child_exec_lua('require("ffi").C.block_autocmds() require("ffi").C.unblock_autocmds()')
    eq(vim.NIL, child_exec_lua('return _G.au1_termresponse1'))
    child_exec_lua('require("ffi").C.unblock_autocmds()')
    eq('foobar', child_exec_lua('return _G.au1_termresponse1'))
    eq('foobar', child_exec_lua('return _G.au1_sequence1'))
    eq('baz', child_exec_lua('return _G.au1_termresponse2'))
    eq('foobar', child_exec_lua('return _G.au1_sequence2')) -- unchanged
    -- Second autocmd triggers due to "baz" (via the nested TermResponse), then from "foobar".
    eq({ 'baz', 'foobar' }, child_exec_lua('return _G.au2_sequences'))
  end)

  it('nvim_ui_send works', function()
    child_session:request('nvim_ui_send', '\027]2;TEST_TITLE\027\\')
    retry(nil, nil, function()
      eq('TEST_TITLE', api.nvim_buf_get_var(0, 'term_title'))
    end)
  end)

  it('stdin and stdout are tty fds in embedded server #38172', function()
    eq(
      { 'tty', 'tty' },
      child_exec_lua('return { vim.uv.guess_handle(0), vim.uv.guess_handle(1) }')
    )
    -- Also works after :restart #38745
    feed_data(':restart lua ={ vim.uv.guess_handle(0), vim.uv.guess_handle(1) }\r')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      { "tty", "tty" }                                  |
      {5:-- TERMINAL --}                                    |
    ]])
    -- The server is now detached and needs to be quit explicitly.
    feed_data(':qall!\r')
    screen:expect({ any = vim.pesc('[Process exited 0]') })
  end)
end)

describe('TUI', function()
  before_each(clear)

  it('resize at startup #17285 #15044 #11330', function()
    local screen = Screen.new(50, 10)
    screen:add_extra_attr_ids({
      [100] = { foreground = tonumber('0x4040ff'), fg_indexed = true },
      [101] = { foreground = Screen.colors.Gray100, background = Screen.colors.DarkGreen },
    })
    fn.jobstart({
      nvim_prog,
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set notermguicolors',
      '--cmd',
      nvim_set,
      '--cmd',
      'let start = reltime() | while v:true | if reltimefloat(reltime(start)) > 2 | break | endif | endwhile',
    }, {
      term = true,
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
      },
    })
    exec([[
      sleep 500m
      vs new
    ]])
    screen:expect(([[
      ^                         │                        |
      {1:~                        }│{100:~                       }|*6
      {1:~                        }│                        |
      {3:new                       }{101:{MATCH:<.*%s} [-] }|
                                                        |
    ]]):format(is_os('win') and '[/\\]nvim%.exe' or '/nvim'))
  end)

  -- #28667, #28668
  for _, guicolors in ipairs({ 'notermguicolors', 'termguicolors' }) do
    it('has no black flicker when clearing regions during startup with ' .. guicolors, function()
      local screen = Screen.new(50, 10)
      -- Colorscheme is automatically detected as light in _core/defaults.lua, so fg
      -- should be dark except on Windows, where it doesn't respond to the OSC11 query,
      -- so bg is dark.
      local fg = is_os('win') and Screen.colors.NvimLightGrey2 or Screen.colors.NvimDarkGrey2
      local bg = is_os('win') and Screen.colors.NvimDarkGrey2 or Screen.colors.NvimLightGrey2
      screen:add_extra_attr_ids({
        [100] = {
          foreground = fg,
          background = bg,
        },
      })
      fn.jobstart({
        nvim_prog,
        '--clean',
        '--cmd',
        'set ' .. guicolors,
        '--cmd',
        'echo "foo"',
        '--cmd',
        'sleep 10',
      }, {
        term = true,
        env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
      })
      if guicolors == 'termguicolors' then
        screen:expect([[
          {100:^                                                  }|
          {100:                                                  }|*7
          {100:foo                                               }|
                                                            |
        ]])
      else
        screen:expect([[
          ^                                                  |
                                                            |*7
          foo                                               |
                                                            |
        ]])
      end
    end)
  end

  it('argv[0] can be overridden #23953', function()
    t.skip(is_os('win'), 'N/A for Windows')
    t.skip(t.is_arch('s390x'), 'FIXME s390x')
    local screen = Screen.new(50, 7, { rgb = false })
    fn.jobstart(
      { testprg('shell-test'), 'EXECVP', nvim_prog, 'Xargv0nvim', '--clean' },
      { term = true, env = { VIMRUNTIME = os.getenv('VIMRUNTIME') } }
    )
    command('startinsert')
    screen:expect([[
      ^                                                  |
      ~                                                 |*3
      [No Name]                       0,0-1          All|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(':put =v:argv + [v:progname]\n')
    screen:expect([[
      Xargv0nvim                                        |
      --embed                                           |
      --clean                                           |
      ^Xargv0nvim                                        |
      [No Name] [+]                   5,1            Bot|
      4 more lines                                      |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it("float is still highlighted with 'winblend' over uninitialized cells #34360", function()
    write_file(
      'Xblend.lua',
      [[
        local win = vim.api.nvim_open_win(0, false, { relative = 'editor', width = 3, height = 1, row = 1000, col = 0, zindex = 400 })
        vim.api.nvim_set_option_value('winblend', 30, { win = win })
        vim.fn.setline(1, "foo")
        vim.api.nvim_buf_set_extmark(0, vim.api.nvim_create_namespace(''), 0, 0, { end_col = 3, hl_group = 'Title' })
    ]]
    )
    finally(function()
      os.remove('Xblend.lua')
    end)
    local screen = tt.setup_child_nvim({ '--clean', '-u', 'Xblend.lua' })
    screen:expect([[
      {5:^foo}                                               |
      ~                                                 |*3
      [No Name] [+]                   1,1            All|
      {5:foo}                                               |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('with non-tty (pipe) stdout/stderr', function()
    t.skip(is_os('win'), 'N/A for Windows')
    finally(function()
      os.remove('testF')
      os.remove(testlog)
    end)
    local screen = tt.setup_screen(
      0,
      ('"%s" --clean --cmd "set noswapfile noshowcmd noruler" --cmd "normal iabc" > /dev/null 2>&1 && cat testF && rm testF'):format(
        nvim_prog
      ),
      nil,
      { VIMRUNTIME = os.getenv('VIMRUNTIME'), NVIM_LOG_FILE = testlog }
    )
    feed_data(':w testF\n:q\n')
    screen:expect([[
      :w testF                                          |
      :q                                                |
      abc                                               |
      ^                                                  |
      [Process exited 0]                                |
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    assert_log('TUI: timed out waiting for DA1 response', testlog)
  end)

  it('<C-h> #10134', function()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noruler',
      '--cmd',
      ':nnoremap <C-h> :echomsg "\\<C-h\\>"<CR>',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    command([[call chansend(b:terminal_job_id, "\<C-h>")]])
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      <C-h>                                             |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('draws line with many trailing spaces correctly #24955', function()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'call setline(1, ["1st line" .. repeat(" ", 153), "2nd line"])',
    }, { cols = 80, env = env_notermguicolors })
    screen:expect([[
      ^1st line                                                                        |
                                                                                      |*2
      2nd line                                                                        |
      {3:[No Name] [+]                                                 1,1            All}|
                                                                                      |
      {5:-- TERMINAL --}                                                                  |
    ]])
    feed_data('$')
    screen:expect([[
      1st line                                                                        |
                                                                                      |
      ^                                                                                |
      2nd line                                                                        |
      {3:[No Name] [+]                                                 1,161          All}|
                                                                                      |
      {5:-- TERMINAL --}                                                                  |
    ]])
  end)

  it('draws screen lines with leading spaces correctly #29711', function()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'set foldcolumn=6 | call setline(1, ["", repeat("aabb", 1000)]) | echo 42',
    }, { extra_rows = 10, cols = 66 })
    screen:expect([[
            ^                                                            |
            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabb|*12
            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba@@@|
      [No Name] [+]                                   1,0-1          Top|
      42                                                                |
      {5:-- TERMINAL --}                                                    |
    ]])
    feed_data('\12') -- Ctrl-L
    -- The first line counts as 3 cells.
    -- For the second line, 6 repeated spaces at the start counts as 2 cells,
    -- so each screen line of the second line counts as 62 cells.
    -- After drawing the first line and 8 screen lines of the second line,
    -- 3 + 8 * 62 = 499 cells have been counted.
    -- The 6 repeated spaces at the start of the next screen line exceeds the
    -- 500-cell limit, so the buffer is flushed after these spaces.
    screen:expect([[
            ^                                                            |
            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabb|*12
            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba@@@|
      [No Name] [+]                                   1,0-1          Top|
                                                                        |
      {5:-- TERMINAL --}                                                    |
    ]])
  end)

  it('no heap-buffer-overflow when changing &columns', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    -- Set a different bg colour and change $TERM to something dumber so the `print_spaces()`
    -- codepath in `clear_region()` is hit.
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'set notermguicolors | highlight Normal ctermbg=red',
      '--cmd',
      'call setline(1, ["a"->repeat(&columns)])',
    }, { env = { TERM = 'ansi' } })

    screen:expect([[
      {117:^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}|
      {117:~                                                 }|*3
      {118:[No Name] [+]                   1,1            All}|
      {117:                                                  }|
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(':set columns=12\n')
    screen:expect([[
      {117:^aaaaaaaaaaaa                                      }|
      {117:aaaaaaaaaaaa                                      }|*3
      {118:<        All}{117:                                      }|
      {117:                                                  }|
      {5:-- TERMINAL --}                                    |
    ]])

    -- Wider than TUI, so screen state will look weird.
    -- Wait for the statusline to redraw to confirm that the TUI lives and ASAN is happy.
    feed_data(':set columns=99|set stl=redrawn%m\n')
    screen:expect({ any = 'redrawn%[%+%]' })
  end)

  it('missing DSR response does not lead to hit-enter prompt #38877', function()
    local child_server = n.new_pipename()
    exec_lua('vim.uv.os_unsetenv("NVIM_TEST")')
    local job = fn.jobstart({ nvim_prog, '--clean', '--listen', child_server }, {
      -- Use pty = true for a PTY without a terminal, so that there is no DSR response.
      pty = true,
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
        COLORTERM = 'xterm-256color',
        NVIM_LOG_FILE = testlog,
      },
    })
    finally(function()
      exec_lua(function()
        vim.fn.jobstop(job)
        vim.fn.jobwait({ job }, 5000)
      end)
      os.remove(testlog)
    end)
    retry(nil, nil, function()
      t.neq(nil, vim.uv.fs_stat(child_server))
    end)
    local child_session = n.connect(child_server)
    local expected_msg =
      'defaults.lua: Did not detect DSR response from terminal. This results in a slower startup time.'
    retry(nil, 4000, function()
      eq({ true, { mode = 'n', blocking = false } }, { child_session:request('nvim_get_mode') })
      if not is_os('win') then -- ConPTY provides DSR response on Windows?
        eq(
          { true, { output = expected_msg } },
          { child_session:request('nvim_exec2', 'messages', { output = true }) }
        )
      end
    end)
  end)
end)

describe('TUI UIEnter/UILeave', function()
  it('fires exactly once, after VimEnter', function()
    clear()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile noshowcmd noruler',
      '--cmd',
      'let g:evs = []',
      '--cmd',
      'autocmd UIEnter *  :call add(g:evs, "UIEnter")',
      '--cmd',
      'autocmd UILeave *  :call add(g:evs, "UILeave")',
      '--cmd',
      'autocmd VimEnter * :call add(g:evs, "VimEnter")',
    }, { env = env_notermguicolors })
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data(':echo g:evs\n')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      ['VimEnter', 'UIEnter']                           |
      {5:-- TERMINAL --}                                    |
    ]])
  end)
end)

describe('TUI FocusGained/FocusLost', function()
  local screen --[[@type test.functional.ui.screen]]
  local child_session --[[@type test.Session]]

  before_each(function()
    clear()
    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile noshowcmd noruler background=dark',
    }, { env = env_notermguicolors })

    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    child_session = n.connect(child_server)
    child_session:request(
      'nvim_exec2',
      [[
      autocmd FocusGained * echo 'gained'
      autocmd FocusLost * echo 'lost'
    ]],
      {}
    )
    feed_data('\034\016') -- CTRL-\ CTRL-N
  end)

  it('in normal-mode', function()
    retry(2, 3 * screen.timeout, function()
      feed_data('\027[I')
      screen:expect([[
        ^                                                  |
        {100:~                                                 }|*3
        {3:[No Name]                                         }|
        gained                                            |
        {5:-- TERMINAL --}                                    |
      ]])

      feed_data('\027[O')
      screen:expect([[
        ^                                                  |
        {100:~                                                 }|*3
        {3:[No Name]                                         }|
        lost                                              |
        {5:-- TERMINAL --}                                    |
      ]])
    end)
  end)

  it('in insert-mode', function()
    feed_data(':set noshowmode\r')
    feed_data('i')
    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      :set noshowmode                                   |
      {5:-- TERMINAL --}                                    |
    ]])
    retry(2, 3 * screen.timeout, function()
      feed_data('\027[I')
      screen:expect([[
        ^                                                  |
        {100:~                                                 }|*3
        {3:[No Name]                                         }|
        gained                                            |
        {5:-- TERMINAL --}                                    |
      ]])
      feed_data('\027[O')
      screen:expect([[
        ^                                                  |
        {100:~                                                 }|*3
        {3:[No Name]                                         }|
        lost                                              |
        {5:-- TERMINAL --}                                    |
      ]])
    end)
  end)

  -- During cmdline-mode we ignore :echo invoked by timers/events.
  -- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
  it('in cmdline-mode does NOT :echo', function()
    feed_data(':')
    feed_data('\027[I')
    screen:expect([[
                                                        |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
      :^                                                 |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[O')
    screen:expect_unchanged()
  end)

  it('in cmdline-mode', function()
    -- Set up autocmds that modify the buffer, instead of just calling :echo.
    -- This is how we can test handling of focus gained/lost during cmdline-mode.
    -- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
    child_session:request(
      'nvim_exec2',
      [[
      autocmd!
      autocmd FocusLost * call append(line('$'), 'lost')
      autocmd FocusGained * call append(line('$'), 'gained')
    ]],
      {}
    )
    retry(2, 3 * screen.timeout, function()
      -- Enter cmdline-mode.
      feed_data(':')
      screen:sleep(1)
      -- Send focus lost/gained termcodes.
      feed_data('\027[O')
      feed_data('\027[I')
      screen:sleep(1)
      -- Exit cmdline-mode. Redraws from timers/events are blocked during
      -- cmdline-mode, so the buffer won't be updated until we exit cmdline-mode.
      feed_data('\n')
      screen:expect { any = 'lost' .. (' '):rep(46) .. '|\ngained' }
    end)
  end)

  it('in terminal-mode', function()
    feed_data(':set shell=' .. testprg('shell-test') .. ' shellcmdflag=EXE\n')
    feed_data(':set shellxquote=\n') -- win: avoid extra quotes
    feed_data(':set noshowmode laststatus=0\n')

    feed_data(':terminal zia\n')
    -- Wait for terminal to be ready.
    screen:expect([[
      ^ready $ zia                                       |
                                                        |
      [Process exited 0]                                |
                                                        |*2
      :terminal zia                                     |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data('\027[I')
    screen:expect {
      grid = [[
      ^ready $ zia                                       |
                                                        |
      [Process exited 0]                                |
                                                        |*2
      gained                                            |
      {5:-- TERMINAL --}                                    |
    ]],
      timeout = (4 * screen.timeout),
    }

    feed_data('\027[O')
    screen:expect([[
      ^ready $ zia                                       |
                                                        |
      [Process exited 0]                                |
                                                        |*2
      lost                                              |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('in hit-enter prompt', function()
    tt.override_screen_expect_for_conpty(screen)
    feed_data(":echom 'msg1'|echom 'msg2'|echom 'msg3'|echom 'msg4'|echom 'msg5'\n")
    screen:expect([[
      msg1                                              |
      msg2                                              |
      msg3                                              |
      msg4                                              |
      msg5                                              |
      {102:Press ENTER or type command to continue}^           |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027[I')
    feed_data('\027[I')
    screen:expect_unchanged()
  end)
end)

-- These tests require `tt` because --headless/--embed does not initialize the TUI.
describe("TUI 't_Co' (terminal colors)", function()
  local screen --[[@type test.functional.ui.screen]]

  local function assert_term_colors(term, colorterm, maxcolors)
    clear({ env = { TERM = term }, args = {} })
    screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      nvim_set .. ' notermguicolors',
    }, {
      env = {
        LANG = 'C',
        TERM = term or '',
        COLORTERM = colorterm or '',
      },
    })

    local tline --[[@type string]]
    if maxcolors == 8 then
      tline = '{112:~                                                 }'
    elseif maxcolors == 16 then
      tline = '~                                                 '
    else
      tline = '{100:~                                                 }'
    end

    screen:expect(string.format(
      [[
      ^                                                  |
      %s|*4
                                                        |
      {5:-- TERMINAL --}                                    |
    ]],
      tline
    ))

    feed_data(':echo &t_Co\n')
    screen:expect(string.format(
      [[
      ^                                                  |
      %s|*4
      %-3s                                               |
      {5:-- TERMINAL --}                                    |
    ]],
      tline,
      tostring(maxcolors and maxcolors or '')
    ))
  end

  -- ansi and no terminal type at all:

  if is_os('win') then
    it('guessed vtpcon with no TERM uses 256 colors', function()
      assert_term_colors(nil, nil, 256)
    end)
  else
    it('no TERM uses 8 colors', function()
      assert_term_colors(nil, nil, 8)
    end)
  end

  it('TERM=ansi no COLORTERM uses 8 colors', function()
    assert_term_colors('ansi', nil, 8)
  end)

  it('TERM=ansi with COLORTERM=anything-no-number uses 16 colors', function()
    assert_term_colors('ansi', 'yet-another-term', 16)
  end)

  it('unknown TERM COLORTERM with 256 in name uses 256 colors', function()
    assert_term_colors('ansi', 'yet-another-term-256color', 256)
  end)

  it('TERM=ansi-256color sets 256 colours', function()
    assert_term_colors('ansi-256color', nil, 256)
  end)

  -- Unknown terminal types:

  it('unknown TERM no COLORTERM sets 8 colours', function()
    assert_term_colors('yet-another-term', nil, 8)
  end)

  it('unknown TERM with COLORTERM=anything-no-number uses 16 colors', function()
    assert_term_colors('yet-another-term', 'yet-another-term', 16)
  end)

  it('unknown TERM with 256 in name sets 256 colours', function()
    assert_term_colors('yet-another-term-256color', nil, 256)
  end)

  it('unknown TERM COLORTERM with 256 in name uses 256 colors', function()
    assert_term_colors('yet-another-term', 'yet-another-term-256color', 256)
  end)

  -- Linux kernel terminal emulator:

  it('TERM=linux uses 256 colors', function()
    assert_term_colors('linux', nil, 256)
  end)

  it('TERM=linux-16color uses 256 colors', function()
    assert_term_colors('linux-16color', nil, 256)
  end)

  it('TERM=linux-256color uses 256 colors', function()
    assert_term_colors('linux-256color', nil, 256)
  end)

  -- screen:
  --
  -- FreeBSD and Windows fall back to the built-in screen-256colour entry.
  -- Linux and MacOS have a screen entry in external terminfo with 8 colours,
  -- which is raised to 16 by COLORTERM.

  it('TERM=screen no COLORTERM uses 8/256 colors', function()
    if is_os('freebsd') or is_os('win') then
      assert_term_colors('screen', nil, 256)
    else
      assert_term_colors('screen', nil, 8)
    end
  end)

  it('TERM=screen COLORTERM=screen uses 16/256 colors', function()
    if is_os('freebsd') or is_os('win') then
      assert_term_colors('screen', 'screen', 256)
    else
      assert_term_colors('screen', 'screen', 16)
    end
  end)

  it('TERM=screen COLORTERM=screen-256color uses 256 colors', function()
    assert_term_colors('screen', 'screen-256color', 256)
  end)

  it('TERM=screen-256color no COLORTERM uses 256 colors', function()
    assert_term_colors('screen-256color', nil, 256)
  end)

  -- tmux:
  --
  -- FreeBSD and MacOS fall back to the built-in tmux-256colour entry.
  -- Linux has a tmux entry in external terminfo with 8 colours,
  -- which is raised to 256.

  it('TERM=tmux no COLORTERM uses 256 colors', function()
    assert_term_colors('tmux', nil, 256)
  end)

  it('TERM=tmux COLORTERM=tmux uses 256 colors', function()
    assert_term_colors('tmux', 'tmux', 256)
  end)

  it('TERM=tmux COLORTERM=tmux-256color uses 256 colors', function()
    assert_term_colors('tmux', 'tmux-256color', 256)
  end)

  it('TERM=tmux-256color no COLORTERM uses 256 colors', function()
    assert_term_colors('tmux-256color', nil, 256)
  end)

  -- xterm and imitators:

  it('TERM=xterm uses 256 colors', function()
    assert_term_colors('xterm', nil, 256)
  end)

  it('TERM=xterm COLORTERM=gnome-terminal uses 256 colors', function()
    assert_term_colors('xterm', 'gnome-terminal', 256)
  end)

  it('TERM=xterm COLORTERM=mate-terminal uses 256 colors', function()
    assert_term_colors('xterm', 'mate-terminal', 256)
  end)

  it('TERM=xterm-256color uses 256 colors', function()
    assert_term_colors('xterm-256color', nil, 256)
  end)

  -- rxvt and stterm:
  --
  -- FreeBSD and MacOS fall back to the built-in rxvt-256color and
  -- st-256colour entries.
  -- Linux has an rxvt, an st, and an st-16color entry in external terminfo
  -- with 8, 8, and 16 colours respectively, which are raised to 256.

  it('TERM=rxvt no COLORTERM uses 256 colors', function()
    assert_term_colors('rxvt', nil, 256)
  end)

  it('TERM=rxvt COLORTERM=rxvt uses 256 colors', function()
    assert_term_colors('rxvt', 'rxvt', 256)
  end)

  it('TERM=rxvt-256color uses 256 colors', function()
    assert_term_colors('rxvt-256color', nil, 256)
  end)

  it('TERM=st no COLORTERM uses 256 colors', function()
    assert_term_colors('st', nil, 256)
  end)

  it('TERM=st COLORTERM=st uses 256 colors', function()
    assert_term_colors('st', 'st', 256)
  end)

  it('TERM=st COLORTERM=st-256color uses 256 colors', function()
    assert_term_colors('st', 'st-256color', 256)
  end)

  it('TERM=st-16color no COLORTERM uses 8/256 colors', function()
    assert_term_colors('st', nil, 256)
  end)

  it('TERM=st-16color COLORTERM=st uses 16/256 colors', function()
    assert_term_colors('st', 'st', 256)
  end)

  it('TERM=st-16color COLORTERM=st-256color uses 256 colors', function()
    assert_term_colors('st', 'st-256color', 256)
  end)

  it('TERM=st-256color uses 256 colors', function()
    assert_term_colors('st-256color', nil, 256)
  end)

  -- gnome and vte:
  --
  -- FreeBSD and MacOS fall back to the built-in vte-256color entry.
  -- Linux has a gnome, a vte, a gnome-256color, and a vte-256color entry in
  -- external terminfo with 8, 8, 256, and 256 colours respectively, which are
  -- raised to 256.

  it('TERM=gnome no COLORTERM uses 256 colors', function()
    assert_term_colors('gnome', nil, 256)
  end)

  it('TERM=gnome COLORTERM=gnome uses 256 colors', function()
    assert_term_colors('gnome', 'gnome', 256)
  end)

  it('TERM=gnome COLORTERM=gnome-256color uses 256 colors', function()
    assert_term_colors('gnome', 'gnome-256color', 256)
  end)

  it('TERM=gnome-256color uses 256 colors', function()
    assert_term_colors('gnome-256color', nil, 256)
  end)

  it('TERM=vte no COLORTERM uses 256 colors', function()
    assert_term_colors('vte', nil, 256)
  end)

  it('TERM=vte COLORTERM=vte uses 256 colors', function()
    assert_term_colors('vte', 'vte', 256)
  end)

  it('TERM=vte COLORTERM=vte-256color uses 256 colors', function()
    assert_term_colors('vte', 'vte-256color', 256)
  end)

  it('TERM=vte-256color uses 256 colors', function()
    assert_term_colors('vte-256color', nil, 256)
  end)

  -- others:

  -- TODO(blueyed): this is made pending, since it causes failure + later hang
  --                when using non-compatible libvterm (#9494/#10179).
  pending('TERM=interix uses 8 colors', function()
    assert_term_colors('interix', nil, 8)
  end)

  it('TERM=iTerm.app uses 256 colors', function()
    assert_term_colors('iTerm.app', nil, 256)
  end)

  it('TERM=iterm uses 256 colors', function()
    assert_term_colors('iterm', nil, 256)
  end)
end)

-- These tests require `tt` because --headless/--embed does not initialize the TUI.
describe("TUI 'term' option", function()
  local screen --[[@type test.functional.ui.screen]]

  local function assert_term(term_envvar, term_expected)
    clear()
    screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      nvim_set .. ' notermguicolors',
    }, {
      env = {
        LANG = 'C',
        TERM = term_envvar or '',
      },
    })

    local full_timeout = screen.timeout
    retry(nil, 2 * full_timeout, function() -- Wait for TUI thread to set 'term'.
      feed_data(":echo 'term='.(&term)\n")
      screen:expect { any = 'term=' .. term_expected, timeout = 250 }
    end)
  end

  it('gets builtin term if $TERM is invalid', function()
    assert_term('foo', 'ansi')
  end)

  it('gets system-provided term if $TERM is valid', function()
    if is_os('openbsd') then
      assert_term('xterm', 'xterm')
    elseif is_os('bsd') then -- BSD lacks terminfo, builtin is always used.
      assert_term('xterm', 'xterm')
    elseif is_os('mac') then
      local status, _ = pcall(assert_term, 'xterm', 'xterm')
      if not status then
        pending('macOS: unibilium could not find terminfo')
      end
    else
      assert_term('xterm', 'xterm')
    end
  end)

  it('builtin terms', function()
    -- These non-standard terminfos are always builtin.
    assert_term('win32con', 'win32con')
    assert_term('conemu', 'conemu')
    assert_term('vtpcon', 'vtpcon')
  end)
end)

-- These tests require `tt` because --headless/--embed does not initialize the TUI.
describe('TUI', function()
  local screen --[[@type test.functional.ui.screen]]

  -- Runs (child) `nvim` in a TTY (:terminal), to start the builtin TUI.
  local function nvim_tui(extra_args)
    clear()
    screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      nvim_set .. ' notermguicolors',
      extra_args,
    }, {
      env = {
        LANG = 'C',
      },
    })
  end

  it('-V3log logs terminfo values', function()
    local logfile = 'Xtest_tui_verbose_log'
    nvim_tui('-V3' .. logfile)
    finally(function()
      os.remove(logfile)
    end)

    -- Wait for TUI to start.
    feed_data('Gitext')
    screen:expect([[
      text^                                              |
      {100:~                                                 }|*4
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])

    retry(nil, 3000, function() -- Wait for log file to be flushed.
      local log = read_file(logfile) or ''
      eq('--- Terminal info --- {{{\n', string.match(log, '%-%-%- Terminal.-\n')) -- }}}
      ok(#log > 50)
    end)
  end)

  it('does not crash on large inputs #26099', function()
    nvim_tui()

    screen:expect([[
      ^                                                  |
      {100:~                                                 }|*4
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data(string.format('\027]52;c;%s\027\\', string.rep('A', 8192)))

    screen:expect_unchanged()
  end)

  it('queries the terminal for truecolor support', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    clear()
    exec_lua([[
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          local sequence = req:match('^\027P%+q([%x;]+)$')
          if sequence then
            local t = {}
            for cap in vim.gsplit(sequence, ';') do
              local resp = string.format('\027P1+r%s\027\\', sequence)
              vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
              t[vim.text.hexdecode(cap)] = true
            end
            vim.g.xtgettcap = t
            return true
          end
        end,
      })
    ]])

    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--clean',
      '--listen',
      child_server,
    }, {
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),

        -- Force COLORTERM to be unset and use a TERM that does not contain Tc or RGB in terminfo.
        -- This will force the nested nvim instance to query with XTGETTCAP
        COLORTERM = '',
        TERM = 'xterm-256colors',
      },
    })

    screen:expect({ any = '%[No Name%]' })

    local child_session = n.connect(child_server)
    retry(nil, 1000, function()
      eq({
        Tc = true,
        RGB = true,
        setrgbf = true,
        setrgbb = true,
      }, eval("get(g:, 'xtgettcap', '')"))
      eq({ true, 1 }, { child_session:request('nvim_eval', '&termguicolors') })
    end)
  end)

  it('does not query the terminal for truecolor support if $COLORTERM is set', function()
    clear()
    exec_lua([[
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          vim.g.termrequest = req
          local xtgettcap = req:match('^\027P%+q([%x;]+)$')
          if xtgettcap then
            local t = {}
            for cap in vim.gsplit(xtgettcap, ';') do
              local resp = string.format('\027P1+r%s\027\\', xtgettcap)
              vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
              t[vim.text.hexdecode(cap)] = true
            end
            vim.g.xtgettcap = t
            return true
          elseif req:match('^\027P$qm\027\\$') then
            vim.g.decrqss = true
          end
        end,
      })
    ]])

    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--clean',
      '--listen',
      child_server,
    }, {
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
        -- With COLORTERM=256, Nvim should not query the terminal and should not set 'tgc'
        COLORTERM = '256',
        TERM = 'xterm-256colors',
      },
    })

    screen:expect({ any = '%[No Name%]' })

    local child_session = n.connect(child_server)
    retry(nil, 1000, function()
      local xtgettcap = eval("get(g:, 'xtgettcap', {})")
      eq(nil, xtgettcap['Tc'])
      eq(nil, xtgettcap['RGB'])
      eq(nil, xtgettcap['setrgbf'])
      eq(nil, xtgettcap['setrgbb'])
      eq(0, eval([[get(g:, 'decrqss')]]))
      eq({ true, 0 }, { child_session:request('nvim_eval', '&termguicolors') })
    end)
  end)

  it('queries the terminal for OSC 52 support with XTGETTCAP', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    clear()
    if not exec_lua('return pcall(require, "ffi")') then
      pending('N/A: missing LuaJIT FFI')
    end

    -- Change vterm's DA1 response so that it doesn't include 52
    exec_lua(function()
      local ffi = require('ffi')
      ffi.cdef [[
        extern char vterm_primary_device_attr[]
      ]]

      ffi.copy(ffi.C.vterm_primary_device_attr, '61;22')
    end)

    exec_lua([[
      _G.query = false
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          local sequence = req:match('^\027P%+q([%x;]+)$')
          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
            local resp = string.format('\027P1+r%s=%s\027\\', sequence, vim.text.hexencode('\027]52;;\027\\'))
            vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
            _G.query = true
            return true
          end
        end,
      })
    ]])

    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '--clean',
    }, {
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
      },
    })

    screen:expect({ any = '%[No Name%]' })

    local child_session = n.connect(child_server)
    retry(nil, 1000, function()
      eq({ true, { osc52 = true } }, { child_session:request('nvim_eval', 'g:termfeatures') })
    end)
    eq(true, exec_lua([[return _G.query]]))

    -- Attach another (non-TUI) UI to the child instance
    local alt = Screen.new(nil, nil, nil, child_session)
    finally(function()
      alt:detach()
      -- Avoid a dangling process after :detach.
      child_session:request('nvim_command', 'qall!')
    end)

    -- Detach the first (primary) client so only the second UI is attached
    feed_data(':detach\n')

    alt:expect({ any = '%[No Name%]' })

    -- osc52 should be cleared from termfeatures
    eq({ true, {} }, { child_session:request('nvim_eval', 'g:termfeatures') })
  end)

  it('determines OSC 52 support from DA1 response', function()
    t.skip(is_os('win'), 'FIXME: does not work on Windows')
    clear()
    exec_lua([[
      -- Check that we do not emit an XTGETTCAP request when DA1 indicates support
      _G.query = false
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          local sequence = req:match('^\027P%+q([%x;]+)$')
          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
            _G.query = true
            return true
          end
        end,
      })
    ]])

    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '--clean',
    }, {
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
      },
    })

    screen:expect({ any = '%[No Name%]' })

    local child_session = n.connect(child_server)
    retry(nil, 1000, function()
      eq({ true, { osc52 = true } }, { child_session:request('nvim_eval', 'g:termfeatures') })
    end)
    eq(false, exec_lua([[return _G.query]]))
  end)

  it('does not query the terminal for OSC 52 support when disabled', function()
    clear()
    exec_lua([[
      _G.query = false
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          local sequence = req:match('^\027P%+q([%x;]+)$')
          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
            _G.query = true
            return true
          end
        end,
      })
    ]])

    local child_server = new_pipename()
    screen = tt.setup_child_nvim({
      '--listen',
      child_server,
      '--clean',
      '--cmd',
      'let g:termfeatures = #{osc52: v:false}',
    }, {
      env = {
        VIMRUNTIME = os.getenv('VIMRUNTIME'),
      },
    })

    screen:expect({ any = '%[No Name%]' })

    local child_session = n.connect(child_server)
    eq({ true, { osc52 = false } }, { child_session:request('nvim_eval', 'g:termfeatures') })
    eq(false, exec_lua([[return _G.query]]))
  end)
end)

describe('TUI bg color', function()
  if t.skip(is_os('win')) then
    return
  end

  before_each(clear)

  it('is properly set in a nested Nvim instance when background=dark', function()
    command('highlight clear Normal')
    command('set background=dark') -- set outer Nvim background
    local child_server = new_pipename()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--listen',
      child_server,
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile',
    })
    screen:expect({ any = '%[No Name%]' })
    local child_session = n.connect(child_server)
    retry(nil, nil, function()
      eq({ true, 'dark' }, { child_session:request('nvim_eval', '&background') })
    end)
  end)

  it('is properly set in a nested Nvim instance when background=light', function()
    command('highlight clear Normal')
    command('set background=light') -- set outer Nvim background
    local child_server = new_pipename()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--listen',
      child_server,
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile',
    })
    screen:expect({ any = '%[No Name%]' })
    local child_session = n.connect(child_server)
    retry(nil, nil, function()
      eq({ true, 'light' }, { child_session:request('nvim_eval', '&background') })
    end)
  end)

  it('queries the terminal for background color', function()
    exec_lua([[
      vim.api.nvim_create_autocmd('TermRequest', {
        callback = function(ev)
          local req = ev.data.sequence
          if req == '\027]11;?' then
            vim.g.oscrequest = true
            return true
          end
        end,
      })
    ]])
    tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile',
    })
    retry(nil, 1000, function()
      eq(true, eval("get(g:, 'oscrequest', v:false)"))
    end)
  end)

  it('triggers OptionSet from automatic background processing', function()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile',
      '-c',
      'autocmd OptionSet background echo "did OptionSet, yay!"',
    })
    screen:expect([[
      ^                                                  |
      {5:~}                                                 |*3
      {3:[No Name]                       0,0-1          All}|
      did OptionSet, yay!                               |
      {5:-- TERMINAL --}                                    |
    ]])
  end)

  it('sends theme update notifications when background changes #31652', function()
    command('set background=dark') -- set outer Nvim background
    local child_server = new_pipename()
    local screen = tt.setup_child_nvim({
      '--clean',
      '--listen',
      child_server,
      '--cmd',
      'colorscheme vim',
      '--cmd',
      'set noswapfile',
    })
    screen:expect({ any = '%[No Name%]' })
    local child_session = n.connect(child_server)
    retry(nil, nil, function()
      eq({ true, 'dark' }, { child_session:request('nvim_eval', '&background') })
    end)
    command('set background=light') -- set outer Nvim background
    retry(nil, nil, function()
      eq({ true, 'light' }, { child_session:request('nvim_eval', '&background') })
    end)
  end)
end)

describe('TUI client', function()
  local function start_tui_and_remote_client()
    local server_super = n.clear()
    local client_super = n.new_session(true)
    finally(function()
      client_super:close()
      server_super:close()
    end)

    local server_pipe = new_pipename()
    local screen_server = tt.setup_child_nvim({
      '--clean',
      '--listen',
      server_pipe,
      '--cmd',
      'colorscheme vim',
      '--cmd',
      nvim_set .. ' laststatus=2 background=dark',
    }, { env = env_notermguicolors })
    screen_server:expect([[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    feed_data('iHello, World')
    screen_server:expect([[
      Hello, World^                                      |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027')
    local s0 = [[
      Hello, Worl^d                                      |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen_server:expect(s0)

    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
    screen_server:expect({ any = 'GUI Running: 0' })

    set_session(client_super)
    local screen_client = tt.setup_child_nvim({
      '--remote-ui',
      '--server',
      server_pipe,
    }, { env = env_notermguicolors })
    screen_client:expect(s0)

    return server_super, screen_server, screen_client
  end

  it('connects to remote instance (with its own TUI)', function()
    local _, screen_server, screen_client = start_tui_and_remote_client()

    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
    screen_client:expect({ any = 'GUI Running: 0' })

    -- grid smaller than containing terminal window is cleared properly
    feed_data(":call setline(1,['a'->repeat(&columns)]->repeat(&lines))\n")
    feed_data('0:set lines=3\n')
    local s1 = [[
      ^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|
      {3:[No Name] [+]                                     }|
                                                        |*4
      {5:-- TERMINAL --}                                    |
    ]]
    screen_client:expect(s1)
    screen_server:expect(s1)
  end)

  it(':restart works when connecting to remote instance (with its own TUI)', function()
    local _, screen_server, screen_client = start_tui_and_remote_client()

    -- Both clients should attach to the new server.
    feed_data(':restart +qall!\n')
    local screen_restarted = [[
      ^                                                  |
      {100:~                                                 }|*3
      {3:[No Name]                                         }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen_client:expect(screen_restarted)
    screen_server:expect(screen_restarted)

    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
    screen_client:expect({ any = 'GUI Running: 0' })

    -- The :vsplit command should only be executed once.
    feed_data(':restart vsplit\r')
    screen_restarted = [[
      ^                         │                        |
      {100:~                        }│{100:~                       }|*3
      {3:[No Name]                 }{2:[No Name]               }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    screen_client:expect(screen_restarted)
    screen_server:expect(screen_restarted)

    feed_data(':qall!\r')
    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
    screen_server:expect({ any = vim.pesc('[Process exited 0]') })
  end)

  local function start_headless_server_and_client(use_testlog)
    local server = n.new_session(false, {
      args_rm = { '--cmd' },
      args = {
        '--cmd',
        'colorscheme vim',
        '--cmd',
        nvim_set .. ' notermguicolors background=dark',
      },
    })
    local client_super =
      n.new_session(true, use_testlog and { env = { NVIM_LOG_FILE = testlog } } or {})
    finally(function()
      client_super:close()
      server:close()
      os.remove(testlog)
    end)

    set_session(server)
    --- @type string
    local server_pipe = api.nvim_get_vvar('servername')
    server:request('nvim_input', 'iHalloj!<Esc>')

    set_session(client_super)
    local screen_client = tt.setup_child_nvim({
      '--remote-ui',
      '--server',
      server_pipe,
    }, { env = env_notermguicolors })
    screen_client:expect([[
      Halloj^!                                           |
      {100:~                                                 }|*4
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])

    return server, server_pipe, screen_client
  end

  it('connects to remote instance (--headless)', function()
    local server, server_pipe, screen_client = start_headless_server_and_client(false)

    -- No heap-use-after-free when receiving UI events after deadly signal #22184
    server:request('nvim_input', ('a'):rep(1000))
    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigterm')]])
    screen_client:expect(is_os('win') and { any = '%[Process exited 1%]' } or [[
      Nvim: Caught deadly signal 'SIGTERM'              |
      ^                                                  |
      [Process exited 1]                                |
                                                        |*3
      {5:-- TERMINAL --}                                    |
    ]])

    eq(0, api.nvim_get_vvar('shell_error'))
    -- exits on input eof #22244
    -- Use system() without input so that stdin is closed.
    fn.system({ nvim_prog, '--remote-ui', '--server', server_pipe })
    eq(1, api.nvim_get_vvar('shell_error'))

    command('bwipe!')
    -- Start another remote client to attach to the same server.
    fn.jobstart({ nvim_prog, '--remote-ui', '--server', server_pipe }, { term = true })
    command('startinsert')
    screen_client:expect([[
      {100:<<<}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|
      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|*3
      aaaaaa^                                            |
      {5:-- INSERT --}                                      |
      {5:-- TERMINAL --}                                    |
    ]])
    feed_data('\027')

    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
    screen_client:expect({ any = 'GUI Running: 0' })
  end)

  it(':restart works when connecting to remote instance (--headless)', function()
    local _, server_pipe, screen_client = start_headless_server_and_client(false)

    -- The client should attach to the new server and the original server should exit.
    feed_data(':restart +qall!\n')
    screen_client:expect([[
      ^                                                  |
      {100:~                                                 }|*4
                                                        |
      {5:-- TERMINAL --}                                    |
    ]])
    retry(nil, nil, function()
      eq(nil, vim.uv.fs_stat(server_pipe))
    end)

    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
    screen_client:expect({ any = 'GUI Running: 0' })

    feed_data(':q!\r')
    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
  end)

  local ffi_str_defs = [[
    local ffi = require('ffi')
    local cstr = ffi.typeof('char[?]')
    ffi.cdef('typedef struct { char *data; size_t size; } String;')
    local function to_api_string(str)
      return ffi.new('String', { data = cstr(#str + 1, str), size = #str })
    end
  ]]

  it('does not crash or hang with a very long title', function()
    local server, _, screen_client = start_headless_server_and_client(true)
    local server_exec_lua = tt.make_lua_executor(server)
    if not server_exec_lua('return pcall(require, "ffi")') then
      pending('N/A: missing LuaJIT FFI')
    end

    server:request('nvim_set_option_value', 'titlestring', '%t%( %M%) - Nvim', {})
    local bufname = api.nvim_buf_get_name(0)
    local old_title = api.nvim_buf_get_var(0, 'term_title')
    if not is_os('win') then
      eq(bufname, old_title)
    end
    -- Normally a title cannot be longer than the 65535-byte buffer as maketitle()
    -- limits it length. Use FFI to send a very long title directly.
    server_exec_lua(ffi_str_defs .. [[
      ffi.cdef('void ui_call_set_title(String title);')
      ffi.C.ui_call_set_title(to_api_string(('a'):rep(65536)))
    ]])
    screen_client:expect_unchanged()
    assert_log('set_title: title string too long!', testlog)
    eq(old_title, api.nvim_buf_get_var(0, 'term_title'))

    -- Following escape sequences are not affected.
    server:request('nvim_set_option_value', 'title', true, {})
    retry(nil, nil, function()
      eq('[No Name] + - Nvim', api.nvim_buf_get_var(0, 'term_title'))
    end)
  end)

  it('logs chdir failure properly', function()
    t.skip(is_os('win'), 'N/A for Windows')
    local server, _, screen_client = start_headless_server_and_client(true)
    local server_exec_lua = tt.make_lua_executor(server)
    if not server_exec_lua('return pcall(require, "ffi")') then
      pending('N/A: missing LuaJIT FFI')
    end

    -- Use FFI to send a chdir event to a non-directory path.
    server_exec_lua(ffi_str_defs .. [[
      ffi.cdef('void ui_call_chdir(String path);')
      ffi.C.ui_call_chdir(to_api_string('README.md'))
    ]])
    screen_client:expect_unchanged()
    assert_log('Failed to chdir to README%.md: not a directory', testlog)
  end)

  it('nvim_ui_send works with remote client #36317', function()
    local server, _, _ = start_headless_server_and_client(false)
    server:request('nvim_ui_send', '\027]2;TEST_TITLE\027\\')
    retry(nil, nil, function()
      eq('TEST_TITLE', api.nvim_buf_get_var(0, 'term_title'))
    end)
  end)

  it('throws error when no server exists', function()
    clear()
    local screen = tt.setup_child_nvim({
      '--remote-ui',
      '--server',
      '127.0.0.1:2436546',
    }, { cols = 60 })

    screen:expect([[
      Remote ui failed to start: {MATCH:.*}|
      ^                                                            |
      [Process exited 1]                                          |
                                                                  |*3
      {5:-- TERMINAL --}                                              |
    ]])
  end)

  local function test_remote_tui_quit(status)
    local server_super, screen_server, screen_client = start_tui_and_remote_client()

    -- quitting the server
    set_session(server_super)
    feed_data(status and ':' .. status .. 'cquit!\n' or ':quit!\n')
    status = status and status or 0
    screen_server:expect({ any = 'Process exited ' .. status })
    screen_client:expect({ any = 'Process exited ' .. status })
  end

  describe('exits when server quits', function()
    it('with :quit', function()
      test_remote_tui_quit()
    end)

    it('with :cquit', function()
      test_remote_tui_quit(42)
    end)
  end)

  it('suspend/resume works with multiple clients', function()
    t.skip(is_os('win'), 'N/A for Windows')
    local server_super, screen_server, screen_client = start_tui_and_remote_client()

    local screen_normal = [[
      Hello, Worl^d                                      |
      {100:~                                                 }|*3
      {3:[No Name] [+]                                     }|
                                                        |
      {5:-- TERMINAL --}                                    |
    ]]
    local screen_suspended = [[
                                                        |*5
      ^[Process suspended]                               |
      {5:-- TERMINAL --}                                    |
    ]]

    screen_client:expect({ grid = screen_normal, unchanged = true })
    screen_server:expect({ grid = screen_normal, unchanged = true })

    -- Suspend both clients.
    feed_data(':suspend\r')
    screen_client:expect({ grid = screen_suspended })
    screen_server:expect({ grid = screen_suspended })

    -- Resume the remote client.
    n.feed('<Space>')
    screen_client:expect({ grid = screen_normal })
    screen_server:expect({ grid = screen_suspended, unchanged = true })

    -- Resume the embedding client.
    server_super:request('nvim_input', '<Space>')
    screen_server:expect({ grid = screen_normal })
    screen_client:expect({ grid = screen_normal, unchanged = true })

    -- Suspend both clients again.
    feed_data(':suspend\r')
    screen_client:expect({ grid = screen_suspended })
    screen_server:expect({ grid = screen_suspended })

    -- Resume the remote client.
    n.feed('<Space>')
    screen_client:expect({ grid = screen_normal })
    screen_server:expect({ grid = screen_suspended, unchanged = true })

    -- Suspend the remote client again.
    feed_data(':suspend\r')
    screen_client:expect({ grid = screen_suspended })
    screen_server:expect({ grid = screen_suspended, unchanged = true })

    -- Resume the embedding client.
    server_super:request('nvim_input', '<Space>')
    screen_server:expect({ grid = screen_normal })
    screen_client:expect({ grid = screen_suspended, unchanged = true })

    -- Resume the remote client.
    n.feed('<Space>')
    screen_client:expect({ grid = screen_normal })
    screen_server:expect({ grid = screen_normal, unchanged = true })

    feed_data(':quit!\r')
    screen_server:expect({ any = vim.pesc('[Process exited 0]') })
    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
  end)
end)