xei-core 3.0.10

xei (晴) core library — headless editor engine shared by TUI and desktop frontends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
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
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::buffer::{Buffer, Position};
use crate::completion::Completions;
use crate::config;
use crate::explorer::Explorer;
use crate::fold::FoldState;
use crate::git::{GitBlame, GitGutter};
use crate::multi_cursor::MultiCursor;
use crate::lsp::LspClient;
use crate::git_workbench::GitWorkbench;
use crate::preview::PreviewState;
use crate::scm::ScmPanel;
use crate::session::{self, Session, SessionFile};
use crate::settings::SettingsPanel;
use crate::nav::{FindKind, Jump, JumpList, LastFind, Marks};
use crate::ops::{
    self, delete_range, extract_text, range_for_motion, range_for_textobject, LastChange, Motion,
    Operator, TextObject,
};
use crate::macros::MacroBank;
use crate::palette::{Palette, PaletteAction};
use crate::registers::Registers;
use crate::substitute::{self, SubstituteCmd};
use crate::syntax::SyntaxEngine;
use crate::term::Terminal;
use crate::theme::{self, Theme, OCEAN};
use crate::undo::UndoStack;
use crate::xlc::{Xlc, XlcCmd};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Normal,
    Insert,
    Visual,
    VisualLine,
    VisualBlock,
    XlcInput,
    Search,
    Explorer,
    Terminal,
    Palette,
    /// Light Source Control panel (Ctrl+G) — stage / commit / graph
    SourceControl,
    /// Full Git workbench (Ctrl+Shift+G) — branch / sync / diff / stash
    GitWorkbench,
    /// Unified settings (Ctrl+,) — About / Setting / Help
    Settings,
    /// Pretty document preview (Markdown / JSON) — Ctrl+Shift+V
    Preview,
    /// Workspace find / replace (Ctrl+Shift+F)
    WorkspaceSearch,
    /// `:screensaver` / xeifetch splash
    Screensaver,
    /// DAP debugger panel (F5 / Ctrl+Shift+D)
    Debug,
    /// LSP call hierarchy panel
    CallHierarchy,
    /// Interactive git rebase planner
    Rebase,
    /// PR multi-file review surface
    PrReview,
    /// Live self-benchmark results screen (`:bench`)
    Bench,
}

/// Sampled resource usage of the xei process, filled by the frontend for the
/// `:status` line. GPU is `None` where no per-process figure is obtainable
/// (e.g. macOS without elevated tooling) and renders as `—`.
#[derive(Debug, Clone, Copy, Default)]
pub struct ProcMetrics {
    /// CPU busy normalized to one core (100% = one full core, like `top`).
    pub cpu_pct: f32,
    /// Total logical cores, so the UI can also show cores-in-use (cpu%/100).
    pub cores: u32,
    pub mem_pct: f32,
    pub mem_mb: f32,
    pub gpu_pct: Option<f32>,
    /// Set once the first sample lands, so the UI can show `…` until then.
    pub sampled: bool,
}

pub struct App {
    pub running: bool,
    pub mode: Mode,
    pub buffer: Buffer,
    pub message: String,
    pub filename: Option<PathBuf>,
    pub scroll: usize,
    pub xlc: Xlc,
    pub undo_stack: UndoStack,
    /// Deprecated alias surface: prefer `registers`. Kept in sync with unnamed.
    pub yank_buffer: Option<String>,
    pub registers: Registers,
    pub marks: Marks,
    pub jumps: JumpList,
    pub last_find: Option<LastFind>,
    /// After `"` waiting for register name
    pub pending_register: bool,
    /// After `m` waiting for mark name
    pub pending_mark_set: bool,
    /// After `'` or `` ` `` waiting for mark name (`true` = linewise `'`)
    pub pending_mark_jump: Option<bool>,
    pub pending_key: Option<char>,
    pub pending_ft: Option<char>,
    pub count: Option<usize>,
    pub pending_hints: Vec<(&'static str, &'static str)>,
    /// Which-key delay + Space-leader path.
    pub which_key: crate::which_key::WhichKeyState,
    pub visual_anchor: Option<Position>,
    /// Last committed search pattern (used by n/N after leaving search mode).
    pub search_pattern: Option<String>,
    /// Live query while in Search mode (does not touch `search_pattern` until commit).
    pub search_input: String,
    pub search_matches: Vec<Position>,
    pub search_current: usize,
    /// Cursor when `/` was pressed — restored on Esc cancel.
    pub search_origin: Option<Position>,
    pub search_scroll_origin: usize,
    /// Pattern that existed before this search session (restored on cancel).
    search_pattern_backup: Option<String>,
    /// `true` = forward `/`, `false` = reverse `?`
    pub search_forward: bool,
    pub completions: Completions,
    pub modified: bool,
    pub mouse: MouseState,
    pub viewport: EditorViewport,
    pub explorer: Explorer,
    pub terminal: Terminal,
    pub explorer_width: u16,
    pub terminal_width: u16,
    pub resize_target: Option<ResizeTarget>,
    pub explorer_separator_x: u16,
    pub terminal_separator_x: u16,
    pub screen_width: u16,
    pub screen_height: u16,
    pub theme: &'static Theme,
    pub xlc_height: u16,
    pub xlc_separator_y: u16,
    pub file_mtime: Option<std::time::SystemTime>,
    pub buffers: Vec<BufferTab>,
    pub current_buffer: usize,
    pub syntax: SyntaxEngine,
    pub lsp: LspClient,
    pub debug: bool,
    /// `:status` — show live CPU/MEM/GPU of this process in the status line.
    /// The frontend samples (platform-specific) and writes into `metrics`; core
    /// only owns the toggle + the last-sampled snapshot for rendering.
    pub show_metrics: bool,
    pub metrics: ProcMetrics,
    /// Latest `:bench` results (shown in `Mode::Bench`).
    pub bench_report: Option<crate::bench::BenchReport>,
    /// Last change for `.` repeat
    pub last_change: Option<LastChange>,
    /// Pending operator (`d`/`c`/`y`) while waiting for motion/object
    pub pending_operator: Option<Operator>,
    /// Pending text-object modifier `i`/`a` after operator
    pub pending_to_mod: Option<char>,
    /// Tab bar hit regions for mouse (filled by UI each frame)
    pub tab_hit_regions: Vec<(u16, u16, usize)>, // x_start, x_end, tab_index
    pub tab_bar_y: u16,
    /// Screen-row → buffer-row map for the current frame (handles soft-wrap).
    /// Index 0 = `viewport.text_y`. Built in the TUI draw path.
    pub screen_row_to_buffer: Vec<usize>,
    /// For each screen row, visual-column base within that buffer line
    /// (0, text_width, 2*text_width, …). Parallel to `screen_row_to_buffer`.
    pub screen_row_visual_base: Vec<usize>,
    pub palette: Palette,
    /// Hover popup text (LSP)
    pub hover_text: Option<String>,
    /// Double-click tracking (ms-ish ticks via counter)
    pub last_click: Option<(u16, u16, std::time::Instant)>,
    pub macros: MacroBank,
    pub tab_width: usize,
    pub clipboard_sync: bool,
    pub relative_number: bool,
    /// Soft-wrap long lines; false = horizontal scroll via `hscroll`.
    pub wrap_lines: bool,
    /// Persist undo history to ~/.xei/undo on close (config `undo_caching`).
    pub undo_caching: bool,
    /// Per-feature GPU toggles under `gpu_acc`.
    pub gpu_graphics: bool,
    pub gpu_hyperlinks: bool,
    /// Horizontal pan (visual columns) when wrap_lines is off.
    pub hscroll: usize,
    /// Last buffer version handed to the syntax highlighter (render cache).
    pub syntax_seen_version: u64,
    /// Last buffer version pushed to the LSP (didChange gate).
    lsp_synced_version: u64,
    /// Git gutter signs for the current file
    pub git: GitGutter,
    /// Optional git blame overlay (`gb` toggle)
    pub blame: GitBlame,
    /// Indent-based folds (`za` / `zc` / `zo` / `zM` / `zR`)
    pub folds: FoldState,
    /// Extra carets (primary = `buffer.cursor`)
    pub multi: MultiCursor,
    /// Light Source Control side panel (Ctrl+G)
    pub scm: ScmPanel,
    /// Full Git workbench (Ctrl+Shift+G)
    pub git_wb: GitWorkbench,
    /// Settings — About / Setting / Help (Ctrl+,)
    pub settings: SettingsPanel,
    /// Pretty preview pane (Markdown / JSON / media)
    pub preview: PreviewState,
    /// Kitty image asset for PreviewKind::Image
    pub preview_image: Option<crate::media::ImageAsset>,
    /// Audio player for PreviewKind::Audio
    pub preview_audio: Option<crate::media::AudioPlayer>,
    /// Editor splits (Ctrl+W v/s)
    pub split: crate::split::SplitState,
    /// Peek definition overlay
    pub peek: crate::peek::PeekState,
    /// Workspace find/replace panel
    pub workspace_search: crate::workspace_search::WorkspaceSearch,
    /// `:screensaver` xeifetch overlay
    pub screensaver: crate::screensaver::Screensaver,
    /// Desktop pet GIF overlay
    pub pet: crate::pet::PetState,
    /// Pane hit regions filled each frame: (x, y, w, h, pane_idx)
    pub pane_hit_regions: Vec<(u16, u16, u16, u16, usize)>,
    /// Split separator for mouse drag-resize (filled by UI each frame).
    pub split_sep_hit: Option<SplitSepHit>,
    /// Git workbench Log rows: (x, y, w, h, commit_index) for right-click menus
    pub git_log_hits: Vec<(u16, u16, u16, u16, usize)>,
    /// Git toolbar chips: (x, y, w, h, key 1..=8)
    pub git_tab_hits: Vec<(u16, u16, u16, u16, u8)>,
    /// DAP panel tab hits: (x, y, w, h, pane_id 0..3)
    pub dap_tab_hits: Vec<(u16, u16, u16, u16, u8)>,
    /// DAP list row hits: (x, y, w, h, row_index)
    pub dap_row_hits: Vec<(u16, u16, u16, u16, usize)>,
    /// DAP panel body rect for mouse (x, y, w, h)
    pub dap_panel_rect: Option<(u16, u16, u16, u16)>,
    /// Terminal rect (side panel / full window / pane-bound) for wheel routing
    pub terminal_rect: Option<(u16, u16, u16, u16)>,
    /// Inline preview images wanted this frame: (path, x, y, w_cells, rows).
    pub preview_gfx: Vec<(String, u16, u16, u16, u16)>,
    /// PR review tab chips: (x, y, w, h, tab 0=Files 1=Comments 2=Body)
    pub pr_tab_hits: Vec<(u16, u16, u16, u16, u8)>,
    /// PR review list rows: (x, y, w, h, row index)
    pub pr_row_hits: Vec<(u16, u16, u16, u16, usize)>,
    /// Git docked columns: (x, y, w, h, pane_id 0=Changes 1=Log 2=Files)
    pub git_pane_hits: Vec<(u16, u16, u16, u16, u8)>,
    /// Editor right-click context menu (Insert / Normal / Visual)
    pub editor_ctx: Option<EditorContextMenu>,
    /// Show LSP inlay hints when available
    pub inlay_hints_enabled: bool,
    /// Code actions awaiting palette selection (Ctrl+.)
    pub code_action_bank: Vec<crate::lsp::CodeActionItem>,
    /// GPU-terminal enhancements (Ghostty/Kitty sync, undercurl, graphics…)
    pub gpu_acc: bool,
    /// Which-key style chord hints after prefix keys.
    pub key_hints: bool,
    /// DAP debugger client + panel state.
    pub dap: crate::dap::DapClient,
    /// Call hierarchy panel (gC / SPC l c).
    pub call_hierarchy: crate::call_hierarchy::CallHierarchyState,
    /// Interactive rebase planner.
    pub rebase: crate::rebase::RebaseState,
    /// PR review (files + comments + diff).
    pub pr_review: crate::pr_review::PrReviewState,
    /// Plugin hooks (`~/.xei/hooks.toml`).
    pub hooks: crate::hooks::HooksConfig,
    /// Release check + self-update (welcome notice · :update).
    pub update: crate::update::UpdateState,
    /// Hook results from background threads (drained by poll_hook_messages).
    hook_msg_tx: std::sync::mpsc::Sender<String>,
    hook_msg_rx: std::sync::mpsc::Receiver<String>,
    /// Async git gutter/blame refresh (latest generation wins).
    #[allow(clippy::type_complexity)]
    git_refresh_rx: Option<
        std::sync::mpsc::Receiver<(
            u64,
            String,
            (bool, std::collections::HashMap<usize, crate::git::GitSign>),
            Option<(bool, std::collections::HashMap<usize, crate::git::BlameLine>)>,
        )>,
    >,
    git_refresh_gen: u64,
    /// Show LSP code lenses in the editor.
    pub code_lens_enabled: bool,
    /// Detected terminal capabilities (filled by TUI shell at startup).
    /// Core only stores a simple summary string so headless tests stay free of
    /// crossterm queries; detailed flags live in the TUI `term_caps` module.
    pub term_caps_summary: String,
    pub term_sync: bool,
    pub term_undercurl: bool,
    pub term_underline_color: bool,
    pub term_hyperlinks: bool,
    /// Physical pixels per cell (from the frontend probe; 0 = unknown → 14).
    pub cell_px: u32,
    pub cell_px_h: u32,
    pub term_modern: bool,
    /// Terminal speaks Kitty graphics protocol (Ghostty/Kitty/WezTerm).
    pub term_kitty_graphics: bool,
    /// While replaying a macro — suppress nested recording
    pub replaying_macro: bool,
    /// Pending rename: new name input via XLC or message
    pub rename_pending: bool,
    /// Last document state pushed to the LSP via didChange (path + text hash).
    /// `sync_lsp_document` uses these to send post-edit full-text syncs exactly
    /// once per change instead of the old pre-edit push_undo notification.
    lsp_synced_path: Option<PathBuf>,
    lsp_synced_hash: u64,
}

#[derive(Clone)]
pub struct BufferTab {
    pub buffer: Buffer,
    pub filename: Option<PathBuf>,
    pub scroll: usize,
    pub modified: bool,
    pub undo_stack: UndoStack,
    pub file_mtime: Option<std::time::SystemTime>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResizeTarget {
    Explorer,
    Terminal,
    Xlc,
    /// Drag the split divider between editor panes
    Split,
}

/// Hit target for the split divider (mouse drag resize).
#[derive(Clone, Copy, Debug)]
pub struct SplitSepHit {
    /// True = vertical split (left|right), divider is a column.
    pub vertical: bool,
    /// Screen x (vertical) or y (horizontal) of the divider line.
    pub pos: u16,
    /// Parent split area origin + size — used to compute ratio on drag.
    pub area_x: u16,
    pub area_y: u16,
    pub area_w: u16,
    pub area_h: u16,
}

#[derive(Clone, Copy, Debug, Default)]
pub struct MouseState {
    pub dragging: bool,
    pub drag_anchor: Option<Position>,
}

/// Right-click menu over the editor buffer.
#[derive(Debug, Clone)]
pub struct EditorContextMenu {
    pub x: u16,
    pub y: u16,
    pub sel: usize,
    pub items: Vec<EditorCtxItem>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorCtxItem {
    Cut,
    Copy,
    Paste,
    SelectAll,
    Undo,
    Redo,
    GoToDefinition,
    FormatDocument,
    CommandPalette,
}

impl EditorCtxItem {
    pub fn label(self) -> &'static str {
        match self {
            EditorCtxItem::Cut => "Cut",
            EditorCtxItem::Copy => "Copy",
            EditorCtxItem::Paste => "Paste",
            EditorCtxItem::SelectAll => "Select All",
            EditorCtxItem::Undo => "Undo",
            EditorCtxItem::Redo => "Redo",
            EditorCtxItem::GoToDefinition => "Go to Definition",
            EditorCtxItem::FormatDocument => "Format Document",
            EditorCtxItem::CommandPalette => "Command Palette…",
        }
    }
    pub fn key_hint(self) -> &'static str {
        match self {
            EditorCtxItem::Cut => "⌘X",
            EditorCtxItem::Copy => "⌘C",
            EditorCtxItem::Paste => "⌘V",
            EditorCtxItem::SelectAll => "⌘A",
            EditorCtxItem::Undo => "u",
            EditorCtxItem::Redo => "^R",
            EditorCtxItem::GoToDefinition => "gd",
            EditorCtxItem::FormatDocument => "^⇧I",
            EditorCtxItem::CommandPalette => "⇧⌘P",
        }
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct EditorViewport {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
    /// X of first text column (after line-number gutter).
    pub text_x: u16,
    /// Y of first editor content row (same as `y` when borderless).
    pub text_y: u16,
}

impl Default for App {
    fn default() -> Self {
        let (hook_msg_tx, hook_msg_rx) = std::sync::mpsc::channel();
        Self {
            running: true,
            mode: Mode::Normal,
            buffer: Buffer::new(),
            message: String::from("Welcome to xei! i=insert :=XLC h/j/k/l=move"),
            filename: None,
            scroll: 0,
            xlc: Xlc::new(),
            undo_stack: UndoStack::new(),
            yank_buffer: None,
            registers: Registers::new(),
            marks: Marks::new(),
            jumps: JumpList::new(),
            last_find: None,
            pending_register: false,
            pending_mark_set: false,
            pending_mark_jump: None,
            pending_key: None,
            pending_ft: None,
            count: None,
            pending_hints: Vec::new(),
            which_key: crate::which_key::WhichKeyState::default(),
            visual_anchor: None,
            search_pattern: None,
            search_input: String::new(),
            search_matches: Vec::new(),
            search_current: 0,
            search_origin: None,
            search_scroll_origin: 0,
            search_pattern_backup: None,
            search_forward: true,
            completions: Completions::new(),
            modified: false,
            mouse: MouseState::default(),
            viewport: EditorViewport::default(),
            explorer: Explorer::new(),
            terminal: Terminal::new(),
            explorer_width: 22,
            terminal_width: 30,
            resize_target: None,
            explorer_separator_x: 0,
            terminal_separator_x: 0,
            screen_width: 80,
            screen_height: 24,
            theme: &OCEAN,
            xlc_height: 11,
            xlc_separator_y: 0,
            file_mtime: None,
            buffers: vec![BufferTab {
                buffer: Buffer::new(),
                filename: None,
                scroll: 0,
                modified: false,
                undo_stack: UndoStack::new(),
                file_mtime: None,
            }],
            current_buffer: 0,
            syntax: SyntaxEngine::new(),
            lsp: LspClient::new(),
            debug: false,
            show_metrics: false,
            metrics: ProcMetrics::default(),
            bench_report: None,
            last_change: None,
            pending_operator: None,
            pending_to_mod: None,
            tab_hit_regions: Vec::new(),
            tab_bar_y: 0,
            screen_row_to_buffer: Vec::new(),
            screen_row_visual_base: Vec::new(),
            palette: Palette::new(),
            hover_text: None,
            last_click: None,
            macros: MacroBank::new(),
            tab_width: 4,
            clipboard_sync: true,
            relative_number: false,
            wrap_lines: true,
            undo_caching: false,
            gpu_graphics: true,
            gpu_hyperlinks: true,
            hscroll: 0,
            syntax_seen_version: 0,
            lsp_synced_version: 0,
            git: GitGutter::new(),
            blame: GitBlame::default(),
            folds: FoldState::new(),
            multi: MultiCursor::new(),
            scm: ScmPanel::new(),
            git_wb: GitWorkbench::new(),
            settings: SettingsPanel::new(),
            preview: PreviewState::new(),
            preview_image: None,
            preview_audio: None,
            split: crate::split::SplitState::new(),
            peek: crate::peek::PeekState::new(),
            workspace_search: crate::workspace_search::WorkspaceSearch::new(),
            screensaver: crate::screensaver::Screensaver::new(),
            pet: crate::pet::PetState::new(),
            pane_hit_regions: Vec::new(),
            split_sep_hit: None,
            git_log_hits: Vec::new(),
            git_tab_hits: Vec::new(),
            dap_tab_hits: Vec::new(),
            dap_row_hits: Vec::new(),
            dap_panel_rect: None,
            terminal_rect: None,
            preview_gfx: Vec::new(),
            pr_tab_hits: Vec::new(),
            pr_row_hits: Vec::new(),
            git_pane_hits: Vec::new(),
            editor_ctx: None,
            inlay_hints_enabled: true,
            code_action_bank: Vec::new(),
            gpu_acc: true,
            key_hints: true,
            dap: crate::dap::DapClient::new(),
            call_hierarchy: crate::call_hierarchy::CallHierarchyState::new(),
            rebase: crate::rebase::RebaseState::new(),
            pr_review: crate::pr_review::PrReviewState::new(),
            hooks: crate::hooks::HooksConfig::load(),
            update: crate::update::UpdateState::new(),
            hook_msg_tx,
            hook_msg_rx,
            git_refresh_rx: None,
            git_refresh_gen: 0,
            code_lens_enabled: true,
            term_caps_summary: String::new(),
            term_sync: false,
            term_undercurl: false,
            term_underline_color: false,
            cell_px: 0,
            cell_px_h: 0,
            term_hyperlinks: false,
            term_modern: false,
            term_kitty_graphics: false,
            replaying_macro: false,
            rename_pending: false,
            lsp_synced_path: None,
            lsp_synced_hash: 0,
        }
    }
}

/// FNV-1a over the whole document — cheap enough per sync tick, and unlike a
/// sampled fingerprint it cannot miss an edit.
fn text_hash(s: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for &b in s.as_bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    h
}

impl App {
    pub fn apply_config(&mut self) {
        let cfg = config::load();
        self.tab_width = cfg.tab_width;
        self.clipboard_sync = cfg.clipboard_sync;
        self.relative_number = cfg.relative_number;
        self.wrap_lines = cfg.wrap_lines;
        if self.wrap_lines {
            self.hscroll = 0;
        }
        self.undo_caching = cfg.undo_caching;
        self.gpu_graphics = cfg.gpu_graphics;
        self.gpu_hyperlinks = cfg.gpu_hyperlinks;
        self.gpu_acc = cfg.gpu_acc;
        self.key_hints = cfg.key_hints;
        self.lsp
            .apply_config(cfg.lsp_enabled, cfg.lsp_servers.clone());
        if let Some(t) = theme::find(&cfg.theme) {
            self.theme = t;
        }
        self.apply_pet_from_config(&cfg);
    }

    pub fn apply_pet_from_config(&mut self, cfg: &config::Config) {
        self.pet.x = cfg.pet_x;
        self.pet.y = cfg.pet_y;
        let new_w = cfg.pet_width_cells.max(4);
        if new_w != self.pet.width_cells {
            self.pet.width_cells = new_w;
            self.pet.invalidate_display_cache();
        } else {
            self.pet.width_cells = new_w;
        }
        self.pet.speed = crate::pet::PetState::clamp_speed(cfg.pet_speed);
        let path = crate::pet::expand_path(&cfg.pet_path);
        let path_s = path.display().to_string();
        if !cfg.pet_path.is_empty()
            && (self.pet.path != path_s || !self.pet.has_frames())
        {
            self.pet.load_path(&path_s);
        }
        if cfg.pet_path.is_empty() {
            self.pet.path.clear();
        }
        // Pet only runs with GPU + Kitty graphics — never enable otherwise.
        // Do **not** clamp x/y here: before the first draw `screen_*` is still
        // the default 80×24, which would permanently trash a bottom-right save.
        self.pet.enabled = cfg.pet_enabled && self.pet_graphics_ok() && self.pet.has_frames();
    }

    /// Pet overlay is allowed only with gpu_acc + Kitty graphics terminal.
    pub fn pet_graphics_ok(&self) -> bool {
        self.gpu_acc && self.term_kitty_graphics
    }

    /// Max cell coords for nudging in Settings (uses live terminal size).
    pub fn pet_pos_max(&self) -> (u16, u16) {
        let w = self.screen_width.max(1);
        let h = self.screen_height.max(1);
        // Until the first real draw, report a generous max so we don't clamp
        // config values when the user opens Settings very early.
        if w <= 80 && h <= 24 && self.screen_width == 80 && self.screen_height == 24 {
            // Still might be a real 80×24 — use actual size either way.
        }
        let max_x = w.saturating_sub(self.pet.width_cells.max(1));
        let max_y = h.saturating_sub(2); // tab/status
        (max_x, max_y)
    }

    /// Paint-time position only (does not mutate saved coords).
    pub fn pet_screen_xy(&self) -> (u16, u16) {
        self.pet.screen_xy(self.screen_width, self.screen_height)
    }

    /// `:status` — toggle the live CPU/MEM/GPU readout in the status line.
    pub fn toggle_status_metrics(&mut self) {
        self.show_metrics = !self.show_metrics;
        if self.show_metrics {
            // Force an immediate sample next frame instead of showing stale data.
            self.metrics.sampled = false;
            self.message = "status: live CPU/MEM/GPU on — :status to hide".into();
        } else {
            self.message = "status: metrics off".into();
        }
    }

    /// Frontend hook: store the latest sampled process metrics.
    pub fn set_metrics(&mut self, m: ProcMetrics) {
        self.metrics = m;
    }

    /// `:bench` — run the self-benchmark and switch to the results screen.
    pub fn run_bench(&mut self) {
        let report = crate::bench::run(self);
        self.message = format!("bench: {:.1} ms total · r rerun · Esc exit", report.total_ms);
        self.bench_report = Some(report);
        self.mode = Mode::Bench;
    }

    pub fn exit_bench(&mut self) {
        if self.mode == Mode::Bench {
            self.mode = Mode::Normal;
            self.message.clear();
        }
    }

    pub fn toggle_screensaver(&mut self) {
        if self.mode == Mode::Screensaver {
            self.screensaver.close();
            self.mode = Mode::Normal;
            self.message.clear();
        } else {
            // Don't stack over terminal/palette awkwardly — close light overlays
            if self.palette.open {
                self.palette.close();
            }
            self.screensaver.open();
            self.mode = Mode::Screensaver;
            self.message = "xeifetch · Esc exit · weather loading…".into();
        }
    }

    pub fn new() -> Self {
        let mut app = Self::default();
        app.apply_config();
        app.dap.load_persisted_breakpoints();
        app
    }

    pub fn open_file(path: &str) -> Self {
        let pathbuf = PathBuf::from(path);
        let abs_path = if pathbuf.is_absolute() {
            pathbuf
        } else {
            env::current_dir()
                .unwrap_or_default()
                .join(&pathbuf)
        };
        let content = fs::read_to_string(&abs_path).unwrap_or_default();
        let message = format!("Opened: {}", abs_path.display());
        let buffer = Buffer::from_string(&content);
        let mut undo = UndoStack::new();
        undo.push(buffer.snapshot());
        let mtime = std::fs::metadata(&abs_path).ok().and_then(|m| m.modified().ok());
        let mut app = Self {
            buffer: buffer.clone(),
            filename: Some(abs_path.clone()),
            message,
            modified: false,
            undo_stack: undo.clone(),
            file_mtime: mtime,
            buffers: vec![BufferTab {
                buffer,
                filename: Some(abs_path.clone()),
                scroll: 0,
                modified: false,
                undo_stack: undo,
                file_mtime: mtime,
            }],
            current_buffer: 0,
            ..Self::default()
        };
        app.apply_config();
        {
            let text = app.buffer.text();
            app.undo_stack
                .attach_file(&abs_path, app.undo_caching, &text);
            app.lsp
                .auto_start_with_text(&abs_path.display().to_string(), Some(&text));
            app.lsp_synced_path = Some(abs_path.clone());
            app.lsp_synced_hash = text_hash(&text);
        }
        app.refresh_git();
        app
    }

    /// Restore tabs/cursors from `~/.xei/session` (used when started with no file args).
    pub fn restore_session(&mut self) {
        let session = session::load();
        if session.files.is_empty() {
            return;
        }
        for (i, f) in session.files.iter().enumerate() {
            if i == 0 {
                // Replace the empty first tab
                let content = fs::read_to_string(&f.path).unwrap_or_default();
                self.buffer = Buffer::from_string(&content);
                self.filename = Some(PathBuf::from(&f.path));
                self.buffer.cursor.row = f.row.min(self.buffer.line_count().saturating_sub(1));
                let line_len = self.buffer.line(self.buffer.cursor.row).chars().count();
                self.buffer.cursor.col = f.col.min(line_len);
                self.modified = false;
                if !self.buffers.is_empty() {
                    self.buffers[0].buffer = self.buffer.clone();
                    self.buffers[0].filename = self.filename.clone();
                    self.buffers[0].modified = false;
                }
            } else {
                self.open_new_tab(&f.path);
                self.buffer.cursor.row = f.row.min(self.buffer.line_count().saturating_sub(1));
                let line_len = self.buffer.line(self.buffer.cursor.row).chars().count();
                self.buffer.cursor.col = f.col.min(line_len);
            }
        }
        let active = session.active.min(self.buffers.len().saturating_sub(1));
        if active != self.current_buffer {
            self.save_state_to_tab();
            self.current_buffer = active;
            self.restore_state_from_tab();
        }
        if let Some(ref p) = self.filename {
            let text = self.buffer.text();
            self.lsp
                .auto_start_with_text(&p.display().to_string(), Some(&text));
            self.lsp_synced_path = Some(p.clone());
            self.lsp_synced_hash = text_hash(&text);
        }
        self.refresh_git();
        self.dap.load_persisted_breakpoints();
        self.message = format!("Restored session ({} file(s))", session.files.len());
    }

    pub fn save_session(&self) {
        let mut files = Vec::new();
        for (i, tab) in self.buffers.iter().enumerate() {
            let Some(ref path) = tab.filename else {
                continue;
            };
            let (row, col) = if i == self.current_buffer {
                (self.buffer.cursor.row, self.buffer.cursor.col)
            } else {
                (tab.buffer.cursor.row, tab.buffer.cursor.col)
            };
            files.push(SessionFile {
                path: path.display().to_string(),
                row,
                col,
            });
        }
        if files.is_empty() {
            return;
        }
        let active = self
            .buffers
            .iter()
            .enumerate()
            .filter(|(_, t)| t.filename.is_some())
            .position(|(i, _)| i == self.current_buffer)
            .unwrap_or(0);
        session::save(&Session { files, active });
        let _ = self.dap.persist_breakpoints();
    }

    /// Non-blocking: `git diff` (+ `git blame` when the panel is up) run on a
    /// background thread; results land via [`App::poll_git_refresh`].
    pub fn refresh_git(&mut self) {
        if let Some(ref p) = self.filename {
            let path = p.display().to_string();
            let want_blame = self.blame.enabled || self.blame.open;
            self.git_refresh_gen = self.git_refresh_gen.wrapping_add(1);
            let generation = self.git_refresh_gen;
            let (tx, rx) = std::sync::mpsc::channel();
            self.git_refresh_rx = Some(rx);
            std::thread::spawn(move || {
                let gutter = crate::git::compute_gutter(&path);
                let blame = if want_blame {
                    Some(crate::git::compute_blame(&path))
                } else {
                    None
                };
                let _ = tx.send((generation, path, gutter, blame));
            });
        } else {
            self.git.clear();
            self.blame.clear();
            self.blame.enabled = false;
        }
        self.rebuild_folds();
    }

    /// Apply a finished background git refresh (call once per frame).
    pub fn poll_git_refresh(&mut self) -> bool {
        use std::sync::mpsc::TryRecvError;
        let Some(rx) = self.git_refresh_rx.take() else {
            return false;
        };
        match rx.try_recv() {
            Ok((generation, path, (g_avail, signs), blame)) => {
                if generation != self.git_refresh_gen {
                    return false;
                }
                self.git.path = path.clone();
                self.git.available = g_avail;
                self.git.signs = signs;
                if let Some((b_avail, lines)) = blame {
                    self.blame.path = path;
                    self.blame.available = b_avail;
                    self.blame.lines = lines;
                    if !b_avail && self.blame.open {
                        self.blame.close_panel();
                        self.blame.enabled = false;
                        self.message = "Blame unavailable (not a git file?)".into();
                    }
                }
                true
            }
            Err(TryRecvError::Empty) => {
                self.git_refresh_rx = Some(rx);
                false
            }
            Err(TryRecvError::Disconnected) => false,
        }
    }

    pub fn rebuild_folds(&mut self) {
        let lines = self.buffer.lines();
        self.folds.rebuild(&lines, self.tab_width.max(1));
    }

    /// Toggle blame side panel (`Ctrl+B` / `gb`) with slide animation.
    pub fn toggle_blame(&mut self) {
        let path = self
            .filename
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        if path.is_empty() {
            self.message = "No file for blame".into();
            return;
        }
        self.message = self.blame.toggle_panel(&path);
    }

    /// Toggle DAP debug panel *focus* (Ctrl+Shift+D). Visibility and focus are
    /// separate: Esc drops focus back to the editor keeping the panel docked;
    /// `q` in the panel closes it.
    pub fn toggle_debug_panel(&mut self) {
        if self.mode == Mode::Debug {
            self.mode = Mode::Normal;
            self.message = "Debug unfocused · Ctrl+Shift+D refocus · q in panel closes".into();
        } else if self.dap.panel_open {
            self.mode = Mode::Debug;
            self.message = "Debug · F5 start · F9 bp · F10/F11 step · Esc unfocus".into();
        } else {
            self.dap.panel_open = true;
            self.dap.arm_panel_animation();
            self.mode = Mode::Debug;
            self.message = "Debug · F5 start · F9 bp · F10/F11 step · Esc unfocus".into();
        }
    }

    /// Close the debug panel entirely (`q` from the panel).
    pub fn close_debug_panel(&mut self) {
        self.dap.panel_open = false;
        if self.mode == Mode::Debug {
            self.mode = Mode::Normal;
        }
        self.message = "Debug panel closed".into();
    }

    /// `:mbb` — fresh blank tab landing on the welcome screen.
    pub fn open_blank_tab(&mut self) {
        self.save_state_to_tab();
        let buffer = Buffer::new();
        let mut undo = UndoStack::new();
        undo.push(buffer.snapshot());
        self.buffers.push(crate::BufferTab {
            buffer,
            filename: None,
            scroll: 0,
            modified: false,
            undo_stack: undo,
            file_mtime: None,
        });
        self.current_buffer = self.buffers.len() - 1;
        self.restore_state_from_tab();
        self.split.clamp_tabs(self.buffers.len());
        self.refresh_git();
        self.mode = Mode::Normal;
        self.message = "New tab · i insert · Ctrl+P files · :e <file>".into();
    }

    /// F9 — toggle breakpoint on cursor line.
    pub fn dap_toggle_breakpoint(&mut self) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = "No file for breakpoint".into();
            return;
        };
        let line = self.buffer.cursor.row;
        let on = self.dap.toggle_breakpoint(&path, line);
        self.message = if on {
            format!("● Breakpoint L{}", line + 1)
        } else {
            format!("○ Cleared BP L{}", line + 1)
        };
    }

    /// F5 — start or continue.
    pub fn dap_start_or_continue(&mut self) {
        use crate::dap::DapState;
        match self.dap.state {
            DapState::Stopped => {
                self.dap.continue_exec();
                self.message = "→ continue".into();
            }
            DapState::Running | DapState::Starting => {
                self.message = format!("DAP {}", self.dap.state.label());
            }
            DapState::Idle | DapState::Ending => {
                let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
                    self.message = "Open a file to debug".into();
                    return;
                };
                let cwd = self
                    .filename
                    .as_ref()
                    .and_then(|p| p.parent().map(|d| d.to_path_buf()));
                let ext = self.file_extension();
                let lang = ext.as_deref().map(|e| match e {
                    "py" | "pyw" => "python",
                    "rs" => "rust",
                    "go" => "go",
                    "c" | "h" | "cc" | "cpp" | "cxx" | "hpp" => "cpp",
                    "js" | "mjs" | "cjs" | "ts" | "tsx" => "node",
                    _ => "unknown",
                });
                let was_closed = !self.dap.panel_open;
                match self.dap.start(&path, cwd.as_deref(), lang, &[]) {
                    Ok(()) => {
                        if was_closed {
                            self.dap.arm_panel_animation();
                        }
                        self.mode = Mode::Debug;
                        self.message = format!(
                            "▶ DAP {} · {}",
                            self.dap.adapter_name,
                            self.dap.last_program.as_deref().unwrap_or(&path)
                        );
                    }
                    Err(e) => {
                        self.message = e;
                    }
                }
            }
        }
    }

    /// Launch a program (XLC `:DapLaunch <path> [args…]`).
    pub fn dap_launch_program(&mut self, program_line: &str) {
        let mut parts = program_line.split_whitespace();
        let Some(program) = parts.next() else {
            self.message = "DapLaunch: missing program".into();
            return;
        };
        let args: Vec<String> = parts.map(|s| s.to_string()).collect();
        let cwd = Path::new(program)
            .parent()
            .map(|p| p.to_path_buf())
            .or_else(|| {
                self.filename
                    .as_ref()
                    .and_then(|p| p.parent().map(|d| d.to_path_buf()))
            });
        let was_closed = !self.dap.panel_open;
        match self.dap.start(program, cwd.as_deref(), None, &args) {
            Ok(()) => {
                if was_closed {
                    self.dap.arm_panel_animation();
                }
                self.mode = Mode::Debug;
                self.message = format!("▶ DAP launch {program_line}");
            }
            Err(e) => self.message = e,
        }
    }

    /// F6 — suspend a running program.
    pub fn dap_pause(&mut self) {
        self.dap.pause();
        self.message = "⏸ pause requested".into();
    }

    /// Evaluate expression in the stopped frame (Console REPL).
    pub fn dap_evaluate(&mut self, expr: &str) {
        self.dap.evaluate(expr);
        self.message = format!("eval: {expr}");
    }

    /// `:bp if <expr>` — conditional breakpoint on cursor line.
    pub fn dap_set_condition(&mut self, condition: &str) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = "No file for breakpoint".into();
            return;
        };
        let line = self.buffer.cursor.row;
        let cond = condition.trim();
        if cond.is_empty() {
            self.dap.set_breakpoint_condition(&path, line, None);
            self.message = format!("○ condition cleared L{}", line + 1);
        } else {
            self.dap
                .set_breakpoint_condition(&path, line, Some(cond.to_string()));
            self.message = format!("● L{} if {cond}", line + 1);
        }
    }

    /// `:bp log <msg>` — logpoint on cursor line.
    pub fn dap_set_logpoint(&mut self, msg: &str) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = "No file for logpoint".into();
            return;
        };
        let line = self.buffer.cursor.row;
        let m = msg.trim();
        if m.is_empty() {
            self.dap.set_breakpoint_log(&path, line, None);
            self.message = format!("○ logpoint cleared L{}", line + 1);
        } else {
            self.dap
                .set_breakpoint_log(&path, line, Some(m.to_string()));
            self.message = format!("● L{} log {m}", line + 1);
        }
    }

    /// Launch using a named config from `.vscode/launch.json`.
    pub fn dap_launch_config(&mut self, name: Option<&str>) {
        let hint = self.filename.as_deref();
        let configs = crate::dap::load_launch_configs(hint);
        if configs.is_empty() {
            self.message = "No .vscode/launch.json configurations found".into();
            return;
        }
        let cfg = if let Some(n) = name {
            configs.iter().find(|c| c.name == n)
        } else {
            configs.first()
        };
        let Some(cfg) = cfg else {
            let names: Vec<_> = configs.iter().map(|c| c.name.as_str()).collect();
            self.message = format!("Unknown config. Available: {}", names.join(", "));
            return;
        };
        let was_closed = !self.dap.panel_open;
        let result = if cfg.request == "attach" {
            // Prefer port from env-less configs: look for numeric in program or name
            // launch.json attach often has "port" field — re-parse via args empty + name
            self.dap_attach_from_config(cfg)
        } else {
            if cfg.program.is_empty() {
                self.message = format!("Config '{}' has no program", cfg.name);
                return;
            }
            let cwd = cfg
                .cwd
                .as_ref()
                .map(PathBuf::from)
                .or_else(|| {
                    self.filename
                        .as_ref()
                        .and_then(|p| p.parent().map(|d| d.to_path_buf()))
                });
            let lang = match cfg.adapter_type.as_str() {
                "python" | "debugpy" => Some("python"),
                "go" | "delve" => Some("go"),
                "lldb" | "cppdbg" | "codelldb" => Some("rust"),
                "node" | "pwa-node" => Some("node"),
                _ => None,
            };
            self.dap
                .start(&cfg.program, cwd.as_deref(), lang, &cfg.args)
        };
        match result {
            Ok(()) => {
                if was_closed {
                    self.dap.arm_panel_animation();
                }
                self.mode = Mode::Debug;
                self.message = format!("▶ launch.json · {}", cfg.name);
            }
            Err(e) => self.message = e,
        }
    }

    fn dap_attach_from_config(&mut self, cfg: &crate::dap::LaunchConfig) -> Result<(), String> {
        let lang = match cfg.adapter_type.as_str() {
            "python" | "debugpy" => Some("python"),
            "node" | "pwa-node" => Some("node"),
            "lldb" | "cppdbg" | "codelldb" => Some("native"),
            other if !other.is_empty() => Some(other),
            _ => None,
        };
        if let Some(pid) = cfg.pid {
            return self.dap.attach_pid(pid);
        }
        if let Some(port) = cfg.port {
            return self
                .dap
                .attach_port(port, lang, cfg.host.as_deref());
        }
        // Heuristic fallback: program field as port or pid
        if let Some(port) = cfg.program.parse::<u16>().ok().or_else(|| {
            cfg.program
                .rsplit(':')
                .next()
                .and_then(|s| s.parse().ok())
        }) {
            let host = if cfg.program.contains(':') {
                cfg.program.split(':').next()
            } else {
                None
            };
            return self.dap.attach_port(port, lang, host);
        }
        if let Ok(pid) = cfg.program.parse::<u32>() {
            return self.dap.attach_pid(pid);
        }
        Err(format!(
            "Attach config '{}' needs port, processId/pid, or program=port|pid",
            cfg.name
        ))
    }

    /// `:DapAttach pid <n>` or `:DapAttach port <n> [lang]`
    pub fn dap_attach(&mut self, spec: &str) {
        let parts: Vec<&str> = spec.split_whitespace().collect();
        if parts.is_empty() {
            self.message = "Usage: DapAttach pid <n> | DapAttach port <n> [python|node]".into();
            return;
        }
        let was_closed = !self.dap.panel_open;
        let result = match parts[0] {
            "pid" => {
                let Some(pid) = parts.get(1).and_then(|s| s.parse::<u32>().ok()) else {
                    self.message = "Usage: DapAttach pid <n>".into();
                    return;
                };
                self.dap.attach_pid(pid)
            }
            "port" => {
                let Some(port) = parts.get(1).and_then(|s| s.parse::<u16>().ok()) else {
                    self.message = "Usage: DapAttach port <n> [python|node]".into();
                    return;
                };
                let lang = parts.get(2).copied();
                self.dap.attach_port(port, lang, None)
            }
            // Bare number: prefer port if ≤65535, else pid
            n if n.parse::<u32>().is_ok() => {
                let num: u32 = n.parse().unwrap();
                if num <= 65535 {
                    self.dap.attach_port(num as u16, Some("python"), None)
                } else {
                    self.dap.attach_pid(num)
                }
            }
            _ => {
                self.message = "Usage: DapAttach pid <n> | DapAttach port <n> [lang]".into();
                return;
            }
        };
        match result {
            Ok(()) => {
                if was_closed {
                    self.dap.arm_panel_animation();
                }
                self.mode = Mode::Debug;
                self.message = format!("▶ attach · {spec}");
            }
            Err(e) => self.message = e,
        }
    }

    /// List launch.json configs into message / XLC.
    pub fn dap_list_configs(&mut self) {
        let hint = self.filename.as_deref();
        let configs = crate::dap::load_launch_configs(hint);
        if configs.is_empty() {
            self.message = "No launch.json configs".into();
            self.xlc.add_output("No .vscode/launch.json found");
            return;
        }
        self.xlc.add_output("=== launch.json ===");
        for c in &configs {
            self.xlc.add_output(&format!(
                "  {}  [{}]  {}",
                c.name, c.request, c.program
            ));
        }
        self.message = format!("{} launch config(s) — :DapConfig <name>", configs.len());
    }

    pub fn dap_stop(&mut self) {
        self.dap.stop();
        self.message = "■ Debug stopped".into();
    }

    pub fn dap_step_over(&mut self) {
        self.dap.step_over();
        self.message = "→ step over".into();
    }

    pub fn dap_step_into(&mut self) {
        self.dap.step_into();
        self.message = "→ step into".into();
    }

    pub fn dap_step_out(&mut self) {
        self.dap.step_out();
        self.message = "→ step out".into();
    }

    /// Open call hierarchy (incoming by default).
    pub fn open_call_hierarchy(&mut self, outgoing: bool) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = "No file for call hierarchy".into();
            return;
        };
        if !self.lsp.server_running {
            self.message = "LSP not running".into();
            return;
        }
        let dir = if outgoing {
            crate::call_hierarchy::CallDirection::Outgoing
        } else {
            crate::call_hierarchy::CallDirection::Incoming
        };
        let c = self.buffer.cursor();
        // Word under cursor as provisional root name
        let word = {
            let w = self.word_under_cursor();
            if w.is_empty() {
                "?".into()
            } else {
                w
            }
        };
        self.sync_lsp_document();
        self.call_hierarchy.begin(&word, dir);
        self.mode = Mode::CallHierarchy;
        self.lsp
            .request_call_hierarchy(&path, c.row, c.col, dir);
        self.message = format!("Call hierarchy ({})…", dir.label());
    }

    pub fn toggle_call_direction(&mut self) {
        if !self.call_hierarchy.open {
            return;
        }
        let dir = self.call_hierarchy.direction.toggle();
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            return;
        };
        let c = self.buffer.cursor();
        let name = self.call_hierarchy.root_name.clone();
        self.call_hierarchy.begin(&name, dir);
        self.lsp
            .request_call_hierarchy(&path, c.row, c.col, dir);
    }

    /// Apply finished call hierarchy from LSP poll.
    pub fn poll_call_hierarchy(&mut self) {
        if !self.lsp.call_hierarchy_ready {
            return;
        }
        self.lsp.call_hierarchy_ready = false;
        let items = std::mem::take(&mut self.lsp.pending_call_hierarchy);
        if let Some(dir) = self.lsp.pending_call_direction {
            self.call_hierarchy.direction = dir;
        }
        if let Some(first) = items.first() {
            if self.call_hierarchy.root_name == "?" || self.call_hierarchy.root_name.is_empty() {
                self.call_hierarchy.root_name = first.name.clone();
            }
        }
        self.call_hierarchy.set_items(items);
        self.message = self.call_hierarchy.message.clone();
    }

    pub fn open_rebase(&mut self, count: usize) {
        let hint = self.filename.as_deref();
        let Some(root) = crate::git_ops::find_git_root(hint) else {
            self.message = "Not a git repository".into();
            return;
        };
        match self.rebase.open_for(&root, count) {
            Ok(()) => {
                self.mode = Mode::Rebase;
                self.message = self.rebase.message.clone();
            }
            Err(e) => self.message = e,
        }
    }

    pub fn run_rebase_plan(&mut self) {
        match self.rebase.run() {
            Ok(msg) => {
                self.mode = Mode::Normal;
                self.message = msg;
            }
            Err(e) => self.message = e,
        }
    }

    pub fn open_pr_review(&mut self, number: u64) {
        let hint = self.filename.as_deref();
        let Some(root) = crate::git_ops::find_git_root(hint).or_else(|| {
            self.git_wb.root.clone()
        }) else {
            self.message = "Not a git repository".into();
            return;
        };
        match self.pr_review.open_pr(&root, number) {
            Ok(()) => {
                self.mode = Mode::PrReview;
                self.message = self.pr_review.message.clone();
            }
            Err(e) => self.message = e,
        }
    }

    pub fn open_pr_review_selected(&mut self) {
        // From git workbench PR list — pr_sel is visual index into filtered list
        let idxs: Vec<usize> = if !self.git_wb.pr_filter.is_empty() {
            self.git_wb.pr_filtered.clone()
        } else {
            (0..self.git_wb.prs.len()).collect()
        };
        let num = idxs
            .get(self.git_wb.pr_sel)
            .and_then(|&i| self.git_wb.prs.get(i))
            .map(|p| p.number)
            .or_else(|| self.git_wb.prs.get(self.git_wb.pr_sel).map(|p| p.number));
        if let Some(n) = num {
            self.open_pr_review(n);
        } else {
            self.message = "No PR selected".into();
        }
    }

    pub fn toggle_code_lens(&mut self) {
        self.code_lens_enabled = !self.code_lens_enabled;
        self.message = if self.code_lens_enabled {
            self.lsp.mark_code_lens_dirty();
            "code lens on".into()
        } else {
            "code lens off".into()
        };
    }

    pub fn reload_hooks(&mut self) {
        self.hooks = crate::hooks::HooksConfig::load();
        self.message = format!(
            "hooks reloaded · enabled={}",
            self.hooks.enabled
        );
    }

    /// Run the hook for `event` on a background thread; results arrive via
    /// poll_hook_messages() so a slow hook never blocks the editor.
    fn fire_hook(&mut self, event: crate::hooks::HookEvent) {
        if !self.hooks.has_hook(event) {
            return;
        }
        let cfg = self.hooks.clone();
        let file = self.filename.clone();
        let tx = self.hook_msg_tx.clone();
        std::thread::spawn(move || {
            if let Some(msg) = crate::hooks::run_hooks(&cfg, event, file.as_deref()) {
                let _ = tx.send(msg);
            }
        });
    }

    /// Drain finished hook results into the status message (call per frame).
    pub fn poll_hook_messages(&mut self) {
        while let Ok(msg) = self.hook_msg_rx.try_recv() {
            self.message = msg;
        }
    }

    /// After DAP poll: jump editor to stopped frame if path matches an openable file.
    pub fn dap_apply_stopped_location(&mut self) {
        if !self.dap.location_dirty {
            return;
        }
        self.dap.location_dirty = false;
        let Some(path) = self.dap.current_path.clone() else {
            return;
        };
        let Some(line) = self.dap.current_line else {
            return;
        };
        // Open / switch to file if needed
        let same = self
            .filename
            .as_ref()
            .map(|p| {
                let a = std::fs::canonicalize(p).unwrap_or_else(|_| p.clone());
                let b = std::fs::canonicalize(&path).unwrap_or_else(|_| PathBuf::from(&path));
                a == b
            })
            .unwrap_or(false);
        if !same && Path::new(&path).is_file() {
            self.open_new_tab(&path);
        }
        if self.buffer.line_count() == 0 {
            return;
        }
        self.buffer.cursor.row = line.min(self.buffer.line_count().saturating_sub(1));
        self.buffer.move_to_line_start();
        self.update_scroll();
    }

    pub fn fold_toggle(&mut self) {
        let row = self.buffer.cursor.row;
        self.rebuild_folds();
        if let Some(msg) = self.folds.toggle(row) {
            self.message = msg.into();
            if self.folds.is_hidden(self.buffer.cursor.row) {
                for r in &self.folds.ranges {
                    if self.folds.is_closed(r.start)
                        && self.buffer.cursor.row > r.start
                        && self.buffer.cursor.row <= r.end
                    {
                        self.buffer.cursor.row = r.start;
                        self.buffer.clamp_col();
                        break;
                    }
                }
            }
            self.update_scroll();
        } else {
            self.message = "No fold here".into();
        }
    }

    pub fn fold_close(&mut self) {
        self.rebuild_folds();
        if self.folds.close_at(self.buffer.cursor.row) {
            self.message = "fold closed".into();
        } else {
            self.message = "No fold here".into();
        }
    }

    pub fn fold_open(&mut self) {
        if self.folds.open_at(self.buffer.cursor.row) {
            self.message = "fold opened".into();
        } else {
            self.message = "No closed fold here".into();
        }
    }

    pub fn fold_close_all(&mut self) {
        self.rebuild_folds();
        self.folds.close_all();
        self.message = "all folds closed".into();
        self.update_scroll();
    }

    pub fn fold_open_all(&mut self) {
        self.folds.open_all();
        self.message = "all folds opened".into();
    }

    /// Toggle light Source Control panel (Ctrl+G).
    /// From Git workbench → step back to light SCM.
    pub fn toggle_scm(&mut self) {
        if self.mode == Mode::GitWorkbench {
            self.leave_git_workbench_to_scm();
            return;
        }
        if self.scm.open && self.mode == Mode::SourceControl {
            if self.scm.closing {
                let hint = self.filename.as_deref();
                self.scm.open_and_refresh(hint);
                return;
            }
            self.close_scm();
            return;
        }
        if self.palette.open {
            self.palette.close();
        }
        if self.preview.open {
            self.preview.close_immediate();
        }
        if self.git_wb.open {
            self.git_wb.close();
        }
        let hint = self.filename.as_deref();
        self.scm.open_and_refresh(hint);
        self.mode = Mode::SourceControl;
        if let Some(ref err) = self.scm.error {
            self.message = err.clone();
        } else {
            let n = self.scm.total_files();
            let branch = if self.scm.branch.is_empty() {
                "git".into()
            } else {
                self.scm.branch.clone()
            };
            self.message = format!(
                "SCM · {} · {} change(s)  ·  Ctrl+Shift+G full Git",
                branch, n
            );
        }
    }

    /// Begin slide-out close (mode flips to Normal when anim settles).
    pub fn close_scm(&mut self) {
        if !self.scm.open {
            if self.mode == Mode::SourceControl {
                self.mode = Mode::Normal;
            }
            return;
        }
        self.scm.close();
    }

    pub fn close_scm_immediate(&mut self) {
        self.scm.close_immediate();
        if matches!(self.mode, Mode::SourceControl) {
            self.mode = Mode::Normal;
        }
    }

    /// Open full Git workbench (Ctrl+Shift+G).
    pub fn open_git_workbench(&mut self) {
        let from_scm = self.mode == Mode::SourceControl || self.scm.open;
        if self.palette.open {
            self.palette.close();
        }
        if self.preview.open {
            self.preview.close_immediate();
        }
        // Keep SCM state but hide panel while in workbench
        if self.scm.open && !self.scm.closing {
            // leave scm open flag? close visual only
            self.scm.close_immediate();
        }
        // Hint = open file, else cwd (same resolution light SCM uses via find_git_root)
        let cwd = env::current_dir().ok();
        let hint = self
            .filename
            .as_deref()
            .or(cwd.as_deref());
        self.git_wb.open_at(hint, from_scm);
        self.mode = Mode::GitWorkbench;
        let b = if self.git_wb.branch.is_empty() {
            "git".into()
        } else {
            self.git_wb.branch.clone()
        };
        let root_note = self
            .git_wb
            .root
            .as_ref()
            .and_then(|r| r.file_name())
            .and_then(|n| n.to_str())
            .unwrap_or(".");
        self.message = format!(
            "Git · {} @ {}  ·  Status ready  ·  Esc back",
            b, root_note
        );
    }

    pub fn toggle_git_workbench(&mut self) {
        if self.mode == Mode::GitWorkbench {
            self.close_git_workbench();
        } else {
            self.open_git_workbench();
        }
    }

    /// Esc / close from workbench: back to light SCM if we came from there.
    pub fn close_git_workbench(&mut self) {
        let back_to_scm = self.git_wb.from_scm;
        self.git_wb.close();
        if back_to_scm {
            let hint = self.filename.as_deref();
            self.scm.open_and_refresh(hint);
            self.mode = Mode::SourceControl;
            self.message = String::from("Source Control");
        } else {
            self.mode = Mode::Normal;
            self.message.clear();
        }
    }

    fn leave_git_workbench_to_scm(&mut self) {
        self.git_wb.from_scm = true;
        self.close_git_workbench();
    }

    /// Open unified Settings (Ctrl+,). Starts on About page.
    pub fn open_settings(&mut self) {
        if self.mode == Mode::Settings {
            self.close_settings();
            return;
        }
        if self.palette.open {
            self.palette.close();
        }
        if self.preview.open {
            self.preview.close_immediate();
        }
        if self.git_wb.open {
            self.git_wb.close();
        }
        if self.scm.open {
            self.scm.close_immediate();
        }
        self.settings.open_panel();
        self.mode = Mode::Settings;
        self.message = format!(
            "Settings · {}  ·  Tab pages · Enter apply · s save · Esc",
            crate::settings::SettingsPanel::version_string()
        );
    }

    pub fn close_settings(&mut self) {
        // Apply draft theme/editor opts if dirty? Prefer explicit save.
        self.settings.close();
        self.mode = Mode::Normal;
        self.message.clear();
    }

    pub fn apply_settings_draft(&mut self) {
        let cfg = self.settings.draft.clone();
        self.tab_width = cfg.tab_width;
        self.clipboard_sync = cfg.clipboard_sync;
        self.relative_number = cfg.relative_number;
        self.wrap_lines = cfg.wrap_lines;
        if self.wrap_lines {
            self.hscroll = 0;
        }
        self.undo_caching = cfg.undo_caching;
        self.gpu_graphics = cfg.gpu_graphics;
        self.gpu_hyperlinks = cfg.gpu_hyperlinks;
        self.gpu_acc = cfg.gpu_acc;
        self.key_hints = cfg.key_hints;
        self.lsp
            .apply_config(cfg.lsp_enabled, cfg.lsp_servers.clone());
        if let Some(t) = theme::find(&cfg.theme) {
            self.theme = t;
            set_cursor_esc(t.cursor);
        }
        self.apply_pet_from_config(&cfg);
        // Restart LSP for current file with new server map
        self.lsp_restart_for_current();
    }

    /// Set which-key hints if the feature is enabled.
    pub fn set_hints(&mut self, hints: Vec<(&'static str, &'static str)>) {
        if self.key_hints {
            self.pending_hints = hints;
        } else {
            self.pending_hints.clear();
        }
    }

    /// Begin a prefix chord with title + delayed popup.
    pub fn begin_chord(
        &mut self,
        title: &str,
        hints: Vec<(&'static str, &'static str)>,
    ) {
        self.which_key.begin_prefix(title);
        self.set_hints(hints);
    }

    /// Open Space leader root map.
    pub fn begin_leader(&mut self) {
        self.which_key.begin_leader();
        self.set_hints(crate::which_key::leader_hints(""));
        self.message = String::from("-- SPC --");
    }

    /// Enter Space submenu (`f`, `g`, …).
    pub fn leader_enter_sub(&mut self, key: char, label: &str) {
        self.which_key.enter_leader_sub(key, label);
        self.set_hints(crate::which_key::leader_hints(&key.to_string()));
        self.message = format!("-- SPC {label} --");
    }

    /// Clear leader / which-key session.
    pub fn clear_which_key(&mut self) {
        self.which_key.clear();
        self.pending_hints.clear();
    }

    /// Whether the which-key popup should draw this frame.
    pub fn which_key_visible(&self) -> bool {
        if !self.key_hints || self.pending_hints.is_empty() {
            return false;
        }
        if !self.which_key.ready() {
            return false;
        }
        self.which_key.is_leader()
            || self.pending_key.is_some()
            || self.pending_operator.is_some()
            || self.pending_register
            || self.pending_mark_set
            || self.pending_mark_jump.is_some()
            || self.split.pending_chord
            || self.pending_to_mod.is_some()
    }

    pub fn toggle_terminal_side(&mut self) {
        if self.terminal.open && !self.terminal.full_panel {
            self.terminal.open = false;
            self.terminal.shutdown();
            self.mode = Mode::Normal;
        } else {
            // Switch from full to side, or open side
            self.terminal.full_panel = false;
            self.terminal.pane_bound = None;
            self.terminal.close_confirm = false;
            self.terminal.open = true;
            self.terminal.start(self.filename.as_ref());
            self.mode = Mode::Terminal;
        }
    }

    /// Ctrl+Shift+T — terminal as a real split window (not Mode::Terminal).
    /// Stays in Normal so Ctrl+W / Git / layout chords keep working.
    pub fn toggle_terminal_full(&mut self) {
        if self.terminal.open && self.terminal.full_panel {
            // Closing always goes through confirm (same as Esc)
            self.request_close_pane_terminal();
            return;
        }
        // Open as a window: ensure a split exists so the editor stays visible.
        if !self.split.is_split() {
            let tab = self.current_buffer;
            let scroll = self.scroll;
            let cur = (self.buffer.cursor.row, self.buffer.cursor.col);
            self.split
                .open_split(crate::split::SplitKind::Vertical, tab, scroll, cur);
            self.split.set_focus(1);
            self.sync_split_from_active();
        }
        self.terminal.full_panel = true;
        self.terminal.pane_bound =
            Some(self.split.focus.min(self.split.panes.len().saturating_sub(1)));
        self.terminal.close_confirm = false;
        self.terminal.open = true;
        // Defer `start()` until first draw so COLUMNS/LINES match the pane
        // size (agent TUIs like opencode/claude read size at spawn).
        // Critical: stay in Normal — terminal is a pane, not a mode that
        // swallows layout shortcuts.
        if matches!(self.mode, Mode::Terminal | Mode::Insert) {
            self.mode = Mode::Normal;
        }
        self.message =
            "Terminal focused · keys → shell (Ctrl+C works) · ^⇧W close · ^W w other pane"
                .into();
    }

    /// Whether the focused split pane is showing the Ctrl+Shift+T terminal.
    pub fn terminal_window_focused(&self) -> bool {
        if !self.terminal.open || !self.terminal.full_panel {
            return false;
        }
        match self.terminal.pane_bound {
            Some(i) if self.split.is_split() => {
                self.split.focus.min(self.split.panes.len().saturating_sub(1)) == i
            }
            // Unsplit but still full_panel (split closed under us)
            _ => true,
        }
    }

    pub fn request_close_pane_terminal(&mut self) {
        if !self.terminal.open || !self.terminal.full_panel {
            return;
        }
        if self.terminal.close_confirm {
            // Second Ctrl+Shift+W while confirming — cancel
            self.terminal.close_confirm = false;
            self.message = "Close cancelled".into();
            return;
        }
        self.terminal.close_confirm = true;
        self.message = "Close terminal?  [y]es  /  [n]o  ·  Ctrl+Shift+W cancel".into();
    }

    pub fn confirm_close_pane_terminal(&mut self, yes: bool) {
        self.terminal.close_confirm = false;
        if !yes {
            self.message = "Close cancelled".into();
            return;
        }
        if self.terminal.open && self.terminal.full_panel {
            self.terminal.open = false;
            self.terminal.full_panel = false;
            self.terminal.pane_bound = None;
            self.terminal.shutdown();
            if matches!(self.mode, Mode::Terminal) {
                self.mode = Mode::Normal;
            }
            self.message = "Terminal window closed".into();
        }
    }

    /// Whether progressive GPU-terminal features should run this session.
    pub fn gpu_active(&self) -> bool {
        self.gpu_acc
            && (self.term_modern
                || self.term_sync
                || self.term_underline_color
                || self.term_undercurl)
    }

    /// Install terminal caps discovered by the TUI shell.
    pub fn set_term_caps(
        &mut self,
        summary: String,
        sync: bool,
        undercurl: bool,
        underline_color: bool,
        hyperlinks: bool,
        modern: bool,
        kitty_graphics: bool,
    ) {
        self.term_caps_summary = summary;
        self.term_sync = sync;
        self.term_kitty_graphics = kitty_graphics;
        self.term_undercurl = undercurl;
        self.term_underline_color = underline_color;
        self.term_hyperlinks = hyperlinks;
        self.term_modern = modern;
    }

    pub fn save_settings(&mut self) {
        self.settings.save();
        self.apply_settings_draft();
        self.message = self
            .settings
            .status
            .clone()
            .unwrap_or_else(|| "Settings saved".into());
    }

    pub fn scm_refresh(&mut self) {
        let hint = self.filename.as_deref();
        self.scm.refresh(hint);
        self.refresh_git();
    }

    pub fn scm_commit(&mut self) {
        match self.scm.commit(false) {
            Ok(()) => {
                let summary = self
                    .scm
                    .last_result
                    .clone()
                    .unwrap_or_else(|| "Committed".into());
                self.message = format!("{}", summary);
                self.refresh_git();
            }
            Err(e) => {
                self.message = e;
            }
        }
    }

    pub fn scm_stage_selected(&mut self) {
        match self.scm.stage_selected() {
            Ok(()) => {
                self.message = "Staged/unstaged".into();
                self.refresh_git();
            }
            Err(e) => self.message = e,
        }
    }

    pub fn scm_stage_all(&mut self) {
        match self.scm.stage_all() {
            Ok(()) => {
                self.message = self
                    .scm
                    .last_result
                    .clone()
                    .unwrap_or_else(|| "Staged all".into());
                self.refresh_git();
            }
            Err(e) => self.message = e,
        }
    }

    pub fn scm_open_selected_file(&mut self) {
        let Some(entry) = self.scm.entry_at(self.scm.selected).cloned() else {
            return;
        };
        let path = if let Some(ref root) = self.scm.root {
            root.join(&entry.path)
        } else {
            PathBuf::from(&entry.path)
        };
        let path_str = path.display().to_string();
        self.close_scm_immediate();
        self.open_new_tab(&path_str);
    }

    /// Toggle pretty preview for the current buffer (Markdown / JSON / media).
    pub fn toggle_preview(&mut self) {
        if self.preview.open && self.mode == Mode::Preview {
            if self.preview.closing {
                let text = self.buffer.text();
                let ext = self.file_extension();
                self.preview.base_dir = self
                    .filename
                    .as_ref()
                    .and_then(|p| p.parent().map(|d| d.to_path_buf()));
                self.preview.cell_dims =
                    (self.cell_px_or_default(), self.cell_px_h_or_default());
                self.preview.open_for(&text, ext.as_deref());
                return;
            }
            self.close_preview();
            return;
        }
        if self.scm.open {
            self.close_scm_immediate();
        }
        if self.palette.open {
            self.palette.close();
        }
        // Prefer path-based media if current file is an image/csv/npy/audio
        if let Some(ref path) = self.filename.clone() {
            if crate::media::is_media_path(path) {
                match self.open_media_preview(path) {
                    Ok(()) => return,
                    Err(e) => {
                        self.message = e;
                        return;
                    }
                }
            }
        }
        let text = self.buffer.text();
        let ext = self.file_extension();
        self.clear_media_handles();
        self.preview.open_for(&text, ext.as_deref());
        self.mode = Mode::Preview;
        let kind = self
            .preview
            .kind
            .map(|k| k.label())
            .unwrap_or("Preview");
        self.message = format!("Preview · {kind} — Esc close · j/k scroll · r refresh");
    }

    /// Open media / data preview from a filesystem path (explorer Enter).
    /// Effective pixels-per-cell for image caches.
    pub fn cell_px_or_default(&self) -> u32 {
        if self.cell_px >= 4 { self.cell_px } else { 14 }
    }

    pub fn cell_px_h_or_default(&self) -> u32 {
        if self.cell_px_h >= 6 {
            self.cell_px_h
        } else {
            self.cell_px_or_default() * 2
        }
    }

    pub fn open_media_preview(&mut self, path: &std::path::Path) -> Result<(), String> {
        self.clear_media_handles();
        self.preview.open_path(path)?;
        let kind = self.preview.kind;
        match kind {
            Some(crate::preview::PreviewKind::Image) => {
                match crate::media::ImageAsset::load(path, self.cell_px_or_default()) {
                    Ok(img) => {
                        self.message = format!(
                            "Image · {}×{} · ←/→ resize · Esc close",
                            img.src_w, img.src_h
                        );
                        self.preview_image = Some(img);
                    }
                    Err(e) => {
                        self.preview.lines.push(crate::preview::PreviewLine {
                            spans: vec![(format!("  load error: {e}"), crate::preview::PreviewStyle::AlertWarning)],
                            image: None,
                        });
                        self.message = e;
                    }
                }
            }
            Some(crate::preview::PreviewKind::Audio) => {
                self.preview_audio = Some(crate::media::AudioPlayer::new(path.to_path_buf()));
                self.message = "Audio · Space play/stop · Esc close".into();
            }
            Some(k) => {
                self.message = format!("Preview · {} — Esc close · j/k scroll", k.label());
            }
            None => {}
        }
        self.mode = Mode::Preview;
        Ok(())
    }

    pub fn clear_media_handles(&mut self) {
        if let Some(mut a) = self.preview_audio.take() {
            a.stop();
        }
        self.preview_image = None;
    }

    /// Begin reverse transform close (mode flips when anim settles).
    pub fn close_preview(&mut self) {
        if !self.preview.open {
            self.mode = Mode::Normal;
            return;
        }
        self.clear_media_handles();
        self.preview.close();
    }

    pub fn close_preview_immediate(&mut self) {
        self.clear_media_handles();
        self.preview.close_immediate();
        self.mode = Mode::Normal;
    }

    pub fn refresh_preview_if_open(&mut self) {
        if self.preview.open && !self.preview.closing {
            let text = self.buffer.text();
            let ext = self.file_extension();
            self.preview.rebuild(&text, ext.as_deref());
        }
    }

    /// Settle modes after panel/preview close animations complete.
    pub fn settle_anims(&mut self) {
        if self.scm.take_just_closed() {
            self.mode = Mode::Normal;
        }
        if self.preview.take_just_closed() {
            self.clear_media_handles();
            self.mode = Mode::Normal;
        }
    }

    /// Breadcrumb path segments for the current file (VS Code-style).
    pub fn breadcrumbs(&self) -> Vec<String> {
        let Some(ref path) = self.filename else {
            return vec!["untitled".into()];
        };
        let mut parts: Vec<String> = Vec::new();
        for c in path.components() {
            match c {
                std::path::Component::Normal(s) => {
                    parts.push(s.to_string_lossy().into_owned());
                }
                std::path::Component::RootDir => parts.push("/".into()),
                std::path::Component::Prefix(p) => {
                    parts.push(p.as_os_str().to_string_lossy().into_owned());
                }
                _ => {}
            }
        }
        // Keep last 4 segments for readability
        if parts.len() > 4 {
            let tail: Vec<_> = parts.into_iter().rev().take(4).collect::<Vec<_>>();
            let mut v: Vec<_> = tail.into_iter().rev().collect();
            v.insert(0, "".into());
            v
        } else if parts.is_empty() {
            vec!["untitled".into()]
        } else {
            parts
        }
    }

    pub fn file_extension(&self) -> Option<String> {
        self.filename
            .as_ref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .map(|s| s.to_lowercase())
    }

    pub fn file_name(&self) -> &str {
        self.filename
            .as_ref()
            .and_then(|p| p.file_stem())
            .and_then(|s| s.to_str())
            .unwrap_or("untitled")
    }

    pub fn push_undo(&mut self) {
        self.undo_stack.push(self.buffer.snapshot());
        self.modified = true;
        if self.current_buffer < self.buffers.len() {
            self.buffers[self.current_buffer].modified = true;
        }
        // didChange is sent by sync_lsp_document (post-edit); notifying here
        // would push the *pre-edit* snapshot since push_undo runs first.
    }

    /// Push the current buffer to the LSP if it differs from what the server
    /// last saw. Frontends call this from their loop (throttled) and before
    /// position-based requests, so the server always answers against the
    /// post-edit document — including plain insert-mode typing, which never
    /// produced a didChange before.
    pub fn sync_lsp_document(&mut self) {
        if !self.lsp.server_running {
            return;
        }
        let Some(path) = self.filename.clone() else {
            return;
        };
        let path_str = path.display().to_string();
        if !crate::lsp::has_server_for(&path_str) {
            return;
        }
        // Version gate: skip the O(file) join + hash entirely when the text
        // hasn't mutated since the last sync (this runs every ~5 frames).
        let path_changed = self.lsp_synced_path.as_ref() != Some(&path);
        if !path_changed && self.lsp_synced_version == self.buffer.version() {
            return;
        }
        let text = self.buffer.text();
        let hash = text_hash(&text);
        if path_changed || self.lsp_synced_hash != hash {
            self.lsp.notify_change(&path_str, &text);
            self.lsp_synced_path = Some(path);
            self.lsp_synced_hash = hash;
        }
        self.lsp_synced_version = self.buffer.version();
    }

    pub fn undo(&mut self) {
        let current = self.buffer.snapshot();
        if let Some(snap) = self.undo_stack.undo(current) {
            self.buffer.restore(&snap);
            self.message = String::from("UNDO");
        } else {
            self.message = String::from("Already at oldest change");
        }
    }

    pub fn redo(&mut self) {
        let current = self.buffer.snapshot();
        if let Some(snap) = self.undo_stack.redo(current) {
            self.buffer.restore(&snap);
            self.modified = true;
            self.message = String::from("REDO");
        } else {
            self.message = String::from("Already at newest change");
        }
    }

    /// Apply operator to a motion; records last_change for `.`
    pub fn apply_operator_motion(&mut self, op: Operator, motion: Motion, count: usize) {
        let count = count.max(1);
        let range = range_for_motion(&self.buffer, motion, count);
        self.apply_operator_range(op, range, true);
        self.last_change = Some(LastChange::Operator { op, motion, count });
        self.clear_operator_pending();
    }

    pub fn apply_operator_textobject(&mut self, op: Operator, obj: TextObject, count: usize) {
        let count = count.max(1);
        // count>1: apply repeatedly from cursor (vim-ish for words)
        for i in 0..count {
            let Some(range) = range_for_textobject(&self.buffer, obj) else {
                if i == 0 {
                    self.message = String::from("Text object not found");
                }
                break;
            };
            let record = i == 0;
            self.apply_operator_range(op, range, record);
            if op == Operator::Yank {
                break;
            }
            if op == Operator::Change {
                break;
            }
        }
        self.last_change = Some(LastChange::TextObject { op, obj, count });
        self.clear_operator_pending();
    }

    fn apply_operator_range(
        &mut self,
        op: Operator,
        range: ops::EditRange,
        push_undo_first: bool,
    ) {
        match op {
            Operator::Yank => {
                let text = extract_text(&self.buffer, range);
                let linewise = range.linewise;
                let stored = if linewise && !text.ends_with('\n') {
                    format!("{}\n", text)
                } else {
                    text
                };
                let label = self.registers.active_label();
                self.store_yank(stored, linewise);
                self.message = format!("Yanked → {}", label);
            }
            Operator::Delete => {
                if push_undo_first {
                    self.push_undo();
                }
                let text = delete_range(&mut self.buffer, range);
                let linewise = range.linewise;
                let stored = if linewise && !text.ends_with('\n') {
                    format!("{}\n", text)
                } else {
                    text
                };
                self.store_yank(stored, linewise);
                self.update_scroll();
                self.message = String::from("Deleted");
            }
            Operator::Change => {
                if push_undo_first {
                    self.push_undo();
                }
                let text = delete_range(&mut self.buffer, range);
                self.store_yank(text, range.linewise);
                self.mode = Mode::Insert;
                self.message = String::from("-- INSERT --");
                self.update_scroll();
            }
        }
    }

    pub fn store_yank(&mut self, text: String, linewise: bool) {
        self.registers.store(text.clone(), linewise);
        self.yank_buffer = Some(text);
    }

    pub fn apply_substitute_cmd(&mut self, cmd: SubstituteCmd) {
        self.push_undo();
        let lines: Vec<String> = self.buffer.lines().to_vec();
        let row = self.buffer.cursor.row;
        let (new_lines, n) = substitute::apply_substitute(&lines, &cmd, row);
        // rebuild buffer preserving cursor row
        let text = new_lines.join("\n");
        let col = self.buffer.cursor.col;
        self.buffer = Buffer::from_string(&text);
        self.buffer.cursor.row = row.min(self.buffer.line_count().saturating_sub(1));
        self.buffer.cursor.col = col;
        self.buffer.clamp_col();
        self.message = format!("{} substitution(s)", n);
        self.xlc.add_output(&format!("{} substitution(s) on {}", n, if cmd.global_file { "file" } else { "line" }));
        self.sync_lsp_document();
    }

    /// Visual-block range: (min_row, max_row, min_col, max_col) inclusive cols.
    pub fn block_range(&self) -> Option<(usize, usize, usize, usize)> {
        let anchor = self.visual_anchor?;
        let cur = self.buffer.cursor();
        let (r0, r1) = if anchor.row <= cur.row {
            (anchor.row, cur.row)
        } else {
            (cur.row, anchor.row)
        };
        let (c0, c1) = if anchor.col <= cur.col {
            (anchor.col, cur.col)
        } else {
            (cur.col, anchor.col)
        };
        Some((r0, r1, c0, c1))
    }

    pub fn yank_block(&mut self) {
        let Some((r0, r1, c0, c1)) = self.block_range() else {
            return;
        };
        let mut lines = Vec::new();
        for row in r0..=r1 {
            let chars: Vec<char> = self.buffer.line(row).chars().collect();
            let s = c0.min(chars.len());
            let e = (c1 + 1).min(chars.len());
            if s < e {
                lines.push(chars[s..e].iter().collect::<String>());
            } else {
                lines.push(String::new());
            }
        }
        self.store_yank(lines.join("\n"), false);
        self.enter_normal();
        self.message = String::from("Yanked block");
    }

    pub fn delete_block(&mut self) {
        let Some((r0, r1, c0, c1)) = self.block_range() else {
            return;
        };
        self.push_undo();
        let mut yanked = Vec::new();
        for row in r0..=r1 {
            let chars: Vec<char> = self.buffer.line(row).chars().collect();
            let s = c0.min(chars.len());
            let e = (c1 + 1).min(chars.len());
            if s < e {
                yanked.push(chars[s..e].iter().collect::<String>());
                let new_line: String = chars[..s].iter().chain(chars[e..].iter()).collect();
                self.buffer.set_line(row, new_line);
            } else {
                yanked.push(String::new());
            }
        }
        self.store_yank(yanked.join("\n"), false);
        self.buffer.cursor = Position::new(r0, c0);
        self.buffer.clamp_col();
        self.enter_normal();
        self.message = String::from("Deleted block");
    }

    pub fn request_references(&mut self) {
        self.sync_lsp_document();
        if let Some(ref path) = self.filename.clone() {
            let c = self.buffer.cursor();
            self.lsp
                .request_references(&path.display().to_string(), c.row, c.col);
            self.message = String::from("Finding references…");
        }
    }

    pub fn request_rename(&mut self, new_name: &str) {
        if new_name.is_empty() {
            self.message = String::from("Empty name");
            return;
        }
        self.sync_lsp_document();
        if let Some(ref path) = self.filename.clone() {
            let c = self.buffer.cursor();
            self.lsp
                .request_rename(&path.display().to_string(), c.row, c.col, new_name);
            self.message = format!("Renaming to {}", new_name);
        }
    }

    /// Copy current visual selection, or the current line in Normal mode, to
    /// the system clipboard (Cmd+C / Ctrl+C style).
    pub fn clipboard_copy(&mut self) {
        if matches!(self.mode, Mode::Visual | Mode::VisualLine) {
            self.yank_selection();
            // yank_selection already store_yank → system
            self.message = String::from("Copied to clipboard");
            return;
        }
        // Normal / Insert: copy current line
        let line = self.buffer.line(self.buffer.cursor.row).to_string();
        let text = if line.ends_with('\n') {
            line
        } else {
            format!("{}\n", line)
        };
        self.store_yank(text, true);
        self.message = String::from("Copied line to clipboard");
    }

    /// Paste from system clipboard (Cmd+V / Ctrl+V style) into the buffer.
    pub fn clipboard_paste(&mut self) {
        // Force system clipboard path
        self.registers.select('+');
        if self.mode == Mode::Insert {
            if let Some(val) = self.registers.load_for_put() {
                self.push_undo();
                for c in val.text.chars() {
                    if c == '\n' {
                        self.buffer.insert_newline_with_indent(false);
                    } else if c != '\r' {
                        self.buffer.insert_char(c);
                    }
                }
                self.update_scroll();
                self.message = String::from("Pasted from clipboard");
            } else {
                self.message = String::from("Clipboard empty");
            }
        } else {
            // Normal / Visual: put after (and leave insert if visual was replaced)
            if matches!(self.mode, Mode::Visual | Mode::VisualLine) {
                self.delete_selection();
            }
            self.registers.select('+');
            self.paste();
            self.message = String::from("Pasted from clipboard");
        }
    }

    /// Insert pasted text at the cursor verbatim (no auto-indent — a bracketed
    /// paste from the outer terminal should land exactly as-is). Used by the
    /// TUI's `Event::Paste` handler in editor Insert mode.
    pub fn paste_text_at_cursor(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        self.push_undo();
        let clean = text.replace('\r', "");
        self.buffer.insert_str(&clean);
        self.update_scroll();
        self.sync_lsp_document();
        self.message = String::from("Pasted");
    }

    /// Select entire buffer (Ctrl+A / context menu).
    pub fn select_all(&mut self) {
        let last = self.buffer.line_count().saturating_sub(1);
        let end_col = self.buffer.line(last).chars().count();
        self.visual_anchor = Some(Position::new(0, 0));
        self.buffer.cursor = Position::new(last, end_col);
        self.mode = Mode::Visual;
        self.completions.deactivate();
        self.message = String::from("-- VISUAL -- select all");
    }

    /// Open editor right-click context menu at screen coords.
    pub fn open_editor_ctx(&mut self, x: u16, y: u16) {
        let mut items = vec![
            EditorCtxItem::Cut,
            EditorCtxItem::Copy,
            EditorCtxItem::Paste,
            EditorCtxItem::SelectAll,
            EditorCtxItem::Undo,
            EditorCtxItem::Redo,
        ];
        if self.filename.is_some() {
            items.push(EditorCtxItem::GoToDefinition);
            items.push(EditorCtxItem::FormatDocument);
        }
        items.push(EditorCtxItem::CommandPalette);
        self.editor_ctx = Some(EditorContextMenu {
            x,
            y,
            sel: 0,
            items,
        });
        self.message = "Menu · j/k · Enter · Esc".into();
    }

    pub fn close_editor_ctx(&mut self) {
        self.editor_ctx = None;
    }

    /// Run selected editor context-menu action.
    pub fn run_editor_ctx_action(&mut self) -> Result<String, String> {
        let menu = self
            .editor_ctx
            .clone()
            .ok_or_else(|| "No menu".to_string())?;
        let item = *menu
            .items
            .get(menu.sel)
            .ok_or_else(|| "No item".to_string())?;
        self.editor_ctx = None;
        match item {
            EditorCtxItem::Cut => {
                if matches!(self.mode, Mode::Visual | Mode::VisualLine | Mode::VisualBlock) {
                    if self.mode == Mode::VisualBlock {
                        self.delete_block();
                    } else {
                        self.delete_selection();
                    }
                    Ok("Cut".into())
                } else {
                    self.delete_line();
                    Ok(self.message.clone())
                }
            }
            EditorCtxItem::Copy => {
                self.clipboard_copy();
                Ok(self.message.clone())
            }
            EditorCtxItem::Paste => {
                self.clipboard_paste();
                Ok(self.message.clone())
            }
            EditorCtxItem::SelectAll => {
                self.select_all();
                Ok("Select all".into())
            }
            EditorCtxItem::Undo => {
                self.undo();
                Ok(self.message.clone())
            }
            EditorCtxItem::Redo => {
                self.redo();
                Ok(self.message.clone())
            }
            EditorCtxItem::GoToDefinition => {
                let path = self
                    .filename
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .ok_or_else(|| "No file".to_string())?;
                let c = self.buffer.cursor();
                self.push_jump();
                self.sync_lsp_document();
                self.lsp.request_definition(&path, c.row, c.col);
                Ok("Requested definition…".into())
            }
            EditorCtxItem::FormatDocument => {
                self.format_document();
                Ok(self.message.clone())
            }
            EditorCtxItem::CommandPalette => {
                self.open_command_palette();
                Ok("Command palette".into())
            }
        }
    }

    /// Snapshot current location for jumplist (call before big moves).
    pub fn push_jump(&mut self) {
        self.jumps.push(Jump {
            pos: self.buffer.cursor(),
            scroll: self.scroll,
            path: self.filename.clone(),
        });
    }

    pub fn jump_back(&mut self) {
        let current = Jump {
            pos: self.buffer.cursor(),
            scroll: self.scroll,
            path: self.filename.clone(),
        };
        if let Some(j) = self.jumps.back(current) {
            self.apply_jump(j);
            self.message = String::from("Jump ←");
        } else {
            self.message = String::from("Already at oldest jump");
        }
    }

    pub fn jump_forward(&mut self) {
        if let Some(j) = self.jumps.forward() {
            self.apply_jump(j);
            self.message = String::from("Jump →");
        } else {
            self.message = String::from("Already at newest jump");
        }
    }

    fn apply_jump(&mut self, j: Jump) {
        // Switch buffer if path differs and is open
        if let Some(ref path) = j.path {
            if self.filename.as_ref() != Some(path) {
                let path_str = path.display().to_string();
                // Prefer existing tab without re-pushing jump
                self.open_new_tab(&path_str);
            }
        }
        self.buffer.cursor = j.pos;
        self.buffer.clamp_col();
        self.scroll = j.scroll;
        self.update_scroll();
    }

    pub fn set_mark(&mut self, name: char) {
        if self.marks.set(name, self.buffer.cursor(), self.filename.clone()) {
            self.message = format!("Mark '{}' set", name);
        } else {
            self.message = String::from("Invalid mark (use a-z)");
        }
        self.pending_mark_set = false;
    }

    pub fn jump_to_mark(&mut self, name: char, linewise: bool) {
        self.pending_mark_jump = None;
        let Some(mark) = self.marks.get(name).cloned() else {
            self.message = format!("Mark '{}' not set", name);
            return;
        };
        self.push_jump();
        if let Some(ref path) = mark.path {
            if self.filename.as_ref() != Some(path) {
                self.open_new_tab(&path.display().to_string());
            }
        }
        self.buffer.cursor = mark.pos;
        if linewise {
            self.buffer.move_to_first_non_blank();
        }
        self.buffer.clamp_col();
        self.update_scroll();
        self.message = format!("Jump to '{}'", name);
    }

    pub fn record_find(&mut self, kind: FindKind, forward: bool, ch: char) {
        self.last_find = Some(LastFind { ch, kind, forward });
    }

    pub fn repeat_find(&mut self, reverse: bool) {
        let Some(lf) = self.last_find else {
            self.message = String::from("No previous f/t");
            return;
        };
        let (kind, forward, ch) = lf.repeat(reverse);
        match (kind, forward) {
            (FindKind::Find, true) => self.buffer.find_char_forward(ch),
            (FindKind::Find, false) => self.buffer.find_char_backward(ch),
            (FindKind::Till, true) => self.buffer.till_char_forward(ch),
            (FindKind::Till, false) => self.buffer.till_char_backward(ch),
        }
        self.update_scroll();
    }

    pub fn clear_operator_pending(&mut self) {
        self.pending_operator = None;
        self.pending_to_mod = None;
        self.pending_key = None;
        self.pending_hints.clear();
        self.which_key.clear();
    }

    pub fn begin_operator(&mut self, op: Operator) {
        self.pending_operator = Some(op);
        self.pending_to_mod = None;
        self.pending_key = None;
        let name = match op {
            Operator::Delete => "d",
            Operator::Change => "c",
            Operator::Yank => "y",
        };
        let hints = match op {
            Operator::Delete => crate::which_key::as_hints(crate::which_key::map_operator_delete()),
            Operator::Change => crate::which_key::as_hints(crate::which_key::map_operator_change()),
            Operator::Yank => crate::which_key::as_hints(crate::which_key::map_operator_yank()),
        };
        self.begin_chord(name, hints);
        self.message = format!("-- {} --", name);
    }

    /// Replay last change (`.` command).
    pub fn repeat_last_change(&mut self) {
        let Some(change) = self.last_change.clone() else {
            self.message = String::from("No change to repeat");
            return;
        };
        match change {
            LastChange::Operator { op, motion, count } => {
                self.apply_operator_motion(op, motion, count);
            }
            LastChange::TextObject { op, obj, count } => {
                self.apply_operator_textobject(op, obj, count);
            }
            LastChange::DeleteChar { count } => {
                self.push_undo();
                for _ in 0..count.max(1) {
                    if self.buffer.cursor.col < self.buffer.current_line_len() {
                        self.buffer.delete_char_at_cursor();
                    }
                }
            }
            LastChange::ReplaceChar { ch } => {
                self.push_undo();
                self.buffer.replace_char(ch);
            }
        }
        self.message = String::from("Repeated");
    }

    pub fn goto_line(&mut self, line_1based: usize) {
        self.push_jump();
        let target = line_1based.saturating_sub(1).min(self.buffer.line_count().saturating_sub(1));
        self.buffer.cursor.row = target;
        self.buffer.move_to_line_start();
        self.update_scroll();
        self.message = format!("Line {}", target + 1);
    }

    pub fn search_word_under_cursor_backward(&mut self) {
        let word = self.word_under_cursor();
        if word.is_empty() {
            self.message = String::from("No word under cursor");
            return;
        }
        self.push_jump();
        self.search_pattern = Some(word.clone());
        self.search_forward = false;
        self.recompute_search(&word, true);
        if self.search_matches.len() > 1 {
            self.search_prev();
        } else if self.search_matches.is_empty() {
            self.message = format!("Pattern not found: {}", word);
        } else {
            self.message = format!("?{}/  1/1", word);
        }
    }

    pub fn quit(&mut self) {
        // Persist or discard undo history for every open file (undo_caching).
        self.save_state_to_tab();
        let caching = self.undo_caching;
        for tab in &mut self.buffers {
            if tab.filename.is_some() {
                let text = tab.buffer.text();
                tab.undo_stack.finish(caching, &text);
            }
        }
        // Detached so quitting is instant; the hook keeps running after exit.
        crate::hooks::run_hooks_detached(
            &self.hooks,
            crate::hooks::HookEvent::Quit,
            self.filename.as_deref(),
        );
        self.save_session();
        self.running = false;
    }

    pub fn enter_insert(&mut self) {
        self.push_undo();
        self.visual_anchor = None;
        self.mode = Mode::Insert;
        self.message = String::from("-- INSERT --");
    }

    pub fn enter_normal(&mut self) {
        self.mode = Mode::Normal;
        self.visual_anchor = None;
        self.pending_key = None;
        self.pending_ft = None;
        self.pending_hints.clear();
        self.count = None;
        self.pending_register = false;
        self.pending_mark_set = false;
        self.pending_mark_jump = None;
        self.clear_operator_pending();
        self.completions.deactivate();
        self.palette.close();
        self.hover_text = None;
        // Keep multi-cursors when returning to normal (Esc once clears them)
        self.message = String::new();
    }

    pub fn clear_multi_cursors(&mut self) {
        if self.multi.is_active() {
            self.multi.clear();
            self.message = "Multi-cursor cleared".into();
        }
    }

    /// Ctrl+D — add next occurrence of word under primary cursor.
    pub fn multi_cursor_add_next(&mut self) {
        let primary = self.buffer.cursor();
        let Some((_, end, word)) = crate::multi_cursor::word_at(&self.buffer, primary) else {
            self.message = "No word under cursor".into();
            return;
        };
        // Search after the last multi-cursor (or after primary word)
        let from = self
            .multi
            .extras
            .last()
            .copied()
            .map(|p| Position {
                row: p.row,
                col: p.col + word.chars().count(),
            })
            .unwrap_or(end);
        if let Some(pos) = crate::multi_cursor::find_next(&self.buffer, &word, from) {
            self.multi.add(primary, pos);
            self.message = format!("cursors: {}", self.multi.count(primary));
        } else {
            self.message = "No more matches".into();
        }
    }

    /// Ctrl+Alt+Down / `]c` — column cursor below primary.
    pub fn multi_cursor_add_below(&mut self) {
        let p = self.buffer.cursor();
        if p.row + 1 >= self.buffer.line_count() {
            self.message = "No line below".into();
            return;
        }
        let mut np = Position {
            row: p.row + 1,
            col: p.col,
        };
        let max = self.buffer.line(np.row).chars().count();
        if np.col > max {
            np.col = max;
        }
        self.multi.add(p, np);
        self.message = format!("cursors: {}", self.multi.count(p));
    }

    pub fn multi_cursor_add_above(&mut self) {
        let p = self.buffer.cursor();
        if p.row == 0 {
            self.message = "No line above".into();
            return;
        }
        let mut np = Position {
            row: p.row - 1,
            col: p.col,
        };
        let max = self.buffer.line(np.row).chars().count();
        if np.col > max {
            np.col = max;
        }
        self.multi.add(p, np);
        self.message = format!("cursors: {}", self.multi.count(p));
    }

    /// Apply insert-mode edit at every cursor (bottom→top so offsets stay valid).
    pub fn multi_insert_char(&mut self, ch: char) {
        if !self.multi.is_active() {
            self.buffer.insert_char(ch);
            return;
        }
        let primary = self.buffer.cursor();
        let mut all = self.multi.all(primary);
        all.sort_by(|a, b| b.row.cmp(&a.row).then(b.col.cmp(&a.col)));
        let mut updated = Vec::with_capacity(all.len());
        for pos in all {
            self.buffer.cursor = pos;
            self.buffer.insert_char(ch);
            updated.push(self.buffer.cursor);
        }
        updated.sort_by(|a, b| a.row.cmp(&b.row).then(a.col.cmp(&b.col)));
        updated.dedup();
        if let Some(first) = updated.first().copied() {
            self.buffer.cursor = first;
            self.multi.set_from_all(updated);
        }
        self.multi.clamp_all(&self.buffer);
        self.modified = true;
    }

    pub fn multi_backspace(&mut self) {
        if !self.multi.is_active() {
            self.buffer.backspace();
            return;
        }
        let primary = self.buffer.cursor();
        let mut all = self.multi.all(primary);
        all.sort_by(|a, b| b.row.cmp(&a.row).then(b.col.cmp(&a.col)));
        let mut updated = Vec::with_capacity(all.len());
        for pos in all {
            self.buffer.cursor = pos;
            self.buffer.backspace();
            updated.push(self.buffer.cursor);
        }
        updated.sort_by(|a, b| a.row.cmp(&b.row).then(a.col.cmp(&b.col)));
        updated.dedup();
        if let Some(first) = updated.first().copied() {
            self.buffer.cursor = first;
            self.multi.set_from_all(updated);
        }
        self.multi.clamp_all(&self.buffer);
        self.modified = true;
    }

    pub fn multi_delete_char(&mut self) {
        if !self.multi.is_active() {
            self.buffer.delete_char_at_cursor();
            return;
        }
        let primary = self.buffer.cursor();
        let mut all = self.multi.all(primary);
        all.sort_by(|a, b| b.row.cmp(&a.row).then(b.col.cmp(&a.col)));
        let mut updated = Vec::with_capacity(all.len());
        for pos in all {
            self.buffer.cursor = pos;
            self.buffer.delete_char_at_cursor();
            updated.push(self.buffer.cursor);
        }
        updated.sort_by(|a, b| a.row.cmp(&b.row).then(a.col.cmp(&b.col)));
        updated.dedup();
        if let Some(first) = updated.first().copied() {
            self.buffer.cursor = first;
            self.multi.set_from_all(updated);
        }
        self.multi.clamp_all(&self.buffer);
        self.modified = true;
    }

    pub fn multi_move_each(&mut self, f: impl Fn(&mut crate::buffer::Buffer)) {
        if !self.multi.is_active() {
            f(&mut self.buffer);
            return;
        }
        let primary = self.buffer.cursor();
        let all = self.multi.all(primary);
        let mut updated = Vec::with_capacity(all.len());
        for pos in all {
            self.buffer.cursor = pos;
            f(&mut self.buffer);
            updated.push(self.buffer.cursor);
        }
        updated.sort_by(|a, b| a.row.cmp(&b.row).then(a.col.cmp(&b.col)));
        updated.dedup();
        if let Some(first) = updated.first().copied() {
            self.buffer.cursor = first;
            self.multi.set_from_all(updated);
        }
        self.multi.clamp_all(&self.buffer);
    }

    pub fn multi_newline(&mut self) {
        if !self.multi.is_active() {
            let row = self.buffer.cursor.row;
            let trimmed = self.buffer.line(row).trim_end().to_string();
            let ends_block = trimmed.ends_with('{')
                || trimmed.ends_with('[')
                || trimmed.ends_with('(')
                || trimmed.ends_with(':')
                || trimmed.ends_with("=>")
                || trimmed.ends_with("->");
            let ends_close = trimmed.ends_with(')') || trimmed.ends_with(']');
            self.buffer
                .insert_newline_with_indent(ends_block && !ends_close);
            if let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) {
                // Newline splits after `row` → shift BPs on later lines +1
                self.dap.shift_breakpoints(&path, row, 1);
            }
            return;
        }
        let primary = self.buffer.cursor();
        let mut all = self.multi.all(primary);
        all.sort_by(|a, b| b.row.cmp(&a.row).then(b.col.cmp(&a.col)));
        let mut updated = Vec::with_capacity(all.len());
        for pos in all {
            self.buffer.cursor = pos;
            let trimmed = self.buffer.line(self.buffer.cursor.row).trim_end().to_string();
            let ends_block = trimmed.ends_with('{')
                || trimmed.ends_with('[')
                || trimmed.ends_with('(')
                || trimmed.ends_with(':')
                || trimmed.ends_with("=>")
                || trimmed.ends_with("->");
            let ends_close = trimmed.ends_with(')') || trimmed.ends_with(']');
            self.buffer
                .insert_newline_with_indent(ends_block && !ends_close);
            updated.push(self.buffer.cursor);
        }
        updated.sort_by(|a, b| a.row.cmp(&b.row).then(a.col.cmp(&b.col)));
        updated.dedup();
        if let Some(first) = updated.first().copied() {
            self.buffer.cursor = first;
            self.multi.set_from_all(updated);
        }
        self.multi.clamp_all(&self.buffer);
        self.modified = true;
    }

    pub fn open_file_palette(&mut self) {
        let root = self
            .filename
            .as_ref()
            .and_then(|p| p.parent().map(|d| d.to_path_buf()))
            .unwrap_or_else(|| env::current_dir().unwrap_or_default());
        self.palette.open_files(&root);
        self.mode = Mode::Palette;
        self.message = String::from("Open file — type to filter, Enter open, Esc cancel");
    }

    pub fn open_command_palette(&mut self) {
        self.palette.open_commands();
        self.mode = Mode::Palette;
        self.message = String::from("Commands — type to filter, Enter run, Esc cancel");
    }

    pub fn open_problems_palette(&mut self) {
        self.palette.open_problems(&self.lsp.diagnostics);
        self.mode = Mode::Palette;
        self.message = format!("Problems — {} items", self.lsp.diagnostics.len());
    }

    pub fn execute_palette_selection(&mut self) {
        let action = self.palette.selected_action().cloned();
        self.palette.close();
        self.mode = Mode::Normal;
        let Some(action) = action else {
            return;
        };
        match action {
            PaletteAction::OpenFile(path) => {
                self.open_new_tab(&path.display().to_string());
            }
            PaletteAction::Goto { row, col } => {
                self.push_jump();
                self.buffer.cursor.row = row.min(self.buffer.line_count().saturating_sub(1));
                self.buffer.cursor.col = col;
                self.buffer.clamp_col();
                self.update_scroll();
                self.message = format!("Jumped to {}:{}", row + 1, col + 1);
            }
            PaletteAction::GotoFile { path, row, col } => {
                self.goto_file_location(&path.display().to_string(), row, col);
            }
            PaletteAction::CodeAction(i) => {
                self.apply_code_action(i);
            }
            PaletteAction::Command(id) => self.run_palette_command(id),
        }
    }

    /// Jump to path:line:col (opens tab if needed).
    pub fn goto_file_location(&mut self, path: &str, row: usize, col: usize) {
        self.push_jump();
        let cur = self
            .filename
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        if cur != path {
            self.open_new_tab(path);
        }
        self.buffer.cursor.row = row.min(self.buffer.line_count().saturating_sub(1));
        let line = self.buffer.line(self.buffer.cursor.row);
        // col may already be char index from search; clamp only
        self.buffer.cursor.col = col.min(line.chars().count());
        self.buffer.clamp_col();
        self.update_scroll();
        self.sync_split_from_active();
        self.message = format!("{}:{}:{}", path, row + 1, col + 1);
    }

    pub fn project_root(&self) -> std::path::PathBuf {
        if let Some(ref f) = self.filename {
            if let Some(parent) = f.parent() {
                // walk up for Cargo.toml / package.json / .git
                let mut cur = parent.to_path_buf();
                loop {
                    if cur.join("Cargo.toml").exists()
                        || cur.join("package.json").exists()
                        || cur.join(".git").exists()
                        || cur.join("go.mod").exists()
                        || cur.join("pyproject.toml").exists()
                    {
                        return cur;
                    }
                    if !cur.pop() {
                        break;
                    }
                }
                return parent.to_path_buf();
            }
        }
        std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
    }

    pub fn open_workspace_search(&mut self) {
        let root = self.project_root();
        self.workspace_search.open_at(root);
        self.mode = Mode::WorkspaceSearch;
        self.message = String::from("Find in files — type pattern, Enter open hit");
    }

    pub fn open_document_symbols(&mut self) {
        let path = self.filename.as_ref().map(|p| p.display().to_string());
        if let Some(path) = path {
            self.sync_lsp_document();
            self.lsp.request_document_symbols(&path);
            self.message = String::from("Loading document symbols…");
        } else {
            self.message = String::from("No file for symbols");
        }
    }

    pub fn open_workspace_symbols(&mut self) {
        if !self.lsp.server_running {
            self.message = String::from("LSP not running");
            return;
        }
        self.sync_lsp_document();
        self.lsp.request_workspace_symbols("");
        self.message = String::from("Loading workspace symbols…");
    }

    pub fn apply_pending_symbols(&mut self) {
        let symbols = std::mem::take(&mut self.lsp.pending_symbols);
        if symbols.is_empty() {
            return;
        }
        let cur_path = self
            .filename
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        let items: Vec<crate::palette::PaletteItem> = symbols
            .into_iter()
            .map(|s| {
                let path = if s.path.is_empty() {
                    cur_path.clone()
                } else {
                    s.path.clone()
                };
                let detail = if s.detail.is_empty() {
                    format!("{}  L{}", s.kind, s.row + 1)
                } else {
                    format!("{}  {}  L{}", s.kind, s.detail, s.row + 1)
                };
                crate::palette::PaletteItem {
                    label: s.name,
                    detail,
                    action: PaletteAction::GotoFile {
                        path: std::path::PathBuf::from(path),
                        row: s.row,
                        col: s.col,
                    },
                }
            })
            .collect();
        self.palette.open_symbols(items);
        self.mode = Mode::Palette;
        self.message = format!("Symbols — {} items", self.palette.items.len());
    }

    pub fn request_peek_definition(&mut self) {
        let path = self.filename.as_ref().map(|p| p.display().to_string());
        if let Some(path) = path {
            self.sync_lsp_document();
            let c = self.buffer.cursor();
            self.lsp.request_peek_definition(&path, c.row, c.col);
            self.message = String::from("Peek definition…");
        }
    }

    pub fn open_peek_at(&mut self, path: &str, row: usize, col: usize) {
        let fallback = if self.filename.as_ref().map(|p| p.display().to_string()).as_deref()
            == Some(path)
        {
            Some(self.buffer.text())
        } else {
            None
        };
        self.peek.open_at(
            std::path::PathBuf::from(path),
            row,
            col,
            fallback.as_deref(),
            8,
        );
        self.message = format!(
            "Peek {} — Enter open · Esc dismiss",
            self.peek.path.display()
        );
    }

    pub fn promote_peek(&mut self) {
        if !self.peek.open {
            return;
        }
        let path = self.peek.path.display().to_string();
        let row = self.peek.target_row;
        let col = self.peek.target_col;
        self.peek.close();
        self.goto_file_location(&path, row, col);
    }

    // ── Splits ──────────────────────────────────────────

    pub fn split_vertical(&mut self) {
        self.open_split_kind(crate::split::SplitKind::Vertical, "Vertical");
    }

    pub fn split_horizontal(&mut self) {
        self.open_split_kind(crate::split::SplitKind::Horizontal, "Horizontal");
    }

    fn open_split_kind(&mut self, kind: crate::split::SplitKind, label: &str) {
        use crate::split::SplitAdd;
        self.save_state_to_tab();
        self.sync_split_from_active();
        let cur = (self.buffer.cursor.row, self.buffer.cursor.col);
        let r = self
            .split
            .open_split(kind, self.current_buffer, self.scroll, cur);
        self.message = match r {
            SplitAdd::Opened => {
                format!("{label} split · Ctrl+W w cycle · Ctrl+W q close")
            }
            SplitAdd::Added => format!(
                "Pane added ({}) · Ctrl+W w cycle · Ctrl+W q close",
                self.split.pane_count()
            ),
            SplitAdd::Full => format!("Max {} panes", crate::split::MAX_PANES),
            SplitAdd::MixedKind => {
                "Already split the other way — Ctrl+W q panes first".into()
            }
        };
    }

    /// Vim `C-w q`: close the *focused* pane; neighbors survive (the split
    /// collapses once one pane remains).
    pub fn close_split(&mut self) {
        if !self.split.is_split() {
            return;
        }
        let closed = self
            .split
            .focus
            .min(self.split.panes.len().saturating_sub(1));
        // Pane terminal dies with its pane; higher indices shift down.
        if self.terminal.open && self.terminal.full_panel {
            match self.terminal.pane_bound {
                Some(b) if b == closed => {
                    self.terminal.open = false;
                    self.terminal.full_panel = false;
                    self.terminal.pane_bound = None;
                    self.terminal.close_confirm = false;
                    self.terminal.shutdown();
                }
                Some(b) if b > closed => {
                    self.terminal.pane_bound = Some(b - 1);
                }
                _ => {}
            }
        }
        let survivor = self.split.remove_focused();
        if self.split.is_split() {
            self.apply_focused_pane();
            self.message = format!("Pane closed · {} left", self.split.pane_count());
            return;
        }
        // Collapsed to a single view: adopt the survivor snapshot.
        if self.terminal.pane_bound.is_some() {
            self.terminal.pane_bound = None; // continues as the full-main window
        }
        if let Some(p) = survivor {
            if p.tab_index != self.current_buffer && p.tab_index < self.buffers.len() {
                self.save_state_to_tab();
                self.current_buffer = p.tab_index;
                self.restore_state_from_tab();
                self.lsp_restart_for_current();
                self.refresh_git();
            }
            let max_row = self.buffer.line_count().saturating_sub(1);
            self.buffer.cursor.row = p.cursor.0.min(max_row);
            self.buffer.cursor.col = p.cursor.1;
            self.buffer.clamp_col();
            self.scroll = p.scroll;
            self.update_scroll();
        }
        self.message = String::from("Pane closed");
    }

    /// Vim `C-w h/j/k/l`: directional focus along the split axis (steps one
    /// pane per press; works for any pane count).
    pub fn focus_dir(&mut self, dir: char) {
        if !self.split.is_split() {
            return;
        }
        let vertical = self.split.kind == crate::split::SplitKind::Vertical;
        let delta: isize = match (vertical, dir) {
            (true, 'h') | (false, 'k') => -1,
            (true, 'l') | (false, 'j') => 1,
            _ => return, // off-axis — splits are single-direction
        };
        let n = self.split.panes.len() as isize;
        let cur = self.split.focus.min(self.split.panes.len().saturating_sub(1)) as isize;
        let next = (cur + delta).clamp(0, n - 1) as usize;
        if next == cur as usize {
            return;
        }
        self.sync_split_from_active();
        self.split.set_focus(next);
        self.apply_focused_pane();
        self.message = format!("Pane {}", next + 1);
    }

    /// Persist active buffer scroll into the focused pane, then switch focus.
    pub fn focus_other_pane(&mut self) {
        if !self.split.is_split() {
            return;
        }
        self.sync_split_from_active();
        self.split.focus_other();
        self.apply_focused_pane();
        self.message = format!("Pane {}", self.split.focus + 1);
    }

    pub fn focus_pane(&mut self, idx: usize) {
        if !self.split.is_split() {
            return;
        }
        self.sync_split_from_active();
        self.split.set_focus(idx);
        self.apply_focused_pane();
    }

    /// Write current scroll/tab into focused pane slot.
    pub fn sync_split_from_active(&mut self) {
        if !self.split.is_split() {
            return;
        }
        let cur = (self.buffer.cursor.row, self.buffer.cursor.col);
        let p = self.split.focused_pane_mut();
        p.tab_index = self.current_buffer;
        p.scroll = self.scroll;
        p.cursor = cur;
    }

    /// Load focused pane's tab into the active editor.
    pub fn apply_focused_pane(&mut self) {
        if !self.split.is_split() {
            return;
        }
        let pane = self.split.focused_pane().clone();
        if pane.tab_index != self.current_buffer && pane.tab_index < self.buffers.len() {
            self.save_state_to_tab();
            self.current_buffer = pane.tab_index;
            self.restore_state_from_tab();
            self.lsp_restart_for_current();
            self.refresh_git();
        }
        // Per-pane cursor (clamped — the buffer may have changed underneath).
        let max_row = self.buffer.line_count().saturating_sub(1);
        self.buffer.cursor.row = pane.cursor.0.min(max_row);
        self.buffer.cursor.col = pane.cursor.1;
        self.buffer.clamp_col();
        self.scroll = pane.scroll;
        self.update_scroll();
    }

    /// Assign a different tab to the focused pane (e.g. after gt in a split).
    pub fn sync_focused_pane_tab(&mut self) {
        if self.split.is_split() {
            let cur = (self.buffer.cursor.row, self.buffer.cursor.col);
            let p = self.split.focused_pane_mut();
            p.tab_index = self.current_buffer;
            p.scroll = self.scroll;
            p.cursor = cur;
        }
    }

    fn run_palette_command(&mut self, id: &str) {
        match id {
            "noop" => {}
            "save" => self.save_file(),
            "wq" => {
                self.save_file();
                if !self.modified {
                    self.quit();
                }
            }
            "quit" => {
                if self.modified {
                    self.message =
                        String::from("Unsaved changes. Use Save or Force quit.");
                } else {
                    self.quit();
                }
            }
            "quit!" => self.quit(),
            "explorer" => {
                if self.explorer.open {
                    self.explorer.close();
                } else {
                    self.explorer.toggle_at(self.filename.as_ref());
                    self.mode = Mode::Explorer;
                }
            }
            "scm" => self.toggle_scm(),
            "git" | "git_workbench" => self.open_git_workbench(),
            "settings" => self.open_settings(),
            "preview" => self.toggle_preview(),
            "terminal" => self.toggle_terminal_side(),
            "terminal_full" => self.toggle_terminal_full(),
            "xlc" => self.enter_xlc(None),
            "tab_next" => self.next_tab(),
            "tab_prev" => self.prev_tab(),
            "tab_close" => self.close_current_tab(),
            "problems" => self.open_problems_palette(),
            "files" => self.open_file_palette(),
            "workspace_find" => self.open_workspace_search(),
            "symbols" => self.open_document_symbols(),
            "workspace_symbols" => self.open_workspace_symbols(),
            "split_v" => self.split_vertical(),
            "split_h" => self.split_horizontal(),
            "split_close" => self.close_split(),
            "help" => {
                self.enter_xlc(None);
                self.xlc.input = "help".into();
                self.execute_xlc();
            }
            "lsp_def" => {
                let path = self.filename.as_ref().map(|p| p.display().to_string());
                if let Some(path) = path {
                    let c = self.buffer.cursor();
                    self.push_jump();
                    self.sync_lsp_document();
                    self.lsp.request_definition(&path, c.row, c.col);
                    self.message = String::from("Requested definition…");
                }
            }
            "lsp_peek" => self.request_peek_definition(),
            "format" => self.format_document(),
            "code_action" => self.request_code_actions(),
            id if id.starts_with("theme:") => {
                let name = &id[6..];
                if let Some(t) = theme::find(name) {
                    self.theme = t;
                    config::save_theme(t.name);
                    set_cursor_esc(t.cursor);
                    self.message = format!("Theme: {}", t.name);
                }
            }
            _ => {
                self.message = format!("Unknown command: {}", id);
            }
        }
    }

    pub fn diag_next(&mut self) {
        if self.lsp.diagnostics.is_empty() {
            self.message = String::from("No diagnostics");
            return;
        }
        let cur = self.buffer.cursor();
        let mut diags = self.lsp.diagnostics.clone();
        diags.sort_by_key(|d| (d.row, d.col_start));
        let next = diags
            .iter()
            .find(|d| d.row > cur.row || (d.row == cur.row && d.col_start > cur.col))
            .or_else(|| diags.first());
        if let Some(d) = next {
            self.push_jump();
            self.buffer.cursor.row = d.row;
            self.buffer.cursor.col = d.col_start;
            self.buffer.clamp_col();
            self.update_scroll();
            self.message = format!("[{:?}] {}", d.severity, d.message);
        }
    }

    pub fn diag_prev(&mut self) {
        if self.lsp.diagnostics.is_empty() {
            self.message = String::from("No diagnostics");
            return;
        }
        let cur = self.buffer.cursor();
        let mut diags = self.lsp.diagnostics.clone();
        diags.sort_by_key(|d| (d.row, d.col_start));
        let prev = diags
            .iter()
            .rev()
            .find(|d| d.row < cur.row || (d.row == cur.row && d.col_start < cur.col))
            .or_else(|| diags.last());
        if let Some(d) = prev {
            self.push_jump();
            self.buffer.cursor.row = d.row;
            self.buffer.cursor.col = d.col_start;
            self.buffer.clamp_col();
            self.update_scroll();
            self.message = format!("[{:?}] {}", d.severity, d.message);
        }
    }

    /// Jump to next git gutter change (from `git diff HEAD`).
    pub fn git_change_next(&mut self) {
        self.refresh_git();
        if self.git.signs.is_empty() {
            self.message = String::from("No git changes");
            return;
        }
        let cur = self.buffer.cursor.row;
        let mut rows: Vec<usize> = self.git.signs.keys().copied().collect();
        rows.sort_unstable();
        let next = rows.iter().copied().find(|r| *r > cur).or_else(|| rows.first().copied());
        if let Some(row) = next {
            self.push_jump();
            self.buffer.cursor.row = row;
            self.buffer.move_to_line_start();
            self.update_scroll();
            let sign = self.git.sign_at(row).map(|s| format!("{s:?}")).unwrap_or_default();
            self.message = format!("Git change · L{} · {sign}", row + 1);
        }
    }

    /// Jump to previous git gutter change.
    pub fn git_change_prev(&mut self) {
        self.refresh_git();
        if self.git.signs.is_empty() {
            self.message = String::from("No git changes");
            return;
        }
        let cur = self.buffer.cursor.row;
        let mut rows: Vec<usize> = self.git.signs.keys().copied().collect();
        rows.sort_unstable();
        let prev = rows
            .iter()
            .rev()
            .copied()
            .find(|r| *r < cur)
            .or_else(|| rows.last().copied());
        if let Some(row) = prev {
            self.push_jump();
            self.buffer.cursor.row = row;
            self.buffer.move_to_line_start();
            self.update_scroll();
            let sign = self.git.sign_at(row).map(|s| format!("{s:?}")).unwrap_or_default();
            self.message = format!("Git change · L{} · {sign}", row + 1);
        }
    }

    /// Force-reload current file from disk (discards local unsaved edits).
    pub fn reload_from_disk(&mut self) {
        let Some(path) = self.filename.clone() else {
            self.message = String::from("No file to reload");
            return;
        };
        let path_s = path.display().to_string();
        match std::fs::read_to_string(&path) {
            Ok(content) => {
                let cursor = self.buffer.cursor();
                let scroll = self.scroll;
                self.buffer = Buffer::from_string(&content);
                self.buffer.cursor.row =
                    cursor.row.min(self.buffer.line_count().saturating_sub(1));
                self.buffer.cursor.col = cursor.col;
                self.buffer.clamp_col();
                self.scroll = scroll.min(self.buffer.line_count().saturating_sub(1));
                self.modified = false;
                self.record_mtime();
                self.undo_stack = UndoStack::new();
                self.undo_stack.push(self.buffer.snapshot());
                if let Some(p) = self.filename.clone() {
                    let text = self.buffer.text();
                    self.undo_stack
                        .attach_file(&p, self.undo_caching, &text);
                }
                self.rebuild_folds();
                self.refresh_git();
                self.lsp_restart_for_current();
                self.sync_lsp_document();
                self.message = format!("↻ Reloaded {path_s}");
            }
            Err(e) => {
                self.message = format!("Reload failed: {e}");
            }
        }
    }

    /// Run a simple git remote command (fetch / pull / push) from workspace root.
    /// Network git ops run in the background (workbench runner + spinner);
    /// the result lands in the status line via `poll_loading` in the frontend.
    pub fn git_remote(&mut self, action: &str) {
        use crate::git_workbench::RemoteAction;
        if self.git_wb.root.is_none() {
            let hint = self.filename.as_deref();
            self.git_wb.root = crate::git_ops::find_git_root(hint);
        }
        if self.git_wb.root.is_none() {
            self.message = String::from("Not a git repository");
            return;
        }
        let act = match action {
            "fetch" => RemoteAction::Fetch,
            "pull" => RemoteAction::Pull,
            "push" => RemoteAction::Push,
            _ => {
                self.message = format!("unknown git action: {action}");
                return;
            }
        };
        self.message = self.git_wb.remote_action(act);
    }

    pub fn toggle_relative_number(&mut self) {
        self.relative_number = !self.relative_number;
        // Persist like theme changes so `SPC t r` survives restart.
        let mut cfg = config::load();
        cfg.relative_number = self.relative_number;
        config::save(&cfg);
        self.message = if self.relative_number {
            "relative_number on (saved)".into()
        } else {
            "relative_number off (saved)".into()
        };
    }

    pub fn toggle_inlay_hints(&mut self) {
        self.inlay_hints_enabled = !self.inlay_hints_enabled;
        self.message = if self.inlay_hints_enabled {
            "inlay hints on".into()
        } else {
            "inlay hints off".into()
        };
    }

    pub fn prompt_rename(&mut self) {
        self.enter_xlc(Some("Rename "));
    }

    /// Switch to tab index if it exists (0-based).
    pub fn goto_tab(&mut self, idx: usize) {
        if idx < self.buffers.len() {
            self.save_state_to_tab();
            self.current_buffer = idx;
            self.restore_state_from_tab();
            self.message = format!("Tab {}", idx + 1);
        } else {
            self.message = format!("No tab {}", idx + 1);
        }
    }

    pub fn request_hover(&mut self) {
        self.sync_lsp_document();
        if let Some(ref path) = self.filename {
            let c = self.buffer.cursor();
            self.lsp
                .request_hover(&path.display().to_string(), c.row, c.col);
            self.message = String::from("Hover…");
        }
    }

    /// Select word under cursor (double-click / `viw`-ish helper).
    pub fn select_word_under_cursor(&mut self) {
        if let Some(range) = ops::range_for_textobject(&self.buffer, TextObject::InnerWord) {
            self.visual_anchor = Some(range.start);
            self.buffer.cursor = Position::new(range.end.row, range.end.col.saturating_sub(1));
            self.mode = Mode::Visual;
            self.message = String::from("-- VISUAL --");
        }
    }

    pub fn enter_visual(&mut self) {
        self.mode = Mode::Visual;
        self.visual_anchor = Some(self.buffer.cursor());
        self.message = String::from("-- VISUAL --");
    }

    pub fn enter_visual_line(&mut self) {
        self.mode = Mode::VisualLine;
        self.visual_anchor = Some(self.buffer.cursor());
        self.message = String::from("-- VISUAL LINE --");
    }

    pub fn enter_visual_block(&mut self) {
        self.mode = Mode::VisualBlock;
        self.visual_anchor = Some(self.buffer.cursor());
        self.message = String::from("-- VISUAL BLOCK --");
    }

    pub fn enter_xlc(&mut self, prompt: Option<&str>) {
        self.mode = Mode::XlcInput;
        self.xlc.open_panel(prompt);
    }

    pub fn close_xlc(&mut self) {
        self.xlc.close();
        self.mode = Mode::Normal;
    }

    /// Start incremental `/` (forward) or `?` (backward) search.
    pub fn enter_search(&mut self) {
        self.enter_search_dir(true);
    }

    pub fn enter_search_backward(&mut self) {
        self.enter_search_dir(false);
    }

    fn enter_search_dir(&mut self, forward: bool) {
        self.completions.deactivate();
        self.pending_key = None;
        self.pending_ft = None;
        self.pending_hints.clear();
        self.count = None;
        self.clear_operator_pending();
        self.search_forward = forward;
        self.search_origin = Some(self.buffer.cursor());
        self.search_scroll_origin = self.scroll;
        self.search_pattern_backup = self.search_pattern.clone();
        self.search_input.clear();
        self.mode = Mode::Search;
        self.message = if forward {
            String::from("Search / — Enter accept · Esc cancel · ↑↓ cycle")
        } else {
            String::from("Search ? — reverse · Enter accept · Esc cancel")
        };
    }

    /// Commit live search input as the new pattern and leave Search mode.
    pub fn commit_search(&mut self) {
        let pattern = self.search_input.clone();
        if pattern.is_empty() {
            // Empty Enter reuses previous pattern (vim-like).
            if let Some(prev) = self.search_pattern.clone() {
                self.push_jump();
                self.recompute_search(&prev, false);
                if self.search_matches.is_empty() {
                    self.message = format!("Pattern not found: {}", prev);
                } else {
                    self.search_next();
                    self.message = format!(
                        "/{}/  {}/{}",
                        prev,
                        self.search_current + 1,
                        self.search_matches.len()
                    );
                }
            } else {
                self.message = String::from("No previous search pattern");
            }
        } else {
            self.push_jump();
            self.search_pattern = Some(pattern.clone());
            self.recompute_search(&pattern, true);
            if self.search_matches.is_empty() {
                self.message = format!("Pattern not found: {}", pattern);
            } else {
                let slash = if self.search_forward { '/' } else { '?' };
                self.message = format!(
                    "{}{}/  {}/{}",
                    slash,
                    pattern,
                    self.search_current + 1,
                    self.search_matches.len()
                );
            }
        }
        self.search_input.clear();
        self.search_origin = None;
        self.search_pattern_backup = None;
        self.mode = Mode::Normal;
    }

    /// Cancel search: restore cursor, restore previous committed pattern.
    pub fn cancel_search(&mut self) {
        if let Some(origin) = self.search_origin.take() {
            self.buffer.cursor = origin;
            self.scroll = self.search_scroll_origin;
        }
        self.search_input.clear();
        self.search_pattern = self.search_pattern_backup.take();
        self.search_matches.clear();
        self.search_current = 0;
        if let Some(ref pat) = self.search_pattern.clone() {
            // Rebuild match list for n/N without moving the restored cursor.
            self.collect_matches(pat);
            let cur = self.buffer.cursor();
            if let Some(idx) = self
                .search_matches
                .iter()
                .position(|p| p.row == cur.row && p.col == cur.col)
            {
                self.search_current = idx;
            }
        }
        self.mode = Mode::Normal;
        self.message = String::from("Search cancelled");
    }

    /// Update live query while typing in Search mode.
    pub fn update_search_input(&mut self) {
        let pattern = self.search_input.clone();
        if pattern.is_empty() {
            self.search_matches.clear();
            self.search_current = 0;
            if let Some(origin) = self.search_origin {
                self.buffer.cursor = origin;
                self.scroll = self.search_scroll_origin;
            }
            self.message = String::from("Search — type to filter, Enter accept, Esc cancel");
            return;
        }
        self.recompute_search(&pattern, true);
        if self.search_matches.is_empty() {
            self.message = format!("/{}/  0 matches", pattern);
        } else {
            self.message = format!(
                "/{}/  {}/{}",
                pattern,
                self.search_current + 1,
                self.search_matches.len()
            );
        }
    }

    /// Pattern currently used for highlighting (live input or committed).
    pub fn active_search_pattern(&self) -> Option<&str> {
        if self.mode == Mode::Search {
            if self.search_input.is_empty() {
                None
            } else {
                Some(self.search_input.as_str())
            }
        } else {
            self.search_pattern.as_deref()
        }
    }

    pub fn search_pattern_len_chars(&self) -> usize {
        self.active_search_pattern()
            .map(|p| p.chars().count())
            .unwrap_or(0)
    }

    /// Matches on `row` plus the global index of the first one. `search_matches`
    /// is built in row order by `collect_matches`, so this binary-searches the
    /// row's slice instead of the renderer scanning every match for every
    /// character of every visible line. The base index lets callers keep
    /// comparing against `search_current` (a global index).
    pub fn search_matches_row_slice(&self, row: usize) -> (usize, &[Position]) {
        let lo = self.search_matches.partition_point(|p| p.row < row);
        let hi = self.search_matches.partition_point(|p| p.row <= row);
        (lo, &self.search_matches[lo..hi])
    }

    pub fn is_current_search_match(&self, row: usize, col: usize) -> bool {
        self.search_matches
            .get(self.search_current)
            .map(|p| p.row == row && p.col == col)
            .unwrap_or(false)
    }

    pub fn selected_range(&self) -> Option<(Position, Position)> {
        let anchor = self.visual_anchor?;
        let cursor = self.buffer.cursor();
        if self.mode == Mode::VisualLine {
            let (start_row, end_row) = if anchor.row <= cursor.row {
                (anchor.row, cursor.row)
            } else {
                (cursor.row, anchor.row)
            };
            Some((
                Position::new(start_row, 0),
                Position::new(end_row, self.buffer.line(end_row).chars().count()),
            ))
        } else if self.mode == Mode::VisualBlock {
            // For highlight compatibility, return unordered corners; UI uses block_range
            if anchor.row < cursor.row || (anchor.row == cursor.row && anchor.col <= cursor.col) {
                Some((anchor, cursor))
            } else {
                Some((cursor, anchor))
            }
        } else if anchor.row < cursor.row || (anchor.row == cursor.row && anchor.col <= cursor.col)
        {
            Some((anchor, cursor))
        } else {
            Some((cursor, anchor))
        }
    }

    pub fn execute_xlc(&mut self) {
        let cmd = self.xlc.execute();
        match cmd {
            XlcCmd::Save => self.save_file(),
            XlcCmd::SaveAs(path) => {
                self.filename = Some(PathBuf::from(&path));
                self.save_file();
            }
            XlcCmd::SaveAndQuit => {
                self.save_file();
                if !self.modified {
                    self.quit();
                } else {
                    self.xlc.add_output("Save failed; not quitting.");
                }
            }
            XlcCmd::Quit => {
                if self.modified {
                    self.message = String::from("Unsaved changes. Use :w first or :q! to force quit.");
                    self.xlc.add_output("Unsaved changes. Use w to save first, or q! to force quit.");
                } else {
                    self.quit();
                }
            }
            XlcCmd::ForceQuit => self.quit(),
            XlcCmd::Open(path) => self.open_in_place(&path),
            XlcCmd::Move(dest) => self.move_file(&dest),
            XlcCmd::Rename(name) => {
                if let Some(ref path) = self.filename {
                    let parent = path.parent()
                        .map(|p| p.to_path_buf())
                        .unwrap_or_else(|| {
                            env::current_dir().unwrap_or_default()
                        });
                    let new_path = parent.join(name);
                    self.move_file(&new_path.display().to_string());
                } else {
                    self.xlc.add_output("No file to rename.");
                }
            }
            XlcCmd::DeleteFile => {
                if let Some(ref path) = self.filename {
                    match fs::remove_file(path) {
                        Ok(_) => self.xlc.add_output(&format!("Deleted: {}", path.display())),
                        Err(e) => self.xlc.add_output(&format!("Error: {}", e)),
                    }
                } else {
                    self.xlc.add_output("No file to delete.");
                }
            }
            XlcCmd::Pwd => {
                let cwd = env::current_dir()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|_| "?".to_string());
                self.xlc.add_output(&cwd);
            }
            XlcCmd::Ls => {
                if let Ok(entries) = std::fs::read_dir(".") {
                    for entry in entries.flatten() {
                        let meta = entry.file_type().ok();
                        let name = entry.file_name();
                        let prefix = if meta.map(|m| m.is_dir()).unwrap_or(false) { "/" } else { "" };
                        self.xlc.add_output(&format!("  {}{}", name.to_string_lossy(), prefix));
                    }
                } else {
                    self.xlc.add_output("Could not list directory.");
                }
            }
            XlcCmd::Help => {
                self.xlc.add_output("=== xei Commands ===");
                self.xlc.add_output("  w, save         Save current file");
                self.xlc.add_output("  w <path>        Save to a new path");
                self.xlc.add_output("  e, open <file>  Open a file");
                self.xlc.add_output("  mv, move <dest> Move/rename current file");
                self.xlc.add_output("  rename <name>   Rename in same directory");
                self.xlc.add_output("  rm              Delete current file");
                self.xlc.add_output("  pwd             Show working directory");
                self.xlc.add_output("  ls              List files");
                self.xlc.add_output("  q               Quit (with unsaved warning)");
                self.xlc.add_output("  q!              Force quit");
                self.xlc.add_output("  wq, x           Save and quit");
                self.xlc.add_output("  find, / <pat>   Search in buffer");
                self.xlc.add_output("  theme [name]    Switch or list themes");
                self.xlc.add_output("  bd              Close current tab");
                self.xlc.add_output("  <number>        Go to line (e.g. :42)");
                self.xlc.add_output("  s/pat/repl/g    Substitute on line");
                self.xlc.add_output("  %s/pat/repl/g   Substitute in file");
                self.xlc.add_output("  problems        Diagnostics list");
                self.xlc.add_output("  preview         Pretty preview (md/json)");
                self.xlc.add_output("  git             Full Git workbench");
                self.xlc.add_output("  screensaver     xeifetch splash (Esc exit)");
                self.xlc.add_output("  xeifetch / ss   Alias for screensaver");
                self.xlc.add_output("  bench           Self-benchmark (r rerun · Esc exit)");
                self.xlc.add_output("  status          Toggle live CPU/MEM/GPU readout");
                self.xlc.add_output("  pet [path.gif]  Desktop pet (Kitty/Ghostty)");
                self.xlc.add_output("  settings        Settings panel (Ctrl+,)");
                self.xlc.add_output("  gh-login / gha  GitHub CLI browser login");
                self.xlc.add_output("  gh-logout       GitHub CLI logout");
                self.xlc.add_output("  gh-status       GitHub auth status");
                self.xlc.add_output("  Rename <name>   LSP rename");
                self.xlc.add_output("  dap / debug     Toggle debug panel");
                self.xlc.add_output("  dap start/stop  Start / stop DAP session");
                self.xlc.add_output("  bp              Toggle breakpoint");
                self.xlc.add_output("  bp if <expr>    Conditional breakpoint");
                self.xlc.add_output("  bp log <msg>    Logpoint");
                self.xlc.add_output("  launch <prog>   DAP launch program");
                self.xlc.add_output("  DapConfig [n]   launch.json configs");
                self.xlc.add_output("  eval <expr>     DAP evaluate (stopped)");
                self.xlc.add_output("  DapAttach …     attach pid <n> | port <n> [lang]");
                self.xlc.add_output("  calls           Call hierarchy (incoming)");
                self.xlc.add_output("  rebase [N]      Interactive rebase last N commits");
                self.xlc.add_output("  rebase-abort    Abort in-progress rebase");
                self.xlc.add_output("  codelens        Toggle LSP code lenses");
                self.xlc.add_output("  pr <n>          Open PR review surface");
                self.xlc.add_output("  hooks           Reload ~/.xei/hooks.toml");
                self.xlc.add_output("  help, h, ?      Show this help");
            }
            XlcCmd::DapPanel => {
                self.toggle_debug_panel();
                self.xlc.add_output("Debug panel (F5 start · F9 bp · F10/F11 step)");
            }
            XlcCmd::DapStart => {
                self.dap_start_or_continue();
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapStop => {
                self.dap_stop();
                self.xlc.add_output("Debug stopped");
            }
            XlcCmd::DapLaunch(prog) => {
                self.dap_launch_program(&prog);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapBreakpoint => {
                self.dap_toggle_breakpoint();
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapCondition(expr) => {
                self.dap_set_condition(&expr);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapLogpoint(msg) => {
                self.dap_set_logpoint(&msg);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapConfig(name) => {
                if name.is_none() {
                    self.dap_list_configs();
                } else {
                    self.dap_launch_config(name.as_deref());
                    self.xlc.add_output(&self.message.clone());
                }
            }
            XlcCmd::DapEval(expr) => {
                self.dap_evaluate(&expr);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::DapAttach(spec) => {
                self.dap_attach(&spec);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::Rebase(n) => {
                self.open_rebase(n);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::RebaseAbort => {
                let hint = self.filename.as_deref();
                if let Some(root) = crate::git_ops::find_git_root(hint) {
                    match crate::rebase::rebase_abort(&root) {
                        Ok(m) => {
                            self.message = m.clone();
                            self.xlc.add_output(&m);
                        }
                        Err(e) => {
                            self.message = e.clone();
                            self.xlc.add_output(&e);
                        }
                    }
                } else {
                    self.xlc.add_output("Not a git repository");
                }
            }
            XlcCmd::RebaseContinue => {
                let hint = self.filename.as_deref();
                if let Some(root) = crate::git_ops::find_git_root(hint) {
                    match crate::rebase::rebase_continue(&root) {
                        Ok(m) => {
                            self.message = m.clone();
                            self.xlc.add_output(&m);
                        }
                        Err(e) => {
                            self.message = e.clone();
                            self.xlc.add_output(&e);
                        }
                    }
                } else {
                    self.xlc.add_output("Not a git repository");
                }
            }
            XlcCmd::CallHierarchy => {
                self.open_call_hierarchy(false);
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::CodeLens => {
                self.toggle_code_lens();
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::PrReview(n) => {
                if n == 0 {
                    self.xlc.add_output("Usage: pr <number>");
                } else {
                    self.open_pr_review(n);
                    self.xlc.add_output(&self.message.clone());
                }
            }
            XlcCmd::Update => {
                // No check result yet (throttled/first run)? Force one now and
                // install automatically when it lands.
                self.message = if self.update.latest.is_none() && !self.update.installing {
                    self.update
                        .check_now_and_install(env!("CARGO_PKG_VERSION"))
                } else {
                    self.update.start_install()
                };
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::BlankTab => {
                self.open_blank_tab();
            }
            XlcCmd::Bench => {
                self.run_bench();
            }
            XlcCmd::StatusMetrics => {
                self.toggle_status_metrics();
            }
            XlcCmd::HooksReload => {
                self.reload_hooks();
                self.xlc.add_output(&self.message.clone());
            }
            XlcCmd::Preview => {
                self.toggle_preview();
                self.xlc.add_output("Preview toggled (Ctrl+Shift+V / Esc)");
            }
            XlcCmd::GhLogin => {
                self.xlc.add_output("Starting browser login (non-blocking)…");
                self.open_git_workbench();
                self.git_wb.tab = crate::git_workbench::GitTab::Auth;
                match self.git_wb.start_browser_login() {
                    Ok(()) => {
                        self.message = "Auth · complete sign-in in browser".into();
                        self.xlc.add_output("Opened Auth tab — finish login in browser");
                    }
                    Err(e) => {
                        self.message = e.clone();
                        self.xlc.add_output(&e);
                    }
                }
            }
            XlcCmd::GhLogout => match crate::gh::auth_logout() {
                Ok(m) => {
                    self.message = m.clone();
                    self.xlc.add_output(&m);
                    self.git_wb.refresh_auth();
                }
                Err(e) => {
                    self.message = e.clone();
                    self.xlc.add_output(&e);
                }
            },
            XlcCmd::GhStatus => {
                let info = crate::gh::auth_status();
                self.git_wb.auth = info.clone();
                self.xlc.add_output(&info.detail);
                self.message = info.detail;
            }
            XlcCmd::GitWorkbench => {
                self.open_git_workbench();
                self.xlc.add_output("Git workbench (Ctrl+Shift+G)");
            }
            XlcCmd::Settings => {
                self.open_settings();
                self.xlc.add_output("Settings (Ctrl+,)");
            }
            XlcCmd::Screensaver => {
                self.toggle_screensaver();
                self.xlc.add_output("xeifetch screensaver (Esc to leave)");
            }
            XlcCmd::Pet(path) => {
                if path.is_empty() {
                    let st = if self.pet.enabled { "on" } else { "off" };
                    let frames = self.pet.frame_count();
                    let gfx = if self.pet_graphics_ok() {
                        "gpu+kitty ok"
                    } else {
                        "needs gpu_acc + Kitty/Ghostty"
                    };
                    let err = self.pet.load_error.as_deref().unwrap_or("");
                    self.xlc.add_output(&format!(
                        "pet {st} · path={} · frames={frames} · pos={},{} · w={} · speed={}  [{gfx}] {err}",
                        self.pet.path,
                        self.pet.x,
                        self.pet.y,
                        self.pet.width_cells,
                        crate::pet::PetState::speed_label(self.pet.speed),
                    ));
                    self.message =
                        "Use :pet ~/pic.gif · :pet on|off · Settings → Pet (needs GPU)".into();
                } else if matches!(path.as_str(), "off" | "disable" | "0" | "false") {
                    self.pet.enabled = false;
                    let mut cfg = config::load();
                    cfg.pet_enabled = false;
                    config::save(&cfg);
                    self.xlc.add_output("pet off");
                    self.message = "Pet off".into();
                } else if matches!(path.as_str(), "on" | "enable" | "1" | "true") {
                    if !self.pet_graphics_ok() {
                        self.pet.enabled = false;
                        self.xlc.add_output(
                            "pet requires gpu_acc + Kitty/Ghostty graphics (Settings → Setting)",
                        );
                        self.message = "Pet needs GPU + Kitty graphics".into();
                    } else if !self.pet.has_frames() {
                        self.pet.enabled = false;
                        self.xlc.add_output("pet: no frames — :pet ~/path.gif first");
                        self.message = "Load a GIF first: :pet ~/path.gif".into();
                    } else {
                        self.pet.enabled = true;
                        let mut cfg = config::load();
                        cfg.pet_enabled = true;
                        config::save(&cfg);
                        self.xlc.add_output("pet on");
                        self.message = "Pet on".into();
                    }
                } else {
                    if !self.pet_graphics_ok() {
                        self.xlc.add_output(
                            "pet requires gpu_acc + Kitty/Ghostty — enable gpu_acc in Settings",
                        );
                        self.message = "Pet needs GPU + Kitty graphics".into();
                        // Still load path so it's ready once GPU is on
                    }
                    let p = crate::pet::expand_path(&path);
                    let ps = p.display().to_string();
                    self.pet.load_path(&ps);
                    self.pet.enabled = self.pet.has_frames() && self.pet_graphics_ok();
                    let mut cfg = config::load();
                    cfg.pet_path = path.clone(); // keep user form (~/…)
                    cfg.pet_enabled = self.pet.enabled;
                    cfg.pet_x = self.pet.x;
                    cfg.pet_y = self.pet.y;
                    cfg.pet_width_cells = self.pet.width_cells;
                    cfg.pet_speed = self.pet.speed;
                    config::save(&cfg);
                    if let Some(ref e) = self.pet.load_error {
                        self.xlc.add_output(&format!("pet load error: {e}"));
                        self.message = e.clone();
                    } else if !self.pet_graphics_ok() {
                        self.xlc.add_output(&format!(
                            "pet loaded {} ({} frames) but not shown — GPU/Kitty required",
                            ps,
                            self.pet.frame_count()
                        ));
                    } else {
                        self.xlc.add_output(&format!(
                            "pet loaded {} ({} frames)",
                            ps,
                            self.pet.frame_count()
                        ));
                        self.message = format!("Pet · {} frames", self.pet.frame_count());
                    }
                }
            }
            XlcCmd::Search(pattern) => {
                self.search_pattern = Some(pattern.clone());
                self.recompute_search(&pattern, true);
                let n = self.search_matches.len();
                self.message = if n == 0 {
                    format!("Pattern not found: {}", pattern)
                } else {
                    format!("/{}/  1/{}", pattern, n)
                };
                self.xlc.add_output(&format!("Search /{}/ → {} match(es)", pattern, n));
            }
            XlcCmd::Theme(name) => {
                if name.is_empty() {
                    self.xlc.add_output("Available themes:");
                    for t in theme::all_themes() {
                        let marker = if self.theme.name == t.name { " *" } else { "  " };
                        self.xlc.add_output(&format!("{}{}", marker, t.name));
                    }
                } else if let Some(t) = theme::find(&name) {
                    self.theme = t;
                    config::save_theme(t.name);
                    set_cursor_esc(t.cursor);
                    self.message = format!("Theme: {}", t.name);
                    self.xlc.add_output(&format!("Switched to theme: {}", t.name));
                } else {
                    self.xlc.add_output(&format!("Unknown theme: {}. Use :theme to list.", name));
                }
            }
            XlcCmd::BufDelete => {
                self.close_current_tab();
                self.xlc.add_output("Buffer closed");
            }
            XlcCmd::LspStart(cmd) => {
                if let Some(ref path) = self.filename {
                    let root = path.parent().map(|p| p.display().to_string()).unwrap_or_default();
                    self.lsp.start(&cmd, &root, &path.display().to_string());
                    self.xlc.add_output(&format!("LSP started: {}", cmd));
                }
            }
            XlcCmd::GotoLine(n) => {
                self.goto_line(n);
                self.xlc.add_output(&format!("Jumped to line {}", n));
            }
            XlcCmd::Problems => {
                self.open_problems_palette();
            }
            XlcCmd::Substitute(raw) => {
                if let Some(cmd) = substitute::parse_substitute(&raw) {
                    self.apply_substitute_cmd(cmd);
                } else {
                    self.xlc.add_output("Invalid :s syntax. Use :s/pat/repl/g or :%s/pat/repl/g");
                    self.message = String::from("Invalid substitute");
                }
            }
            XlcCmd::LspRename(name) => {
                self.request_rename(&name);
            }
            XlcCmd::None => {
                self.message = String::from("Unknown command. Try :help");
                self.xlc.add_output("Try :help for available commands.");
            }
        }
    }

    fn open_in_place(&mut self, path: &str) {
        self.open_new_tab(path);
    }

    fn move_file(&mut self, dest: &str) {
        if let Some(ref path) = self.filename {
            let dest_path = PathBuf::from(dest);
            match fs::rename(path, &dest_path) {
                Ok(_) => {
                    self.filename = Some(dest_path);
                    self.message = format!("Moved to: {}", dest);
                    self.xlc.add_output(&format!("Moved to: {}", dest));
                }
                Err(e) => {
                    self.xlc.add_output(&format!("Error moving: {}", e));
                }
            }
        } else {
            self.xlc.add_output("No file to move.");
        }
    }

    /// Recompute matches for `pattern`. If `jump`, move cursor to nearest match
    /// in the active search direction from origin/cursor.
    pub fn recompute_search(&mut self, pattern: &str, jump: bool) {
        self.collect_matches(pattern);
        if self.search_matches.is_empty() {
            self.search_current = 0;
            return;
        }
        let from = self
            .search_origin
            .unwrap_or_else(|| self.buffer.cursor());
        let idx = if self.search_forward {
            self.search_matches
                .iter()
                .position(|p| p.row > from.row || (p.row == from.row && p.col >= from.col))
                .unwrap_or(0)
        } else {
            self.search_matches
                .iter()
                .rposition(|p| p.row < from.row || (p.row == from.row && p.col <= from.col))
                .unwrap_or(self.search_matches.len() - 1)
        };
        self.search_current = idx;
        if jump {
            let pos = self.search_matches[idx];
            self.buffer.cursor = pos;
            self.update_scroll();
        }
    }

    fn collect_matches(&mut self, pattern: &str) {
        self.search_matches.clear();
        if pattern.is_empty() {
            return;
        }
        let smart_case = !pattern.chars().any(|c| c.is_uppercase());
        let pat_lower = if smart_case {
            pattern.to_lowercase()
        } else {
            String::new()
        };

        for (row, line) in self.buffer.lines().iter().enumerate() {
            if smart_case {
                // Case-insensitive: walk char-by-char comparing lowered windows.
                let line_chars: Vec<char> = line.chars().collect();
                let pat_chars: Vec<char> = pat_lower.chars().collect();
                if pat_chars.is_empty() {
                    continue;
                }
                let plen = pat_chars.len();
                if line_chars.len() < plen {
                    continue;
                }
                let line_lower: Vec<char> = line_chars.iter().map(|c| c.to_lowercase().next().unwrap_or(*c)).collect();
                let mut i = 0;
                while i + plen <= line_lower.len() {
                    if line_lower[i..i + plen] == pat_chars[..] {
                        self.search_matches.push(Position::new(row, i));
                        i += 1; // overlapping allowed (vim default for most)
                    } else {
                        i += 1;
                    }
                }
            } else {
                let mut search_from = 0usize;
                while search_from <= line.len() {
                    if let Some(byte_rel) = line[search_from..].find(pattern) {
                        let byte_abs = search_from + byte_rel;
                        let col = line[..byte_abs].chars().count();
                        self.search_matches.push(Position::new(row, col));
                        search_from = byte_abs + pattern.len().max(1);
                    } else {
                        break;
                    }
                }
            }
        }
    }

    /// Backward-compatible alias.
    pub fn perform_search(&mut self) {
        if let Some(pat) = self.search_pattern.clone() {
            self.recompute_search(&pat, true);
        }
    }

    pub fn search_next(&mut self) {
        // `n` follows the direction used when the pattern was committed.
        if self.search_forward {
            self.search_step(true);
        } else {
            self.search_step(false);
        }
    }

    pub fn search_prev(&mut self) {
        // `N` is opposite of search direction.
        if self.search_forward {
            self.search_step(false);
        } else {
            self.search_step(true);
        }
    }

    fn search_step(&mut self, forward: bool) {
        if let Some(pat) = self.search_pattern.clone() {
            let cur = self.buffer.cursor();
            self.collect_matches(&pat);
            if self.search_matches.is_empty() {
                self.message = format!("Pattern not found: {}", pat);
                return;
            }
            let idx = if forward {
                self.search_matches
                    .iter()
                    .position(|p| p.row > cur.row || (p.row == cur.row && p.col > cur.col))
                    .unwrap_or(0)
            } else {
                self.search_matches
                    .iter()
                    .rposition(|p| p.row < cur.row || (p.row == cur.row && p.col < cur.col))
                    .unwrap_or(self.search_matches.len() - 1)
            };
            self.search_current = idx;
            let pos = self.search_matches[idx];
            let wrapped = if forward {
                idx == 0 && (pos.row < cur.row || (pos.row == cur.row && pos.col <= cur.col))
            } else {
                idx == self.search_matches.len() - 1
                    && (pos.row > cur.row || (pos.row == cur.row && pos.col >= cur.col))
            };
            self.buffer.cursor = pos;
            self.update_scroll();
            let slash = if self.search_forward { '/' } else { '?' };
            self.message = if wrapped {
                if forward {
                    format!(
                        "search hit BOTTOM, continuing at TOP  {}/{}",
                        idx + 1,
                        self.search_matches.len()
                    )
                } else {
                    format!(
                        "search hit TOP, continuing at BOTTOM  {}/{}",
                        idx + 1,
                        self.search_matches.len()
                    )
                }
            } else {
                format!("{}{}/  {}/{}", slash, pat, idx + 1, self.search_matches.len())
            };
        } else {
            self.message = String::from("No search pattern — press / or ? first");
        }
    }

    /// Search for the word under the cursor (`*` in vim).
    pub fn search_word_under_cursor(&mut self) {
        let word = self.word_under_cursor();
        if word.is_empty() {
            self.message = String::from("No word under cursor");
            return;
        }
        self.push_jump();
        self.search_pattern = Some(word.clone());
        self.search_forward = true;
        self.recompute_search(&word, true);
        // Advance to next occurrence after current position
        if self.search_matches.len() > 1 {
            self.search_next();
        } else if self.search_matches.is_empty() {
            self.message = format!("Pattern not found: {}", word);
        } else {
            self.message = format!("/{}/  1/1", word);
        }
    }

    fn word_under_cursor(&self) -> String {
        let line = self.buffer.line(self.buffer.cursor.row);
        let chars: Vec<char> = line.chars().collect();
        if chars.is_empty() {
            return String::new();
        }
        let mut col = self.buffer.cursor.col.min(chars.len().saturating_sub(1));
        if col < chars.len() && !(chars[col].is_alphanumeric() || chars[col] == '_') {
            // Try char before cursor
            if col > 0 && (chars[col - 1].is_alphanumeric() || chars[col - 1] == '_') {
                col -= 1;
            } else {
                return String::new();
            }
        }
        let mut start = col;
        while start > 0 && (chars[start - 1].is_alphanumeric() || chars[start - 1] == '_') {
            start -= 1;
        }
        let mut end = col;
        while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
            end += 1;
        }
        chars[start..end].iter().collect()
    }

    pub fn save_file(&mut self) {
        if let Some(path) = self.filename.clone() {
            match fs::write(&path, self.buffer.text()) {
                Ok(_) => {
                    self.modified = false;
                    if self.current_buffer < self.buffers.len() {
                        self.buffers[self.current_buffer].modified = false;
                        self.buffers[self.current_buffer].filename = Some(path.clone());
                    }
                    self.record_mtime();
                    self.refresh_git();
                    self.save_session();
                    self.message = format!("✓ Saved: {}", path.display());
                    self.xlc.add_output(&format!("✓ Saved: {}", path.display()));
                    self.fire_hook(crate::hooks::HookEvent::Save);
                }
                Err(e) => {
                    self.message = format!("✗ Error: {}", e);
                    self.xlc.add_output(&format!("✗ Error: {}", e));
                }
            }
        } else {
            self.message = String::from("No filename. Use :w <filename>");
            self.xlc.add_output("No filename. Use: w <path>");
        }
    }

    pub fn move_left(&mut self) {
        self.buffer.move_left();
    }

    pub fn move_right(&mut self) {
        self.buffer.move_right();
    }

    pub fn move_up(&mut self) {
        self.buffer.move_up();
        self.update_scroll();
    }

    pub fn move_down(&mut self) {
        self.buffer.move_down();
        self.update_scroll();
    }

    pub fn update_scroll(&mut self) {
        let cursor_row = self.buffer.cursor.row;
        let visible_height = self.viewport.height.max(1) as usize;
        // Soft-wrap-aware: viewport width minus gutter (~5 cols).
        let text_width = self
            .viewport
            .width
            .saturating_sub(5)
            .max(1) as usize;

        let wrap = self.wrap_lines;
        let wrap_rows = |row: usize| -> usize {
            if !wrap {
                return 1;
            }
            let vis = Self::line_visual_width(&self.buffer, row);
            if vis == 0 {
                1
            } else {
                (vis + text_width - 1) / text_width
            }
        };

        if cursor_row < self.scroll {
            self.scroll = cursor_row;
        }

        // Ensure the cursor's wrap segment is on-screen.
        let screen_col = self
            .buffer
            .buffer_col_to_screen_col(cursor_row, self.buffer.cursor.col);
        let cursor_wrap = if wrap { screen_col / text_width } else { 0 };

        // Horizontal-scroll mode: pan so the cursor stays visible.
        if !wrap {
            if screen_col < self.hscroll {
                self.hscroll = screen_col;
            } else if screen_col >= self.hscroll + text_width {
                self.hscroll = screen_col + 1 - text_width;
            }
        }

        // Visual rows from scroll .. cursor_row-1, plus cursor wrap offset + 1
        let mut needed = cursor_wrap + 1;
        for r in self.scroll..cursor_row {
            needed = needed.saturating_add(wrap_rows(r));
        }
        while needed > visible_height && self.scroll < cursor_row {
            needed = needed.saturating_sub(wrap_rows(self.scroll));
            self.scroll += 1;
        }
        // Fallback: pure buffer-line window if still off (tiny viewports)
        if cursor_row < self.scroll {
            self.scroll = cursor_row;
        }

        // Keep focused split pane scroll in sync
        if self.split.is_split() {
            let p = self.split.focused_pane_mut();
            p.scroll = self.scroll;
            p.tab_index = self.current_buffer;
        }
    }

    fn line_visual_width(buffer: &crate::buffer::Buffer, row: usize) -> usize {
        let line = buffer.line(row);
        let mut vis = 0usize;
        for ch in line.chars() {
            vis += if ch == '\t' {
                4 - (vis % 4)
            } else {
                unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)
            };
        }
        vis
    }

    pub fn delete_line(&mut self) {
        self.push_undo();
        let row = self.buffer.cursor.row;
        let deleted = self.buffer.delete_line();
        self.store_yank(format!("{}\n", deleted), true);
        if let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) {
            // Deleted the whole line at `row` → remove BP on it, shift later −1
            self.dap.shift_breakpoints(&path, row, -1);
        }
    }

    pub fn delete_word(&mut self) {
        self.push_undo();
        let deleted = self.buffer.delete_word();
        self.store_yank(deleted, false);
    }

    /// `p` — put after cursor / below line
    pub fn paste(&mut self) {
        self.paste_impl(false);
    }

    /// `P` — put before cursor / above line
    pub fn paste_before(&mut self) {
        self.paste_impl(true);
    }

    fn paste_impl(&mut self, before: bool) {
        let Some(val) = self.registers.load_for_put() else {
            // fallback yank_buffer
            if let Some(text) = self.yank_buffer.clone() {
                self.paste_text(&text, text.contains('\n'), before);
            }
            return;
        };
        self.paste_text(&val.text, val.linewise, before);
    }

    fn paste_text(&mut self, text: &str, linewise: bool, before: bool) {
        if text.is_empty() {
            return;
        }
        self.push_undo();
        if linewise {
            let lines: Vec<&str> = text.trim_end_matches('\n').split('\n').collect();
            if before {
                let row = self.buffer.cursor.row;
                for (i, line) in lines.iter().enumerate() {
                    self.buffer.insert_line_at(row + i, line.to_string());
                }
                self.buffer.cursor.row = row;
                self.buffer.cursor.col = 0;
            } else {
                for line in lines {
                    self.buffer.paste_line_after(line);
                }
            }
        } else {
            // Charwise: `p` inserts after the cursor char, `P` before it.
            if !before && self.buffer.cursor.col < self.buffer.current_line_len() {
                self.buffer.move_right();
            }
            // Bulk insert (O(n)) instead of char-by-char (O(n²) on long lines).
            let clean = text.replace('\r', "");
            self.buffer.insert_str(&clean);
            // Vim leaves the cursor ON the last pasted character (unless the
            // paste ended on a newline, which lands the cursor at col 0).
            if !clean.is_empty() && !clean.ends_with('\n') {
                self.buffer.move_left();
            }
        }
        self.update_scroll();
        self.message = String::from("Pasted");
    }

    pub fn yank_selection(&mut self) {
        if let Some((start, end)) = self.selected_range() {
            let mut lines: Vec<String> = Vec::new();
            for row in start.row..=end.row {
                let chars: Vec<char> = self.buffer.line(row).chars().collect();
                let s = if row == start.row && row == end.row {
                    let to = (end.col + 1).min(chars.len());
                    let from = start.col.min(to);
                    chars[from..to].iter().collect()
                } else if row == start.row {
                    let from = start.col.min(chars.len());
                    chars[from..].iter().collect()
                } else if row == end.row {
                    let to = (end.col + 1).min(chars.len());
                    chars[..to].iter().collect()
                } else {
                    chars.iter().collect()
                };
                lines.push(s);
            }
            let linewise = self.mode == Mode::VisualLine;
            let text = lines.join("\n");
            let label = self.registers.active_label();
            self.store_yank(
                if linewise {
                    format!("{}\n", text)
                } else {
                    text
                },
                linewise,
            );
            self.enter_normal();
            self.message = format!("Yanked → {}", label);
        }
    }

    pub fn delete_selection(&mut self) {
        if let Some((start, end)) = self.selected_range() {
            self.push_undo();
            let mut deleted_text = String::new();

            if self.mode == Mode::VisualLine {
                self.buffer.cursor.row = start.row;
                let count = end.row - start.row + 1;
                for _ in 0..count {
                    let line = self.buffer.delete_line();
                    if !deleted_text.is_empty() { deleted_text.push('\n'); }
                    deleted_text.push_str(&line);
                }
                self.store_yank(format!("{}\n", deleted_text), true);
                self.enter_normal();
                self.message = String::from("Deleted");
                return;
            }

            if start.row == end.row {
                let line = self.buffer.line(start.row);
                let deleted: String = line.chars().skip(start.col).take(end.col.saturating_sub(start.col) + 1).collect();
                let prefix: String = line.chars().take(start.col).collect();
                let suffix: String = line.chars().skip(end.col + 1).collect();
                self.buffer.set_line(start.row, prefix + &suffix);
                deleted_text = deleted;
            } else {
                let first_chars: Vec<char> = self.buffer.line(start.row).chars().collect();
                let last_chars: Vec<char> = self.buffer.line(end.row).chars().collect();

                deleted_text.push_str(&first_chars[start.col.min(first_chars.len())..].iter().collect::<String>());
                for row in (start.row + 1)..end.row {
                    deleted_text.push('\n');
                    deleted_text.push_str(self.buffer.line(row));
                }
                deleted_text.push('\n');
                let last_end = (end.col + 1).min(last_chars.len());
                deleted_text.push_str(&last_chars[..last_end].iter().collect::<String>());

                let first_prefix: String = first_chars.iter().take(start.col).collect();
                let last_suffix: String = last_chars.iter().skip(end.col + 1).collect();

                self.buffer.cursor.row = end.row;
                for _row in (start.row + 1..=end.row).rev() {
                    self.buffer.cursor.row = _row;
                    self.buffer.delete_line();
                }
                self.buffer.cursor.row = start.row;
                self.buffer.set_line(start.row, first_prefix + &last_suffix);
            }

            self.store_yank(deleted_text, false);
            self.buffer.cursor = Position::new(start.row, start.col);
            self.buffer.clamp_col();
            self.enter_normal();
            self.message = String::from("Deleted");
        }
    }

    pub fn record_mtime(&mut self) {
        if let Some(ref path) = self.filename {
            self.file_mtime = std::fs::metadata(path).ok().and_then(|m| m.modified().ok());
        }
    }

    /// Live-refresh: if the open file changed on disk, reload the buffer.
    /// Preserves cursor/scroll as much as possible; rebuilds folds / git / LSP.
    pub fn check_external_change(&mut self) {
        // Also refresh other open tabs' mtimes lightly — only reload the *active* buffer.
        self.check_active_file_external();
        if self.debug && !self.lsp.diagnostics.is_empty() {
            let rows: Vec<String> = self
                .lsp
                .diagnostics
                .iter()
                .map(|d| d.row.to_string())
                .collect();
            self.xlc.add_output(&format!("diag rows: {}", rows.join(",")));
        }
    }

    fn check_active_file_external(&mut self) {
        let Some(path) = self.filename.clone() else {
            return;
        };
        let path_s = path.display().to_string();
        let Ok(meta) = std::fs::metadata(&path) else {
            return;
        };
        let Ok(mtime) = meta.modified() else {
            return;
        };
        let Some(prev) = self.file_mtime else {
            // First observation — just record
            self.file_mtime = Some(mtime);
            return;
        };
        if prev == mtime {
            return;
        }

        let Ok(content) = std::fs::read_to_string(&path) else {
            // File deleted or unreadable — keep buffer, warn
            self.file_mtime = Some(mtime);
            self.message = format!("⚠ File missing or unreadable: {path_s}");
            return;
        };

        let had_local_edits = self.modified;
        let cursor = self.buffer.cursor();
        let scroll = self.scroll;

        self.buffer = Buffer::from_string(&content);
        // Restore cursor within new bounds
        self.buffer.cursor.row = cursor.row.min(self.buffer.line_count().saturating_sub(1));
        self.buffer.cursor.col = cursor.col;
        self.buffer.clamp_col();
        self.scroll = scroll.min(self.buffer.line_count().saturating_sub(1));
        self.modified = false;
        self.file_mtime = Some(mtime);
        self.undo_stack = UndoStack::new();
        self.undo_stack.push(self.buffer.snapshot());
        self.rebuild_folds();
        self.refresh_git();
        self.lsp_restart_for_current();
        self.sync_lsp_document();

        self.message = if had_local_edits {
            "↻ Live reload (disk won — local unsaved edits discarded)".into()
        } else {
            "↻ Live reload".into()
        };
    }

    pub fn save_state_to_tab(&mut self) {
        if self.current_buffer < self.buffers.len() {
            let tab = &mut self.buffers[self.current_buffer];
            tab.buffer = self.buffer.clone();
            tab.filename = self.filename.clone();
            tab.scroll = self.scroll;
            tab.modified = self.modified;
            tab.undo_stack = self.undo_stack.clone();
            tab.file_mtime = self.file_mtime;
        }
    }

    pub fn restore_state_from_tab(&mut self) {
        if let Some(tab) = self.buffers.get(self.current_buffer).cloned() {
            self.buffer = tab.buffer;
            self.filename = tab.filename;
            self.scroll = tab.scroll;
            self.modified = tab.modified;
            self.undo_stack = tab.undo_stack;
            self.file_mtime = tab.file_mtime;
        }
    }

    pub fn open_new_tab(&mut self, path: &str) {
        self.save_state_to_tab();

        let pathbuf = PathBuf::from(path);
        let abs_path = if pathbuf.is_absolute() {
            pathbuf
        } else {
            env::current_dir().unwrap_or_default().join(&pathbuf)
        };

        for (i, tab) in self.buffers.iter().enumerate() {
            if tab.filename.as_ref() == Some(&abs_path) {
                self.current_buffer = i;
                self.restore_state_from_tab();
                self.lsp_restart_for_current();
                self.refresh_git();
                self.sync_focused_pane_tab();
                self.message = format!("Switched to: {}", abs_path.display());
                return;
            }
        }

        let content = fs::read_to_string(&abs_path).unwrap_or_default();
        let buffer = Buffer::from_string(&content);
        let mtime = std::fs::metadata(&abs_path).ok().and_then(|m| m.modified().ok());
        let mut undo = UndoStack::new();
        undo.push(buffer.snapshot());
        undo.attach_file(&abs_path, self.undo_caching, &content);

        self.buffers.push(BufferTab {
            buffer,
            filename: Some(abs_path.clone()),
            scroll: 0,
            modified: false,
            undo_stack: undo,
            file_mtime: mtime,
        });
        self.current_buffer = self.buffers.len() - 1;
        self.restore_state_from_tab();
        let text = self.buffer.text();
        self.lsp
            .auto_start_with_text(&abs_path.display().to_string(), Some(&text));
        self.lsp_synced_path = Some(abs_path.clone());
        self.lsp_synced_hash = text_hash(&text);
        self.refresh_git();
        self.sync_focused_pane_tab();
        self.message = format!("Opened: {}", abs_path.display());
        self.fire_hook(crate::hooks::HookEvent::Open);
    }

    pub fn next_tab(&mut self) {
        if self.buffers.len() < 2 {
            return;
        }
        self.save_state_to_tab();
        self.current_buffer = (self.current_buffer + 1) % self.buffers.len();
        self.restore_state_from_tab();
        self.lsp_restart_for_current();
        self.refresh_git();
        self.sync_focused_pane_tab();
    }

    pub fn prev_tab(&mut self) {
        if self.buffers.len() < 2 {
            return;
        }
        self.save_state_to_tab();
        if self.current_buffer == 0 {
            self.current_buffer = self.buffers.len() - 1;
        } else {
            self.current_buffer -= 1;
        }
        self.restore_state_from_tab();
        self.lsp_restart_for_current();
        self.refresh_git();
        self.sync_focused_pane_tab();
    }

    pub fn lsp_restart_for_current(&mut self) {
        if let Some(ref path) = self.filename {
            let p = path.display().to_string();
            // Always open with live buffer text so unsaved edits aren't lost.
            let text = self.buffer.text();
            self.lsp.auto_start_with_text(&p, Some(&text));
            self.lsp_synced_path = Some(path.clone());
            self.lsp_synced_hash = text_hash(&text);
        } else {
            // No file — drop per-document state so stale diagnostics from the
            // previous buffer don't paint the empty one.
            self.lsp.diagnostics.clear();
            self.lsp.semantic_tokens.clear();
            self.lsp.inlay_hints.clear();
        }
    }

    pub fn format_document(&mut self) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = String::from("No file to format");
            return;
        };
        if !self.lsp.server_running {
            self.message = String::from("LSP not running");
            return;
        }
        self.sync_lsp_document();
        self.lsp.request_formatting(&path);
        self.message = String::from("Formatting…");
    }

    pub fn request_code_actions(&mut self) {
        let Some(path) = self.filename.as_ref().map(|p| p.display().to_string()) else {
            self.message = String::from("No file");
            return;
        };
        if !self.lsp.server_running {
            self.message = String::from("LSP not running");
            return;
        }
        self.sync_lsp_document();
        let c = self.buffer.cursor();
        self.lsp.request_code_action(&path, c.row, c.col);
        self.message = String::from("Code actions…");
    }

    /// Apply multi-file full-text edits (rename / format / code action).
    pub fn apply_file_edits(&mut self, edits: Vec<crate::lsp::FileEdit>) {
        if edits.is_empty() {
            self.message = String::from("No edits to apply");
            return;
        }
        let n = edits.len();
        let cur_path = self
            .filename
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        for edit in edits {
            let is_current = edit.path == cur_path
                || self
                    .filename
                    .as_ref()
                    .and_then(|p| p.canonicalize().ok())
                    .and_then(|p| {
                        std::path::Path::new(&edit.path)
                            .canonicalize()
                            .ok()
                            .map(|e| e == p)
                    })
                    .unwrap_or(false);

            if is_current {
                self.push_undo();
                let row = self.buffer.cursor.row;
                let col = self.buffer.cursor.col;
                self.buffer = crate::buffer::Buffer::from_string(&edit.text);
                self.buffer.cursor.row = row.min(self.buffer.line_count().saturating_sub(1));
                self.buffer.cursor.col = col;
                self.buffer.clamp_col();
                self.modified = true;
                self.update_scroll();
                // keep LSP in sync
                self.lsp_synced_hash = 0; // force didChange
                self.sync_lsp_document();
            } else {
                // Write other files to disk and refresh if open in a tab
                if let Err(e) = std::fs::write(&edit.path, &edit.text) {
                    self.message = format!("Edit failed {}: {e}", edit.path);
                    continue;
                }
                // Update open tab if present
                for tab in &mut self.buffers {
                    if tab
                        .filename
                        .as_ref()
                        .map(|p| p.display().to_string() == edit.path)
                        .unwrap_or(false)
                    {
                        tab.buffer = crate::buffer::Buffer::from_string(&edit.text);
                        tab.modified = false;
                    }
                }
            }
        }
        self.message = format!("Applied {n} file edit(s)");
    }

    pub fn open_code_actions_palette(&mut self) {
        let actions = std::mem::take(&mut self.lsp.pending_code_actions);
        if actions.is_empty() {
            return;
        }
        self.code_action_bank = actions;
        let items: Vec<crate::palette::PaletteItem> = self
            .code_action_bank
            .iter()
            .enumerate()
            .map(|(i, a)| {
                let detail = if !a.kind.is_empty() {
                    a.kind.clone()
                } else if !a.edits.is_empty() {
                    format!("{} file(s)", a.edits.len())
                } else {
                    a.command.clone().unwrap_or_default()
                };
                crate::palette::PaletteItem {
                    label: a.title.clone(),
                    detail,
                    action: crate::palette::PaletteAction::CodeAction(i),
                }
            })
            .collect();
        self.palette.open_code_actions(items);
        self.mode = Mode::Palette;
        self.message = format!("Code actions — {} items", self.code_action_bank.len());
    }

    pub fn apply_code_action(&mut self, index: usize) {
        let Some(action) = self.code_action_bank.get(index).cloned() else {
            return;
        };
        self.code_action_bank.clear();
        if !action.edits.is_empty() {
            self.apply_file_edits(action.edits);
            return;
        }
        if let Some(cmd) = action.command {
            self.lsp
                .execute_command(&cmd, action.command_args_json.as_deref());
            self.message = format!("Running {cmd}");
            return;
        }
        self.message = String::from("Code action had no edit/command");
    }

    pub fn close_current_tab(&mut self) {
        // Persist or discard the closing buffer's history (undo_caching).
        self.save_state_to_tab();
        if let Some(tab) = self.buffers.get_mut(self.current_buffer) {
            if tab.filename.is_some() {
                let text = tab.buffer.text();
                tab.undo_stack.finish(self.undo_caching, &text);
            }
        }
        if self.buffers.len() <= 1 {
            self.lsp.shutdown();
            self.buffer = Buffer::new();
            self.filename = None;
            self.scroll = 0;
            self.modified = false;
            self.undo_stack = UndoStack::new();
            self.undo_stack.push(self.buffer.snapshot());
            self.file_mtime = None;
            self.buffers[0] = BufferTab {
                buffer: self.buffer.clone(),
                filename: None,
                scroll: 0,
                modified: false,
                undo_stack: self.undo_stack.clone(),
                file_mtime: None,
            };
            return;
        }

        self.buffers.remove(self.current_buffer);
        if self.current_buffer >= self.buffers.len() {
            self.current_buffer = self.buffers.len() - 1;
        }
        self.restore_state_from_tab();
        // Re-point the LSP at the newly current tab (same language → reuse the
        // running server; different → restart). The old unconditional shutdown
        // left the surviving tabs with no LSP at all.
        self.lsp_restart_for_current();
        self.refresh_git();
        self.message = String::from("Buffer closed");
    }
}

pub fn set_cursor_esc(color: ratatui::style::Color) {
    use ratatui::style::Color;
    if let Color::Rgb(r, g, b) = color {
        print!("\x1b]12;rgb:{:02x}{:02x}/{:02x}{:02x}/{:02x}{:02x}\x1b\\", r, r, g, g, b, b);
        let _ = std::io::stdout().flush();
    }
}

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

    fn app_with(text: &str) -> App {
        let mut app = App::new();
        app.buffer = Buffer::from_string(text);
        app.viewport = EditorViewport {
            x: 0,
            y: 0,
            width: 80,
            height: 24,
            text_x: 5,
            text_y: 0,
        };
        app
    }

    #[test]
    fn hscroll_follows_cursor_when_wrap_off() {
        let long = "x".repeat(300);
        let mut app = app_with(&long);
        app.wrap_lines = false;
        // viewport width 80 − 5 gutter = 75 text cols
        app.buffer.cursor.col = 200;
        app.update_scroll();
        assert_eq!(app.hscroll, 200 + 1 - 75);
        // Moving back left pulls the pan window back.
        app.buffer.cursor.col = 10;
        app.update_scroll();
        assert_eq!(app.hscroll, 10);
        // Wrap mode never pans.
        app.wrap_lines = true;
        app.hscroll = 0;
        app.buffer.cursor.col = 250;
        app.update_scroll();
        assert_eq!(app.hscroll, 0);
    }

    #[test]
    fn split_panes_keep_independent_cursors() {
        let text = vec!["word here"; 50].join("\n");
        let mut app = app_with(&text);
        app.buffer.cursor.row = 10;
        app.buffer.cursor.col = 3;
        app.split_vertical();
        // Pane 1: move somewhere else.
        app.focus_other_pane();
        app.buffer.cursor.row = 40;
        app.buffer.cursor.col = 7;
        // Back to pane 0 — its cursor must be restored.
        app.focus_other_pane();
        assert_eq!((app.buffer.cursor.row, app.buffer.cursor.col), (10, 3));
        // And pane 1 kept its own.
        app.focus_other_pane();
        assert_eq!((app.buffer.cursor.row, app.buffer.cursor.col), (40, 7));
    }

    #[test]
    fn close_split_keeps_the_other_pane() {
        let text = vec!["line"; 100].join("\n");
        let mut app = app_with(&text);
        app.buffer.cursor.row = 8;
        app.split_vertical();
        app.focus_pane(1);
        // Pane 0 (the unfocused one) sits at scroll 5.
        app.split.panes[0].scroll = 5;
        app.close_split();
        assert!(!app.split.is_split());
        // Vim C-w q: the focused pane closes; the *other* view survives.
        assert_eq!(app.scroll, 5);
    }

    #[test]
    fn search_finds_all_matches_char_safe() {
        let mut app = app_with("hello\nhello world\nHELLO");
        app.search_pattern = Some("hello".into());
        app.collect_matches("hello");
        // smart-case: all lowercase → case-insensitive → 3 matches
        assert_eq!(app.search_matches.len(), 3);
        assert_eq!(app.search_matches[0], Position::new(0, 0));
        assert_eq!(app.search_matches[1], Position::new(1, 0));
        assert_eq!(app.search_matches[2], Position::new(2, 0));
    }

    #[test]
    fn search_case_sensitive_when_pattern_has_upper() {
        let mut app = app_with("hello\nHELLO\nHello");
        app.collect_matches("Hello");
        assert_eq!(app.search_matches.len(), 1);
        assert_eq!(app.search_matches[0], Position::new(2, 0));
    }

    #[test]
    fn search_utf8_char_indices() {
        let mut app = app_with("안녕 hello 안녕");
        app.collect_matches("안녕");
        assert_eq!(app.search_matches.len(), 2);
        assert_eq!(app.search_matches[0].col, 0);
        // "안녕 " = 3 chars, then "hello " = 6, second at col 9
        assert_eq!(app.search_matches[1].col, 9);
    }

    #[test]
    fn enter_search_cancel_restores_cursor() {
        let mut app = app_with("abc\ndef\nghi");
        app.buffer.cursor = Position::new(1, 1);
        app.scroll = 0;
        app.enter_search();
        app.search_input = "ghi".into();
        app.update_search_input();
        assert_eq!(app.buffer.cursor.row, 2);
        app.cancel_search();
        assert_eq!(app.mode, Mode::Normal);
        assert_eq!(app.buffer.cursor, Position::new(1, 1));
        assert!(app.search_input.is_empty());
    }

    #[test]
    fn commit_search_keeps_pattern_for_n() {
        let mut app = app_with("foo bar foo");
        app.enter_search();
        app.search_input = "foo".into();
        app.update_search_input();
        app.commit_search();
        assert_eq!(app.mode, Mode::Normal);
        assert_eq!(app.search_pattern.as_deref(), Some("foo"));
        assert_eq!(app.search_matches.len(), 2);
        let first = app.buffer.cursor;
        app.search_next();
        assert_ne!(app.buffer.cursor, first);
    }

    #[test]
    fn search_jumps_to_nearest_from_origin() {
        let mut app = app_with("aa\nbb\naa\ncc\naa");
        app.buffer.cursor = Position::new(1, 0); // on "bb"
        app.enter_search();
        app.search_input = "aa".into();
        app.update_search_input();
        // nearest at-or-after origin (row 1) is row 2
        assert_eq!(app.buffer.cursor.row, 2);
    }

    #[test]
    fn paste_before_charwise_cursor_on_last_char() {
        let mut app = app_with("abc");
        app.buffer.cursor = Position::new(0, 1); // on 'b'
        app.registers.select('z');
        app.registers.store("XY".into(), false);
        app.registers.select('z');
        app.paste_before();
        assert_eq!(app.buffer.line(0), "aXYbc");
        // vim: cursor ends on the last pasted char ('Y')
        assert_eq!(app.buffer.cursor, Position::new(0, 2));
    }

    #[test]
    fn paste_after_charwise_cursor_on_last_char() {
        let mut app = app_with("ab");
        app.buffer.cursor = Position::new(0, 0); // on 'a'
        app.registers.select('z');
        app.registers.store("XY".into(), false);
        app.registers.select('z');
        app.paste();
        assert_eq!(app.buffer.line(0), "aXYb");
        assert_eq!(app.buffer.cursor, Position::new(0, 2));
    }

    #[test]
    fn close_tab_keeps_remaining_tab_state() {
        let dir = std::env::temp_dir();
        let f1 = dir.join("xei_test_close_a.rs");
        let f2 = dir.join("xei_test_close_b.rs");
        let _ = std::fs::write(&f1, "fn a() {}");
        let _ = std::fs::write(&f2, "fn b() {}");
        let mut app = App::open_file(f1.to_str().unwrap());
        app.open_new_tab(f2.to_str().unwrap());
        assert_eq!(app.buffers.len(), 2);
        app.close_current_tab();
        assert_eq!(app.buffers.len(), 1);
        assert_eq!(app.filename.as_deref(), Some(f1.as_path()));
        assert_eq!(app.buffer.line(0), "fn a() {}");
        let _ = std::fs::remove_file(&f1);
        let _ = std::fs::remove_file(&f2);
    }

    #[test]
    fn xlc_wq_is_save_and_quit() {
        let dir = std::env::temp_dir().join("xei_test_wq.txt");
        let _ = std::fs::write(&dir, "data");
        let mut app = App::open_file(dir.to_str().unwrap());
        app.buffer.insert_char('!');
        app.modified = true;
        app.xlc.input = "wq".into();
        app.execute_xlc();
        assert!(!app.running);
        assert!(!app.modified);
        let _ = std::fs::remove_file(&dir);
    }
}