konoma 0.18.0

Terminal file browser built for AI pair-programming — full-screen previews (Markdown, images, PDF, CSV), git suite, and an agent-watch mode that follows your AI's edits (macOS and Linux)
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
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
//! Application state: the `App` struct and its methods — mode (Tree/Preview), the tree,
//! tabs, and the current preview target. Git view methods live in the `git_view` submodule.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::Result;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui_image::errors::Errors;
use ratatui_image::picker::Picker;
use ratatui_image::protocol::Protocol;
use ratatui_image::thread::{ResizeRequest, ResizeResponse, ThreadProtocol};
use ratatui_image::{FilterType, Resize};
use tokio::sync::mpsc::UnboundedSender;

use crate::config::Config;
use crate::i18n::tr;
use crate::preview::PreviewKind;

mod bookmark_actions;
mod file_actions;
mod git_view;
mod md_tasks;
mod paste_jump;
mod session_actions;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    #[default]
    Tree,
    Preview,
}

/// Display mode (outer): what is currently shown full-screen. The **outer chip** in the status bar (colors assigned by `ui`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisplayMode {
    Tree,
    Preview,
    Image,
    /// CSV/TSV table preview (aligned grid + cell cursor).
    Table,
}

/// Internal mode (inner): what is currently being operated. Shows the **inner chip** only while active and switches the footer keys too.
/// Priority: dialog > each footer mode (filter/search/sort/bookmarks) > visual.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InternalMode {
    Visual,
    /// Windowed-preview line selection (`v` in a code/text preview).
    PreviewVisual,
    Filter,
    /// Changed-files-only tree view (`C`; Agent Watch).
    ChangedFilter,
    Search,
    Sort,
    Mark,
    Bookmarks,
    Tabs,
    Outline,
    Info,
    Create,
    Rename,
    BatchRename,
    RenamePreview,
    DeleteConfirm,
    DropConfirm,
    QuitConfirm,
    BookmarkConfirm,
    GitChanges,
    GitDiff,
    Commit,
    GitLog,
    GitDetail,
    GitBranch,
    GitGraph,
    GitGraphPicker,
}

/// Preview paging key style. Specified via the `ui.keys` setting (default vim).
/// Diffs use only the page/half-page keys. j/k line movement, arrows, and PageUp/Down are common to both styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyScheme {
    /// vim style: Ctrl-f/Ctrl-b=page, Ctrl-d/Ctrl-u=half.
    Vim,
    /// less style: Space/b=page, d/u=half.
    Less,
}

impl KeyScheme {
    pub fn parse(s: &str) -> Self {
        match s {
            "less" => Self::Less,
            _ => Self::Vim,
        }
    }
}

/// diff layout (config `git.diff`; cycle at runtime with `s`). Auto picks vertical/horizontal automatically from the terminal width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLayout {
    /// Vertical (unified).
    Unified,
    /// Side-by-side.
    Split,
    /// Horizontal if wide, vertical if narrow.
    Auto,
}

impl DiffLayout {
    /// Parse a config value. "split"/"horizontal"/"side-by-side"=horizontal / "auto"=auto / otherwise=vertical.
    pub fn parse(s: &str) -> Self {
        let n: String = s
            .chars()
            .filter(|c| !matches!(c, ' ' | '-' | '_'))
            .flat_map(|c| c.to_lowercase())
            .collect();
        match n.as_str() {
            "split" | "horizontal" | "sidebyside" | "side" => Self::Split,
            "auto" => Self::Auto,
            _ => Self::Unified, // "unified" / "vertical" / 不明
        }
    }
    /// Resolve whether to lay out side-by-side at the actual display width `width`. Auto decides by a threshold.
    pub fn is_split(self, width: u16) -> bool {
        match self {
            DiffLayout::Unified => false,
            DiffLayout::Split => true,
            DiffLayout::Auto => width >= DIFF_AUTO_MIN_WIDTH,
        }
    }
    /// Cycle to the next layout (vertical→horizontal→Auto→vertical). For `s`.
    #[cfg_attr(not(feature = "git"), allow(dead_code))]
    pub fn next(self) -> Self {
        match self {
            DiffLayout::Unified => DiffLayout::Split,
            DiffLayout::Split => DiffLayout::Auto,
            DiffLayout::Auto => DiffLayout::Unified,
        }
    }
}

/// Minimum inner width for side-by-side under Auto (below this, vertical). A guideline so two-column code is not cramped.
const DIFF_AUTO_MIN_WIDTH: u16 = 90;

/// Layout of the status chrome (config `ui.statusbar`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusbarLayout {
    /// Context (mode/path/zoom) on top (right of the tab row), key hints at the bottom (default).
    Split,
    /// Combine both context and key hints into a single bottom line.
    Bottom,
}

impl StatusbarLayout {
    pub fn parse(s: &str) -> Self {
        match s {
            "bottom" => Self::Bottom,
            _ => Self::Split,
        }
    }
}

/// Path display style. Used for the title (tree/preview). Cycle with the `p` key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathStyle {
    /// Relative to the launch directory name (e.g. konoma/src/main.rs). Default.
    Relative,
    /// Relative to HOME (e.g. ~/work/konoma).
    Home,
    /// Full path (e.g. /Users/me/work/konoma).
    Full,
}

impl PathStyle {
    pub fn parse(s: &str) -> Self {
        match s {
            "home" => Self::Home,
            "full" => Self::Full,
            _ => Self::Relative,
        }
    }
    pub fn next(self) -> Self {
        match self {
            Self::Relative => Self::Home,
            Self::Home => Self::Full,
            Self::Full => Self::Relative,
        }
    }
}

/// A single entry shown in the tree.
#[derive(Debug, Clone)]
pub struct Entry {
    pub path: PathBuf,
    pub is_dir: bool,
    pub depth: usize,
    pub expanded: bool,
}

/// Tree sort key (FR / M7 auxiliary). Switch via the footer menu (`s`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Name,
    Size,
    Modified,
    Ext,
}

/// Sort settings. `reverse`=flip ascending/descending, `dirs_first`=group directories at the top.
/// Default is "name, ascending, directories first" (matches the previous behavior). Global (not per-tab).
#[derive(Clone, Copy)]
pub struct Sort {
    pub key: SortKey,
    pub reverse: bool,
    pub dirs_first: bool,
}

impl Default for Sort {
    fn default() -> Self {
        Self {
            key: SortKey::Name,
            reverse: false,
            dirs_first: true,
        }
    }
}

impl SortKey {
    /// Parse a config string (case-insensitive). Unknown/empty falls back to Name.
    pub fn parse(s: &str) -> Self {
        match s.trim().to_lowercase().as_str() {
            "size" => SortKey::Size,
            "modified" | "mtime" | "mod" => SortKey::Modified,
            "ext" | "extension" | "type" => SortKey::Ext,
            _ => SortKey::Name,
        }
    }
}

impl Sort {
    /// Build the startup sort order from the `[ui.sort]` config.
    pub fn from_config(c: &crate::config::SortConfig) -> Self {
        Self {
            key: SortKey::parse(&c.key),
            reverse: c.reverse,
            dirs_first: c.dirs_first,
        }
    }
}

/// Destructive/creation operations confirmed through a modal dialog (M7 Phase B, safety first).
// git 専用バリアント(GitDiscard/GitDeleteBranch)は非 git ビルドでは構築経路が無い(その構築元は
// git ディスパッチ専用)。バリアント自体は match の網羅性のため残し、非 git のみ dead_code を許す。
#[cfg_attr(not(feature = "git"), allow(dead_code))]
#[derive(Clone)]
enum PendingOp {
    /// Create with the entered name. A trailing `/` means a folder. `dir` is the destination (based on the cursor).
    Create { dir: PathBuf },
    /// Rename the target to the entered name within the same parent.
    Rename { target: PathBuf },
    /// Send the target to the trash (recoverable).
    Delete { targets: Vec<PathBuf> },
    /// Template-input stage of batch rename (`targets`=targets in display order). On confirm, builds a plan and moves to preview.
    BatchRenameInput { targets: Vec<PathBuf> },
    /// Preview→apply stage of batch rename (`plan`=(old, new) pairs).
    BatchRenameApply { plan: Vec<(PathBuf, PathBuf)> },
    /// In the Git view, `x`=discard a file's changes (via a confirmation dialog). On confirm, git::discard.
    GitDiscard { path: PathBuf },
    /// In the Git view, `c`=enter a commit message. On confirm, git::commit (uses the staged index).
    GitCommit,
    /// In the branch list, `n`=enter a new branch name. On confirm, git::create_branch (create and switch).
    GitCreateBranch,
    /// In the branch list, `d`=delete confirmation. `y`=safe (-d) / `!`=force (-D).
    GitDeleteBranch { name: String },
    /// A transfer received via file drag & drop (through a terminal paste). `c`=copy / `m`=move / Esc=cancel.
    /// `sources`=the dropped existing paths, `dir`=the drop destination (directory based on the cursor).
    DropTransfer { sources: Vec<PathBuf>, dir: PathBuf },
    /// Quit the whole app. A confirmation is requested before exiting (see `ui.confirm_quit`).
    Quit,
    /// Overwrite an existing bookmark under `key` with `target` (confirmation via `ui.confirm_bookmark_overwrite`).
    BookmarkOverwrite { key: char, target: PathBuf },
}

/// A confirmation (yes/no) or text-input modal. On confirm, calls fileops according to `op`.
struct Dialog {
    op: PendingOp,
    kind: DialogKind,
}

/// Dialog kind. Confirm=y/n for a destructive op (delete) / Input=name entry for create/rename.
/// `allow_permanent`=whether the delete confirmation also offers `!`=permanent delete (unrecoverable) (true=delete confirmation only).
enum DialogKind {
    Confirm {
        message: String,
        allow_permanent: bool,
    },
    Input {
        title: String,
        buffer: String,
        /// Insertion position (**character** index within buffer, 0..=char count). Move with ←→/Home/End.
        cursor: usize,
    },
    /// Confirmation preview for batch rename. `lines`=the "old → new" list, `scroll`=the top visible line.
    Preview {
        title: String,
        lines: Vec<String>,
        scroll: usize,
    },
}

/// File clipboard operation kind. Copy=duplicate / Cut=move (consumed on paste).
#[derive(Clone, Copy, PartialEq, Eq)]
enum ClipOp {
    Copy,
    Cut,
}

/// Copy/cut targets pushed with `Y`/`X`. Apply them with `P` to the cursor-based directory.
#[derive(Clone)]
struct Clipboard {
    op: ClipOp,
    paths: Vec<PathBuf>,
}

/// Snapshot of one tab's tree context (FR-5).
/// The active tab's working state lives in App's fields as the source of truth, and is saved/loaded here on switch.
/// It keeps not just the tree but also the **mode/preview state per tab**, restoring them on switch instead of dropping to Tree.
/// The heavy image state (protocol/source image) is not carried over and is reloaded on restore (zoom/center are kept).
/// `Default` exists only as the placeholder `load_active` leaves in the slot after moving the
/// snapshot out — the active slot is never read (tab_label/tab_root use the live App fields)
/// and the next save_active overwrites it.
#[derive(Clone, Default)]
struct TabState {
    root: PathBuf,
    open_dir: PathBuf,
    entries: Vec<Entry>,
    selected: usize,
    show_hidden: bool,
    tree_viewport: u16,
    mode: Mode,
    preview_path: Option<PathBuf>,
    preview_kind: Option<PreviewKind>,
    preview_scroll: u16,
    preview_hscroll: u16,
    preview_viewport: u16,
    preview_byte_top: u64,
    preview_top_line: usize,
    image_zoom: f64,
    image_center: (f64, f64),
    // PDF の現在ページ/総ページ数もタブごとに保持(別タブから戻ったとき同じページを再描画する)。
    pdf_page: u32,
    pdf_pages: Option<u32>,
    // CSV/TSV テーブルのセルカーソル/スクロールもタブごとに保持(テーブル本体は復元時に再パース)。
    table_cur_row: usize,
    table_cur_col: usize,
    table_top_row: usize,
    table_left_col: usize,
    // windowed(Code/Text)プレビューの 2D キャレット位置(別タブから戻っても同じ行/列に戻る)。選択(anchor)は持ち越さない。
    preview_cursor_line: usize,
    preview_cursor_col: usize,
    // Markdown/Mermaid の raw ソース表示(`R`)状態もタブごとに保持する。
    md_raw: bool,
    // Markdown プレビューの Tab フォーカスと、インライン図のその場ズーム/全画面復帰情報も
    // タブごとに保持する。タブ非依存のままだと、両タブが md プレビュー中の切替(enter_preview を
    // 経ない唯一の経路)で前タブのフォーカス/ズームが別文書へ漏れ、hjkl が見えない図のパンに
    // 化ける(image_zoom が TabState 保存されるのと同じ扱いに揃える)。
    focused_item: Option<usize>,
    fence_zoom: f64,
    fence_center: (f64, f64),
    fence_return: Option<(u16, Option<usize>)>,
    // git オーバーレイもタブごとに保持する(別タブでドキュメントを見て戻っても git モードのまま)。
    git_view: bool,
    git_view_sel: usize,
    git_view_entries: Vec<crate::git::ChangeEntry>,
    came_from_git_view: bool,
    git_log: Option<Vec<crate::git::CommitInfo>>,
    git_log_sel: usize,
    git_detail: Option<Vec<crate::git::DiffLine>>,
    git_detail_meta: Option<crate::git::CommitMeta>,
    git_detail_title: Option<String>,
    git_detail_scroll: u16,
    git_detail_hscroll: u16,
    git_detail_viewport: u16,
    git_detail_total: usize,
    git_branches: Option<Vec<crate::git::BranchInfo>>,
    git_branch_sel: usize,
    git_branch_filter: String,
    git_branch_filtering: bool,
    git_graph: Option<Vec<crate::git::GraphRow>>,
    git_graph_sel: usize,
    // グラフ本体(git_graph)を保存する以上、それを装飾する派生状態(基準ピン・凡例・表示ブランチ・
    // 優先順)も同じタブに保存しないと、別タブで基準/表示を変えて戻ったとき凡例や `base:` タイトルが
    // 他タブのまま残る(load_active はグラフを再構築しない)。git_detail_meta/title を git_detail と
    // 一緒に保存するのと同じ扱い。ピッカー(モーダル)の一時状態は保存せず復元時にリセットする。
    git_graph_base: Option<String>,
    git_graph_base_label: Option<String>,
    git_graph_visible: std::collections::HashSet<String>,
    git_graph_legend: Vec<crate::git::LegendEntry>,
    git_graph_hidden: usize,
    git_graph_order: Vec<String>,
    // --- タブ毎の選択 / 絞り込み / プレビュー検索 (#2/#6: タブ跨ぎのデータ損失 footgun 対策) ---
    // これらが TabState に無いと、タブAで選択 → 別タブ/別 dir で D/X/Y/P したとき、
    // 見えていない旧選択のファイルが操作対象になる(マーカー不可視で気付けない)。
    // クリップボード(Y/X/P の paths バッファ)は app 全体共有のままで、ここには入れない(ユーザ確定事項)。
    selection: BTreeSet<PathBuf>,
    visual_anchor: Option<usize>,
    tree_filter: Option<String>,
    filter_input: Option<String>,
    filter_pool: Vec<Entry>,
    changed_filter: bool,
    preview_search: Option<String>,
    search_input: Option<String>,
    search_matches: Vec<(u64, usize, usize)>,
    search_idx: usize,
}

/// The media payload loaded on a separate thread (sent back to the UI thread).
pub enum MediaPayload {
    /// A still image (single-frame GIF / video thumb / PDF page) → goes to image_src.
    Static(image::DynamicImage),
    /// All GIF frames (composited RGBA + delay) → goes to gif_frames.
    Gif(Vec<(image::DynamicImage, std::time::Duration)>),
    /// A raster of a vector source (SVG file / mermaid diagram). The SVG is retained so zooming
    /// re-rasterizes at the needed density (sharp zoom) instead of blowing up pixels.
    Vector {
        img: image::DynamicImage,
        svg: std::sync::Arc<Vec<u8>>,
    },
}

/// Result of media loading from another thread. Matched by generation via `gen`; results made stale by navigation are discarded.
pub struct MediaResult {
    gen: u64,
    /// None = decode/rasterize failure (the render side shows a fallback).
    payload: Option<MediaPayload>,
}

/// The geometry a kitty image targets: `(crop rect (x,y,w,h) in source px, display cols, rows)`.
type KittyGeom = ((u32, u32, u32, u32), u16, u16);

/// Result of an async kitty image build (resize + `o=z` compress) from a worker thread. Matched by
/// `gen` (latest-wins): a build superseded by a newer zoom/pan is discarded. None = build failed.
pub struct KittyResult {
    gen: u64,
    image: Option<crate::preview::kitty::KittyImage>,
}

/// Heavy media loading to run on a separate thread (pure work that does not reference App).
enum MediaJob {
    /// Rasterize an SVG (path, max-edge px). Vector-backed: keeps the source for sharp zoom.
    Svg(PathBuf, u32),
    /// Expand all GIF frames. Falls back to still-image decode for single-frame/non-animated GIFs.
    Gif(PathBuf),
    /// Extract one representative frame from a video (delegated to ffmpegthumbnailer/ffmpeg). Thumbnail only; no playback.
    Video(PathBuf),
    /// Rasterize page N (1-based) of a PDF (delegated to pdftocairo/pdftoppm/qlmanage/sips). Loaded one page at a time.
    Pdf(PathBuf, u32),
    /// Render a standalone mermaid file to SVG (pure Rust) and rasterize it (max-edge px, theme).
    /// None (unsupported diagram / parse failure) → the caller's text-diagram fallback shows.
    Mermaid(PathBuf, u32, String),
    /// Render mermaid source text (a ```mermaid fence opened full-screen) and rasterize it.
    MermaidSrc(String, u32, String),
    /// Re-rasterize the retained SVG source at a new max-edge px (sharp zoom). The path is only
    /// the base for relative resources inside the SVG (mermaid output has none).
    SvgReraster(std::sync::Arc<Vec<u8>>, PathBuf, u32),
}

impl MediaJob {
    /// Load the actual data (called on a separate thread or via the synchronous fallback). None on failure.
    fn run(self) -> Option<MediaPayload> {
        match self {
            MediaJob::Svg(p, max_px) => {
                let data = std::fs::read(&p).ok()?;
                let img = crate::preview::svg::rasterize_bytes(&data, &p, max_px)?;
                Some(MediaPayload::Vector {
                    img,
                    svg: std::sync::Arc::new(data),
                })
            }
            MediaJob::Gif(p) => match crate::preview::image::decode_gif(&p) {
                Some(frames) => Some(MediaPayload::Gif(frames)),
                // 単一フレーム/アニメでない GIF → 静止画として表示。
                None => crate::preview::image::decode_static(&p).map(MediaPayload::Static),
            },
            MediaJob::Video(p) => crate::preview::video::thumbnail(&p).map(MediaPayload::Static),
            MediaJob::Pdf(p, page) => {
                crate::preview::pdf::render_page(&p, page).map(MediaPayload::Static)
            }
            MediaJob::Mermaid(p, max_px, theme) => {
                let code = std::fs::read_to_string(&p).ok()?;
                MediaJob::MermaidSrc(code, max_px, theme).run()
            }
            MediaJob::MermaidSrc(code, max_px, theme) => {
                let svg = crate::preview::markdown::mermaid_to_svg(&code, &theme)?;
                let data = svg.into_bytes();
                let img =
                    crate::preview::svg::rasterize_bytes(&data, Path::new("mermaid.svg"), max_px)?;
                Some(MediaPayload::Vector {
                    img,
                    svg: std::sync::Arc::new(data),
                })
            }
            MediaJob::SvgReraster(svg, p, max_px) => {
                let img = crate::preview::svg::rasterize_bytes(&svg, &p, max_px)?;
                Some(MediaPayload::Vector { img, svg })
            }
        }
    }
}

/// Result of the **heavy ignored set (`git::ignored`)** computed on a separate thread. Staleness is judged by `gen`, and
/// only the latest generation is applied (results from after moving to another repo while computing are discarded). `workdir` is the
/// repo workdir being computed; on apply it is put into `git_ignored_for` to serve as the Phase G cache key.
pub struct IgnoredResult {
    gen: u64,
    workdir: PathBuf,
    set: std::collections::HashSet<PathBuf>,
}

pub struct App {
    pub mode: Mode,
    pub root: PathBuf,
    /// The directory opened at startup. The base for relative-path display (kept separately because root moves up with h).
    pub open_dir: PathBuf,
    /// The directory opened at startup (immutable). The reset target for `A` ResetAnchor. Kept separately because open_dir moves with `a`.
    launch_dir: PathBuf,
    pub path_style: PathStyle,
    pub key_scheme: KeyScheme,
    pub lang: crate::i18n::Lang,
    pub cfg: Config,

    /// The tree flattened into display order. For M0 it is fine to simply rebuild it every time.
    pub entries: Vec<Entry>,
    pub selected: usize,
    pub show_hidden: bool,
    /// Tree sort settings (FR / M7 auxiliary). Global (not per-tab). Changed via the `s` menu.
    pub sort: Sort,
    /// Whether the `s` sort-selection menu is showing (while true, main intercepts keys).
    sort_menu: bool,
    /// Bookmarks (M7 auxiliary). Lowercase a-z=local (per launch dir) / uppercase A-Z=global.
    pub bookmarks: crate::bookmarks::Bookmarks,
    /// Tab-session persistence (`[ui] restore_tabs`). Attached by main like the loader senders;
    /// `None` (tests) = tab operations never write session files.
    session_store: Option<crate::session::SessionStore>,
    /// True only while `restore_session` is rebuilding the saved tabs. Suppresses the per-op
    /// `save_session` calls that `tab_new`/`tab_goto` would otherwise fire, so a crash mid-restore
    /// cannot overwrite the on-disk session with a partial set; one complete write happens at the end.
    session_restoring: bool,
    /// State of waiting for a letter after `m`/`'` (Set=register / Jump=jump).
    /// Waiting for the letter key after `m` (bookmark set). (`'` opens the list directly.)
    mark_set_pending: bool,
    /// Whether the bookmark-list overlay is showing.
    bookmark_list: bool,
    /// Selection position in the list (a flat index over local on top and global below, concatenated).
    bookmark_list_sel: usize,
    /// Confirmation/input dialog (create `a` / rename `R` / delete `D`). While showing, main intercepts keys.
    dialog: Option<Dialog>,
    /// Multi-selection (M7 Phase B). The set of **absolute paths** selected via `V`/visual. The target of batch delete, etc.
    /// Held by path (not by index), so the selection is preserved across tree rebuilds and filtering.
    selection: BTreeSet<PathBuf>,
    /// Anchor of visual (range) selection mode (entries index). Visual mode is active while it is Some.
    /// Range = anchor to cursor. On confirm, it is taken into `selection`.
    visual_anchor: Option<usize>,
    /// File clipboard (M7 Phase B). Push with `Y`=copy/`X`=cut, apply with `P`=paste.
    clipboard: Option<Clipboard>,
    /// Height (in rows) of the tree display area at the last render. Used as the page size for paging.
    pub tree_viewport: u16,

    /// Tree filter (`/`). Some=filter is active (the query). entries holds the result of narrowing filter_pool.
    tree_filter: Option<String>,
    /// Editing buffer for the filter query. Some=input mode (intercepts keys).
    filter_input: Option<String>,
    /// All entries to filter from (recursively collected under root). Built once when `/` starts.
    filter_pool: Vec<Entry>,
    /// Changed-files-only tree filter (`C`). While true, entries is a flat list of the files with a git
    /// status under root (the review companion for AI-made changes; broot's `:gs` equivalent). Per tab.
    changed_filter: bool,
    /// Follow mode (`F`, global): while true, an external file change (e.g. an AI agent writing) jumps the
    /// tree selection to that file and opens its preview. Any other keypress turns it off (Zed-style).
    follow_mode: bool,
    /// Files changed during the current follow session (since `F` was last turned ON; first-change order,
    /// deduped). Powers the session-scoped `n`/`N` review in follow-opened diffs — "what just changed",
    /// not the whole dirty worktree. Kept after follow turns off (review continues); reset by the next ON.
    follow_session: Vec<PathBuf>,
    /// Whether the current GitDiff preview was opened by follow mode. While true, `n`/`N` and the title's
    /// position indicator use `follow_session` instead of the full git change set.
    diff_follow_scope: bool,

    /// The target, kind, and scroll position (vertical/horizontal) while in Preview mode.
    /// Horizontal scroll is used to view long lines when not wrapping (ui.wrap=false).
    /// To avoid scrolling past the end, the actual clamp is done at render time (when content and screen size are known).
    pub preview_path: Option<PathBuf>,
    pub preview_kind: Option<PreviewKind>,
    pub preview_scroll: u16,
    pub preview_hscroll: u16,
    /// Height (in rows) of the text display area at the last render. Used as the page size for paging.
    pub preview_viewport: u16,
    /// Total wrapped display rows of the current decorated Markdown at the last render (what
    /// `preview_scroll` is clamped against). Set by the preview renderer; used with `MdCache::src_lines`
    /// to map the scroll position back to an approximate source line when opening the editor (`e`).
    pub md_view_rows: usize,

    /// less-style windowed reading for Code/Text (does not read the whole file). Always Some during a Code/Text preview.
    /// While Some, scrolling uses preview_byte_top (the line-head byte) instead of preview_scroll.
    preview_win: Option<crate::preview::window::FileWindow>,
    /// Byte offset of the top line of the window (the scroll position when windowed).
    preview_byte_top: u64,
    /// Absolute line number of the top of the window (0-based). For the line-number gutter. Changes with scrolling, and
    /// is corrected from the total line count when reaching the end.
    preview_top_line: usize,
    /// Cache of the total line count (computed once with count_lines when line numbers are ON).
    preview_total_lines: Option<usize>,
    /// Cache of the highlighted window (avoids re-highlighting on every render).
    win_cache: Option<WinCache>,

    /// Whether the current Code preview is a "heavy first time" (waiting for grammar compilation of a cold language).
    /// While true, the render shows a loading display (indicator) or plain text (progressive).
    /// Judged with `code::is_ext_warm` at preview start; if already warm, false from the start (immediate coloring).
    hl_pending: bool,
    /// Whether a background-thread warm is in progress (prevents double-launch). Common to indicator/progressive.
    hl_warming: bool,
    /// Frame index of the central spinner (advanced by the run loop while waiting on the indicator = animation).
    spinner_frame: usize,

    /// The file requested for external-editor launch via `e`, plus the 1-based line to open at (matching
    /// the on-screen preview position; None = open at the top). The run loop takes it, suspends the TUI, and
    /// launches (because entering/leaving the terminal must happen on the render thread, here we only raise the "request").
    pending_edit: Option<(PathBuf, Option<usize>)>,

    /// Flag requesting launch of an external git tool (lazygit, etc.) via `O`. The run loop takes it, suspends the TUI, and launches.
    pending_git_tool: bool,

    /// Cache of decorated preview content (Markdown/Mermaid).
    /// Avoids re-parsing (pulldown-cmark/syntect/mermaid layout) on every scroll.
    /// It depends on width (to fit mermaid to the display width), so the key is (path, width).
    md_cache: Option<MdCache>,

    /// `R`: show a Markdown/Mermaid preview as its raw source (windowed, like a code file) instead of the
    /// decorated render. Raw mode makes lines/columns match the file, so the 2D caret selection/copy works.
    md_raw: bool,

    /// Cache of raw diff lines for the GitDiff preview (per path). Avoids recomputing `git diff` every frame.
    diff_cache: Option<DiffCache>,
    gutter_cache: Option<GutterCache>,

    /// Interactive items in the Markdown preview (links + task checkboxes, collected on each render).
    /// Focus with Tab/⇧Tab; Enter opens a link / toggles a checkbox, Space toggles a checkbox.
    md_items: Vec<MdItem>,
    /// Index of the focused item (within md_items). None=nothing selected.
    focused_item: Option<usize>,
    /// Per-`<details>`-block open override (ordinal → open), set by `Space`/`Enter` on the summary.
    /// Absent = the default (from the `open` attribute + `ui.md_details`). Reset on file/tab change.
    details_open: std::collections::HashMap<usize, bool>,

    /// In-preview search (`/`, less style). Some=search is active (the query). Highlights matches and moves with n/N.
    /// Supported in Code/Text (windowed) and table previews — see `search_target`.
    preview_search: Option<String>,
    /// Editing buffer for the search query. Some=input mode (intercepts keys, runs on Enter).
    search_input: Option<String>,
    /// For each occurrence: (line-head byte offset, 0-based line number, byte column within the line). The result of `find_all_matches`.
    /// Multiple occurrences on one line become separate elements (so `n`/`N` move per occurrence).
    /// **Table previews reuse this slot as `(0, data row, column)`** — cell coordinates in reading order.
    search_matches: Vec<(u64, usize, usize)>,
    /// The matching table cells as a set, for O(1) lookup while rendering (mirrors `search_matches`).
    /// Kept separate so a large result set does not turn cell drawing into a linear scan.
    table_search_hits: std::collections::HashSet<(usize, usize)>,
    /// Index of the current match (within search_matches).
    search_idx: usize,

    /// Image backend (M2). None if the terminal is unsupported or uninitialized, in which case images fall back to text.
    /// For rendering, ui::preview passes `image` by &mut to StatefulImage. Resize/encode is
    /// offloaded to a separate thread via `img_tx`, and the result is applied in apply_image_resize.
    picker: Option<Picker>,
    img_tx: Option<UnboundedSender<ResizeRequest>>,
    pub image: Option<ThreadProtocol>,
    /// On a kitty-graphics terminal, still images take konoma's own transmit path instead of
    /// ratatui-image's `image`/`ThreadProtocol`: the pixels are **zlib-compressed** (`o=z`), which
    /// shrinks the terminal transfer 2×–50× (the real latency; see docs/PERF-IMAGE-TRANSFER-2026-07).
    /// `use_kitty` is set from the picker's protocol type; on other terminals (sixel/iterm2/
    /// halfblocks) `kitty_image` stays None and the `image` path is used unchanged.
    use_kitty: bool,
    kitty_is_tmux: bool,
    /// The prepared compressed image for the current crop (None until built / on non-kitty terminals).
    kitty_image: Option<crate::preview::kitty::KittyImage>,
    /// Offloads the kitty resize+compress (~30–50 ms) to a worker thread so rapid zoom/pan does not
    /// hitch the UI. The **first** build after opening a file stays synchronous (so the image appears
    /// without a blank frame); subsequent rebuilds (zoom/pan/resize) go async and the previous image
    /// keeps showing until the new one arrives. None in tests → everything runs synchronously.
    kitty_tx: Option<std::sync::mpsc::Sender<KittyResult>>,
    /// Latest-wins generation for async kitty builds: only the newest spawn's result is applied.
    kitty_gen: u64,
    /// The (crop, cols, rows) the current kitty image (or in-flight build) targets. Prevents
    /// re-spawning the same build every frame while the geometry is unchanged.
    kitty_want: Option<KittyGeom>,
    /// The geometry the **currently shown** kitty image was actually built for. A build is in flight
    /// exactly when this differs from `kitty_want` (covers pan, where the cell size is unchanged).
    kitty_shown: Option<KittyGeom>,
    /// The source image (decoded). Zoom/pan crops this at render time and rebuilds the protocol
    /// (because ratatui-image has no offset pan). Held in an `Arc` so the async kitty-build worker
    /// can share it without copying the (potentially large) pixels.
    image_src: Option<std::sync::Arc<image::DynamicImage>>,
    /// Zoom factor. 1.0=the whole image fits, >1.0 zooms in (overflowing the viewport clips and enables pan).
    pub image_zoom: f64,
    /// Display center (image-normalized coordinates [0,1]). Moved by pan. Default is the center.
    image_center: (f64, f64),
    /// The most recently built crop rectangle (source-image px: x,y,w,h). The protocol is rebuilt only when it changes.
    image_crop: Option<(u32, u32, u32, u32)>,
    /// The most recent visible fraction (0..1, w/h). Less than 1 = the image overflows the viewport and is clipped = pan is possible.
    image_vis_frac: (f64, f64),
    /// SVG source of the current image preview when it is vector-backed (SVG file / mermaid diagram).
    /// Zooming past the raster's density re-rasterizes this at the needed scale on a worker thread
    /// ("sharp zoom"); raster images leave it None (pixel zoom only).
    vector_svg: Option<std::sync::Arc<Vec<u8>>>,
    /// Logical (layout) pixel size of a vector-backed image = the dimensions of its **first** raster.
    /// `image_layout` sizes/zooms against this identity, so swapping in a sharper raster changes only
    /// pixel density, never the on-screen geometry (HiDPI-style backing store).
    image_logical: Option<(u32, u32)>,
    /// A full-screen sharp-zoom re-raster is in flight (at most one — key-repeat `+` must not spawn
    /// the same job a dozen times; the inline-fence analog is `MdImgEntry::reraster_inflight`).
    /// Cleared when a media result arrives (`apply_media`) and by `clear_image` (generation bump).
    vector_reraster_inflight: bool,
    /// Where to return when closing a full-screen mermaid-fence view (`q`): the Markdown preview's
    /// scroll offset and Tab-focus index at the moment the fence was opened.
    fence_return: Option<(u16, Option<usize>)>,
    /// Signature of the inline-image overlay drawn last frame (urls + screen rects). When it
    /// changes (scroll/focus moved a diagram, or the document was left), the run loop clears the
    /// terminal once to sweep orphaned kitty unicode-placeholder rows (they are printed into the
    /// terminal grid and a blank-over-blank diff never repaints them).
    md_overlay_last: Option<u64>,
    /// Overlay signature seen during the current frame (None until the overlay draws).
    md_overlay_seen: Option<u64>,
    /// The overlay moved/vanished since the previous frame → the run loop full-redraws once.
    md_overlay_moved: bool,
    /// In-place zoom of the **focused** inline mermaid diagram (`+`/`-` while focused; 1.0 = fit).
    /// The reserved cell area never changes — the zoom crops within it (embedded-map feel).
    fence_zoom: f64,
    /// Pan center of the in-place zoom (image-normalized [0,1]; hjkl while zoomed).
    fence_center: (f64, f64),

    /// PDF: current page (1-based). Each page is rasterized on demand (one at a time) into image_src.
    pdf_page: u32,
    /// PDF: total page count from poppler `pdfinfo`. None = unknown (no poppler) → page navigation disabled.
    pdf_pages: Option<u32>,
    /// mtime of the previewed media file at load time. Media (image/svg/gif/video/pdf) is reloaded on an
    /// FS event only when this changes (avoids re-decoding / re-running external tools on unrelated edits).
    preview_media_mtime: Option<std::time::SystemTime>,

    /// Parsed CSV/TSV table (Some while a table preview is active and parsing succeeded).
    /// None while not a table, or when parsing failed (then the preview degrades to raw text).
    table_data: Option<crate::preview::table::TableData>,
    /// Cell cursor: 0-based data-row index (header is a fixed non-selectable row above).
    table_cur_row: usize,
    /// Cell cursor: 0-based column index.
    table_cur_col: usize,
    /// First visible data row (vertical scroll). Adjusted at render time to keep the cursor visible.
    table_top_row: usize,
    /// First visible column (horizontal scroll). Adjusted at render time to keep the cursor visible.
    table_left_col: usize,
    /// Visible data-row count at the last render (the page size for PageUp/Down). Set by the renderer.
    table_viewport_rows: u16,

    /// Line cursor for windowed (Code/Text) previews: absolute 0-based logical line under the cursor.
    /// The current line is highlighted; `j`/`k` move it (the window follows). Only meaningful while windowed.
    preview_cursor_line: usize,
    /// Column cursor: 0-based char index within the logical line (`h`/`l` move it). The render clamps it to the
    /// line's length and writes the clamp back. Used for the block caret and charwise (`v`) selection.
    preview_cursor_col: usize,
    /// Visual-selection anchor `(line, col)`. Some = selecting. Charwise (`v`) uses both; linewise (`V`) uses the line.
    preview_visual_anchor: Option<(usize, usize)>,
    /// Whether the active selection is linewise (`V`, whole lines) rather than charwise (`v`, exact character range).
    preview_visual_linewise: bool,

    /// GIF animation (M6). All frames (composited RGBA) + each display duration. Empty means no animation (still image).
    /// A separate path from the still-image asynchronous ThreadProtocol: to avoid the "render an unencoded
    /// new protocol → nothing shows" churn in an animation whose frame changes each time, the current frame is **synchronously encoded**
    /// and atomically swapped into `gif_protocol` (see below). Zoom/pan share image_zoom/image_center.
    gif_frames: Vec<(image::DynamicImage, std::time::Duration)>,
    /// Index of the currently displayed GIF frame.
    gif_idx: usize,
    /// The time the current frame began showing (the start point for the next-frame deadline). None=before the first tick.
    gif_shown_at: Option<std::time::Instant>,
    /// The render protocol (kitty, etc.) of the current frame synchronously encoded to the display size. Drawn with the Image widget.
    gif_protocol: Option<Protocol>,
    /// The (frame index, crop rectangle) gif_protocol was built from. Re-encoded only when it changes (avoids wasteful re-encode).
    gif_proto_key: Option<(usize, (u32, u32, u32, u32))>,

    /// Sending end that offloads heavy media loading (SVG rasterize / GIF full-frame decode) to a separate thread.
    /// The result is received by main's poll loop and applied in apply_media. None=synchronous fallback (tests, etc.).
    media_tx: Option<std::sync::mpsc::Sender<MediaResult>>,
    /// Decoded/encoded cache for inline Markdown images, keyed by resolved absolute path.
    md_image_cache: std::collections::HashMap<PathBuf, MdImgEntry>,
    /// Render cache for the tree's detail columns (`ui.details`): path → formatted cells.
    /// Filled lazily for visible rows (render pre-pass) and dropped on every tree rebuild, so the
    /// per-row stat (and the `items` column's read_dir) runs once per tree generation instead of
    /// on every keypress.
    detail_cells_cache: std::collections::HashMap<PathBuf, Vec<String>>,
    /// Sender that offloads inline-image decoding to a background thread.
    md_img_tx: Option<std::sync::mpsc::Sender<MdImageResult>>,
    /// Remote inline-image URLs whose background download is in flight (deduplicates fetches).
    md_remote_inflight: std::collections::HashSet<String>,
    /// Remote inline-image URLs whose download failed — do not retry; they show a text placeholder.
    md_remote_failed: std::collections::HashSet<String>,
    /// Sender that reports the completion of a background remote-image download to the run loop.
    md_remote_tx: Option<std::sync::mpsc::Sender<RemoteFetch>>,
    /// Sender that offloads inline-image encoding (resize + protocol) to the encode worker thread.
    md_enc_tx: Option<std::sync::mpsc::Sender<MdEncodeRequest>>,
    /// Media-load generation. Incremented in enter_preview/clear to make old thread results stale.
    media_gen: u64,
    /// Whether waiting on another thread's media load (used by the render side to show "Loading…").
    media_loading: bool,

    /// Run2 keymap (Surface × key → Action). Built from the config at startup.
    pub keymaps: crate::keymap::KeyMap,
    /// which-key leader-pending state (`Space`=file management / `y`=path copy). After the press, a
    /// which-key menu is shown in the footer and the next keystroke confirms/cancels (a generalization of the old two-key pending_chord).
    pub pending_leader: Option<crate::keymap::LeaderId>,

    /// A transient message (copy result, etc.). Cleared on the next key input. Shown in the status line.
    pub flash: Option<String>,

    /// Visibility state and scroll position of the `?` help (full key list) overlay.
    pub show_help: bool,
    pub help_scroll: u16,
    /// Visibility state of the `i` file-info popup.
    pub show_info: bool,

    /// Tabs (FR-5). Each tab is a tree context. The active tab's working state is held in the fields above as the source of truth.
    tabs: Vec<TabState>,
    active_tab: usize,
    /// Tab-list overlay (`T`). App-global (not per-tab).
    tab_list: bool,
    tab_list_sel: usize,
    /// Heading-outline overlay (`o` in a Markdown preview): jump to any heading.
    outline_open: bool,
    outline_sel: usize,

    /// git status (FR-7). Absolute path → kind. Cached per root and re-fetched when root changes.
    git_status: std::collections::HashMap<PathBuf, crate::git::FileStatus>,
    /// The set of top-level gitignore-excluded entries (`git::ignored`). Used to decide which tree entries are dimmed.
    /// Since it is a heavy computation, it is cached **per repo (workdir)** (`git_ignored_for`), so moving root to a
    /// subdirectory within the same repository does not rebuild it.
    git_ignored: std::collections::HashSet<PathBuf>,
    /// The root at which `git_status`/`git_branch` were computed. If it differs from the current root, a re-fetch is *considered* (but see `git_status_workdir`).
    git_status_for: Option<PathBuf>,
    /// The **repo workdir** `git_status`/`git_branch` cover. `git status` is run from the workdir, so its
    /// result is identical anywhere within the same repo — moving root with `l`/`h` reuses it instead of
    /// re-running a full worktree scan (slow on large repos). Same idea as `git_ignored_for` for the ignore set.
    git_status_workdir: Option<PathBuf>,
    /// The cached `git_status` may be stale (a file changed, a commit/checkout happened, ignore rules
    /// changed): force a recompute on the next `refresh_git_if_needed` even if the workdir is unchanged.
    git_status_dirty: bool,
    /// The **repo workdir** at which `git_ignored` (heavy) was computed. If it is the same, root moves within the same repository
    /// do not rebuild it (avoids the 410ms recomputation when descending into a subdirectory with `l`).
    git_ignored_for: Option<PathBuf>,
    /// The workdir for which `ignored` is being computed on a separate thread (a guard against duplicate dispatch). None=not computing.
    git_ignored_pending: Option<PathBuf>,
    /// Generation of the `ignored` computation. Incremented by +1 on dispatch; a result is applied only if it matches this generation
    /// (discards stale results from after moving to another repo while computing).
    git_ignored_gen: u64,
    /// Flag to **rebuild even for the same repo** because the ignore rules (`.gitignore`/`.git/info/exclude`) changed.
    /// Comes from FS events. Set when a recompute is wanted even if workdir is the same (the old set is kept until the result is applied).
    git_ignored_dirty: bool,
    /// Sender that returns results to the worker computing `ignored` in the background. If not attached (tests, etc.), a synchronous fallback is used.
    ignored_tx: Option<std::sync::mpsc::Sender<IgnoredResult>>,
    /// git diff layout (vertical/horizontal/Auto). Initialized from the `git.diff` setting and cycled with `s`. Used by both the GitDiff preview
    /// and the commit/working-tree detail.
    diff_layout: DiffLayout,
    /// Title override for the detail (git_detail). Used when opening all working-tree changes from the git view, etc.
    git_detail_title: Option<String>,
    /// The current branch name (fetched at the same time as git status). None if not a repo.
    git_branch: Option<String>,

    /// Whether the Git view (the changes hub) is showing. While true, content shows the change list instead of the tree, and
    /// main intercepts keys. When the feature is disabled or it is not a repo, open_git_view does not set it, so it is always false.
    git_view: bool,
    /// Cursor position in the Git view (index within git_view_entries).
    git_view_sel: usize,
    /// The list of changed files shown in the Git view (rebuilt after open/refresh/write).
    git_view_entries: Vec<crate::git::ChangeEntry>,
    /// Whether the GitDiff preview was entered from the Git view. If true, Esc/q returns to the Git view.
    came_from_git_view: bool,

    /// Some if showing the git log (linear, newest first). Shows a full-screen list in content, and main intercepts keys.
    /// When the feature is disabled, it is not a repo, or there are no commits, open_git_log does not set it, so it stays None.
    git_log: Option<Vec<crate::git::CommitInfo>>,
    /// Cursor position in the git log (index within git_log).
    git_log_sel: usize,
    /// Some if showing the commit detail (the DiffLine list from commit_diff). A full screen overlaid on the log.
    git_detail: Option<Vec<crate::git::DiffLine>>,
    /// The **full message, etc. shown at the top** of the commit detail (on Enter from log/graph). None for worktree diffs.
    git_detail_meta: Option<crate::git::CommitMeta>,
    /// Vertical scroll amount of the commit detail.
    git_detail_scroll: u16,
    /// Horizontal scroll amount of the commit detail (for long diff lines).
    git_detail_hscroll: u16,
    /// Number of visible rows when rendering the detail (for clamping g/G and scrolling; updated by the render side).
    git_detail_viewport: u16,
    /// Total line count when rendering the detail (the commit-message header + diff; for clamping the scroll limit; updated by the render side).
    git_detail_total: usize,
    /// Some if showing the branch list (`b`). Shows a full-screen list in content and main intercepts keys.
    git_branches: Option<Vec<crate::git::BranchInfo>>,
    /// Cursor position in the branch list (index within the **filtered** display list).
    git_branch_sel: usize,
    /// Branch filter query (`/`). Empty means all entries.
    git_branch_filter: String,
    /// Whether the branch filter is being typed (while true, main picks up keys as characters).
    git_branch_filtering: bool,
    /// Some if showing the commit graph (`G`, SourceTree/Git Graph style). Shown full-screen in content.
    git_graph: Option<Vec<crate::git::GraphRow>>,
    /// Cursor position in the graph (index within git_graph; sits on a commit row).
    git_graph_sel: usize,
    /// Phase 2: the base branch tip OID for the graph (if Some, pinned in a straight line on lane0). `s`=set / `x`=clear.
    git_graph_base: Option<String>,
    /// Display label for the base (for the title `base: …`; a branch name or a short hash).
    git_graph_base_label: Option<String>,
    /// The **set of local branch names shown** in the graph (for the cap/toggle when there are many branches).
    /// At startup, auto-selected up to `ui.graph_max_branches` by HEAD + base + recency. If it equals the total branch count, `--all`.
    git_graph_visible: std::collections::HashSet<String>,
    /// Legend (branch ⇄ lane color). Computed and cached on graph rebuild.
    git_graph_legend: Vec<crate::git::LegendEntry>,
    /// The number of local branches **hidden by the cap/toggle** (for the legend's `(+K hidden)`).
    git_graph_hidden: usize,
    /// Whether the branch-visibility panel (`b`) is open.
    git_graph_picker: bool,
    /// Cursor position in the panel (row = branch).
    git_graph_picker_sel: usize,
    /// Tentative selection while editing the panel (committed to `git_graph_visible` with Enter / discarded with q).
    git_graph_picker_set: std::collections::HashSet<String>,
    /// The graph's **priority order (display order of all local branches)**. Initialized by `[ui.graph_base_branches]`→HEAD→recency, and
    /// reordered for the current session only with the panel's `J`/`K`. Used for the order of the legend/panel/cap selection/base derivation.
    git_graph_order: Vec<String>,
    /// Whether `J`/`K` reordering was done in the panel (so the base is re-derived to the top branch on Enter confirm).
    git_graph_reordered: bool,
}

/// Path-copy kind (FR-6). Chosen by the key after `c`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CopyKind {
    /// File name only (`cn`).
    Name,
    /// Full path (`cp`).
    Full,
    /// Path relative to where it was opened (`cr`).
    Relative,
    /// Full path of the parent directory (`cd`).
    Parent,
    /// `@relative/path` reference for AI agents (`y@`). Claude Code reads `@path` as file context, so
    /// the path is strictly relative to `open_dir` (the launch/anchor dir where the agent usually runs),
    /// **without** the leading directory name that `Relative` prepends for display.
    AtRef,
}

/// Commit-info copy kind (chosen after `y` in git log/graph/detail).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(not(feature = "git"), allow(dead_code))]
pub enum GitCopyKind {
    /// Short hash (7 digits).
    ShortHash,
    /// Full hash (40 digits).
    FullHash,
    /// Subject (the first line of the message).
    Subject,
    /// Full message (subject + body, multi-line).
    Message,
    /// Author name.
    Author,
    /// Date.
    Date,
}

/// What the in-preview search (`/`) searches, which decides how matches are found and how `n`/`N`
/// move. Each preview kind addresses positions differently, so the search plumbing routes on this
/// instead of testing preview fields in several places.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchTarget {
    /// Code/Text and raw (`R`) Markdown: byte offsets into the file, moved via the read window.
    Windowed,
    /// CSV/TSV: (data row, column) cell coordinates, moved via the cell cursor.
    Table,
    /// Decorated Markdown/Mermaid: indices into the **decorated** lines, moved by scrolling.
    Markdown,
    /// Media and diffs — no search model (`/` flashes a hint).
    Unsupported,
}

/// CSV/TSV table copy kind (chosen after `y` in the table preview).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableCopyKind {
    /// The current cell's value.
    Cell,
    /// The current row's cells joined by the delimiter (`,` / tab).
    Row,
    /// The current column's header plus every cell value, one per line.
    Column,
}

/// Cache of decorated preview content. The key is (path, display width).
/// Everything derivable once per (path, width) lives here so a frame only clones the visible
/// slice (`md_slice`) instead of re-cloning / re-flowing the whole document on every keypress.
struct MdCache {
    path: PathBuf,
    width: u16,
    /// Decorated lines with links already collapsed (label-only; URLs recovered into `items`) —
    /// exactly what the renderer draws, minus the per-frame focus inversion.
    lines: Vec<Line<'static>>,
    /// Tab-cycle items (links / task checkboxes / code-block headers) in document order,
    /// built once from `lines`. Mirrored into `App::md_items` when the cache is (re)built.
    items: Vec<MdItem>,
    /// Block-level inline images reserved within `lines` (Markdown only; empty otherwise).
    images: Vec<crate::preview::markdown::ImagePlacement>,
    /// Number of source lines in the file. Used with the on-screen wrapped-row count to map the scroll
    /// position back to an approximate source line, so `e` opens the editor near the top of the view.
    src_lines: usize,
    /// Widest line in display cells (horizontal-scroll clamp for wrap=off).
    max_line_cols: usize,
    /// wrap=on: visual (post-wrap) start row of each line via ratatui's own per-line reflow;
    /// `len = lines.len() + 1`, last element = total display rows. Empty when wrap=off or width=0.
    row_prefix: Vec<usize>,
    /// Effective mermaid target rows the cache was built with (fit-to-view). A viewport change
    /// only invalidates documents that actually contain fence diagrams.
    fence_rows: u16,
    /// In-page anchor map (GitHub slug → decorated logical-line index) for `[x](#slug)` jumps.
    anchors: Vec<(String, usize)>,
    /// Effective open/closed state of each `<details>` block (document order) as rendered — the base
    /// a `Space`/`Enter` toggle flips.
    details_states: Vec<bool>,
}

/// Cache of raw diff lines for the GitDiff preview. `file_diff` (the git call) does not depend on display width
/// (side-by-side/coloring is done separately at render time), so the key is the path only. This avoids re-invoking git on every
/// scroll/horizontal scroll/resize (aligned with log/graph: load once on open).
/// Since the diff changes when the working tree changes, it is invalidated by `refresh()` (FS events / manual refresh).
struct DiffCache {
    path: PathBuf,
    lines: Vec<crate::git::DiffLine>,
}

/// Cache of the editor-style git gutter marks (per new-file line) for the currently-previewed code/text
/// file. Keyed by path; a working-tree change (`refresh`) drops it so external edits re-derive. Avoids
/// re-invoking `file_diff` (a git call) on every scroll/keypress while previewing.
struct GutterCache {
    path: PathBuf,
    marks: std::collections::HashMap<u32, GutterMark>,
}

/// One interactive item within a rendered Markdown preview: a link or a task-list checkbox.
/// `line`=index of the decorated line (for scrolling). Both are collected straight from the render
/// result (links = underlined blue spans + collapsed targets, checkboxes = `task_marker_style` spans),
/// so no source re-parsing is needed.
#[derive(Clone)]
struct MdItem {
    line: usize,
    kind: MdItemKind,
}

#[derive(Clone)]
enum MdItemKind {
    /// A link; `target`=URL/relative path.
    Link { target: String },
    /// A task checkbox; `state`=its current state char (` `/`x`/custom) as shown.
    Task { state: char },
    /// A fenced code block (its header line is the focus target; `Enter` copies its raw source).
    CodeBlock,
    /// An inline mermaid diagram (image mode); `ordinal`=fence index in document order.
    /// `Enter` opens it full screen with zoom/pan.
    MermaidFence { ordinal: usize },
    /// A `<details>` summary line; `ordinal`=details-block index in document order.
    /// `Enter`/`Space` toggle it collapsed ⇄ expanded.
    Details { ordinal: usize },
}

/// Cache of highlighted lines for windowed reading.
/// The key is (path, top byte, height). Rebuilt only when scroll/vertical resize changes it.
/// (Line content does not depend on display width, so width is not part of the key.)
struct WinCache {
    path: PathBuf,
    byte_top: u64,
    height: u16,
    /// Whether `lines` carry syntax colors. Plain text is cached too (same key space); the flag
    /// keeps a colored window from being mistaken for a plain one when the highlight state flips.
    styled: bool,
    lines: Vec<Line<'static>>,
}

/// A decoded inline Markdown image plus its background-encoded render protocol(s).
#[derive(Default)]
struct MdImgEntry {
    /// The decoded source image (None while the background decode is in flight). Shared with the encode
    /// worker via `Arc` (cheap clone) so cropping/encoding happens off the UI thread.
    decoded: Option<Arc<image::DynamicImage>>,
    /// The graphics protocol for the fully-visible image, encoded for `proto_size`.
    protocol: Option<Protocol>,
    /// The (cols, rows) `protocol` was encoded for.
    proto_size: Option<(u16, u16)>,
    /// The graphics protocol for a partially-scrolled image: only the visible vertical band, cropped and
    /// encoded so the image renders clipped instead of being hidden. Re-encoded when the band changes.
    clip_protocol: Option<Protocol>,
    /// The (cols, full_rows, row_off, vis_rows) band `clip_protocol` was encoded for.
    clip_key: Option<(u16, u16, u16, u16)>,
    /// An encode request is in flight on the worker thread (at most one per image, so scrolling does not
    /// queue a backlog — when it returns, the next render requests the then-current band).
    enc_inflight: bool,
    /// Decode or encode failed — do not retry; the placeholder/text fallback stays visible.
    failed: bool,
    /// In-place zoom protocol for a **focused inline mermaid diagram** (`+`/`-` while focused):
    /// a crop of the source encoded into the same (cols, rows) cell area (the layout never moves).
    zoom_protocol: Option<Protocol>,
    /// The (cols, rows, crop px rect) `zoom_protocol` was encoded for.
    zoom_key: Option<(u16, u16, PxRect)>,
    /// SVG source of a rendered mermaid fence — kept so in-place zoom can re-rasterize at a higher
    /// density (sharp zoom, same mechanism as the full-screen vector zoom).
    svg: Option<std::sync::Arc<Vec<u8>>>,
    /// Layout size = the **first** raster's dimensions. The markdown layout (cells) is computed from
    /// this, so a sharper re-raster never changes the reserved area (the user-visible size is fixed).
    layout_px: Option<(u32, u32)>,
    /// A sharpening re-raster is in flight (at most one per diagram).
    reraster_inflight: bool,
}

/// Outcome of a fence-sharpen check (the sync variant lets tests re-run with the new raster).
#[derive(PartialEq)]
enum FenceSharpen {
    NotNeeded,
    Spawned,
    AppliedSync,
}

/// Which protocol a background encode produces (so the result is stored in the right slot).
#[derive(Clone, Copy, PartialEq, Debug)]
enum MdEncodeKey {
    /// The whole image at (cols, rows) cells.
    Full { cols: u16, rows: u16 },
    /// A cropped vertical band, keyed by (cols, full_rows, row_off, vis_rows).
    Clip {
        cols: u16,
        full_rows: u16,
        row_off: u16,
        vis_rows: u16,
    },
    /// An in-place zoom crop of a focused inline mermaid diagram, encoded into the same
    /// (cols, rows) area. Keyed by the pixel crop so pan/zoom/re-raster all re-encode naturally.
    Zoom { cols: u16, rows: u16, crop: PxRect },
}

/// A request to encode an inline image (or a cropped band of it) off the UI thread (principle #4).
pub struct MdEncodeRequest {
    path: PathBuf,
    key: MdEncodeKey,
    image: Arc<image::DynamicImage>,
    /// Pixel band to crop before encoding; None encodes the whole image.
    crop: Option<PxRect>,
    cols: u16,
    rows: u16,
}

/// Result of a background inline-image encode, delivered to the run loop.
pub struct MdEncodeResult {
    path: PathBuf,
    key: MdEncodeKey,
    /// None = the encode failed. The worker **always** sends a result: swallowing failures left
    /// `enc_inflight` latched on, freezing all re-encodes of that image and keeping
    /// `md_images_loading()` true forever (busy spinner + 16ms polling — idle CPU 0% broken).
    protocol: Option<Protocol>,
}

/// Background worker that encodes inline-image protocols (the whole image or a cropped band) with a
/// cloned Picker, so the UI thread never blocks on the resize/encode (principle #4). Exits when the
/// request sender is dropped (App teardown).
pub fn md_encode_worker(
    picker: Picker,
    rx: std::sync::mpsc::Receiver<MdEncodeRequest>,
    tx: std::sync::mpsc::Sender<MdEncodeResult>,
) {
    while let Ok(req) = rx.recv() {
        let (path, key) = (req.path.clone(), req.key);
        let picker = &picker; // 借用: move クロージャがループ跨ぎで picker を消費しないように
                              // リクエスト処理全体を panic 捕捉で包む: 1件の new_protocol/crop が panic しても
                              // ワーカースレッドを殺さない(殺すと以後の全エンコードが止まり enc_inflight が恒久 latch)。
        let protocol = crate::preview::markdown::catch_silent(move || {
            let img = match req.crop {
                Some((x, y, w, h)) => req.image.crop_imm(x, y, w, h),
                None => (*req.image).clone(),
            };
            let size = ratatui::layout::Size::new(req.cols, req.rows);
            // フェンス図(ベクタ由来)は予約グリッドまで**拡大も**する(Scale): ラスタが小さくても
            // 左上詰めの余白バンドを作らず領域を満たす=シャープさは密度追従の再ラスタが担う。
            // 写真は従来どおり Fit(自然サイズ超に拡大しない=ぼやけさせない)。
            let resize =
                if crate::preview::markdown::is_mermaid_fence_url(&req.path.to_string_lossy()) {
                    Resize::Scale(Some(FilterType::Lanczos3))
                } else {
                    Resize::Fit(Some(FilterType::Lanczos3))
                };
            // 失敗(Err)でも必ず結果を送り返す: 握り潰すと enc_inflight が立ちっぱなしになる。
            picker.new_protocol(img, size, resize).ok()
        })
        .flatten();
        if tx
            .send(MdEncodeResult {
                path,
                key,
                protocol,
            })
            .is_err()
        {
            break;
        }
    }
}

/// Result of a background inline-image decode, delivered to the run loop.
pub struct MdImageResult {
    path: PathBuf,
    image: Result<image::DynamicImage, String>,
    /// SVG source alongside a rendered mermaid fence (kept for in-place sharp zoom). None otherwise.
    svg: Option<std::sync::Arc<Vec<u8>>>,
    /// True when this is a sharpening re-raster of an already-shown diagram: only the pixels are
    /// replaced — the layout size and the decoration cache stay untouched.
    reraster: bool,
}

/// Result of a background remote-image download (curl → local cache file), delivered to the run loop.
/// It carries no bytes: on success the file is already in the cache, so the run loop just invalidates
/// the decoration cache to re-lay the image out; on failure the URL is remembered so it is not retried.
pub struct RemoteFetch {
    url: String,
    ok: bool,
}

impl App {
    pub fn new(root: PathBuf, cfg: Config) -> Result<Self> {
        let path_style = PathStyle::parse(&cfg.ui.path_style);
        let key_scheme = KeyScheme::parse(&cfg.ui.keys);
        let lang = crate::i18n::Lang::resolve(&cfg.ui.lang);
        let sort = Sort::from_config(&cfg.ui.sort);
        // diff の並び初期値 (設定 git.diff)。実行時 `s` で 縦→横→Auto を巡回。
        let diff_layout = DiffLayout::parse(&cfg.git.diff);
        // Run2 キーマップ: 既定 + 設定 (`[keys.<surface>]` + 旧 copy_* alias) をマージし衝突を検証する。
        // page/half プロファイルは ui.keys (vim/less) に従う。Stage 2 は構築のみ (ディスパッチ未接続)。
        let keymaps = crate::keymap::KeyMap::from_config(
            crate::keymap::scheme_from_str(&cfg.ui.keys),
            &cfg.keys.to_keymap_config(),
        );
        let mut app = Self {
            mode: Mode::Tree,
            root: root.clone(),
            open_dir: root.clone(),
            launch_dir: root.clone(),
            path_style,
            key_scheme,
            lang,
            cfg,
            entries: Vec::new(),
            selected: 0,
            show_hidden: false,
            sort,
            sort_menu: false,
            bookmarks: crate::bookmarks::Bookmarks::load(&root),
            session_store: None,
            session_restoring: false,
            mark_set_pending: false,
            bookmark_list: false,
            bookmark_list_sel: 0,
            dialog: None,
            selection: BTreeSet::new(),
            visual_anchor: None,
            clipboard: None,
            tree_viewport: 0,
            tree_filter: None,
            filter_input: None,
            filter_pool: Vec::new(),
            changed_filter: false,
            follow_mode: false,
            follow_session: Vec::new(),
            diff_follow_scope: false,
            preview_path: None,
            preview_kind: None,
            preview_scroll: 0,
            md_view_rows: 0,
            preview_hscroll: 0,
            preview_viewport: 0,
            preview_win: None,
            preview_byte_top: 0,
            preview_top_line: 0,
            preview_total_lines: None,
            win_cache: None,
            hl_pending: false,
            hl_warming: false,
            spinner_frame: 0,
            pending_edit: None,
            pending_git_tool: false,
            md_cache: None,
            md_raw: false,
            diff_cache: None,
            gutter_cache: None,
            md_items: Vec::new(),
            focused_item: None,
            details_open: std::collections::HashMap::new(),
            preview_search: None,
            search_input: None,
            search_matches: Vec::new(),
            table_search_hits: std::collections::HashSet::new(),
            search_idx: 0,
            picker: None,
            img_tx: None,
            image: None,
            use_kitty: false,
            kitty_is_tmux: false,
            kitty_image: None,
            kitty_tx: None,
            kitty_gen: 0,
            kitty_want: None,
            kitty_shown: None,
            image_src: None,
            image_zoom: 1.0,
            image_center: (0.5, 0.5),
            image_crop: None,
            image_vis_frac: (1.0, 1.0),
            vector_svg: None,
            image_logical: None,
            vector_reraster_inflight: false,
            fence_return: None,
            fence_zoom: 1.0,
            fence_center: (0.5, 0.5),
            md_overlay_last: None,
            md_overlay_seen: None,
            md_overlay_moved: false,
            pdf_page: 1,
            pdf_pages: None,
            preview_media_mtime: None,
            table_data: None,
            table_cur_row: 0,
            table_cur_col: 0,
            table_top_row: 0,
            table_left_col: 0,
            table_viewport_rows: 0,
            preview_cursor_line: 0,
            preview_cursor_col: 0,
            preview_visual_anchor: None,
            preview_visual_linewise: false,
            gif_frames: Vec::new(),
            gif_idx: 0,
            gif_shown_at: None,
            gif_protocol: None,
            gif_proto_key: None,
            media_tx: None,
            md_image_cache: std::collections::HashMap::new(),
            detail_cells_cache: std::collections::HashMap::new(),
            md_img_tx: None,
            md_remote_inflight: std::collections::HashSet::new(),
            md_remote_failed: std::collections::HashSet::new(),
            md_remote_tx: None,
            md_enc_tx: None,
            media_gen: 0,
            media_loading: false,
            keymaps,
            pending_leader: None,
            flash: None,
            show_help: false,
            show_info: false,
            help_scroll: 0,
            tabs: Vec::new(),
            active_tab: 0,
            tab_list: false,
            tab_list_sel: 0,
            outline_open: false,
            outline_sel: 0,
            git_status: std::collections::HashMap::new(),
            git_ignored: std::collections::HashSet::new(),
            git_status_for: None,
            git_status_workdir: None,
            git_status_dirty: false,
            git_ignored_for: None,
            git_ignored_pending: None,
            git_ignored_gen: 0,
            git_ignored_dirty: false,
            ignored_tx: None,
            diff_layout,
            git_detail_title: None,
            git_branch: None,
            git_view: false,
            git_view_sel: 0,
            git_view_entries: Vec::new(),
            came_from_git_view: false,
            git_log: None,
            git_log_sel: 0,
            git_detail: None,
            git_detail_meta: None,
            git_detail_scroll: 0,
            git_detail_hscroll: 0,
            git_detail_viewport: 0,
            git_detail_total: 0,
            git_branches: None,
            git_branch_sel: 0,
            git_branch_filter: String::new(),
            git_branch_filtering: false,
            git_graph: None,
            git_graph_sel: 0,
            git_graph_base: None,
            git_graph_base_label: None,
            git_graph_visible: std::collections::HashSet::new(),
            git_graph_legend: Vec::new(),
            git_graph_hidden: 0,
            git_graph_picker: false,
            git_graph_picker_sel: 0,
            git_graph_picker_set: std::collections::HashSet::new(),
            git_graph_order: Vec::new(),
            git_graph_reordered: false,
        };
        app.rebuild_tree()?;
        // 最初のタブとして現在の状態を登録する。
        app.tabs.push(app.snapshot_tab());
        Ok(app)
    }

    /// Attach the per-project session store (`[ui] restore_tabs`). Called by main only, like the
    /// loader senders — tests that need persistence attach a temp-based store explicitly, so plain
    /// `App::new` (unit/e2e tests) never touches the real `~/.config`.
    pub fn attach_session_store(&mut self, store: crate::session::SessionStore) {
        self.session_store = Some(store);
    }

    /// Summarize startup keymap conflicts / ignored settings into one line (for the startup flash; i18n).
    /// Conflicts have already safely fallen back to defaults (#17/FR-8). None if there is nothing.
    pub fn keymap_report(&self) -> Option<String> {
        let nc = self.keymaps.conflicts.len();
        let nw = self.keymaps.warnings.len();
        if nc == 0 && nw == 0 {
            return None;
        }
        let mut parts: Vec<String> = Vec::new();
        if nc > 0 {
            parts.push(match self.lang {
                crate::i18n::Lang::Jp => format!("キー衝突{nc}件(既定で継続)"),
                crate::i18n::Lang::En => format!("{nc} key conflict(s) (using defaults)"),
            });
        }
        if nw > 0 {
            parts.push(match self.lang {
                crate::i18n::Lang::Jp => format!("無効な設定{nw}件を無視"),
                crate::i18n::Lang::En => format!("{nw} invalid key setting(s) ignored"),
            });
        }
        let head = tr(self.lang, crate::i18n::Msg::Keymap);
        Some(format!("{head}: {}", parts.join(" / ")))
    }

    /// Starting from directly under root, recursively expand the expanded directories and flatten them.
    /// A naive implementation for M0. Support for large directories will later be replaced with lazy loading.
    pub fn rebuild_tree(&mut self) -> Result<()> {
        let mut out = Vec::new();
        // HashSet: build_dir checks membership once per child (a Vec scan is E×N comparisons).
        let expanded_dirs: std::collections::HashSet<PathBuf> = self
            .entries
            .iter()
            .filter(|e| e.is_dir && e.expanded)
            .map(|e| e.path.clone())
            .collect();

        build_dir(
            &self.root,
            0,
            &expanded_dirs,
            self.show_hidden,
            self.sort,
            &mut out,
        )?;
        self.entries = out;
        if self.selected >= self.entries.len() {
            self.selected = self.entries.len().saturating_sub(1);
        }
        // entries を作り直したら visual_anchor(entries 添字)は stale。必ず無効化する。
        self.visual_anchor = None;
        // 詳細セルのキャッシュも世代交代(fs が変わった可能性がある節目=ここで必ず破棄)。
        self.detail_cells_cache.clear();
        Ok(())
    }

    /// Fill the detail-column cell cache for the given visible rows (tree render pre-pass).
    /// A path already cached is skipped; the whole cache is dropped by `rebuild_tree` (the choke
    /// point every fs change goes through), so cells are computed once per tree generation.
    pub fn ensure_detail_cells(&mut self, rows: &[(PathBuf, bool)], cols: &[String]) {
        for (path, is_dir) in rows {
            if self.detail_cells_cache.contains_key(path) {
                continue;
            }
            let meta = crate::fileops::quick_meta(path).unwrap_or(crate::fileops::RowMeta {
                is_dir: *is_dir,
                is_symlink: false,
                size: 0,
                mtime: None,
                mode: 0,
            });
            let cells: Vec<String> = cols
                .iter()
                .map(|id| crate::fileops::detail_cell(id, path, &meta).unwrap_or_default())
                .collect();
            self.detail_cells_cache.insert(path.clone(), cells);
        }
    }

    /// Cached detail cells for one row (filled by `ensure_detail_cells`).
    pub fn detail_cells_get(&self, path: &Path) -> Option<&Vec<String>> {
        self.detail_cells_cache.get(path)
    }

    /// Calls `rebuild_tree`, and on failure does not swallow it but reports via flash. Returns `true` on success.
    /// Used on paths that cannot bail out with `?` (bookmark jump, clearing the filter, rebuilding after a git discard).
    /// The return value lets the caller decide whether to show a subsequent success flash (=false means don't).
    fn rebuild_tree_notify(&mut self) -> bool {
        if let Err(e) = self.rebuild_tree() {
            self.flash = Some(format!(
                "{}{e}",
                crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed)
            ));
            false
        } else {
            true
        }
    }

    // --- ソート (FR・M7 補助) -------------------------------------------------
    /// Whether the `s` sort-selection menu is showing.
    pub fn is_sort_menu(&self) -> bool {
        self.sort_menu
    }
    /// Open the sort menu with `s`. main routes the next key here.
    pub fn open_sort_menu(&mut self) {
        self.sort_menu = true;
    }
    /// Close the sort menu (Esc or an out-of-scope key).
    pub fn close_sort_menu(&mut self) {
        self.sort_menu = false;
    }
    /// Key handling for the sort menu. n/s/m/e=select the key (closes after selecting), r=flip asc/desc, .=directories first
    /// (toggles keep it open). Out-of-scope keys close it. If the order changes, rebuild (while filtering, applied after clearing).
    pub fn sort_menu_key(&mut self, c: char) -> Result<()> {
        let keep_open = match c {
            'n' => {
                self.sort.key = SortKey::Name;
                false
            }
            's' => {
                self.sort.key = SortKey::Size;
                false
            }
            'm' => {
                self.sort.key = SortKey::Modified;
                false
            }
            'e' => {
                self.sort.key = SortKey::Ext;
                false
            }
            'r' => {
                self.sort.reverse = !self.sort.reverse;
                true
            }
            '.' => {
                self.sort.dirs_first = !self.sort.dirs_first;
                true
            }
            _ => {
                self.sort_menu = false;
                return Ok(());
            }
        };
        // 絞り込み中は結果順を変えない(クリア後にツリー再構築で反映)。
        if self.tree_filter.is_none() {
            self.rebuild_tree()?;
        }
        self.sort_menu = keep_open;
        Ok(())
    }
    /// Current sort display for the top context bar (e.g. `sort: mod ↑`).
    pub fn sort_label(&self) -> String {
        let k = match self.sort.key {
            SortKey::Name => "name",
            SortKey::Size => "size",
            SortKey::Modified => "mod",
            SortKey::Ext => "ext",
        };
        let arrow = if self.sort.reverse { "" } else { "" };
        format!("sort: {k} {arrow}")
    }

    // --- モード表示 (2軸: 表示モード × 内部モード) ----------------------------
    /// Display mode (for the outer chip). Preview becomes Image if it is an image.
    pub fn display_mode(&self) -> DisplayMode {
        match self.mode {
            Mode::Tree => DisplayMode::Tree,
            Mode::Preview => {
                if self.is_image_preview() {
                    DisplayMode::Image
                } else if self.is_table_preview() {
                    DisplayMode::Table
                } else {
                    DisplayMode::Preview
                }
            }
        }
    }
    /// Internal mode (for the inner chip and footer switching). None if nothing is being operated.
    /// Priority: dialog > filter/search/sort/mark/bookmarks > visual.
    pub fn internal_mode(&self) -> Option<InternalMode> {
        if let Some(d) = &self.dialog {
            return Some(match &d.kind {
                // アプリ終了確認は非破壊。削除/ドロップとは別チップ/フッターにする。
                DialogKind::Confirm { .. } if self.confirm_is_quit() => InternalMode::QuitConfirm,
                // ブックマーク上書き確認も非破壊=別チップ/フッター。
                DialogKind::Confirm { .. } if self.confirm_is_bookmark() => {
                    InternalMode::BookmarkConfirm
                }
                // D&D 転送は破壊的でないので削除確認とは別チップ/フッターにする。
                DialogKind::Confirm { .. } if self.confirm_is_drop() => InternalMode::DropConfirm,
                DialogKind::Confirm { .. } => InternalMode::DeleteConfirm,
                DialogKind::Preview { .. } => InternalMode::RenamePreview,
                DialogKind::Input { .. } => match &d.op {
                    PendingOp::Create { .. } => InternalMode::Create,
                    PendingOp::BatchRenameInput { .. } => InternalMode::BatchRename,
                    PendingOp::GitCommit => InternalMode::Commit,
                    PendingOp::GitCreateBranch => InternalMode::GitBranch,
                    _ => InternalMode::Rename,
                },
            });
        }
        // コミット詳細は log の上に被さるので先に判定する。
        if self.is_git_detail() {
            return Some(InternalMode::GitDetail);
        }
        if self.is_git_log() {
            return Some(InternalMode::GitLog);
        }
        // パネルはグラフの上に被さる(is_git_graph も true なので先に判定)。
        if self.is_git_graph_picker() {
            return Some(InternalMode::GitGraphPicker);
        }
        if self.is_git_graph() {
            return Some(InternalMode::GitGraph);
        }
        if self.is_git_branches() {
            return Some(InternalMode::GitBranch);
        }
        if self.is_git_view() {
            return Some(InternalMode::GitChanges);
        }
        if self.is_git_diff_preview() {
            return Some(InternalMode::GitDiff);
        }
        if self.is_filtering() {
            return Some(InternalMode::Filter);
        }
        if self.is_searching() {
            return Some(InternalMode::Search);
        }
        if self.is_sort_menu() {
            return Some(InternalMode::Sort);
        }
        if self.is_marking() {
            return Some(InternalMode::Mark);
        }
        if self.is_bookmark_list() {
            return Some(InternalMode::Bookmarks);
        }
        if self.is_tab_list() {
            return Some(InternalMode::Tabs);
        }
        if self.is_outline() {
            return Some(InternalMode::Outline);
        }
        if self.is_info() {
            return Some(InternalMode::Info);
        }
        if self.is_visual() {
            return Some(InternalMode::Visual);
        }
        if self.is_preview_visual() {
            return Some(InternalMode::PreviewVisual);
        }
        if self.changed_filter && matches!(self.mode, Mode::Tree) {
            return Some(InternalMode::ChangedFilter);
        }
        None
    }

    /// The **frontmost surface** that currently receives keys (the single source of truth for Run2 keymap dispatch).
    /// Strictly follows the same priority as internal_mode, while also including the base full screens (Tree/Preview) and overlays (§4).
    /// Off the render path; references only existing bool predicates (same cost as now).
    pub fn surface(&self) -> crate::keymap::Surface {
        use crate::keymap::Surface as S;
        // ダイアログ最優先 (種別で細分: 入力 / 削除確認 / ドロップ確認 / リネームプレビュー)。
        if self.is_dialog() {
            if self.dialog_is_preview() {
                return S::DialogRenamePreview;
            }
            if self.dialog_is_confirm() {
                if self.confirm_is_quit() {
                    return S::DialogConfirmQuit;
                }
                if self.confirm_is_bookmark() {
                    return S::DialogConfirmBookmark;
                }
                if self.confirm_is_drop() {
                    return S::DialogConfirmDrop;
                }
                return S::DialogConfirmDelete;
            }
            return S::DialogInput;
        }
        // ヘルプ (全要素の上)。
        if self.show_help {
            return S::Help;
        }
        // Git オーバーレイ (詳細 > log > graph > branches > 変更ハブ > diff)。feature 無効時は到達しない。
        #[cfg(feature = "git")]
        {
            if self.is_git_detail() {
                return S::GitDetail;
            }
            if self.is_git_log() {
                return S::GitLog;
            }
            // パネルはグラフの上に被さる(is_git_graph も true なので先に判定)。
            if self.is_git_graph_picker() {
                return S::GitGraphPicker;
            }
            if self.is_git_graph() {
                return S::GitGraph;
            }
            if self.is_git_branches() {
                return if self.git_branch_filtering() {
                    S::BranchFilter
                } else {
                    S::GitBranches
                };
            }
            if self.is_git_view() {
                return S::GitChanges;
            }
            if self.is_git_diff_preview() {
                return S::PreviewGitDiff;
            }
        }
        // 入力系 / メニュー / 一覧 / 情報 / ビジュアル。
        if self.is_filtering() {
            return S::Filter;
        }
        if self.is_searching() {
            return S::Search;
        }
        if self.is_sort_menu() {
            return S::Sort;
        }
        if self.is_marking() {
            return S::Mark;
        }
        if self.is_bookmark_list() {
            return S::Bookmarks;
        }
        if self.is_tab_list() {
            return S::Tabs;
        }
        if self.is_outline() {
            return S::Outline;
        }
        if self.is_info() {
            return S::Info;
        }
        if self.is_visual() {
            return S::Visual;
        }
        // 基本全画面 (Preview は画像/テキストで分岐)。
        match self.mode {
            Mode::Preview => {
                if self.is_image_preview() {
                    S::PreviewImage
                } else if self.is_table_preview() {
                    S::PreviewTable
                } else if self.is_preview_visual() {
                    S::PreviewTextVisual
                } else {
                    S::PreviewText
                }
            }
            Mode::Tree => S::Tree,
        }
    }

    // --- コピー/カット&ペースト (M7 Phase B・既定キー Y/X/P・keymap で変更可) ---
    /// Label for the context display: "copy 3" / "cut 3". None if the clipboard is empty.
    pub fn clipboard_label(&self) -> Option<String> {
        self.clipboard.as_ref().map(|c| {
            let verb = match c.op {
                ClipOp::Copy => crate::i18n::tr(self.lang, crate::i18n::Msg::CopyHint),
                ClipOp::Cut => crate::i18n::tr(self.lang, crate::i18n::Msg::CutHint),
            };
            format!("{verb} {}", c.paths.len())
        })
    }
    /// `Y`=copy: push the selection (or the cursor if none) to the clipboard (for duplication). The selection is cleared.
    pub fn copy_selection(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let n = targets.len();
        self.clipboard = Some(Clipboard {
            op: ClipOp::Copy,
            paths: targets,
        });
        self.clear_selection();
        self.flash = Some(format!(
            "{} ({n})",
            crate::i18n::tr(self.lang, crate::i18n::Msg::Copied)
        ));
    }
    /// `X`=cut: push the selection (or the cursor if none) to the clipboard (for moving). The selection is cleared.
    pub fn cut_selection(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let n = targets.len();
        self.clipboard = Some(Clipboard {
            op: ClipOp::Cut,
            paths: targets,
        });
        self.clear_selection();
        self.flash = Some(format!(
            "{} ({n})",
            crate::i18n::tr(self.lang, crate::i18n::Msg::CutDone)
        ));
    }
    /// `P`=paste: apply to the cursor-based directory. Copy duplicates, cut moves (consumed). **Never overwrites.**
    pub fn paste(&mut self) -> Result<()> {
        let Some(clip) = self.clipboard.clone() else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::ClipboardEmpty).into());
            return Ok(());
        };
        let dir = self.op_base_dir();
        let (mut ok, mut last, mut err) = (0usize, None, None);
        for src in &clip.paths {
            // 自分自身(やその中)への貼り付けは無限コピーになるので弾く。
            if dir.starts_with(src) {
                err = Some(
                    crate::i18n::tr(self.lang, crate::i18n::Msg::CannotPasteIntoSelf).to_string(),
                );
                continue;
            }
            let res = match clip.op {
                ClipOp::Copy => crate::fileops::copy_into(&dir, src),
                ClipOp::Cut => crate::fileops::move_into(&dir, src),
            };
            match res {
                Ok(p) => {
                    ok += 1;
                    last = Some(p);
                }
                Err(e) => err = Some(e.to_string()),
            }
        }
        if matches!(clip.op, ClipOp::Cut) {
            self.clipboard = None; // カットは消費(元が移動済み)
        }
        self.refresh()?;
        if let Some(p) = &last {
            self.reveal_and_select(p)?;
        }
        self.flash = Some(match err {
            Some(e) => format!(
                "{} {ok} / {}: {e}",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Pasted),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Failed),
            ),
            None => format!(
                "{} ({ok})",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Pasted)
            ),
        });
        Ok(())
    }

    /// `Space→D`=duplicate: copy each target **in place** (into its own parent directory) with a
    /// collision-free name (`note copy.md`, then `note copy 2.md`). Operates on the selection, or the
    /// cursor entry when none. Directories are duplicated recursively (as a sibling `dir copy`), and
    /// symlinks are copied as links — both via `copy_into`. Never overwrites. The last new item is
    /// revealed and selected so the result is visible.
    pub fn duplicate_selection(&mut self) -> Result<()> {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return Ok(());
        }
        let (mut ok, mut last, mut err) = (0usize, None, None);
        for src in &targets {
            // 親ディレクトリ = 複製先(その場に複製)。ルート等で親が無ければ失敗扱い(クラッシュしない)。
            let Some(dir) = src.parent() else {
                err =
                    Some(crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed).to_string());
                continue;
            };
            match crate::fileops::copy_into(dir, src) {
                Ok(p) => {
                    ok += 1;
                    last = Some(p);
                }
                Err(e) => err = Some(e.to_string()),
            }
        }
        self.clear_selection();
        self.refresh()?;
        if let Some(p) = &last {
            self.reveal_and_select(p)?;
        }
        self.flash = Some(match err {
            Some(e) => format!(
                "{} {ok} / {}: {e}",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Duplicated),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
            ),
            None => format!(
                "{} ({ok})",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Duplicated)
            ),
        });
        Ok(())
    }

    /// The selection listed in the **current sort order (tree display order)**. Used as the numbering order for sequential rename.
    /// Selections not present in entries (collapsed, etc.) are appended at the end in path order.
    fn selection_in_display_order(&self) -> Vec<PathBuf> {
        let mut v: Vec<PathBuf> = self
            .entries
            .iter()
            .filter(|e| self.selection.contains(&e.path))
            .map(|e| e.path.clone())
            .collect();
        for p in &self.selection {
            if !v.contains(p) {
                v.push(p.clone());
            }
        }
        v
    }
    /// Heading for the batch-rename input dialog (the count + a placeholder legend).
    fn batch_rename_title(&self, count: usize) -> String {
        format!(
            "{} {} {}  {{n}} {{n:0W}} {{name}} {{ext}}",
            crate::i18n::tr(self.lang, crate::i18n::Msg::BatchRename),
            count,
            crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
        )
    }
    /// `R` (with a selection)=batch rename. Opens template input that numbers the selection sequentially in display order.
    pub fn start_batch_rename(&mut self) {
        let targets = self.selection_in_display_order();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let title = self.batch_rename_title(targets.len());
        self.dialog = Some(Dialog {
            op: PendingOp::BatchRenameInput { targets },
            kind: DialogKind::Input {
                title,
                buffer: String::new(),
                cursor: 0,
            },
        });
    }

    /// `a`=create. Opens an input dialog to create with the entered name in the cursor-based directory (a trailing `/` makes a folder).
    pub fn start_create(&mut self) {
        let dir = self.op_base_dir();
        let where_ = self.format_path(&dir);
        self.dialog = Some(Dialog {
            op: PendingOp::Create { dir },
            kind: DialogKind::Input {
                title: format!(
                    "{} in {where_}  ({})",
                    crate::i18n::tr(self.lang, crate::i18n::Msg::Create),
                    crate::i18n::tr(self.lang, crate::i18n::Msg::TrailingSlashFolder),
                ),
                buffer: String::new(),
                cursor: 0,
            },
        });
    }

    /// `R`=rename. An input dialog to change the cursor's file/directory name (prefilled with the current name).
    pub fn start_rename(&mut self) {
        let Some(target) = self.entries.get(self.selected).map(|e| e.path.clone()) else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        };
        let name = target
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_string();
        let cursor = name.chars().count(); // 末尾にカーソルを置く。
        self.dialog = Some(Dialog {
            op: PendingOp::Rename { target },
            kind: DialogKind::Input {
                title: crate::i18n::tr(self.lang, crate::i18n::Msg::Rename).into(),
                buffer: name,
                cursor,
            },
        });
    }

    /// `D`=delete (with confirmation). Opens a confirmation dialog targeting **all selected items if there is a selection**, or the cursor item otherwise.
    /// `y`=send to trash (recoverable) / `!`=permanent delete (unrecoverable) / `n`,Esc=cancel.
    pub fn start_delete(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        // メッセージ: 1件は名前、複数件は「N 件 (先頭名 他)」。
        let label = if targets.len() == 1 {
            targets[0]
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("?")
                .to_string()
        } else {
            let first = targets[0]
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("?");
            format!(
                "{} {} ({first} {})",
                targets.len(),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Etc),
            )
        };
        self.dialog = Some(Dialog {
            op: PendingOp::Delete { targets },
            kind: DialogKind::Confirm {
                message: format!(
                    "{}: {label}",
                    crate::i18n::tr(self.lang, crate::i18n::Msg::DeleteTarget),
                ),
                allow_permanent: true,
            },
        });
    }

    /// A mutable reference to the (buffer, cursor) being edited. None if not an input dialog.
    fn dialog_input_mut(&mut self) -> Option<(&mut String, &mut usize)> {
        match self.dialog.as_mut() {
            Some(Dialog {
                kind: DialogKind::Input { buffer, cursor, .. },
                ..
            }) => Some((buffer, cursor)),
            _ => None,
        }
    }

    /// Insert one character at the cursor position in the input dialog and advance the cursor by one.
    pub fn dialog_input_push(&mut self, c: char) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            let at = char_byte(buffer, *cursor);
            buffer.insert(at, c);
            *cursor += 1;
        }
    }
    /// Delete the character just before the cursor (Backspace).
    pub fn dialog_input_backspace(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            if *cursor > 0 {
                let start = char_byte(buffer, *cursor - 1);
                let end = char_byte(buffer, *cursor);
                buffer.replace_range(start..end, "");
                *cursor -= 1;
            }
        }
    }
    /// Delete the character at the cursor position (Delete). The cursor does not move.
    pub fn dialog_input_delete(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            let count = buffer.chars().count();
            if *cursor < count {
                let start = char_byte(buffer, *cursor);
                let end = char_byte(buffer, *cursor + 1);
                buffer.replace_range(start..end, "");
            }
        }
    }
    /// Move the cursor left (←).
    pub fn dialog_cursor_left(&mut self) {
        if let Some((_, cursor)) = self.dialog_input_mut() {
            *cursor = cursor.saturating_sub(1);
        }
    }
    /// Move the cursor right (→). Clamped at the end.
    pub fn dialog_cursor_right(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            *cursor = (*cursor + 1).min(buffer.chars().count());
        }
    }
    /// Move the cursor to the start (Home).
    pub fn dialog_cursor_home(&mut self) {
        if let Some((_, cursor)) = self.dialog_input_mut() {
            *cursor = 0;
        }
    }
    /// Move the cursor to the end (End).
    pub fn dialog_cursor_end(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            *cursor = buffer.chars().count();
        }
    }
    /// Cancel the dialog (Esc / confirm n).
    pub fn dialog_cancel(&mut self) {
        self.dialog = None;
    }

    /// Handle a quit request (`q` at the top level / `Q` from anywhere). If `ui.confirm_quit` is on,
    /// open a yes/no confirmation dialog and return `true` (the caller must NOT quit yet). Otherwise
    /// return `false` (the caller quits immediately).
    pub fn request_quit(&mut self) -> bool {
        if !self.cfg.ui.confirm_quit {
            return false;
        }
        self.dialog = Some(Dialog {
            op: PendingOp::Quit,
            kind: DialogKind::Confirm {
                message: crate::i18n::tr(self.lang, crate::i18n::Msg::QuitConfirm).into(),
                allow_permanent: false,
            },
        });
        true
    }

    /// Confirm the text-input dialog (Enter). Performs create/rename.
    pub fn dialog_submit(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        let DialogKind::Input { buffer, .. } = dialog.kind else {
            return Ok(()); // 確認ダイアログはここへ来ない
        };
        // コミットは名前と扱いが違う(末尾 / を剥がさない・独自の空チェック)ので先に分岐。
        if matches!(dialog.op, PendingOp::GitCommit) {
            let message = buffer.trim();
            if message.is_empty() {
                self.flash =
                    Some(crate::i18n::tr(self.lang, crate::i18n::Msg::MessageEmpty).into());
                return Ok(());
            }
            match crate::git::commit(&self.root, message) {
                Ok(()) => {
                    // ステージ済み index でコミット成功 → git データ再取得+ビュー更新。
                    self.refresh()?;
                    if self.is_git_view() {
                        self.git_view_reload();
                    }
                    self.flash =
                        Some(crate::i18n::tr(self.lang, crate::i18n::Msg::Committed).into());
                }
                Err(e) => {
                    // 失敗(stderr)を表示し、同じメッセージで入力ダイアログを再オープン(やり直せる)。
                    self.flash = Some(format!("{e}"));
                    let cursor = message.chars().count();
                    self.dialog = Some(Dialog {
                        op: PendingOp::GitCommit,
                        kind: DialogKind::Input {
                            title: crate::i18n::tr(self.lang, crate::i18n::Msg::CommitMessage)
                                .into(),
                            buffer: message.to_string(),
                            cursor,
                        },
                    });
                }
            }
            return Ok(());
        }
        // 新規ブランチ作成(コミット同様、名前を素直に trim して扱う)。
        if matches!(dialog.op, PendingOp::GitCreateBranch) {
            let bname = buffer.trim();
            if bname.is_empty() {
                self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NameEmpty).into());
                return Ok(());
            }
            match crate::git::create_branch(&self.root, bname) {
                Ok(()) => {
                    self.refresh()?;
                    self.refresh_git_if_needed(); // ブランチ名/状態のキャッシュを即更新
                    self.close_git_branches(); // 作成&切替済み → 一覧を閉じて Git ビューへ
                    self.flash = Some(format!(
                        "{}: {bname}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::CreatedBranch)
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!("{e}"));
                    let cursor = bname.chars().count();
                    self.dialog = Some(Dialog {
                        op: PendingOp::GitCreateBranch,
                        kind: DialogKind::Input {
                            title: crate::i18n::tr(self.lang, crate::i18n::Msg::NewBranch).into(),
                            buffer: bname.to_string(),
                            cursor,
                        },
                    });
                }
            }
            return Ok(());
        }
        let name = buffer.trim().trim_end_matches('/').trim();
        let want_folder = buffer.trim_end().ends_with('/');
        if name.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NameEmpty).into());
            return Ok(());
        }
        match dialog.op {
            PendingOp::Create { dir } => {
                let created = if want_folder {
                    crate::fileops::create_dir(&dir, name)
                } else {
                    crate::fileops::create_file(&dir, name)
                };
                match created {
                    Ok(path) => {
                        self.refresh()?;
                        self.reveal_and_select(&path)?;
                        self.flash = Some(format!(
                            "{}: {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Created),
                            self.format_path(&path)
                        ));
                    }
                    Err(e) => {
                        self.flash = Some(format!(
                            "{}: {e}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                        ))
                    }
                }
            }
            PendingOp::Rename { target } => match crate::fileops::rename(&target, name) {
                Ok(path) => {
                    self.refresh()?;
                    self.reveal_and_select(&path)?;
                    self.flash = Some(format!(
                        "{}: {}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Renamed),
                        self.format_path(&path)
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            PendingOp::BatchRenameInput { targets } => {
                match build_rename_plan(&targets, name) {
                    Ok(plan) => {
                        // プレビュー(旧 → 新)へ遷移。適用は dialog_preview_apply。
                        let lines: Vec<String> = plan
                            .iter()
                            .map(|(s, d)| {
                                format!(
                                    "{}{}",
                                    s.file_name().and_then(|n| n.to_str()).unwrap_or("?"),
                                    d.file_name().and_then(|n| n.to_str()).unwrap_or("?"),
                                )
                            })
                            .collect();
                        let title = format!(
                            "{} {} {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Rename),
                            plan.len(),
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
                        );
                        self.dialog = Some(Dialog {
                            op: PendingOp::BatchRenameApply { plan },
                            kind: DialogKind::Preview {
                                title,
                                lines,
                                scroll: 0,
                            },
                        });
                    }
                    Err(e) => {
                        // 入力をやり直せるよう、同じテンプレで入力ダイアログを再オープン。
                        self.flash = Some(format!(
                            "{}: {e}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                        ));
                        let cursor = name.chars().count();
                        let title = self.batch_rename_title(targets.len());
                        self.dialog = Some(Dialog {
                            op: PendingOp::BatchRenameInput { targets },
                            kind: DialogKind::Input {
                                title,
                                buffer: name.to_string(),
                                cursor,
                            },
                        });
                    }
                }
            }
            // 削除/Git 破棄は確認ダイアログ側 / 一括リネーム適用はプレビュー側。
            // GitCommit は上で早期 return 済みなので到達しない。
            PendingOp::Delete { .. }
            | PendingOp::BatchRenameApply { .. }
            | PendingOp::GitDiscard { .. }
            | PendingOp::GitCommit
            | PendingOp::GitCreateBranch
            | PendingOp::GitDeleteBranch { .. }
            | PendingOp::DropTransfer { .. }
            | PendingOp::BookmarkOverwrite { .. }
            | PendingOp::Quit => {}
        }
        Ok(())
    }

    /// In the preview, `y`=apply the batch rename. Two-phase rename → reload → clear selection.
    pub fn dialog_preview_apply(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        if let PendingOp::BatchRenameApply { plan } = dialog.op {
            match crate::fileops::batch_rename(&plan) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Renamed),
                        plan.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            }
        }
        Ok(())
    }

    /// Response to a confirmation dialog. yes=execute (delete → trash, recoverable) / no=cancel.
    pub fn dialog_confirm(&mut self, yes: bool) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        if !yes {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::Canceled).into());
            return Ok(());
        }
        match dialog.op {
            PendingOp::Delete { targets } => match crate::fileops::move_to_trash(&targets) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::MovedToTrash),
                        targets.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            // Git ビューの破棄: git::discard → 一覧/ツリーの git status を取り直す。
            // GitDiff プレビューからの破棄(came_from_git_view)なら Git ビューを開き直して戻す。
            PendingOp::GitDiscard { path } => match crate::git::discard(&self.root, &path) {
                Ok(()) => {
                    let from_diff = self.is_git_diff_preview();
                    if from_diff {
                        // プレビューを畳んで Git ビューへ復帰。
                        self.came_from_git_view = false;
                        self.back_to_tree();
                        self.open_git_view();
                    }
                    self.git_view_reload();
                    // 破棄自体は成功。ツリー再構築が失敗した時はその旨を通知し、
                    // 成功 flash で上書きしない(誤って「成功」と見せない)。
                    if self.rebuild_tree_notify() {
                        self.flash = Some(format!(
                            "{}: {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Discarded),
                            self.format_path(&path)
                        ));
                    }
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            // ブランチ削除(安全): git branch -d。失敗(未マージ等)は git の stderr を flash。
            PendingOp::GitDeleteBranch { name } => self.git_delete_branch(&name, false),
            // ブックマーク上書きの確定: 実際に登録する(mark_input と同じ経路)。
            PendingOp::BookmarkOverwrite { key, target } => self.perform_mark_set(key, target),
            _ => {}
        }
        Ok(())
    }

    /// In a confirmation dialog, `!`=**permanent delete / force** (delete=without going through the trash / branch=`-D` force).
    pub fn dialog_delete_permanent(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        // ブランチの強制削除 (`-D`)。
        if let PendingOp::GitDeleteBranch { name } = &dialog.op {
            self.git_delete_branch(&name.clone(), true);
            return Ok(());
        }
        if let PendingOp::Delete { targets } = dialog.op {
            match crate::fileops::delete_permanently(&targets) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::DeletedPermanently),
                        targets.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            }
        }
        Ok(())
    }

    pub fn tree_next(&mut self) {
        if self.selected + 1 < self.entries.len() {
            self.selected += 1;
        }
    }

    pub fn tree_prev(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// To the top of the tree.
    pub fn tree_first(&mut self) {
        self.selected = 0;
    }

    /// To the bottom of the tree.
    pub fn tree_last(&mut self) {
        self.selected = self.entries.len().saturating_sub(1);
    }

    /// Page the tree by one (dir: +1=next / -1=previous). Overlaps one row to keep context.
    pub fn tree_page(&mut self, dir: i32) {
        let page = self.tree_viewport.saturating_sub(1).max(1) as i32;
        self.tree_move(dir * page);
    }

    /// Half-page the tree (vim: Ctrl-d/Ctrl-u, less: d/u).
    pub fn tree_half_page(&mut self, dir: i32) {
        let half = (self.tree_viewport / 2).max(1) as i32;
        self.tree_move(dir * half);
    }

    /// Move the selection by delta rows and clamp it to [0, end].
    fn tree_move(&mut self, delta: i32) {
        self.selected = clamp_cursor(self.selected, delta, self.entries.len());
    }

    /// If a directory, toggle expansion; if a file, transition to Preview.
    /// While filtering (a flat result list), expand-toggle is meaningless, so behave the same as `tree_descend`.
    pub fn tree_activate(&mut self) -> Result<()> {
        if self.tree_filter.is_some() || self.changed_filter {
            return self.tree_descend();
        }
        let Some(entry) = self.entries.get(self.selected).cloned() else {
            return Ok(());
        };
        if entry.is_dir {
            // expanded をトグルして再構築
            if let Some(e) = self.entries.get_mut(self.selected) {
                e.expanded = !e.expanded;
            }
            self.rebuild_tree()?;
        } else {
            self.enter_preview(&entry.path);
        }
        Ok(())
    }

    /// Before switching root, discard state that points to items of the old root.
    /// `selection` is held by path, so under a different root it stays invisible yet becomes a target for mis-operations (a footgun), and
    /// `visual_anchor` is an entries index, so it goes stale under a different root. The filter and preview search are also
    /// for the old root, so they are cleared together (rebuild_tree also invalidates visual_anchor, but we do it explicitly).
    fn clear_for_root_change(&mut self) {
        self.selection.clear();
        self.visual_anchor = None;
        self.clear_filter_state();
        self.search_clear();
    }

    /// Move to the parent directory (raise the root). For `h`. While filtering, first clear the filter (the normal tree of the current root).
    pub fn tree_leave(&mut self) -> Result<()> {
        if self.tree_filter.is_some() {
            self.filter_clear();
            return Ok(());
        }
        if self.changed_filter {
            self.toggle_changed_filter(); // OFF に戻す(通常ツリーへ)
            return Ok(());
        }
        if let Some(parent) = self.root.parent().map(Path::to_path_buf) {
            self.clear_for_root_change();
            self.root = parent;
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        }
        Ok(())
    }

    /// Descend into the selected directory (make that directory the new root). For `l`.
    /// Symmetric to `h` (to the parent). If a file, transition to Preview.
    /// Works on filter results too: directory → move there and clear the filter / file → preview.
    pub fn tree_descend(&mut self) -> Result<()> {
        let Some(entry) = self.entries.get(self.selected).cloned() else {
            return Ok(());
        };
        let was_filtering = self.tree_filter.is_some();
        if entry.is_dir {
            // root を変えるので旧 root の選択/ビジュアル/絞り込み/検索を破棄する(持ち越さない)。
            self.clear_for_root_change();
            self.root = entry.path;
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        } else {
            // ファイルは絞り込みを保ったままプレビュー(戻ると結果一覧に復帰)。
            let _ = was_filtering;
            self.enter_preview(&entry.path);
        }
        Ok(())
    }

    pub fn toggle_hidden(&mut self) -> Result<()> {
        self.show_hidden = !self.show_hidden;
        self.rebuild_tree()
    }

    // --- フォローモード (`F`) — Agent Watch ② -------------------------------------
    /// `F`: toggle follow mode (auto-jump to externally changed files; the "watch the AI work" view).
    /// Turning it ON starts a fresh follow session (the "what changed while following" list for `n`/`N`).
    pub fn toggle_follow(&mut self) {
        self.follow_mode = !self.follow_mode;
        if self.follow_mode {
            self.follow_session.clear();
        }
        let msg = if self.follow_mode {
            crate::i18n::Msg::FollowOn
        } else {
            crate::i18n::Msg::FollowOff
        };
        self.flash = Some(tr(self.lang, msg).into());
    }

    /// Whether follow mode is on (chip display / the run loop's jump gate).
    pub fn follow_enabled(&self) -> bool {
        self.follow_mode
    }

    /// The user took over the keyboard (pressed any key not bound to `F`): stop following (Zed-style —
    /// following is a hands-off state; re-enable with one `F`). Flash so the state change is visible.
    pub fn follow_break(&mut self) {
        if self.follow_mode {
            self.follow_mode = false;
            self.flash = Some(tr(self.lang, crate::i18n::Msg::FollowOff).into());
        }
    }

    /// Follow-mode jump: reveal `path` in the tree and open its preview. Gated to meaningful targets:
    /// under root, an existing visible file, not gitignored, not already being previewed (the preview
    /// auto-reload handles content changes of the current file). No-op outside Tree/Preview surfaces
    /// (dialogs and git views are never hijacked — normally unreachable anyway since any key breaks follow).
    pub fn follow_jump(&mut self, path: &Path) {
        use crate::keymap::Surface;
        if !self.follow_mode {
            return;
        }
        // フォロー自身が開いた diff ビュー(PreviewGitDiff)からも次のファイルへ追従を続ける。
        // それ以外の git ビュー/ダイアログ等は乗っ取らない(通常はキー押下で follow が切れるので届かない)。
        let surface_ok = matches!(
            self.surface(),
            Surface::Tree | Surface::PreviewText | Surface::PreviewImage | Surface::PreviewTable
        );
        #[cfg(feature = "git")]
        let surface_ok = surface_ok || matches!(self.surface(), Surface::PreviewGitDiff);
        if !surface_ok {
            return;
        }
        if self.preview_path.as_deref() == Some(path) {
            return;
        }
        if !self.follow_target_ok(path) {
            return;
        }
        // 追尾がビューを動かす瞬間に古い flash(「follow: on」等)を消す=フッターを
        // その面の操作ヒントに明け渡す(flash は本来キー入力で消えるが、追尾はキー無しで進むため)。
        self.flash = None;
        if self.changed_filter {
            // 変更一覧を最新化してから対象を選択(一覧に居るはず=変更イベント由来)。
            self.reapply_changed_filter();
            if let Some(i) = self.entries.iter().position(|e| e.path == path) {
                self.selected = i;
            }
        } else if !matches!(self.reveal_path_deep(path), Ok(true)) {
            return;
        }
        // 既定(`ui.follow_view="diff"`)は**全画面 diff** で開く=何から何に変わったかがハンク単位で
        // 見える(hunk/livediff/diffpane と同じ提示)。diff を出せない未追跡(全行新規)・リポジトリ外や、
        // バイナリのメディア系はファイルプレビュー(+最初の変更ハンクへスクロール)へフォールバック。
        if self.cfg.ui.follow_view != "file" && !self.follow_is_media(path) {
            let diff = crate::git::file_diff(&self.root, path);
            if !diff.is_empty() {
                self.open_git_diff(path);
                // いま取った diff をキャッシュに載せ、描画での再取得(git 再実行)を省く。
                self.diff_cache = Some(DiffCache {
                    path: path.to_path_buf(),
                    lines: diff,
                });
                // フォロー由来の diff: n/N と位置表示は「このセッションで変わったファイル」を回遊。
                self.diff_follow_scope = true;
                return;
            }
        }
        self.enter_preview(path);
        self.follow_scroll_to_first_change();
    }

    /// Whether `path` is a valid follow target: under root, an existing file, not gitignored, and not
    /// inside a hidden (dot) directory unless hidden files are shown. Shared by the jump and the
    /// session-list recording so both see the same set.
    fn follow_target_ok(&self, path: &Path) -> bool {
        if !path.starts_with(&self.root) || !path.is_file() || self.is_ignored(path) {
            return false;
        }
        if !self.show_hidden {
            // 隠し(ドット)ディレクトリ/ファイル配下はツリーに出せないので追わない(show_hidden で解禁)。
            let hidden = path
                .strip_prefix(&self.root)
                .map(|r| {
                    r.components().any(|c| {
                        c.as_os_str()
                            .to_str()
                            .map(|s| s.starts_with('.'))
                            .unwrap_or(false)
                    })
                })
                .unwrap_or(true);
            if hidden {
                return false;
            }
        }
        true
    }

    /// Record one changed file into the current follow session (called from the run loop's event drain
    /// while follow is ON). Returns whether the path is a valid follow target (the caller uses this to
    /// decide whether it may become the pending jump target). First-change order, deduped.
    pub fn follow_note_change(&mut self, path: &Path) -> bool {
        if !self.follow_mode || !self.follow_target_ok(path) {
            return false;
        }
        if !self.follow_session.iter().any(|p| p == path) {
            self.follow_session.push(path.to_path_buf());
        }
        true
    }

    /// Whether `path` previews as media (image/SVG/video/PDF) — its git diff would be a useless
    /// "binary files differ" line, so follow shows the content preview instead.
    fn follow_is_media(&self, path: &Path) -> bool {
        matches!(
            self.cfg.resolve_preview(path),
            PreviewKind::Image(_)
                | PreviewKind::Svg(_)
                | PreviewKind::Video(_)
                | PreviewKind::Pdf(_)
        )
    }

    /// After a follow jump, scroll the (windowed) preview to the **first changed hunk** instead of the
    /// file top — an edit deep in a large file would otherwise be off-screen and invisible, which defeats
    /// "watch the agent work" (Zed follows the edit position; diffpane scrolls to the latest change).
    /// A few context lines are kept above, and the caret lands on the changed line (ready for `v`/`Y`).
    /// No-ops for non-windowed previews, untracked files (all-new → top is right), and outside a repo.
    fn follow_scroll_to_first_change(&mut self) {
        if !self.is_windowed() {
            return;
        }
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        // ガター設定 OFF でも変更行は取得する(ON なら同じ計算が gutter_cache に載り描画でも再利用)。
        let marks = if self.cfg.ui.git_gutter {
            self.git_gutter_marks()
        } else {
            gutter_marks(&crate::git::file_diff(&self.root, &path))
        };
        let Some(first) = marks.keys().min().copied() else {
            return;
        };
        let line0 = (first as usize).saturating_sub(1); // marks は 1-based
        let top = line0.saturating_sub(3); // 上に文脈を数行残す
        let Some(win) = self.preview_win.as_mut() else {
            return;
        };
        if let Ok((off, _)) = win.advance(0, top) {
            self.preview_byte_top = off;
            self.preview_top_line = top;
            self.preview_cursor_line = line0;
        }
    }

    fn enter_preview(&mut self, path: &Path) {
        // 同一ファイルへの再入(全画面フェンスからの `q` 復帰)か。この場合はインライン画像
        // キャッシュを温存する: キーはフェンス=内容ハッシュ/画像=パスなので stale にならず、
        // 捨てると全フェンスが Loading からやり直し=縮退レイアウトの 1 描画で復元スクロール/
        // フォーカスがクランプされ「元の位置に戻る」約束が破れていた。
        let same_file = self.preview_path.as_deref() == Some(path);
        self.preview_path = Some(path.to_path_buf());
        // 設定駆動でプレビュー種別を解決。未対応は CanNotPreview。
        let kind = self.cfg.resolve_preview(path);
        self.preview_scroll = 0;
        self.preview_hscroll = 0;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        // 画像状態は毎回リセット。SVG/GIF は別スレッドで読み込み開始(UI を塞がない)。
        self.clear_image();
        // PDF はページ数を先に求める(pdfinfo・~数 ms)。None なら単ページ扱い=ページ移動なし。
        if matches!(kind, PreviewKind::Pdf(_)) {
            self.pdf_pages = crate::preview::pdf::page_count(path);
        }
        self.start_media_load(&kind, path);
        self.preview_kind = Some(kind);
        self.fence_return = None; // 通常のプレビュー遷移でフェンス復帰情報は用済み
        self.fence_zoom = 1.0;
        self.fence_center = (0.5, 0.5);
        self.md_raw = false; // 新規ファイルは装飾表示から(Markdown/Mermaid)。`R` で raw へ。
        self.md_cache = None; // 別ファイルに切替: 装飾キャッシュを無効化
        self.md_items.clear();
        if !same_file {
            self.md_image_cache.clear(); // 別ファイル: インライン画像キャッシュも破棄
        }
        self.focused_item = None;
        self.outline_open = false; // 新規プレビューでアウトラインオーバーレイは閉じる
        self.details_open.clear(); // <details> の開閉状態は文書ごと=別ファイルでリセット
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.table_search_hits.clear();
        self.search_idx = 0;
        self.setup_windowed(); // 大きい Code/Text なら less 風ウィンドウ読みに切替
                               // windowed プレビューの 2D キャレット/選択を先頭へリセット。
        self.preview_cursor_line = 0;
        self.preview_cursor_col = 0;
        self.preview_visual_anchor = None;
        self.preview_visual_linewise = false;
        // CSV/TSV はテーブルへパース。カーソル/スクロールを先頭へ戻してから読み込む。
        self.table_cur_row = 0;
        self.table_cur_col = 0;
        self.table_top_row = 0;
        self.table_left_col = 0;
        self.load_table();
        self.mode = Mode::Preview;
    }

    /// Code/Text previews use less-style windowed reading **regardless of size**.
    /// This avoids whole-file highlighting (1.3s/debug for 1600 lines) and reads/colors only the visible window (tens of lines), so
    /// opening is instant even for small files and behavior is symmetric with huge files. Images/md/mermaid are excluded
    /// (md/mermaid need their whole structure understood and are usually small).
    fn setup_windowed(&mut self) {
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        // 重いハイライト待ち状態を判定: Code かつ ハイライト有効 かつ 文法が未コンパイル(cold)なら
        // 初回だけローディング表示/段階表示が要る。温まっていれば最初から即時着色。
        self.hl_pending = self.cfg.ui.syntax_highlight
            && matches!(self.preview_kind, Some(PreviewKind::Code(_)))
            && !crate::preview::code::is_ext_warm(self.current_preview_ext());
        self.hl_warming = false;
        // Code/Text は常に windowed。Markdown/Mermaid は raw 表示(`R`)のときだけ windowed 化=
        // 素のソースを行/桁一致で読み、2D キャレット選択をそのまま乗せる。
        let windowed_kind = matches!(
            self.preview_kind,
            Some(PreviewKind::Code(_)) | Some(PreviewKind::Text(_))
        ) || self.is_raw_source();
        if !windowed_kind {
            return;
        }
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        if let Ok(w) = crate::preview::window::FileWindow::open(&path) {
            self.preview_win = Some(w);
        }
    }

    /// Extension of the current preview target file (empty string if none). Used for the highlight-warm check, etc.
    pub fn current_preview_ext(&self) -> &str {
        self.preview_path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .unwrap_or("")
    }

    /// Whether waiting on heavy code highlighting (whether the render shows a loading/progressive display).
    pub fn is_highlight_pending(&self) -> bool {
        self.hl_pending
    }

    /// Whether the loading display is the "central spinner" style (false=progressive=immediate plain text).
    pub fn loading_is_indicator(&self) -> bool {
        self.cfg.ui.preview_loading != "progressive"
    }

    /// Clear the loading state on warm completion (swap in the colored version). Common to indicator/progressive.
    pub fn clear_highlight_pending(&mut self) {
        self.hl_pending = false;
        self.hl_warming = false;
    }

    /// If the background warm has not started yet, return the launch target (the caller runs `code::warm_file` on a separate thread).
    /// Both indicator and progressive **compile on a background thread** so the UI is not stalled (the spinner keeps spinning).
    /// Launch only when the return value is Some((ext, path)) (= prevents double-launch).
    pub fn take_warm_job(&mut self) -> Option<(String, PathBuf)> {
        if self.hl_pending && !self.hl_warming {
            if let Some(path) = self.preview_path.clone() {
                self.hl_warming = true;
                return Some((self.current_preview_ext().to_string(), path));
            }
        }
        None
    }

    /// Background jobs currently in flight, as i18n labels (drives the top-right busy indicator).
    /// **Derived** from the existing per-job state (no separate begin/end pairing that could leak
    /// a stuck spinner): git-ignored scan / media decode / syntax-highlight warm-up / inline images.
    pub fn busy_jobs(&self) -> Vec<crate::i18n::Msg> {
        let mut v = Vec::new();
        if self.git_ignored_pending.is_some() {
            v.push(crate::i18n::Msg::BusyGitScan);
        }
        if self.media_loading {
            v.push(crate::i18n::Msg::BusyMedia);
        }
        if self.hl_pending || self.hl_warming {
            v.push(crate::i18n::Msg::BusyHighlight);
        }
        if self.md_images_loading() {
            v.push(crate::i18n::Msg::BusyImages);
        }
        v
    }

    /// Whether the top-right busy indicator should be shown/animated right now
    /// (config on + at least one background job in flight). The run loop only schedules
    /// animation ticks while this is true, so idle CPU stays at zero.
    pub fn busy_indicator_active(&self) -> bool {
        self.cfg.ui.busy_indicator && !self.busy_jobs().is_empty()
    }

    /// Advance the spinner by one frame (the run loop calls this periodically while waiting = keeps it spinning).
    pub fn tick_spinner(&mut self) {
        self.spinner_frame = self.spinner_frame.wrapping_add(1);
    }

    /// The current spinner glyph (no emoji; the classic braille-pattern spinner = single-width and color-free in the terminal).
    pub fn spinner_glyph(&self) -> &'static str {
        const FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];
        FRAMES[self.spinner_frame % FRAMES.len()]
    }

    /// `e`: decide the target to open in the external editor and raise the request. Tree=the selected file / Preview=the file being shown.
    /// For a directory or no target, notify via flash and do nothing (only files can be edited).
    /// In Preview the editor is asked to open at the on-screen position (see `preview_edit_line`).
    pub fn request_edit(&mut self) {
        let target = match self.mode {
            Mode::Tree => match self.entries.get(self.selected) {
                Some(e) if e.is_dir => {
                    self.flash = Some(tr(self.lang, crate::i18n::Msg::CannotEditDirectory).into());
                    return;
                }
                Some(e) => Some(e.path.clone()),
                None => None,
            },
            Mode::Preview => self.preview_path.clone(),
        };
        match target {
            Some(p) => self.pending_edit = Some((p, self.preview_edit_line())),
            None => self.flash = Some(tr(self.lang, crate::i18n::Msg::NoFileToEdit).into()),
        }
    }

    /// The 1-based file line to open the external editor at, matching the on-screen position.
    /// - Windowed preview (plain text / code / raw-Markdown via `R`): the exact caret line.
    /// - Rendered Markdown: an **approximate** source line for the top of the current view. Reflow means
    ///   there is no exact scroll-row → source-line mapping, so the top-of-view fraction through the wrapped
    ///   output (`preview_scroll / md_view_rows`) is mapped to that fraction of the source. This lands the
    ///   editor near where you were reading rather than at the top (block-structured docs land on the
    ///   section being read; see `preview_edit_line` verification).
    /// - Otherwise (tree edits, Mermaid, images): None (open at the top).
    fn preview_edit_line(&self) -> Option<usize> {
        if self.mode != Mode::Preview {
            return None;
        }
        if self.is_windowed() {
            return Some(self.preview_cursor_line + 1);
        }
        // Rendered Markdown: reflow means there is no exact scroll-row → source-line mapping. Anchor on a
        // logical line (a Tab-focused item if one is visible, else the top of the view), estimate its
        // source line proportionally, then refine by content (see md_content_anchor_line).
        if matches!(self.preview_kind, Some(PreviewKind::Markdown(_))) {
            if let Some(c) = &self.md_cache {
                let same = self.preview_path.as_ref().is_some_and(|p| *p == c.path);
                if same && c.src_lines > 0 && self.md_view_rows > 0 {
                    // Prefer the on-screen Tab focus (the visible "cursor"); otherwise the top of view.
                    let (logical, row) = match self.md_focused_visible_line() {
                        Some(hit) => hit,
                        None => (
                            self.md_top_logical_line().unwrap_or(0),
                            self.preview_scroll as usize,
                        ),
                    };
                    let est = (row * c.src_lines / self.md_view_rows).min(c.src_lines - 1);
                    return Some(self.md_content_anchor_line(logical, est).unwrap_or(est) + 1);
                }
            }
        }
        None
    }

    /// The (decorated logical line, top display row) of the Tab-focused Markdown item, but only when it
    /// is currently on screen — so `e` opens where the visible cursor is. None if nothing is focused or
    /// the focus has been scrolled out of view (then `e` falls back to the top of the view).
    fn md_focused_visible_line(&self) -> Option<(usize, usize)> {
        let item = self.focused_item.and_then(|i| self.md_items.get(i))?;
        let (row, h) = self.md_visual_span(item.line);
        let scroll = self.preview_scroll as usize;
        let vh = self.preview_viewport.max(1) as usize;
        (row < scroll + vh && row + h > scroll).then_some((item.line, row))
    }

    /// The 0-based decorated (logical) line at the top of the current Markdown view, resolving wrapping
    /// so it matches what the renderer draws (`preview_scroll` is in post-wrap display rows).
    fn md_top_logical_line(&self) -> Option<usize> {
        let c = self.md_cache.as_ref()?;
        if c.lines.is_empty() {
            return None;
        }
        let scroll = self.preview_scroll as usize;
        if !self.cfg.ui.wrap || c.width == 0 || c.row_prefix.len() != c.lines.len() + 1 {
            return Some(scroll.min(c.lines.len() - 1));
        }
        // prefix は各行の開始表示行(単調増加)。scroll を含む行 = pp(p <= scroll) - 1。
        let i = c
            .row_prefix
            .partition_point(|&p| p <= scroll)
            .saturating_sub(1);
        Some(i.min(c.lines.len() - 1))
    }

    /// Refine the proportional editor-open estimate for rendered Markdown by content: take the longest
    /// visible span of decorated logical line `logical` (a single span carries no Markdown markers, so its
    /// text is a verbatim substring of the source) and find the source line containing it, closest to
    /// `est`. Returns a 0-based source line, or None to fall back to `est`. Re-reads the file so it
    /// matches what the editor will open (an agent may have edited it since the preview was built).
    fn md_content_anchor_line(&self, logical: usize, est: usize) -> Option<usize> {
        use ratatui::style::Modifier;
        let c = self.md_cache.as_ref()?;
        let line = c.lines.get(logical)?;
        // Longest non-hidden, non-blank span (hidden spans carry link/URL targets, not on-screen text).
        let key = line
            .spans
            .iter()
            .filter(|s| !s.style.add_modifier.contains(Modifier::HIDDEN))
            .map(|s| s.content.trim())
            .filter(|t| !t.is_empty())
            .max_by_key(|t| t.chars().count())?;
        if key.chars().count() < 4 {
            return None;
        }
        let content = crate::preview::text::load(c.path.as_path()).ok()?;
        let mut best: Option<usize> = None;
        let mut best_d = usize::MAX;
        for (i, sl) in content.lines.iter().enumerate() {
            if sl.contains(key) {
                let d = i.abs_diff(est);
                if d < best_d {
                    best_d = d;
                    best = Some(i);
                }
            }
        }
        best
    }

    /// Taken by the run loop: if set, return the editor-launch target path (+ line) and clear it.
    pub fn take_pending_edit(&mut self) -> Option<(PathBuf, Option<usize>)> {
        self.pending_edit.take()
    }

    /// `O`: request launching an external git tool (lazygit, etc.) (the run loop picks it up, suspends, then launches).
    #[cfg_attr(not(feature = "git"), allow(dead_code))]
    pub fn launch_git_tool(&mut self) {
        self.pending_git_tool = true;
    }

    /// Taken by the run loop: if a git-tool launch request is set, return true and clear it.
    pub fn take_launch_git_tool(&mut self) -> bool {
        std::mem::take(&mut self.pending_git_tool)
    }

    /// Reopen the preview after the external editor exits (reflect the edited content). Caches are also discarded.
    /// Even if the editor replaces the file (temp→rename), the FileWindow is reopened so the latest is read.
    pub fn reload_preview(&mut self) {
        self.md_cache = None;
        self.win_cache = None;
        if matches!(self.mode, Mode::Preview) {
            self.setup_windowed();
            self.reload_media_if_changed();
            // CSV/TSV は外部編集で内容が変わり得る。再パースしてカーソルを範囲内へクランプ(位置は保つ)。
            if matches!(self.preview_kind, Some(PreviewKind::Table { .. })) {
                self.load_table();
                self.clamp_table_cursor();
            }
        }
    }

    /// On an FS-driven reload, re-load media (image/svg/gif/video/pdf) **only when the previewed file
    /// actually changed** (mtime guard). Without this, an image preview stays stale after an external
    /// edit: text/markdown follows via the md_cache clear, but images go through a separate path and were
    /// missed — so when a file is edited externally (e.g. an editor on the right), the konoma preview on the left did not refresh.
    /// The mtime guard avoids re-decoding / re-running external tools (pdftocairo/ffmpeg) on unrelated FS
    /// events. Zoom / pan / page are preserved across the reload.
    fn reload_media_if_changed(&mut self) {
        let is_media = match &self.preview_kind {
            Some(kind) => self.kind_loads_media(kind),
            None => false,
        };
        if !is_media {
            return;
        }
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        let Some(kind) = self.preview_kind.clone() else {
            return;
        };
        if file_mtime(&path) == self.preview_media_mtime {
            return; // 対象ファイルは未変更 → 無駄な再デコード/外部ツール実行を避ける
        }
        // 表示状態(ズーム/中心/ページ)を保持して再ロード。
        let (zoom, center, page) = (self.image_zoom, self.image_center, self.pdf_page);
        self.clear_image(); // ズーム/中心/ページ/メディア世代をリセット
        if matches!(kind, PreviewKind::Pdf(_)) {
            self.pdf_pages = crate::preview::pdf::page_count(&path);
            self.pdf_page = page.clamp(1, self.pdf_pages.unwrap_or(1).max(1));
        }
        self.start_media_load(&kind, &path); // preview_media_mtime も更新される
        self.image_zoom = zoom;
        self.image_center = center;
    }

    /// The directory to watch **in addition** to the tree root so external (agent) edits to the
    /// currently shown file are still detected. Returns the shown file's parent directory **only when
    /// that file lives outside the watched root**: a global-bookmark target, or the repo-wide git view
    /// when the root is a repo subdirectory. Files under the root are already covered by the recursive
    /// root watch (so this returns `None` for them, and whenever no file is shown / not in Preview).
    ///
    /// This closes the gap where the FSEvents watcher only covers `app.root`: an out-of-root preview
    /// or diff never received change events, so an AI/external edit left it stale (the user's own `e`
    /// edit still reloaded via the editor-return path — hence "my edits show, the AI's don't").
    /// Consumed by the run loop in `main.rs`, which adds a non-recursive watch on this directory.
    pub fn out_of_root_watch_dir(&self) -> Option<PathBuf> {
        if !matches!(self.mode, Mode::Preview) {
            return None;
        }
        let p = self.preview_path.as_ref()?;
        if p.starts_with(&self.root) {
            return None; // already covered by the recursive root watch
        }
        p.parent().map(|d| d.to_path_buf())
    }

    /// The repo's `.git` directory to watch **non-recursively** when the tree root is a *subdirectory*
    /// of the repo (so the parent `.git` sits above `root` and is not covered by the recursive root
    /// watch). Without this, an external git op that touches only `.git` (a commit of already-staged
    /// files, an external checkout) fires no event under the subdir, so the cached `git status` /
    /// branch would linger stale — the per-workdir status cache no longer re-verifies on `h`/`l`.
    /// `.git/index` and `.git/HEAD` are direct children, so a non-recursive watch catches the signals
    /// that change status/branch. Returns None when root *is* the repo root (`.git` already watched)
    /// or outside any repo. konoma's own reads are lock-free (`--no-optional-locks`), so this does not
    /// create a self-feedback loop.
    pub fn git_dir_watch(&self) -> Option<PathBuf> {
        let wd = crate::git::workdir(&self.root)?;
        if self.root == wd {
            return None; // root is the repo root → `.git` is already under the recursive watch
        }
        let git = wd.join(".git");
        git.is_dir().then_some(git)
    }

    /// Whether in windowed (large file) mode. Used for the render and scroll branching.
    pub fn is_windowed(&self) -> bool {
        self.preview_win.is_some()
    }

    /// Index of the focused Markdown item (link/checkbox), if any. Read-only query used by the
    /// E2E simulation tests to assert Tab/⇧Tab focus movement.
    #[cfg(test)]
    pub fn focused_item(&self) -> Option<usize> {
        self.focused_item
    }

    /// The link targets in the current Markdown preview's `md_items`, in document order (E2E: assert
    /// exactly which URLs became focusable links — e.g. that a URL inside code did NOT).
    #[cfg(test)]
    pub fn md_link_targets(&self) -> Vec<String> {
        self.md_items
            .iter()
            .filter_map(|it| match &it.kind {
                MdItemKind::Link { target } => Some(target.clone()),
                _ => None,
            })
            .collect()
    }

    /// Whether the current preview is a Markdown/Mermaid file shown as its raw source (`R` toggled on).
    /// Such a preview is windowed like a code file, so the 2D caret selection/copy applies.
    pub fn is_raw_source(&self) -> bool {
        self.md_raw
            && matches!(
                self.preview_kind,
                Some(PreviewKind::Markdown(_)) | Some(PreviewKind::Mermaid(_))
            )
    }

    /// Whether the current preview is Markdown/Mermaid (has a decorated render, so `R` can toggle raw source).
    pub fn is_decorated_kind(&self) -> bool {
        matches!(
            self.preview_kind,
            Some(PreviewKind::Markdown(_)) | Some(PreviewKind::Mermaid(_))
        )
    }

    /// Whether raw source view is currently on (for the footer/title indicator).
    pub fn is_md_raw(&self) -> bool {
        self.md_raw
    }

    /// `R`: toggle a Markdown/Mermaid preview between its decorated render and raw source. No-op for other kinds.
    /// Rebuilds the windowed reader and resets the caret/scroll/selection so the new view starts at the top.
    pub fn toggle_md_raw(&mut self) {
        if !self.is_decorated_kind() {
            return;
        }
        self.md_raw = !self.md_raw;
        // 表示切替=先頭から。窓読み(raw)/装飾(rendered)を張り直す。
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        self.preview_scroll = 0;
        self.preview_hscroll = 0;
        self.preview_cursor_line = 0;
        self.preview_cursor_col = 0;
        self.preview_visual_anchor = None;
        self.preview_visual_linewise = false;
        self.md_cache = None;
        self.setup_windowed();
    }

    // ---- windowed プレビューの 2D キャレット / ビジュアル選択コピー -----------

    /// Whether a visual selection is active in a windowed preview (routes the PreviewTextVisual surface).
    pub fn is_preview_visual(&self) -> bool {
        self.is_windowed() && self.preview_visual_anchor.is_some()
    }

    /// Whether the active preview selection is linewise (`V`) rather than charwise (`v`). For the status chip/footer.
    pub fn preview_visual_linewise(&self) -> bool {
        self.preview_visual_linewise
    }

    /// The active selection for the render/copy: charwise (`v`) or linewise (`V`), normalized so start ≤ end.
    pub fn preview_selection(&self) -> PreviewSelection {
        let Some((al, ac)) = self.preview_visual_anchor else {
            return PreviewSelection::None;
        };
        let (cl, cc) = (self.preview_cursor_line, self.preview_cursor_col);
        if self.preview_visual_linewise {
            PreviewSelection::Line {
                lo: al.min(cl),
                hi: al.max(cl),
            }
        } else {
            // charwise: order by (line, col)
            let (start, end) = if (al, ac) <= (cl, cc) {
                ((al, ac), (cl, cc))
            } else {
                ((cl, cc), (al, ac))
            };
            PreviewSelection::Char { start, end }
        }
    }

    /// `v` (charwise) / `V` (linewise): start a visual selection at the current 2D caret (windowed previews only).
    pub fn preview_enter_visual(&mut self, linewise: bool) {
        if self.is_windowed() {
            self.preview_visual_anchor = Some((self.preview_cursor_line, self.preview_cursor_col));
            self.preview_visual_linewise = linewise;
        }
    }

    /// Exit visual selection without copying (`v`/`V` again / Esc / q).
    pub fn preview_exit_visual(&mut self) {
        self.preview_visual_anchor = None;
    }

    /// The selected text read from the real file: whole logical lines (linewise) or an exact character range
    /// (charwise, end-inclusive). Uses the file's unwrapped/logical lines so a paste keeps the original layout.
    /// Empty when there is no path or the range is out of bounds.
    fn preview_selection_text(&self) -> String {
        let Some(path) = self.preview_path.as_ref() else {
            return String::new();
        };
        let bytes = match std::fs::read(path) {
            Ok(b) => b,
            Err(_) => return String::new(),
        };
        let s = String::from_utf8_lossy(&bytes);
        let lines: Vec<&str> = s.lines().collect();
        if lines.is_empty() {
            return String::new();
        }
        let last = lines.len() - 1;
        match self.preview_selection() {
            PreviewSelection::Line { lo, hi } => {
                let end = hi.min(last);
                if lo > end {
                    String::new()
                } else {
                    lines[lo..=end].join("\n")
                }
            }
            PreviewSelection::None => {
                // not selecting → the current logical line
                let l = self.preview_cursor_line.min(last);
                lines[l].to_string()
            }
            PreviewSelection::Char { start, end } => selection_char_text(&lines, start, end),
        }
    }

    /// `y`: copy the current selection (or the current line if not selecting) to the clipboard, then exit visual.
    pub fn preview_copy_selection(&mut self) {
        let text = self.preview_selection_text();
        self.preview_visual_anchor = None;
        if text.is_empty() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        }
        self.set_clipboard_flash(&text);
    }

    /// The `@path#L12-34` reference text (Claude Code's file+line context syntax) for the current
    /// selection — or the caret line when not selecting. Line numbers are 1-based and inclusive; a single
    /// line is `#L12`. In non-windowed previews (no caret) it degrades to `@path`. None without a target.
    fn preview_selection_ref_text(&self) -> Option<String> {
        let path = self.preview_path.as_ref()?;
        let base = at_ref_text(&self.open_dir, path);
        if !self.is_windowed() {
            return Some(base);
        }
        let (lo, hi) = match self.preview_selection() {
            PreviewSelection::Line { lo, hi } => (lo, hi),
            PreviewSelection::Char { start, end } => (start.0, end.0),
            PreviewSelection::None => (self.preview_cursor_line, self.preview_cursor_line),
        };
        Some(if lo == hi {
            format!("{base}#L{}", lo + 1)
        } else {
            format!("{base}#L{}-{}", lo + 1, hi + 1)
        })
    }

    /// `Y`: copy the `@path#L…` reference of the selection/caret to the clipboard, then exit visual
    /// (paste it to Claude Code to point the conversation at this exact spot).
    pub fn preview_copy_selection_ref(&mut self) {
        let Some(text) = self.preview_selection_ref_text() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        self.preview_visual_anchor = None;
        self.set_clipboard_flash(&text);
    }

    /// `h`/`l`: move the column caret by `dir` chars (windowed previews). The render clamps it to the line length
    /// and writes the clamp back, so overshoot is corrected on the next frame. Falls back to hscroll otherwise.
    pub fn preview_col_move(&mut self, dir: i32) {
        if self.is_windowed() {
            let next = (self.preview_cursor_col as i64 + dir as i64).max(0) as usize;
            self.preview_cursor_col = next;
        } else {
            self.preview_hscroll(dir * 2);
        }
    }

    /// `0`: move the caret to the first column (windowed), else scroll home.
    pub fn preview_col_home(&mut self) {
        if self.is_windowed() {
            self.preview_cursor_col = 0;
        } else {
            self.preview_hscroll_home();
        }
    }

    /// `$`: move the caret to the last column (windowed). The render clamps the sentinel to the line length.
    pub fn preview_col_end(&mut self) {
        if self.is_windowed() {
            self.preview_cursor_col = usize::MAX;
        } else {
            self.preview_hscroll_end();
        }
    }

    /// Page the preview to the next/previous **file** in tree display order (`dir`=+1/-1, wraps
    /// at the ends). Directories are skipped; the tree cursor follows the shown file, so leaving
    /// the preview lands where you are. The anchor is the previewed file's tree position, falling
    /// back to the cursor when the previewed file is not in the tree (e.g. a global-bookmark
    /// target outside the root). With no other file to go to, this is a no-op.
    pub fn preview_jump_file(&mut self, dir: i32) {
        if self.mode != Mode::Preview || self.entries.is_empty() {
            return;
        }
        let anchor = self
            .preview_path
            .as_ref()
            .and_then(|p| self.entries.iter().position(|e| e.path == *p))
            .unwrap_or_else(|| self.selected.min(self.entries.len() - 1));
        let n = self.entries.len() as i64;
        let mut i = anchor as i64;
        for _ in 0..n {
            i = (i + dir as i64).rem_euclid(n);
            if i as usize == anchor {
                break; // 一周した=他にファイルが無い
            }
            if !self.entries[i as usize].is_dir {
                self.selected = i as usize;
                let path = self.entries[i as usize].path.clone();
                self.enter_preview(&path);
                return;
            }
        }
    }

    pub fn back_to_tree(&mut self) {
        // 全画面フェンス表示からの `q` は「ツリーへ」ではなく「元の Markdown ビューへ」戻る
        // (git diff の came_from_git_view と同じ、来た場所へ帰る流儀)。スクロール/フォーカスも復元。
        if matches!(self.preview_kind, Some(PreviewKind::MermaidFence(_))) {
            if let Some(md) = self.preview_path.clone() {
                let ret = self.fence_return.take();
                self.enter_preview(&md);
                if let Some((scroll, focus)) = ret {
                    self.preview_scroll = scroll;
                    self.focused_item = focus;
                }
                return;
            }
        }
        self.mode = Mode::Tree;
        // Re-verify git status when the tree becomes visible again. FSEvents is inherently lossy
        // (bursts get coalesced, and an external commit can arrive as `.git/*.lock`-only churn), so
        // an external git op during Preview may have left `git_status` stale. Invalidating here makes
        // the next render's `refresh_git_if_needed` refetch the cheap statuses+branch (the heavy
        // `ignored` set is kept, since the repo is unchanged) — so returning to the tree always shows
        // fresh markers, instead of a stale change marker until you navigate across a directory (`h`/`l`).
        // Mark dirty too, so the per-workdir status cache (reused across `h`/`l` in the same repo) is
        // bypassed for this deliberate re-verify — otherwise the stale markers would linger.
        self.git_status_for = None;
        self.git_status_dirty = true;
        // Same seam re-verification for the detail columns: their cells are cached per tree
        // generation (Phase G) and a missed fs event would otherwise pin stale size/mtime until
        // the next rebuild. Dropping here keeps them as robust as the git markers.
        self.detail_cells_cache.clear();
        self.preview_path = None;
        self.preview_kind = None;
        self.clear_image(); // graphics 状態を解放
        self.md_cache = None;
        self.md_raw = false;
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        self.hl_pending = false;
        self.hl_warming = false;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        self.md_items.clear();
        self.focused_item = None;
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.table_search_hits.clear();
        self.search_idx = 0;
        self.came_from_git_view = false;
        self.table_data = None;
        self.table_cur_row = 0;
        self.table_cur_col = 0;
        self.table_top_row = 0;
        self.table_left_col = 0;
        self.preview_cursor_line = 0;
        self.preview_cursor_col = 0;
        self.preview_visual_anchor = None;
        self.preview_visual_linewise = false;
    }

    /// Whether this preview kind displays through the media (image) pipeline — and therefore needs
    /// a `start_media_load` whenever its display state was dropped (tab restore / fs reload).
    /// Mermaid kinds count only in image mode; in text mode they draw via the decorated path.
    fn kind_loads_media(&self, kind: &PreviewKind) -> bool {
        matches!(
            kind,
            PreviewKind::Image(_)
                | PreviewKind::Svg(_)
                | PreviewKind::Video(_)
                | PreviewKind::Pdf(_)
        ) || (matches!(kind, PreviewKind::Mermaid(_) | PreviewKind::MermaidFence(_))
            && self.mermaid_image_mode())
    }

    /// Release and reset the image display state (protocol, source image, zoom/pan).
    fn clear_image(&mut self) {
        self.image = None;
        self.kitty_image = None;
        // Discard any in-flight kitty build from the file we are leaving (gen bump) and clear the
        // wanted geometry so the next image triggers a fresh (synchronous first) build.
        self.kitty_gen = self.kitty_gen.wrapping_add(1);
        self.kitty_want = None;
        self.kitty_shown = None;
        self.image_src = None;
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
        self.image_crop = None;
        self.image_vis_frac = (1.0, 1.0);
        self.vector_svg = None;
        self.image_logical = None;
        self.gif_frames = Vec::new();
        self.gif_idx = 0;
        self.gif_shown_at = None;
        self.gif_protocol = None;
        self.gif_proto_key = None;
        self.pdf_page = 1;
        self.pdf_pages = None;
        // 世代を進めて、別ファイルの読み込み中に届く前ファイルのメディア結果を陳腐化させる。
        self.media_gen = self.media_gen.wrapping_add(1);
        self.media_loading = false;
        self.vector_reraster_inflight = false;
        // 画像状態を捨てたら mtime の主張も捨てる(不変条件)。残すと「表示は無いのに mtime は
        // 最新」の地雷になり、reload_media_if_changed が未変更と誤判定して再ロードを塞ぐ
        // (タブ復帰で mermaid がテキスト図に劣化していた真因の一つ)。
        self.preview_media_mtime = None;
    }

    /// Build (or reuse) the decorated cache for a Markdown/Mermaid/code preview at display width
    /// `width`. On a miss (file/width change) this renders, collapses links, collects the Tab items,
    /// and precomputes the wrap layout (row prefix sums via ratatui's own per-line reflow) — all the
    /// per-document work, done once. Frames then only slice the visible range (`md_slice`).
    fn ensure_md_cache(&mut self, width: u16) {
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        // fence 図の目標行数(fit-to-view)が変わったら、図を含む文書だけ作り直す(ビューポートの
        // 高さ変化で全 md を毎回リビルドしない)。
        let fence_rows = self.mermaid_fit_rows();
        if matches!(&self.md_cache, Some(c) if c.path == path && c.width == width
            && (c.fence_rows == fence_rows
                || !c.images.iter().any(|p| crate::preview::markdown::is_mermaid_fence_url(&p.url))))
        {
            return;
        }
        let (raw, images, remote, fences, math, src_lines) = self.build_decorated(&path, width);
        // Kick off background downloads for any remote images shown as "loading". Each completes
        // by invalidating md_cache (apply_remote_fetch) so this rebuilds with the cached file.
        for url in &remote {
            self.ensure_remote_md_fetch(url);
        }
        // Kick off background renders for any ```mermaid fences not yet in the diagram cache
        // (content-hash keyed). Completion invalidates md_cache (apply_md_image), so the loading
        // line re-lays out into the real inline diagram — the remote-image pattern exactly.
        // Synchronous completions (no loader tx = tests) land *before* we store the cache below,
        // so the just-built decoration is already stale — rebuild once with the results in.
        let mut resync = false;
        for code in &fences {
            if code.trim().is_empty() {
                continue; // 空フェンス(書きかけ)は図にならない=レンダを起動しない
            }
            resync |= self.ensure_mermaid_fence_render(code.clone());
        }
        // 数式も同型: latex+display キーで未着のものをレンダ起動(mermaid フェンスと同じ経路)。
        for (latex, display) in &math {
            if latex.trim().is_empty() {
                continue;
            }
            resync |= self.ensure_math_render(latex.clone(), *display);
        }
        // 現在の文書に**もう存在しない**フェンス/数式キーを回収する。キーは内容ハッシュなので、外部
        // 編集(agent-watch の反復編集)で内容が変わるたび新キーが生まれ、旧キーの decoded
        // ラスタ/protocol/SVG は誰も参照しないままファイル切替まで単調成長していた。
        {
            let mut live: std::collections::HashSet<PathBuf> = fences
                .iter()
                .map(|c| PathBuf::from(crate::preview::markdown::mermaid_fence_url(c)))
                .collect();
            live.extend(
                math.iter()
                    .map(|(l, d)| PathBuf::from(crate::preview::markdown::math_url(l, *d))),
            );
            self.md_image_cache.retain(|k, _| {
                let s = k.to_string_lossy();
                !(crate::preview::markdown::is_mermaid_fence_url(&s)
                    || crate::preview::markdown::is_math_url(&s))
                    || live.contains(k)
            });
        }
        let (raw, images, remote, src_lines) = if resync {
            let (raw, images, remote, _fences, _math, src_lines) =
                self.build_decorated(&path, width);
            (raw, images, remote, src_lines)
        } else {
            (raw, images, remote, src_lines)
        };
        let _ = &remote;
        let (lines, targets) = self.postprocess_md(raw);
        // 描画済み mermaid placement のソース序数(文書順)を番兵の照合用に渡す。
        let fence_ords: Vec<usize> = images.iter().filter_map(|p| p.fence_ord).collect();
        let items = build_md_items(&lines, &targets, &fence_ords);
        let anchors = compute_md_anchors(&lines);
        let max_line_cols = lines.iter().map(|l| l.width()).max().unwrap_or(0);
        let row_prefix = if self.cfg.ui.wrap && width > 0 {
            use ratatui::text::Text;
            use ratatui::widgets::{Paragraph, Wrap};
            let mut pre = Vec::with_capacity(lines.len() + 1);
            let mut acc = 0usize;
            pre.push(0);
            for line in &lines {
                acc += Paragraph::new(Text::from(vec![line.clone()]))
                    .wrap(Wrap { trim: false })
                    .line_count(width)
                    .max(1);
                pre.push(acc);
            }
            pre
        } else {
            Vec::new()
        };
        // Mirror the items into the live field (the same refresh decorate_md_items used to do per
        // frame — items only change when the cache is rebuilt) and keep the focus index in range.
        self.md_items = items.clone();
        match self.focused_item {
            Some(_) if self.md_items.is_empty() => self.focused_item = None,
            Some(f) if f >= self.md_items.len() => {
                self.focused_item = Some(self.md_items.len() - 1)
            }
            _ => {}
        }
        self.md_cache = Some(MdCache {
            path,
            width,
            lines,
            items,
            images,
            src_lines,
            max_line_cols,
            row_prefix,
            fence_rows,
            anchors,
            details_states: crate::preview::markdown::current_details_states(),
        });
    }

    /// The default open state of a `<details>` block from `ui.md_details` and its `open` attribute:
    /// `"open"`/`"closed"` force it; `"auto"` (or anything else) honors the attribute like GitHub.
    fn details_default_open(&self, open_attr: bool) -> bool {
        match self.cfg.ui.md_details.as_str() {
            "open" => true,
            "closed" => false,
            _ => open_attr,
        }
    }

    /// `Space`/`Enter` on a focused `<details>` summary: flip its open state and rebuild the cache.
    pub fn toggle_details(&mut self, ordinal: usize) {
        let cur = self
            .md_cache
            .as_ref()
            .and_then(|c| c.details_states.get(ordinal).copied())
            .unwrap_or(true);
        self.details_open.insert(ordinal, !cur);
        self.md_cache = None; // 再構築で開閉を反映
    }

    /// Scroll the current Markdown preview so the heading matching `slug` (a GitHub-style in-page
    /// anchor, minus the leading `#`) is at the top of the view. Returns false if there is no such
    /// heading (so the caller can flash). Keeps the decorated view (unlike a raw-source line jump).
    fn md_scroll_to_anchor(&mut self, slug: &str) -> bool {
        let target = slug.trim().to_lowercase();
        let Some(logical) = self.md_cache.as_ref().and_then(|c| {
            c.anchors
                .iter()
                .find(|(s, _)| *s == target)
                .map(|(_, i)| *i)
        }) else {
            return false;
        };
        let (row, _) = self.md_visual_span(logical);
        // The draw path clamps preview_scroll against the document height, so an anchor near the
        // end simply scrolls as far as it can.
        self.preview_scroll = row.min(u16::MAX as usize) as u16;
        true
    }

    /// Ensure the decorated cache for `width` and return (total display rows, widest line in cells).
    /// The total is wrap-aware via the cached prefix sums, so the scroll clamp matches what the
    /// renderer draws without re-laying-out the whole document every frame.
    pub fn md_layout(&mut self, width: u16) -> (usize, usize) {
        self.ensure_md_cache(width);
        let Some(c) = &self.md_cache else {
            return (0, 0);
        };
        let total = if self.cfg.ui.wrap {
            c.row_prefix.last().copied().unwrap_or(c.lines.len())
        } else {
            c.lines.len()
        };
        (total, c.max_line_cols)
    }

    /// The visible slice of the decorated lines for the (already clamped) display-row `scroll`,
    /// plus the residual scroll offset to pass to Paragraph (the first sliced line may start above
    /// the viewport when wrapped). Only on-screen lines are cloned and the focus inversion touches
    /// only the focused line — O(viewport) per frame instead of O(document).
    pub fn md_slice(&self, scroll: u16, height: u16) -> (Vec<Line<'static>>, u16) {
        let Some(c) = &self.md_cache else {
            return (Vec::new(), 0);
        };
        let s = scroll as usize;
        let h = height.max(1) as usize;
        let (lo, hi, local) = if self.cfg.ui.wrap && c.row_prefix.len() == c.lines.len() + 1 {
            // 可視表示行 [s, s+h) にかかる論理行区間。prefix は各行の開始表示行(単調増加)。
            let lo = c.row_prefix.partition_point(|&p| p <= s).saturating_sub(1);
            let hi = c
                .row_prefix
                .partition_point(|&p| p < s + h)
                .min(c.lines.len());
            (lo, hi.max(lo), (s - c.row_prefix[lo]) as u16)
        } else {
            let lo = s.min(c.lines.len());
            let hi = (s + h).min(c.lines.len());
            (lo, hi, 0)
        };
        let mut out: Vec<Line<'static>> = c.lines[lo..hi].to_vec();
        // 検索中は可視行の一致箇所を強調(現在の一致=オレンジ / 他=黄色)。窓読みと同じ見た目・
        // 同じ関数を使う。可視範囲だけに掛けるので文書サイズに依らず O(viewport)。
        if let Some(q) = self.preview_search.as_deref() {
            let cur = self.search_matches.get(self.search_idx).copied();
            for (i, line) in out.iter_mut().enumerate() {
                let li = lo + i;
                // この行に一致が無ければ触らない(clone/再構築を避ける)。
                if !self.search_matches.iter().any(|(_, l, _)| *l == li) {
                    continue;
                }
                // 現在の一致がこの行なら、行内での出現順位を渡してその 1 つだけオレンジに。
                let rank = cur.and_then(|(_, cl, _)| {
                    (cl == li).then(|| {
                        self.search_matches[..self.search_idx]
                            .iter()
                            .filter(|(_, l, _)| *l == li)
                            .count()
                    })
                });
                *line = highlight_query_in_line(std::mem::take(line), q, rank);
            }
        }
        // フォーカス中アイテムの行だけ反転する(画面外なら何もしない=見た目は全文反転と同一)。
        if let Some(f) = self.focused_item {
            if let Some(it) = c.items.get(f) {
                if it.line >= lo && it.line < hi {
                    // コードブロックのみ行全体反転(ヘッダ帯が既に全幅)。フェンス図は
                    // キャプション span だけ反転(行全体だと中央寄せのインデント空白まで
                    // 反転して巨大な白バーになる=Ghostty 実機で捕まった)。
                    let whole = matches!(it.kind, MdItemKind::CodeBlock);
                    // 同一行内でのマーカー序数 = 自分より前で同じ行に載っている item の数。
                    let first_on_line = c.items.partition_point(|x| x.line < it.line);
                    let ordinal = f - first_on_line;
                    out[it.line - lo] = invert_focused_line(&c.lines[it.line], ordinal, whole);
                }
            }
        }
        (out, local)
    }

    /// Test-only view of the cached decorated lines (link-collapsed form, the same lines the
    /// renderer slices from). Production rendering goes through `md_layout` + `md_slice`.
    /// NOTE: the return value is already collapsed — feeding it into `decorate_md_items` runs
    /// `collapse_links` a second time, which finds no "(URL)" spans and leaves every rebuilt
    /// link item with an empty target. Fine for render/inversion assertions; do NOT use that
    /// combination to test link activation (use the cache built by `md_layout` instead).
    #[cfg(test)]
    pub fn decorated_lines(&mut self, width: u16) -> Vec<Line<'static>> {
        self.ensure_md_cache(width);
        self.md_cache
            .as_ref()
            .map(|c| c.lines.clone())
            .unwrap_or_default()
    }

    /// Block-level inline images reserved in the current decorated Markdown (empty for other kinds
    /// or when there is no image backend). `decorated_lines` must be called first (it fills the cache).
    pub fn md_images(&self) -> Vec<crate::preview::markdown::ImagePlacement> {
        self.md_cache
            .as_ref()
            .map(|c| c.images.clone())
            .unwrap_or_default()
    }

    /// Read the file with a cap and generate decorated lines (plus inline-image placements and the list
    /// of remote image URLs to fetch) according to its kind. A read failure becomes a single safe line.
    /// Only Markdown yields image placements / remote URLs.
    #[allow(clippy::type_complexity)] // (lines, images, remote urls, mermaid fences, math exprs, src line count)
    fn build_decorated(
        &self,
        path: &Path,
        width: u16,
    ) -> (
        Vec<Line<'static>>,
        Vec<crate::preview::markdown::ImagePlacement>,
        Vec<String>,
        Vec<String>,
        Vec<(String, bool)>,
        usize,
    ) {
        let src = match crate::preview::text::load(path) {
            Ok(content) => {
                let mut s = content.lines.join("\n");
                if content.truncated {
                    s.push_str("\n\n— (省略: 表示上限に達しました) —");
                }
                s
            }
            Err(e) => {
                return (
                    vec![Line::from(format!("[can not preview: 読み込み失敗] {e}"))],
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    0,
                )
            }
        };
        // Source line count, used to map the scroll position back to an approximate source line.
        let src_lines = src.lines().count();
        match &self.preview_kind {
            Some(PreviewKind::Markdown(_)) => {
                let theme = &self.cfg.ui.theme;
                let code = crate::preview::markdown::CodeStyle {
                    bg: theme.code_bg(),
                    label_bg: theme.code_label_bg(),
                    label_right: theme.code_label_right(),
                    tab_width: self.cfg.ui.tab_width,
                    wrap: self.cfg.ui.wrap,
                };
                // Front matter: split the leading `---`…`---` off so the body renders normally; a dim
                // metadata block is prepended to the result below (and image line indices offset).
                let (fm_lines, src) = if self.cfg.ui.md_frontmatter {
                    match crate::preview::markdown::strip_front_matter(&src) {
                        (Some(fm), body) => (
                            crate::preview::markdown::render_front_matter(&fm, width),
                            body,
                        ),
                        (None, body) => (Vec::new(), body),
                    }
                } else {
                    (Vec::new(), src)
                };
                // Footnotes: rewrite `[^1]` refs to superscripts and pull `[^1]: …` defs into a
                // section at the end (fence-aware; no-op without definitions).
                let src = if self.cfg.ui.md_footnotes {
                    crate::preview::markdown::process_footnotes(&src)
                } else {
                    src
                };
                // Inline HTML (<kbd>/<del>/<sup>/<sub>/<br>) → Markdown/Unicode tui-markdown renders.
                let src = if self.cfg.ui.md_inline_html {
                    crate::preview::markdown::process_inline_html(&src)
                } else {
                    src
                };
                // <details> の各ブロックの実効開閉状態を計算し、renderer(thread-local)へ渡す+
                // ensure_md_cache が MdCache に載せられるよう stash する(トグルの基準値)。
                let details_states: Vec<bool> =
                    crate::preview::markdown::collect_details_open(&src)
                        .iter()
                        .enumerate()
                        .map(|(ord, &attr)| {
                            self.details_open
                                .get(&ord)
                                .copied()
                                .unwrap_or_else(|| self.details_default_open(attr))
                        })
                        .collect();
                crate::preview::markdown::set_details_open(details_states);
                // Decide how to render each image URL. A local file or a cached remote fetch resolves to
                // a path → Inline (with its display size in cells). An uncached remote URL is Loading
                // (a fetch is kicked off separately, in `decorated_lines`) unless it has already failed.
                // Anything else (no backend / missing file / data: URL) degrades to text (principle #3).
                let font = self.picker.as_ref().map(|p| p.font_size());
                let base_dir = path.parent().map(|p| p.to_path_buf());
                let avail = width.saturating_sub(2);
                let slot_of = |url: &str| -> crate::preview::markdown::ImageSlot {
                    use crate::preview::markdown::ImageSlot;
                    let Some(font) = font else {
                        return ImageSlot::Unavailable;
                    };
                    if let Some(p) = resolve_md_image_path(url, base_dir.as_deref()) {
                        match md_image_dims(&p) {
                            Some((pw, ph)) => {
                                let (cols, rows) = md_image_cells(
                                    pw,
                                    ph,
                                    font.width,
                                    font.height,
                                    avail,
                                    MD_IMAGE_MAX_ROWS,
                                );
                                ImageSlot::Inline { cols, rows }
                            }
                            None => ImageSlot::Unavailable,
                        }
                    } else if crate::preview::markdown::is_remote_image_url(url)
                        && !self.md_remote_failed.contains(url)
                    {
                        ImageSlot::Loading
                    } else {
                        ImageSlot::Unavailable
                    }
                };
                // ```mermaid フェンス: 画像モードならレンダ済みキャッシュ(内容ハッシュキー)を参照。
                // 未着はローディング行、失敗/モードOFFはテキスト図(原則#3)。probe(空文字)は
                // 「抽出するか」の代表判定なので、モードだけで答える。
                let mermaid_on = self.mermaid_image_mode();
                let fence_target_rows = self.mermaid_fit_rows();
                let mermaid_slot = |code: &str| -> crate::preview::markdown::MermaidSlot {
                    use crate::preview::markdown::MermaidSlot;
                    if !mermaid_on {
                        return MermaidSlot::Text;
                    }
                    if code.is_empty() {
                        return MermaidSlot::Loading; // probe: 抽出ON
                    }
                    let Some(font) = font else {
                        return MermaidSlot::Text;
                    };
                    let key = PathBuf::from(crate::preview::markdown::mermaid_fence_url(code));
                    match self.md_image_cache.get(&key) {
                        Some(e) if e.failed => MermaidSlot::Text,
                        Some(e) => match e.decoded.as_ref() {
                            Some(img) => {
                                use image::GenericImageView;
                                // レイアウトは**初回ラスタの寸法**(layout_px)で固定: ズーム時の
                                // シャープ再ラスタで密度が上がっても予約セル数=表示サイズ不変。
                                let (pw, ph) = e.layout_px.unwrap_or_else(|| img.dimensions());
                                let (cols, rows) = mermaid_cells(
                                    pw,
                                    ph,
                                    font.width,
                                    font.height,
                                    avail,
                                    fence_target_rows,
                                );
                                MermaidSlot::Image { cols, rows }
                            }
                            None => MermaidSlot::Loading,
                        },
                        None => MermaidSlot::Loading,
                    }
                };
                // 数式($…$ / $$…$$): 画像モードならレンダ済みキャッシュ(latex+display ハッシュキー)を
                // 参照。未着はローディング、失敗/未対応/フォント無しは生 LaTeX テキストへ降格(原則#3)。
                // インライン式は自前の行に持ち上がる(mermaid フェンスと同型の合成キー画像)。
                let math_on = font.is_some() && self.math_image_mode();
                let math_slot =
                    |latex: &str, display: bool| -> crate::preview::markdown::MathSlot {
                        use crate::preview::markdown::MathSlot;
                        let Some(font) = font else {
                            return MathSlot::Raw;
                        };
                        let key = PathBuf::from(crate::preview::markdown::math_url(latex, display));
                        match self.md_image_cache.get(&key) {
                            Some(e) if e.failed => MathSlot::Raw,
                            Some(e) => match (e.decoded.as_ref(), e.layout_px) {
                                // layout_px は数式では SVG の**内在サイズ(単位)**を持つ(ラスタ px でなく)。
                                // em 高さ→行数、内在アスペクト→桁数を導き、テキストと釣り合うサイズに。
                                (Some(_), Some((uw, uh))) => {
                                    let (cols, rows) =
                                        math_cells(uw, uh, font.width, font.height, avail, display);
                                    MathSlot::Image { cols, rows }
                                }
                                _ => MathSlot::Loading,
                            },
                            None => MathSlot::Loading,
                        }
                    };
                let (mut lines, mut images) = crate::preview::markdown::render_markdown_with_images(
                    &src,
                    width,
                    code,
                    &theme.code_theme,
                    self.cfg.ui.icons,
                    &self.cfg.ui.md_task_state_chars(),
                    &slot_of,
                    &mermaid_slot,
                    tr(self.lang, crate::i18n::Msg::MermaidCaption),
                    self.cfg.ui.md_alerts,
                    &math_slot,
                    math_on,
                );
                let remote = if font.is_some() {
                    crate::preview::markdown::collect_remote_image_urls(&src)
                } else {
                    Vec::new()
                };
                let fences = if mermaid_on {
                    crate::preview::markdown::collect_mermaid_fences(&src)
                } else {
                    Vec::new()
                };
                let math = if math_on {
                    crate::preview::markdown::collect_math_exprs(&src)
                } else {
                    Vec::new()
                };
                // Prepend the front-matter metadata block, shifting image placements down past it.
                if !fm_lines.is_empty() {
                    for p in &mut images {
                        p.line += fm_lines.len();
                    }
                    let mut all = fm_lines;
                    all.extend(lines);
                    lines = all;
                }
                (lines, images, remote, fences, math, src_lines)
            }
            Some(PreviewKind::Mermaid(_)) => (
                crate::preview::markdown::render_mermaid_file(&src, width),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                src_lines,
            ),
            // 単体コードファイルは syntect でシンタックスハイライト。
            Some(PreviewKind::Code(_)) => (
                crate::preview::code::highlight(&src, path, &self.cfg.ui.theme.code_theme),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                src_lines,
            ),
            _ => (
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                src_lines,
            ),
        }
    }

    /// Attach the image backend (terminal Picker and the offload tx) at startup.
    pub fn attach_image_backend(&mut self, picker: Picker, tx: UnboundedSender<ResizeRequest>) {
        // Use konoma's own compressed transmit only on a kitty-graphics terminal; other protocols
        // (sixel/iterm2/halfblocks) keep the ratatui-image path. tmux is detected via $TMUX (the
        // picker's own is_tmux is private), matching how the escapes must be passthrough-wrapped.
        self.use_kitty = matches!(
            picker.protocol_type(),
            ratatui_image::picker::ProtocolType::Kitty
        );
        self.kitty_is_tmux = std::env::var_os("TMUX").is_some();
        self.picker = Some(picker);
        self.img_tx = Some(tx);
    }

    /// Attach the sending end that offloads heavy media loading (SVG/GIF) to a separate thread.
    pub fn attach_media_loader(&mut self, tx: std::sync::mpsc::Sender<MediaResult>) {
        self.media_tx = Some(tx);
    }

    /// Attach the sender that offloads the kitty resize+compress (zoom/pan) to a worker thread.
    /// Without it (tests), kitty builds run synchronously.
    pub fn attach_kitty_loader(&mut self, tx: std::sync::mpsc::Sender<KittyResult>) {
        self.kitty_tx = Some(tx);
    }

    /// Attach the sender that offloads inline Markdown image decoding to a background thread.
    pub fn attach_md_image_loader(&mut self, tx: std::sync::mpsc::Sender<MdImageResult>) {
        self.md_img_tx = Some(tx);
    }

    /// Attach the sender that offloads inline-image encoding (resize + protocol) to the encode worker.
    pub fn attach_md_encoder(&mut self, tx: std::sync::mpsc::Sender<MdEncodeRequest>) {
        self.md_enc_tx = Some(tx);
    }

    /// Apply a completed background decode of an inline Markdown image. Returns whether to redraw.
    pub fn apply_md_image(&mut self, res: MdImageResult) -> bool {
        // エントリはキック時(ensure_mermaid_fence_render / ensure_md_image)に必ず先置きされる。
        // 無い=陳腐化した結果(ファイル切替でキャッシュ破棄済み/prune 済み)なので、復活させずに
        // 捨てる(or_default だと旧図のラスタが再挿入されて次の enter_preview まで残留し、しかも
        // 下の md_cache 無効化が**無関係な現文書**を 1 回無駄に全再構築していた)。
        if !self.md_image_cache.contains_key(&res.path) {
            return false;
        }
        // フェンス図・数式(合成キー)は寸法がここで初めて決まる=ローディング行→実配置に組み直す
        // ため装飾キャッシュを無効化する(remote 画像の apply_remote_fetch と同じ流儀)。
        // **シャープ化の再ラスタは除く**: ピクセル密度の差し替えだけで、レイアウト(予約セル数)は
        // layout_px 固定なので装飾を組み直さない(=md 上の表示サイズは不変・ユーザー要件)。
        let url_str = res.path.to_string_lossy().to_string();
        let is_math = crate::preview::markdown::is_math_url(&url_str);
        if !res.reraster && (crate::preview::markdown::is_mermaid_fence_url(&url_str) || is_math) {
            self.md_cache = None;
        }
        let entry = self.md_image_cache.entry(res.path).or_default();
        if res.reraster {
            entry.reraster_inflight = false;
        }
        match res.image {
            Ok(img) => {
                use image::GenericImageView;
                if entry.layout_px.is_none() {
                    // 数式は SVG の**内在サイズ(単位)**を layout_px に載せる(ラスタ px でなく): em 高さから
                    // 行数、内在アスペクトから桁数を導いてテキストと釣り合うサイズにするため(math_cells)。
                    // 内在サイズが取れない時のみラスタ寸法へフォールバック。フェンス/通常画像は従来どおり。
                    entry.layout_px = if is_math {
                        res.svg
                            .as_deref()
                            .and_then(|d| crate::preview::svg::intrinsic_size_bytes(d))
                            .or_else(|| Some(img.dimensions()))
                    } else {
                        Some(img.dimensions())
                    };
                }
                entry.decoded = Some(Arc::new(img));
                entry.failed = false;
                if let Some(svg) = res.svg {
                    entry.svg = Some(svg);
                }
                if res.reraster {
                    // 高密度ラスタで再エンコードさせる: キーだけ無効化し、旧 protocol は
                    // 新しいエンコードが届くまでの表示用に残す(消すと一瞬空白になる)。
                    entry.proto_size = None;
                    entry.clip_key = None;
                    entry.zoom_key = None;
                }
            }
            // 再ラスタ失敗は現ラスタ据え置き(表示は生きたまま)。初回失敗のみテキスト降格。
            Err(_) if res.reraster => {}
            Err(_) => entry.failed = true,
        }
        true
    }

    /// Drive the **in-place zoom** of the focused inline mermaid diagram: clamp the pan center,
    /// kick a sharpening re-raster when the zoom outgrows the raster density (the layout size stays
    /// fixed via `layout_px`), and request an encode of the current crop into the same (cols, rows)
    /// cell area. All heavy work runs on worker threads; at most one of each is in flight.
    pub fn ensure_md_fence_zoom(&mut self, url: &str, cols: u16, rows: u16) {
        use image::GenericImageView;
        let key_path = PathBuf::from(url);
        let zoom = self.fence_zoom;
        let font = self.picker.as_ref().map(|p| p.font_size());
        let enc_tx = self.md_enc_tx.clone();
        let Some(entry) = self.md_image_cache.get_mut(&key_path) else {
            return;
        };
        let Some(img) = entry.decoded.clone() else {
            return;
        };
        let (sw, sh) = img.dimensions();
        // シャープ化: 表示に必要な密度(セル×フォントpx×ズーム)が現ラスタを超えたら、保持 SVG を
        // 高密度に再ラスタ(全画面のシャープズームと同じ・レイアウトは layout_px 固定で不変)。
        if let Some(f) = font {
            let disp = ((cols as f64 * f.width as f64).max(rows as f64 * f.height as f64) * zoom)
                .ceil() as u32;
            if self.fence_sharpen_if_needed(&key_path, disp) == FenceSharpen::AppliedSync {
                // 同期フォールバック(テスト): 新しいラスタで最初からやり直す。
                drop(img);
                return self.ensure_md_fence_zoom(url, cols, rows);
            }
        }
        // 現ラスタから可視窓を切り出す(比率ベース=再ラスタ後も同じ窓)。中心は端でクランプし書き戻す。
        let f = (1.0 / zoom.max(1.0)).clamp(0.0, 1.0);
        let (crop, center) = fence_crop((sw, sh), f, self.fence_center);
        self.fence_center = center;
        let Some(entry) = self.md_image_cache.get_mut(&key_path) else {
            return;
        };
        let zkey = (cols, rows, crop);
        if entry.zoom_key == Some(zkey) || entry.enc_inflight {
            return;
        }
        let Some(tx) = enc_tx else { return };
        entry.enc_inflight = true;
        let _ = tx.send(MdEncodeRequest {
            path: key_path,
            key: MdEncodeKey::Zoom { cols, rows, crop },
            image: img,
            crop: Some(crop),
            cols,
            rows,
        });
    }

    /// The protocol for the focused inline diagram's current zoom, if encoded for this (cols, rows).
    /// While a fresh crop is still encoding, the previous zoom crop (or the unzoomed full protocol)
    /// stays visible instead of blinking out.
    pub fn md_fence_zoom_proto(&self, url: &str, cols: u16, rows: u16) -> Option<&Protocol> {
        let entry = self.md_image_cache.get(&PathBuf::from(url))?;
        match entry.zoom_key {
            Some((c, r, _)) if (c, r) == (cols, rows) => {
                entry.zoom_protocol.as_ref().or(entry.protocol.as_ref())
            }
            _ => entry.protocol.as_ref(),
        }
    }

    /// Kick a sharpening re-raster of a fence diagram when `needed_px` exceeds the current raster
    /// density (shared by the unzoomed density follow-up and the in-place zoom). Returns what
    /// happened so the synchronous test fallback can re-run with the fresh raster.
    fn fence_sharpen_if_needed(&mut self, key_path: &PathBuf, needed_px: u32) -> FenceSharpen {
        use image::GenericImageView;
        let img_tx = self.md_img_tx.clone();
        let Some(entry) = self.md_image_cache.get_mut(key_path) else {
            return FenceSharpen::NotNeeded;
        };
        let (Some(img), Some(svg)) = (entry.decoded.as_ref(), entry.svg.clone()) else {
            return FenceSharpen::NotNeeded;
        };
        let (sw, sh) = img.dimensions();
        let cur = sw.max(sh);
        if needed_px <= cur + cur / 8 || cur >= 4096 || entry.reraster_inflight {
            return FenceSharpen::NotNeeded;
        }
        entry.reraster_inflight = true;
        let target = needed_px.min(4096);
        let kp = key_path.clone();
        let job = move || {
            let image =
                crate::preview::svg::rasterize_bytes(&svg, Path::new("mermaid.svg"), target)
                    .ok_or_else(|| "rasterize failed".to_string());
            MdImageResult {
                path: kp,
                image,
                svg: None,
                reraster: true,
            }
        };
        if let Some(tx) = img_tx {
            std::thread::spawn(move || {
                let _ = tx.send(job());
            });
            FenceSharpen::Spawned
        } else {
            let res = job();
            // 失敗は AppliedSync を名乗らない: 呼び元(ensure_md_fence_zoom)は AppliedSync で
            // 「新しいラスタでやり直す」再帰をするため、失敗が続くと堂々巡りになる。成功時の
            // 再帰は 1 回で必ず収束する(次パスは needed<=cur か 4096 上限で NotNeeded)。
            let ok = res.image.is_ok();
            self.apply_md_image(res);
            if ok {
                FenceSharpen::AppliedSync
            } else {
                FenceSharpen::NotNeeded
            }
        }
    }

    /// Keep an inline diagram's raster density up with its **display size** (called per visible
    /// mermaid placement). `mermaid_rows` can size diagrams beyond the base raster (svg_max_px),
    /// so without this a large setting would show upscaled-blurry pixels.
    pub fn ensure_md_fence_density(&mut self, url: &str, cols: u16, rows: u16) {
        let Some(f) = self.picker.as_ref().map(|p| p.font_size()) else {
            return;
        };
        let needed =
            ((cols as f64 * f.width as f64).max(rows as f64 * f.height as f64)).ceil() as u32;
        let _ = self.fence_sharpen_if_needed(&PathBuf::from(url), needed);
    }

    /// Frame bookkeeping for the inline-image overlay (called by `ui::render`): reset at frame
    /// start, recorded by the overlay, compared at frame end. A change after a drawn state marks
    /// the frame "moved" so the run loop clears the terminal once (placeholder-orphan sweep).
    pub fn begin_md_overlay_frame(&mut self) {
        self.md_overlay_seen = None;
    }

    /// Record the overlay signature for this frame (urls + screen rects of drawn inline images).
    pub fn note_md_overlay(&mut self, sig: u64) {
        self.md_overlay_seen = Some(sig);
    }

    /// Compare this frame's overlay against the previous frame; latch "moved" on any change away
    /// from a previously drawn state (position shift, or the images left the screen entirely).
    pub fn finish_md_overlay_frame(&mut self) {
        if self.md_overlay_last != self.md_overlay_seen {
            if self.md_overlay_last.is_some() {
                self.md_overlay_moved = true;
            }
            self.md_overlay_last = self.md_overlay_seen;
        }
    }

    /// Whether the run loop should full-clear once to sweep orphaned placeholder rows (resets).
    pub fn take_md_overlay_moved(&mut self) -> bool {
        std::mem::take(&mut self.md_overlay_moved)
    }

    /// Ensure a background mermaid render is in flight (or cached) for one ```mermaid fence.
    /// Keyed by content hash, so an edited fence renders fresh while unchanged fences reuse their
    /// raster. With no loader tx (tests), renders synchronously so behavior stays observable.
    /// Returns true when the render completed **synchronously** (no loader tx = tests): the caller
    /// must rebuild its just-built decoration, which still shows the loading line.
    fn ensure_mermaid_fence_render(&mut self, code: String) -> bool {
        let key = PathBuf::from(crate::preview::markdown::mermaid_fence_url(&code));
        if self.md_image_cache.contains_key(&key) {
            return false;
        }
        self.md_image_cache
            .insert(key.clone(), MdImgEntry::default());
        let max_px = self.mermaid_px();
        let theme = self.cfg.ui.mermaid_theme.clone();
        let render = move || -> (Result<image::DynamicImage, String>, Option<std::sync::Arc<Vec<u8>>>) {
            let Some(svg) = crate::preview::markdown::mermaid_to_svg(&code, &theme) else {
                return (Err("mermaid render failed".to_string()), None);
            };
            let data = std::sync::Arc::new(svg.into_bytes());
            let img =
                crate::preview::svg::rasterize_bytes(&data, Path::new("mermaid.svg"), max_px)
                    .ok_or_else(|| "rasterize failed".to_string());
            (img, Some(data))
        };
        if let Some(tx) = self.md_img_tx.clone() {
            std::thread::spawn(move || {
                // render()(rasterize_bytes=resvg)が panic してもスレッドを殺さず必ず結果を返す:
                // 返さないとエントリが decoded=None && !failed のまま固着し busy が恒久 true になる。
                let (image, svg) = crate::preview::markdown::catch_silent(render)
                    .unwrap_or_else(|| (Err("mermaid render panicked".to_string()), None));
                let _ = tx.send(MdImageResult {
                    path: key,
                    image,
                    svg,
                    reraster: false,
                });
            });
            false
        } else {
            let (image, svg) = render();
            self.apply_md_image(MdImageResult {
                path: key,
                image,
                svg,
                reraster: false,
            });
            true
        }
    }

    /// Ensure a background render is in flight (or cached) for one math expression, keyed by latex +
    /// display so an edited equation renders fresh while unchanged ones reuse their raster. Mirrors
    /// `ensure_mermaid_fence_render`; the SVG is kept so `apply_md_image` can record its intrinsic (em)
    /// size for layout. Returns true on a synchronous completion (no loader tx = tests).
    fn ensure_math_render(&mut self, latex: String, display: bool) -> bool {
        let key = PathBuf::from(crate::preview::markdown::math_url(&latex, display));
        if self.md_image_cache.contains_key(&key) {
            return false;
        }
        self.md_image_cache
            .insert(key.clone(), MdImgEntry::default());
        let max_px = self.math_px();
        // グリフ色(サニタイズ済み)を worker へ move。RaTeX の既定は純黒=ダーク端末で不可視のため、
        // 端末背景に映える色で塗る(config `[ui] math_color`・既定は明るいグレー)。
        let color = self.cfg.ui.math_color().to_string();
        let render =
            move || -> (Result<image::DynamicImage, String>, Option<std::sync::Arc<Vec<u8>>>) {
                let Some(svg) = crate::preview::math::latex_to_svg(&latex, display, &color) else {
                    return (Err("math render failed".to_string()), None);
                };
                let data = std::sync::Arc::new(svg.into_bytes());
                let img = crate::preview::svg::rasterize_bytes(&data, Path::new("math.svg"), max_px)
                    .ok_or_else(|| "rasterize failed".to_string());
                (img, Some(data))
            };
        if let Some(tx) = self.md_img_tx.clone() {
            std::thread::spawn(move || {
                let (image, svg) = crate::preview::markdown::catch_silent(render)
                    .unwrap_or_else(|| (Err("math render panicked".to_string()), None));
                let _ = tx.send(MdImageResult {
                    path: key,
                    image,
                    svg,
                    reraster: false,
                });
            });
            false
        } else {
            let (image, svg) = render();
            self.apply_md_image(MdImageResult {
                path: key,
                image,
                svg,
                reraster: false,
            });
            true
        }
    }

    /// Apply a completed background encode: store the protocol in its full or clip slot. Returns redraw.
    /// A failed encode (`protocol: None`) records the attempted key **without** touching the stored
    /// protocols — the last good state stays visible and the same request is not retried every frame.
    /// Only when nothing was ever encodable (no full protocol at all) does the entry degrade to the
    /// text fallback (principle #3).
    pub fn apply_md_encode(&mut self, res: MdEncodeResult) -> bool {
        let Some(entry) = self.md_image_cache.get_mut(&res.path) else {
            return false;
        };
        entry.enc_inflight = false;
        let mut degrade = false;
        match (res.key, res.protocol) {
            (MdEncodeKey::Full { cols, rows }, Some(p)) => {
                entry.protocol = Some(p);
                entry.proto_size = Some((cols, rows));
            }
            (MdEncodeKey::Full { cols, rows }, None) => {
                entry.proto_size = Some((cols, rows));
                if entry.protocol.is_none() {
                    entry.failed = true;
                    degrade = true;
                }
            }
            (
                MdEncodeKey::Clip {
                    cols,
                    full_rows,
                    row_off,
                    vis_rows,
                },
                p,
            ) => {
                if let Some(p) = p {
                    entry.clip_protocol = Some(p);
                }
                entry.clip_key = Some((cols, full_rows, row_off, vis_rows));
            }
            (MdEncodeKey::Zoom { cols, rows, crop }, p) => {
                if let Some(p) = p {
                    entry.zoom_protocol = Some(p);
                }
                entry.zoom_key = Some((cols, rows, crop));
            }
        }
        if degrade {
            // 新規に failed へ降格した画像はテキスト行へ再レイアウト(見えない空白のまま残さない)。
            self.md_cache = None;
        }
        true
    }

    /// Attach the sender that reports background remote-image download completions to the run loop.
    pub fn attach_remote_md_loader(&mut self, tx: std::sync::mpsc::Sender<RemoteFetch>) {
        self.md_remote_tx = Some(tx);
    }

    /// Apply a completed remote-image download. On success the file is now cached, so drop the
    /// decoration cache to re-lay the image out inline; on failure remember the URL so it is not
    /// retried and shows a text placeholder instead. Returns whether to redraw.
    pub fn apply_remote_fetch(&mut self, res: RemoteFetch) -> bool {
        self.md_remote_inflight.remove(&res.url);
        if !res.ok {
            self.md_remote_failed.insert(res.url);
        }
        // Re-decorate so a now-cached image is laid out (or a failed one degrades to text).
        self.md_cache = None;
        true
    }

    /// Ensure a background download is in flight for the remote image `url` (deduplicated). Skips URLs
    /// that are already cached, already downloading, or known to have failed. The download runs off the
    /// UI thread (principle #4) via `curl`; on completion it reports through `md_remote_tx`.
    fn ensure_remote_md_fetch(&mut self, url: &str) {
        if !crate::preview::markdown::is_remote_image_url(url) {
            return;
        }
        // Already downloaded (cache file exists), already failed, or already downloading → nothing to do.
        if resolve_md_image_path(url, None).is_some()
            || self.md_remote_failed.contains(url)
            || self.md_remote_inflight.contains(url)
        {
            return;
        }
        let (Some(tx), Some(dest)) = (self.md_remote_tx.clone(), md_remote_cache_path(url)) else {
            return;
        };
        self.md_remote_inflight.insert(url.to_string());
        let u = url.to_string();
        std::thread::spawn(move || {
            // ダウンロードが panic しても md_remote_inflight を残さない(残すと busy 固着):
            // panic は取得失敗(ok=false)として必ず報告する。
            let ok = crate::preview::markdown::catch_silent(|| fetch_remote_image(&u, &dest))
                .unwrap_or(false);
            let _ = tx.send(RemoteFetch { url: u, ok });
        });
    }

    /// Ensure the inline image for `url` is decoding in the background and that the protocol for the
    /// currently-visible portion (whole image, or a cropped band when partially scrolled) is encoding on
    /// the worker thread. Called from the renderer for each visible inline image. Both decoding and
    /// encoding are off-thread (principle #4) so this never blocks the UI; the protocol appears a frame
    /// or two later. At most one encode is in flight per image, so scrolling never queues a backlog.
    pub fn ensure_md_image(
        &mut self,
        url: &str,
        cols: u16,
        full_rows: u16,
        row_off: u16,
        vis_rows: u16,
    ) {
        // 合成キー(フェンス図・数式)はそのままキャッシュキー(デコードは ensure_mermaid_fence_render /
        // ensure_math_render 済み)。実ファイル画像だけディスク解決する。数式 `math://` を実ファイル扱い
        // すると resolve が None を返し、エンコードを一度も要求せず予約行が空白のまま残っていた。
        let path = if crate::preview::markdown::is_synthetic_md_url(url) {
            PathBuf::from(url)
        } else {
            let base = self
                .preview_path
                .as_ref()
                .and_then(|p| p.parent())
                .map(|p| p.to_path_buf());
            let Some(p) = resolve_md_image_path(url, base.as_deref()) else {
                return;
            };
            p
        };
        // Kick off a one-time background decode.
        if !self.md_image_cache.contains_key(&path) {
            // 合成キー(フェンス図・数式)はここでは作れない(元の code/latex が要る)。配置が在る以上
            // キャッシュ済みのはずで、来ない前提の防御(次の再装飾で ensure_mermaid_fence_render /
            // ensure_math_render が作り直す)。`math://` を実ファイルとしてデコードさせない。
            if crate::preview::markdown::is_synthetic_md_url(url) {
                return;
            }
            self.md_image_cache
                .insert(path.clone(), MdImgEntry::default());
            if let Some(tx) = self.md_img_tx.clone() {
                let p = path.clone();
                let svg_max_px = self.cfg.ui.svg_max_px;
                std::thread::spawn(move || {
                    // Sniff the format from content (remote-cache files have no extension); rasterize SVG.
                    // panic(病的画像/SVG)も捕捉して必ず結果を返す(返さないと busy 固着)。
                    let image =
                        crate::preview::markdown::catch_silent(|| md_decode_image(&p, svg_max_px))
                            .flatten()
                            .ok_or_else(|| "decode failed".to_string());
                    let _ = tx.send(MdImageResult {
                        path: p,
                        image,
                        svg: None,
                        reraster: false,
                    });
                });
            }
            return;
        }
        let Some(enc_tx) = self.md_enc_tx.clone() else {
            return;
        };
        let Some(entry) = self.md_image_cache.get_mut(&path) else {
            return;
        };
        // Wait if it failed, is still decoding, or already has an encode in flight (one at a time).
        if entry.failed || entry.enc_inflight {
            return;
        }
        let Some(img) = entry.decoded.clone() else {
            return;
        };
        // Fully visible: request an encode of the whole image at (cols, full_rows) unless already cached.
        if row_off == 0 && vis_rows >= full_rows {
            if entry.proto_size == Some((cols, full_rows)) {
                return;
            }
            entry.enc_inflight = true;
            let _ = enc_tx.send(MdEncodeRequest {
                path,
                key: MdEncodeKey::Full {
                    cols,
                    rows: full_rows,
                },
                image: img,
                crop: None,
                cols,
                rows: full_rows,
            });
            return;
        }
        // Partially scrolled: request an encode of just the visible pixel band at (cols, vis_rows), so the
        // image renders clipped to the viewport rather than being hidden.
        if entry.clip_key == Some((cols, full_rows, row_off, vis_rows)) {
            return;
        }
        let (dw, dh) = (img.width(), img.height());
        let (y0, h) = md_band_pixels(full_rows, row_off, vis_rows, dh);
        entry.enc_inflight = true;
        let _ = enc_tx.send(MdEncodeRequest {
            path,
            key: MdEncodeKey::Clip {
                cols,
                full_rows,
                row_off,
                vis_rows,
            },
            image: img,
            crop: Some((0, y0, dw, h)),
            cols,
            rows: vis_rows,
        });
    }

    /// The render protocol to draw for the visible portion of inline image `url`. Prefers the protocol
    /// that exactly matches the current position (full image when fully visible, or the band matching
    /// `(cols, full_rows, row_off, vis_rows)`); while a newly-scrolled band is still encoding it returns
    /// the last encoded protocol so the image stays on screen (and snaps to the exact band on arrival)
    /// rather than blinking out. None only until the very first protocol for this image is ready.
    pub fn md_image_proto(
        &self,
        url: &str,
        cols: u16,
        full_rows: u16,
        row_off: u16,
        vis_rows: u16,
    ) -> Option<&Protocol> {
        let path = if crate::preview::markdown::is_synthetic_md_url(url) {
            PathBuf::from(url)
        } else {
            let base = self
                .preview_path
                .as_ref()
                .and_then(|p| p.parent())
                .map(|p| p.to_path_buf());
            resolve_md_image_path(url, base.as_deref())?
        };
        let entry = self.md_image_cache.get(&path)?;
        // Exact match for the current position.
        if row_off == 0 && vis_rows >= full_rows {
            if entry.proto_size == Some((cols, full_rows)) {
                return entry.protocol.as_ref();
            }
        } else if entry.clip_key == Some((cols, full_rows, row_off, vis_rows)) {
            // クリップのエンコードに失敗していた場合(clip_protocol 無しでキーだけ記録)は
            // 全体 protocol へ降格(空白のまま残さない)。
            return entry.clip_protocol.as_ref().or(entry.protocol.as_ref());
        }
        // Not yet encoded for this exact position: keep the last band (or the full image) visible.
        entry.clip_protocol.as_ref().or(entry.protocol.as_ref())
    }

    /// Whether any inline Markdown image is still loading — a remote download in flight, a decode not yet
    /// finished, or an encode in flight (used by the run loop to keep ticking so results are applied
    /// promptly and the image appears without waiting for the next key press).
    pub fn md_images_loading(&self) -> bool {
        !self.md_remote_inflight.is_empty()
            || self
                .md_image_cache
                .values()
                .any(|e| (e.decoded.is_none() && !e.failed) || e.enc_inflight)
    }

    /// Drop tx and the image state on exit (to terminate the worker thread).
    pub fn detach_image_backend(&mut self) {
        self.clear_image();
        self.img_tx = None;
    }

    /// Decode a still image and place it in image_src (the ThreadProtocol is built asynchronously at render time).
    /// Still images (PNG/JPG) decode fast, so this stays synchronous. On decode failure / no backend, image_src=None.
    fn load_image(&mut self, path: &Path) {
        if self.picker.is_none() || self.img_tx.is_none() {
            return; // バックエンド無し: 描画側がテキストにフォールバック
        }
        let Some(dyn_img) = crate::preview::image::decode_static(path) else {
            return;
        };
        self.set_static_image(dyn_img);
    }

    /// Common processing to set a still image (including SVG raster results / single-frame GIFs) as the display source.
    /// zoom/center are left untouched (enter_preview has the preceding clear_image set defaults, and tab restore has already
    /// overwritten them with the restored values; so that a late asynchronous result does not break the restored zoom/center).
    fn set_static_image(&mut self, img: image::DynamicImage) {
        self.image_src = Some(std::sync::Arc::new(img));
        self.image_crop = None; // 次の描画(prepare_image)でプロトコルを構築させる
                                // kitty 経路の「再ビルドせよ」合図。ズームでなく**ピクセルだけ差し替わる**(PDF ページ送り /
                                // 動画の再サムネ)経路は crop も表示セルも不変=`kitty_want` が変わらず、前ラスタが居残る。
                                // ここで want/shown を無効化し在り得る in-flight を陳腐化(gen bump)=差し替えは必ず再ビルドされる。
                                // (SVG reraster は crop_rect 変化で別途再ビルドされ、fresh/reload は clear_image 経由で二重でも無害。)
        self.kitty_gen = self.kitty_gen.wrapping_add(1);
        self.kitty_want = None;
        self.kitty_shown = None;
    }

    /// Common processing to set all GIF frames into the display state (used from both the synchronous and asynchronous paths).
    /// zoom/center are left untouched for the same reason as set_static_image.
    fn set_gif_frames(&mut self, frames: Vec<(image::DynamicImage, std::time::Duration)>) {
        self.gif_frames = frames;
        self.gif_idx = 0;
        self.gif_shown_at = None; // 最初の tick で計時開始
        self.gif_protocol = None;
        self.gif_proto_key = None;
        self.image_crop = None;
    }

    /// Start loading image-type media according to the preview kind (from enter_preview / tab restore).
    /// Still images are synchronous, while **heavy SVG rasterization / GIF full-frame decode are offloaded to a separate thread**
    /// (to start display fast without blocking the UI thread). With no media_tx (tests, etc.), a synchronous fallback is used.
    fn start_media_load(&mut self, kind: &PreviewKind, path: &Path) {
        // メディア自動再読込の基準時刻を記録(reload_media_if_changed が mtime 比較に使う)。
        self.preview_media_mtime = file_mtime(path);
        match kind {
            PreviewKind::Image(_) if Self::looks_like_gif(path) => {
                self.spawn_or_sync_media(MediaJob::Gif(path.to_path_buf()))
            }
            // 静止画(PNG/JPG 等)はデコードが速いので同期のまま(エンコードは描画時に worker が非同期化)。
            PreviewKind::Image(_) => self.load_image(path),
            PreviewKind::Svg(_) => {
                self.spawn_or_sync_media(MediaJob::Svg(path.to_path_buf(), self.cfg.ui.svg_max_px))
            }
            PreviewKind::Video(_) => self.spawn_or_sync_media(MediaJob::Video(path.to_path_buf())),
            PreviewKind::Pdf(_) => {
                self.spawn_or_sync_media(MediaJob::Pdf(path.to_path_buf(), self.pdf_page))
            }
            // 単体 .mmd/.mermaid: 画像モードなら純 Rust で SVG 化→ラスタライズ(別スレッド)。
            // テキストモード/バックエンド無しは何もしない=装飾テキスト経路が描く(原則#3)。
            PreviewKind::Mermaid(_) if self.mermaid_image_mode() => {
                self.spawn_or_sync_media(MediaJob::Mermaid(
                    path.to_path_buf(),
                    self.mermaid_px(),
                    self.cfg.ui.mermaid_theme.clone(),
                ))
            }
            // 全画面フェンス表示: md からフェンス本文を序数で取り直す(count-guard=コードコピーと同型)。
            PreviewKind::MermaidFence(ord) => {
                if let Some(code) = self.mermaid_fence_code(path, *ord) {
                    self.spawn_or_sync_media(MediaJob::MermaidSrc(
                        code,
                        self.mermaid_px(),
                        self.cfg.ui.mermaid_theme.clone(),
                    ));
                }
            }
            _ => {}
        }
    }

    /// Whether mermaid renders as an image: config says so **and** the terminal has an image backend.
    /// Everything else (config `"text"`, no backend, render failure) degrades to the text diagram.
    pub fn mermaid_image_mode(&self) -> bool {
        self.cfg.ui.mermaid != "text" && self.picker.is_some()
    }

    /// Base raster target (max edge px) for mermaid diagrams — same knob as SVG previews.
    fn mermaid_px(&self) -> u32 {
        self.cfg.ui.svg_max_px
    }

    /// Whether math ($…$ / $$…$$) renders as an image (`[ui] math` != "text" and a graphics backend).
    /// Off → math stays as raw LaTeX inline (the delimiters are left in the text).
    pub fn math_image_mode(&self) -> bool {
        self.cfg.ui.math != "text" && self.picker.is_some()
    }

    /// Raster target (max edge px) for a math equation. Generous so the once-rendered raster stays
    /// crisp when the encode worker fits it into the (usually small) reserved cell area.
    fn math_px(&self) -> u32 {
        1024
    }

    /// Validated `[ui] mermaid_rows`: max rows of an inline diagram (0/invalid → default 24).
    fn mermaid_rows_cap(&self) -> u16 {
        match self.cfg.ui.mermaid_rows {
            0 => 24,
            v => v,
        }
    }

    /// Effective target rows for an inline diagram: the `mermaid_rows` cap, shrunk so the whole
    /// fence block (caption + diagram + bottom margin) fits the preview viewport — the initial
    /// view shows the entire diagram without scrolling (fit-to-view). Viewport 0 (no render yet /
    /// tests without a render pass) keeps the cap.
    fn mermaid_fit_rows(&self) -> u16 {
        let cap = self.mermaid_rows_cap();
        if self.preview_viewport == 0 {
            return cap;
        }
        cap.min(self.preview_viewport.saturating_sub(2)).max(4)
    }

    /// The Nth ```mermaid fence body of the Markdown file at `md`, re-extracted fresh so an external
    /// edit between focusing and opening can't render a stale diagram (None = gone/shifted).
    fn mermaid_fence_code(&self, md: &Path, ord: usize) -> Option<String> {
        let src = std::fs::read_to_string(md).ok()?;
        crate::preview::markdown::collect_mermaid_fences(&src)
            .into_iter()
            .nth(ord)
    }

    /// Run a media-load job on a separate thread (when media_tx is present). Otherwise run it synchronously.
    /// If there is no backend (picker), do nothing (the render side falls back).
    fn spawn_or_sync_media(&mut self, job: MediaJob) {
        if self.picker.is_none() {
            return; // 端末非対応: 描画側がテキスト/メッセージへフォールバック
        }
        let Some(tx) = self.media_tx.clone() else {
            // 同期フォールバック(テスト/チャネル未装着)。
            if let Some(payload) = job.run() {
                self.apply_payload(payload);
            }
            return;
        };
        self.media_gen = self.media_gen.wrapping_add(1);
        self.media_loading = true;
        let gen = self.media_gen;
        std::thread::spawn(move || {
            // job.run() が panic(resvg ラスタ/画像デコードの病的入力)してもスレッドを殺さず
            // 必ず結果を返す: 返さないと media_loading が次のプレビュー遷移まで true 固着し、
            // 「Loading…」表示のまま run ループが 16ms ポーリングを続ける(アイドル 0% が崩れる)。
            let payload = crate::preview::markdown::catch_silent(move || job.run()).flatten();
            let _ = tx.send(MediaResult { gen, payload });
        });
    }

    /// Apply a media-load result from another thread. Stale results (from after moving to another file) are discarded.
    /// Returns true if the state changes from applying / staleness judgment (the caller re-renders).
    pub fn apply_media(&mut self, result: MediaResult) -> bool {
        if result.gen != self.media_gen {
            return false; // 陳腐化: 既に別ファイルへ移っている
        }
        self.media_loading = false;
        // 現世代の結果が届いた=再ラスタの inflight は解消(失敗 None でも解除して詰まらせない)。
        self.vector_reraster_inflight = false;
        match result.payload {
            Some(payload) => {
                self.apply_payload(payload);
                true
            }
            None => true, // 失敗: loading を解除し描画側のフォールバック(生XML/メッセージ)へ
        }
    }

    fn apply_payload(&mut self, payload: MediaPayload) {
        match payload {
            MediaPayload::Static(img) => self.set_static_image(img),
            MediaPayload::Gif(frames) => self.set_gif_frames(frames),
            MediaPayload::Vector { img, svg } => {
                use image::GenericImageView;
                // 初回ラスタ到着=このサイズが論理(レイアウト)サイズ。以降のシャープ再ラスタは
                // ピクセル密度だけを差し替える(clear_image が logical を消す=別ファイルでリセット)。
                if self.image_logical.is_none() {
                    self.image_logical = Some(img.dimensions());
                }
                self.vector_svg = Some(svg);
                self.set_static_image(img);
                // ジョブ実行中にズームがさらに進んでいたら次の 1 本を出して収束させる
                // (足りていれば/上限 4096 なら NotNeeded 側で即 return)。
                self.maybe_sharpen_vector();
            }
        }
    }

    /// Whether waiting on another thread's media load (used by the render side to decide on the "Loading…" display).
    pub fn is_media_loading(&self) -> bool {
        self.media_loading
    }

    /// Decide whether it is a GIF by the leading bytes (looks at the magic, not the extension).
    fn looks_like_gif(path: &Path) -> bool {
        use std::io::Read;
        let Ok(mut f) = std::fs::File::open(path) else {
            return false;
        };
        let mut head = [0u8; 6];
        if f.read_exact(&mut head).is_err() {
            return false;
        }
        &head[..4] == b"GIF8" // GIF87a / GIF89a
    }

    /// Drive the GIF animation. If the current frame's display time has elapsed, advance to the next frame index.
    /// The actual re-encode is done by prepare_gif on the next render (detecting the gif_idx change).
    /// Returns true if advanced (the caller re-renders). Always false if not a GIF.
    pub fn advance_gif_if_due(&mut self) -> bool {
        if self.gif_frames.len() < 2 {
            return false;
        }
        let now = std::time::Instant::now();
        let Some(shown_at) = self.gif_shown_at else {
            // 最初の tick: 計時を開始するだけ(先頭フレームは表示済み)。
            self.gif_shown_at = Some(now);
            return false;
        };
        let delay = self.gif_frames[self.gif_idx].1;
        if now.duration_since(shown_at) < delay {
            return false;
        }
        self.gif_idx = (self.gif_idx + 1) % self.gif_frames.len();
        self.gif_shown_at = Some(now);
        true
    }

    /// Whether a GIF animation is active (used for branching in the render path and footer/zoom checks).
    pub fn is_gif_active(&self) -> bool {
        self.gif_frames.len() >= 2
    }

    /// The render protocol of the current GIF frame synchronously encoded to the display size (referenced by the render side).
    pub fn gif_protocol(&self) -> Option<&Protocol> {
        self.gif_protocol.as_ref()
    }

    /// Call just before rendering (for GIF). Compute the display rectangle target and crop from the current (gif_idx, zoom, center, inner), and
    /// if the frame/crop has changed, **synchronously encode** the current frame and swap it into gif_protocol.
    /// Being synchronous, "render an unencoded protocol → empty" does not happen, and the frame switches atomically (no churn).
    /// The return value is the render-target target. None when there is no backend / size 0.
    pub fn prepare_gif(&mut self, inner: Rect) -> Option<Rect> {
        let picker = self.picker.as_ref()?;
        let scale = self.cfg.ui.image_render_scale;
        let src = &self.gif_frames.get(self.gif_idx)?.0;
        let (target, crop_rect, center, frac) = image_layout(
            src,
            picker.font_size(),
            self.image_zoom,
            self.image_center,
            inner,
            scale,
            None, // GIF はラスタ実寸のまま(ベクタ由来でない)
        )?;
        let key = (self.gif_idx, crop_rect);
        // フレーム or crop(ズーム/パン/リサイズ)が変わったときだけ再エンコード。
        let built = if self.gif_proto_key != Some(key) {
            let (x0, y0, cw, ch) = crop_rect;
            let crop = src.crop_imm(x0, y0, cw, ch);
            let size = ratatui::layout::Size::new(target.width.max(1), target.height.max(1));
            // src/picker の借用はこの式で完結(結果は所有値)→以降 self を変更可。
            // GIF は UI スレッドで毎フレーム同期エンコードするため、軽量で滑らかな Triangle(bilinear) を使う
            // (最近傍 None だとアニメ各フレームがジャギる。最高品質の Lanczos3 は静止画側で使用)。
            Some(picker.new_protocol(crop, size, Resize::Scale(Some(FilterType::Triangle))))
        } else {
            None
        };
        if let Some(res) = built {
            match res {
                Ok(p) => {
                    self.gif_protocol = Some(p);
                    self.gif_proto_key = Some(key);
                }
                Err(_) => {
                    // エンコード失敗: 描画側はメッセージにフォールバック。次フレームで再試行。
                    self.gif_protocol = None;
                    self.gif_proto_key = None;
                }
            }
        }
        self.image_center = center;
        self.image_vis_frac = frac;
        self.image_crop = Some(crop_rect);
        Some(target)
    }

    /// Wait time until the next frame while a GIF is playing (for the poll timeout). None when not playing.
    /// Clamped to [10ms, 100ms] for smoothness (100ms is the same as the normal idle-tick upper bound).
    pub fn gif_poll_timeout(&self) -> Option<std::time::Duration> {
        use std::time::Duration;
        if self.gif_frames.len() < 2 {
            return None;
        }
        let remaining = match self.gif_shown_at {
            None => Duration::ZERO, // まだ計時前: すぐ次の tick を回して計時開始
            Some(t) => self.gif_frames[self.gif_idx]
                .1
                .checked_sub(t.elapsed())
                .unwrap_or(Duration::ZERO),
        };
        Some(remaining.clamp(Duration::from_millis(10), Duration::from_millis(100)))
    }

    // ---- CSV/TSV テーブルプレビュー ------------------------------------------

    /// Parse the current Table-kind preview into `table_data` (None on failure = raw-text fallback).
    /// Does not touch the cursor/scroll (callers reset or restore those as appropriate).
    fn load_table(&mut self) {
        self.table_data = None;
        if let Some(PreviewKind::Table { path, delimiter }) = self.preview_kind.clone() {
            if let Ok(t) = crate::preview::table::parse(&path, delimiter) {
                self.table_data = Some(t);
            }
        }
    }

    /// Clamp the cell cursor into the table's bounds (after a reload/restore that may have shrunk it).
    fn clamp_table_cursor(&mut self) {
        match &self.table_data {
            Some(t) if t.nrows() > 0 && t.ncols > 0 => {
                self.table_cur_row = self.table_cur_row.min(t.nrows() - 1);
                self.table_cur_col = self.table_cur_col.min(t.ncols - 1);
            }
            _ => {
                self.table_cur_row = 0;
                self.table_cur_col = 0;
            }
        }
    }

    /// Whether a CSV/TSV table preview is active **and parsed** (routes the PreviewTable surface / renderer).
    /// A Table kind whose parse failed returns false → the preview degrades to raw text.
    pub fn is_table_preview(&self) -> bool {
        matches!(self.preview_kind, Some(PreviewKind::Table { .. })) && self.table_data.is_some()
    }

    /// The field-separator byte of the active table (`,` by default).
    fn table_delimiter(&self) -> u8 {
        match self.preview_kind {
            Some(PreviewKind::Table { delimiter, .. }) => delimiter,
            _ => b',',
        }
    }

    /// The parsed table (for the renderer). None when not a table preview.
    pub fn table_data(&self) -> Option<&crate::preview::table::TableData> {
        self.table_data.as_ref()
    }

    /// The cell cursor as (data-row, column), both 0-based.
    pub fn table_cursor(&self) -> (usize, usize) {
        (self.table_cur_row, self.table_cur_col)
    }

    /// The current (top data row, left column) scroll offsets.
    pub fn table_scroll(&self) -> (usize, usize) {
        (self.table_top_row, self.table_left_col)
    }

    /// Renderer feedback: store the scroll offsets it settled on (to keep the cursor visible) plus the
    /// visible data-row count (used as the PageUp/Down step). Mirrors how `preview_scroll`/`preview_viewport`
    /// are clamped/recorded at render time.
    pub fn set_table_view(&mut self, top_row: usize, left_col: usize, viewport_rows: u16) {
        self.table_top_row = top_row;
        self.table_left_col = left_col;
        self.table_viewport_rows = viewport_rows;
    }

    /// Move the cell cursor by (drow, dcol), clamped to the table. The renderer scrolls to follow.
    pub fn table_cursor_move(&mut self, drow: i32, dcol: i32) {
        let Some(t) = &self.table_data else {
            return;
        };
        let (nr, nc) = (t.nrows(), t.ncols);
        if nr == 0 || nc == 0 {
            return;
        }
        let r = (self.table_cur_row as i64 + drow as i64).clamp(0, nr as i64 - 1);
        let c = (self.table_cur_col as i64 + dcol as i64).clamp(0, nc as i64 - 1);
        self.table_cur_row = r as usize;
        self.table_cur_col = c as usize;
    }

    /// Jump to the first (`bottom=false`) or last (`bottom=true`) data row.
    pub fn table_row_to(&mut self, bottom: bool) {
        let Some(t) = &self.table_data else {
            return;
        };
        self.table_cur_row = if bottom {
            t.nrows().saturating_sub(1)
        } else {
            0
        };
    }

    /// Jump to the first (`end=false`) or last (`end=true`) column.
    pub fn table_col_to(&mut self, end: bool) {
        let Some(t) = &self.table_data else {
            return;
        };
        self.table_cur_col = if end { t.ncols.saturating_sub(1) } else { 0 };
    }

    /// Move the cursor down/up by whole pages (`dir` = +1 / -1). The page size is the last render's visible rows.
    pub fn table_page(&mut self, dir: i32) {
        let page = self.table_viewport_rows.max(1) as i32;
        self.table_cursor_move(dir * page, 0);
    }

    /// Move the cursor down/up by half a page (`dir` = +1 / -1).
    pub fn table_half_page(&mut self, dir: i32) {
        let half = (self.table_viewport_rows / 2).max(1) as i32;
        self.table_cursor_move(dir * half, 0);
    }

    /// Build the text a table copy would place on the clipboard (None when there is no table).
    /// Cell = the current cell's value; Row = the current row's cells joined by the delimiter;
    /// Column = the column's header + every cell value, one per line.
    fn table_copy_text(&self, kind: TableCopyKind) -> Option<String> {
        let t = self.table_data.as_ref()?;
        let (r, c) = (self.table_cur_row, self.table_cur_col);
        let sep = (self.table_delimiter() as char).to_string();
        Some(match kind {
            TableCopyKind::Cell => {
                if t.nrows() == 0 {
                    t.header(c).to_string()
                } else {
                    t.cell(r, c).to_string()
                }
            }
            TableCopyKind::Row => {
                if t.nrows() == 0 {
                    t.headers.join(&sep)
                } else {
                    t.rows.get(r).map(|row| row.join(&sep)).unwrap_or_default()
                }
            }
            TableCopyKind::Column => {
                let mut vals = vec![t.header(c).to_string()];
                vals.extend(
                    t.rows
                        .iter()
                        .map(|row| row.get(c).cloned().unwrap_or_default()),
                );
                vals.join("\n")
            }
        })
    }

    /// Copy the current cell / row / column to the clipboard and flash the result.
    pub fn table_copy(&mut self, kind: TableCopyKind) {
        let Some(text) = self.table_copy_text(kind) else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        self.set_clipboard_flash(&text);
    }

    /// Whether the current preview is a (renderable) image. Used to route image-only keys (zoom/pan).
    /// Still images are judged by image_src, GIFs by gif_frames (image_src is not used). SVGs are already rasterized.
    pub fn is_image_preview(&self) -> bool {
        (self.image_src.is_some() || self.is_gif_active())
            && matches!(
                self.preview_kind,
                Some(
                    PreviewKind::Image(_)
                        | PreviewKind::Svg(_)
                        | PreviewKind::Video(_)
                        | PreviewKind::Pdf(_)
                        | PreviewKind::Mermaid(_)
                        | PreviewKind::MermaidFence(_)
                )
            )
    }

    /// Whether the current preview is a PDF (used to enable page-navigation keys / footer hints).
    pub fn is_pdf_preview(&self) -> bool {
        matches!(self.preview_kind, Some(PreviewKind::Pdf(_)))
    }

    /// (current, total) page for the PDF preview, or None when not a PDF or the page count is unknown
    /// (no poppler → single-page fallback, navigation disabled). Used for the footer/status indicator.
    pub fn pdf_page_indicator(&self) -> Option<(u32, u32)> {
        if !self.is_pdf_preview() {
            return None;
        }
        let total = self.pdf_pages?;
        Some((self.pdf_page.min(total), total))
    }

    /// Whether PDF page navigation is possible (a known multi-page PDF; requires poppler for both the
    /// count and per-page rendering, so this gates `J`/`K` from doing anything on single-page/no-poppler PDFs).
    pub fn pdf_can_navigate(&self) -> bool {
        matches!(self.pdf_pages, Some(n) if n > 1)
    }

    /// Go to the next PDF page (clamped to the last page). Re-rasterizes that page on demand (one at a time).
    pub fn pdf_next_page(&mut self) {
        self.pdf_goto(self.pdf_page.saturating_add(1));
    }

    /// Go to the previous PDF page (clamped to page 1).
    pub fn pdf_prev_page(&mut self) {
        self.pdf_goto(self.pdf_page.saturating_sub(1));
    }

    /// Jump to a 1-based page (clamped to [1, total]). No-op if not a navigable PDF or already there.
    /// Kicks off an off-thread rasterization of the new page and resets the view to fit (each page shows whole).
    fn pdf_goto(&mut self, page: u32) {
        if !self.pdf_can_navigate() {
            return;
        }
        let Some(total) = self.pdf_pages else { return };
        let page = page.clamp(1, total);
        if page == self.pdf_page {
            return;
        }
        self.pdf_page = page;
        // 新ページは全体が見えるよう fit に戻す(set_static_image は zoom/center を触らないので明示リセット)。
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
        self.image_crop = None;
        if let Some(PreviewKind::Pdf(p)) = self.preview_kind.clone() {
            // 旧ページの画像は到着まで表示したまま(media_gen で陳腐化判定・スピナーが重畳)。
            self.spawn_or_sync_media(MediaJob::Pdf(p, self.pdf_page));
        }
    }

    /// Zoom (multiply the magnification by `factor`; clamped to 1.0–16.0). The actual crop is applied at render time.
    /// With no full-screen image showing, `+`/`-` instead zoom the **focused inline mermaid diagram**
    /// in place (the reserved area in the document never changes — the zoom crops within it).
    pub fn image_zoom_by(&mut self, factor: f64) {
        if self.image_src.is_none() && !self.is_gif_active() {
            if self.focused_mermaid_ordinal().is_some() {
                self.fence_zoom = (self.fence_zoom * factor).clamp(1.0, 16.0);
            }
            return;
        }
        self.image_zoom = (self.image_zoom * factor).clamp(1.0, 16.0);
        self.maybe_sharpen_vector();
    }

    /// Sharp zoom for vector-backed previews (SVG / mermaid): when the zoom outgrows the current
    /// raster's density, re-rasterize the retained SVG at the needed max-edge px on a worker thread
    /// and swap it in on arrival (latest-wins via media_gen). The pixel zoom shows instantly in the
    /// meantime, so this behaves like a map app: briefly soft, then crisp. The geometry never moves
    /// because `image_layout` works in the logical size (`image_logical`), not the raster size.
    /// Memory stays bounded by the rasterizer's HARD_MAX (4096px side ≈ 64 MiB RGBA).
    fn maybe_sharpen_vector(&mut self) {
        use image::GenericImageView;
        // 1 本だけ: キーリピートの `+` 連打(ジョブ完了前に必要密度が伸び続ける)で同じ再ラスタを
        // 多重 spawn しない(1 本 ~数百 ms・過渡 ~128MiB)。到着時(apply_media→apply_payload)に
        // もう一度この関数が走り、その時点の最新ズームへ収束する。
        if self.vector_reraster_inflight {
            return;
        }
        let (Some(svg), Some(src), Some((lw, lh))) =
            (&self.vector_svg, &self.image_src, self.image_logical)
        else {
            return;
        };
        let cur_side = src.dimensions().0.max(src.dimensions().1);
        let want = ((lw.max(lh) as f64) * self.image_zoom).ceil() as u32;
        // 現ラスタで足りている(+12% マージン)か、既に上限(4096)なら何もしない。
        if want <= cur_side + cur_side / 8 || cur_side >= 4096 {
            return;
        }
        let base = self.preview_path.clone().unwrap_or_default();
        // 同期フォールバック(media_tx 無し=テスト)は spawn しない=多重の余地が無いので立てない。
        if self.media_tx.is_some() {
            self.vector_reraster_inflight = true;
        }
        self.spawn_or_sync_media(MediaJob::SvgReraster(svg.clone(), base, want));
    }

    /// Reset to 1x (fit). Zoom=1 and recenter. Applies to the focused inline diagram when no
    /// full-screen image is showing (same dual role as `image_zoom_by`).
    pub fn image_zoom_reset(&mut self) {
        if self.image_src.is_none() && !self.is_gif_active() {
            if self.focused_mermaid_ordinal().is_some() {
                self.fence_zoom = 1.0;
                self.fence_center = (0.5, 0.5);
            }
            return;
        }
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
    }

    /// Current in-place zoom of the focused inline diagram (renderer/footer cue).
    pub fn fence_zoom_level(&self) -> f64 {
        self.fence_zoom
    }

    /// Whether the focused inline diagram's reserved block is fully visible in the preview viewport
    /// (mirrors the renderer's in-place-zoom condition: `row_off == 0 && vis_rows >= rows`).
    /// Viewport 0 (no render pass yet — tests) counts as visible.
    fn focused_fence_fully_visible(&self) -> bool {
        let Some(ord) = self.focused_mermaid_ordinal() else {
            return false;
        };
        let Some((line, rows)) = self.mermaid_placement(ord) else {
            return false;
        };
        let vh = self.preview_viewport as usize;
        if vh == 0 {
            return true;
        }
        let (top, _) = self.md_visual_span(line);
        let scroll = self.preview_scroll as usize;
        top >= scroll && top + rows as usize <= scroll + vh
    }

    /// hjkl/arrows while an inline diagram is focused **and zoomed**: pan the diagram instead of
    /// scrolling the document; `0` fits (zoom reset — the image-view key). Returns true when
    /// consumed. At 1x nothing is consumed, so all keys scroll/navigate the document as usual.
    /// The diagram must also be on screen: after zooming and paging away (Ctrl-f/G), hjkl/j/k
    /// would otherwise pan an invisible diagram and the keys would appear dead.
    pub fn fence_pan_motion(&mut self, m: crate::keymap::Motion) -> bool {
        use crate::keymap::Motion as M;
        if self.fence_zoom <= 1.001 || !self.focused_fence_fully_visible() {
            return false;
        }
        // 0 = フィット(全画面画像と同じキー)。ズーム中のみ奪う(等倍では従来の行頭のまま)。
        if matches!(m, M::LineHome) {
            self.fence_zoom = 1.0;
            self.fence_center = (0.5, 0.5);
            return true;
        }
        let (dx, dy) = match m {
            M::Left => (-1.0, 0.0),
            M::Right => (1.0, 0.0),
            M::Up => (0.0, -1.0),
            M::Down => (0.0, 1.0),
            _ => return false,
        };
        // 1ステップ=可視窓の 1/4(全画面画像のパンと同じ感覚)。端のクランプは描画側の crop 計算。
        let f = 1.0 / self.fence_zoom;
        self.fence_center.0 = (self.fence_center.0 + dx * f * 0.25).clamp(0.0, 1.0);
        self.fence_center.1 = (self.fence_center.1 + dy * f * 0.25).clamp(0.0, 1.0);
        true
    }

    /// Pan. dx/dy are directions (-1/0/+1). Only clipped axes move the center, scaled by the visible fraction.
    /// Clamping is done at render time (prepare_image), looking at the visible fraction.
    pub fn image_pan(&mut self, dx: f64, dy: f64) {
        if self.image_src.is_none() && !self.is_gif_active() {
            return;
        }
        let (fw, fh) = self.image_vis_frac;
        // 1回で可視窓の約25%。見切れていない軸(frac>=1)は動かしても描画時にクランプされる。
        self.image_center.0 += dx * 0.25 * fw;
        self.image_center.1 += dy * 0.25 * fh;
    }

    /// Call just before rendering. From the current (zoom, center, display area inner), compute the image's display rectangle target
    /// (centered; z=1=fit, grows when zooming and clips once it exceeds the viewport) and the source-image crop of
    /// the visible portion; rebuild the protocol if the crop changed. The return value is the render-target target.
    /// Realizes "fit the render area to the image size (fit) → grow when zooming → clip + pan once exceeded".
    pub fn prepare_image(&mut self, inner: Rect) -> Option<Rect> {
        let src = self.image_src.as_ref()?;
        let picker = self.picker.as_ref()?;
        let scale = self.cfg.ui.image_render_scale;
        let (target, crop_rect, center, frac) = image_layout(
            src,
            picker.font_size(),
            self.image_zoom,
            self.image_center,
            inner,
            scale,
            self.image_logical,
        )?;
        let crop_changed = self.image_crop != Some(crop_rect);
        if self.use_kitty {
            // konoma-native compressed transmit. Request a rebuild only when the wanted geometry —
            // the crop (zoom/pan) or the display cell size (a terminal resize at fit) — changes;
            // otherwise the current/in-flight image already targets it, so a static image just
            // re-emits cheap placeholders every frame. The cell-size part matters because at fit zoom
            // a resize changes the area without the crop, and ratatui-image re-encodes on area change
            // internally, so konoma's path must too.
            let want = (crop_rect, target.width, target.height);
            if self.kitty_want != Some(want) {
                self.kitty_want = Some(want);
                self.request_kitty_build(crop_rect, target, picker.font_size());
            }
        } else {
            // ratatui-image path (sixel/iterm2/halfblocks, or kitty when disabled): rebuild the
            // ThreadProtocol only on crop change to avoid a per-frame re-encode.
            let new_tp = if crop_changed {
                let (x0, y0, cw, ch) = crop_rect;
                let crop = src.crop_imm(x0, y0, cw, ch);
                let proto = picker.new_resize_protocol(crop);
                Some(ThreadProtocol::new(
                    self.img_tx.as_ref()?.clone(),
                    Some(proto),
                ))
            } else {
                None
            };
            if let Some(tp) = new_tp {
                self.image = Some(tp);
            }
        }
        self.image_center = center;
        self.image_vis_frac = frac;
        self.image_crop = Some(crop_rect);
        Some(target)
    }

    /// Build the compressed kitty image for the given crop/target. The **first** build after opening
    /// a file (or after a failure left `kitty_image` None) runs synchronously so the image appears
    /// without a blank frame. Subsequent builds (zoom/pan/resize) run on a worker thread so rapid
    /// input does not hitch — the previous image keeps showing until the new one arrives (`apply_kitty`).
    /// With no `kitty_tx` (tests), everything runs synchronously.
    fn request_kitty_build(
        &mut self,
        crop_rect: (u32, u32, u32, u32),
        target: Rect,
        font: ratatui_image::FontSize,
    ) {
        let Some(src) = self.image_src.clone() else {
            return; // no source yet → render falls back
        };
        let (cols, rows) = (target.width, target.height);
        let is_tmux = self.kitty_is_tmux;
        // Every build bumps the generation so a stale async result is discarded by `apply_kitty`.
        self.kitty_gen = self.kitty_gen.wrapping_add(1);

        // Synchronous: the very first build (nothing to show yet) or when there is no worker channel.
        if self.kitty_image.is_none() || self.kitty_tx.is_none() {
            self.kitty_image = crate::preview::kitty::build_from_source(
                &src, crop_rect, cols, rows, font, is_tmux,
            );
            self.kitty_shown = self.kitty_want; // now showing the wanted geometry
            return;
        }

        // Async: keep the previous image visible; the newest spawn's result wins.
        let tx = self.kitty_tx.clone().unwrap();
        let gen = self.kitty_gen;
        std::thread::spawn(move || {
            // A pathological image must not kill the worker (else nothing is ever sent and the
            // previous image lingers); catch and report a failed build instead.
            let image = crate::preview::markdown::catch_silent(move || {
                crate::preview::kitty::build_from_source(&src, crop_rect, cols, rows, font, is_tmux)
            })
            .flatten();
            let _ = tx.send(KittyResult { gen, image });
        });
    }

    /// Apply a completed async kitty build. Stale results (superseded by a newer zoom/pan) and failed
    /// builds are dropped, keeping whatever image is currently shown rather than blanking it.
    pub fn apply_kitty(&mut self, result: KittyResult) -> bool {
        if result.gen != self.kitty_gen {
            return false; // superseded by a newer geometry
        }
        // Either way the newest generation has now settled — mark the wanted geometry as shown so
        // `kitty_build_pending()` clears. Otherwise a failed build (None) would leave it stuck true,
        // spinning the run loop at 16 ms forever (until the next geometry change). On failure the
        // previous image simply stays; on success we swap in the new one.
        self.kitty_shown = self.kitty_want;
        match result.image {
            Some(ki) => {
                self.kitty_image = Some(ki);
                true
            }
            None => false,
        }
    }

    /// Whether an async kitty build is in flight: the wanted geometry differs from what is shown.
    /// Covers pan (same cell size, different crop). The run loop polls faster while this is true so
    /// the result is picked up promptly.
    pub fn kitty_build_pending(&self) -> bool {
        self.use_kitty && self.kitty_want != self.kitty_shown
    }

    /// Whether still images are drawn via konoma's own compressed kitty transmit (kitty terminal).
    pub fn uses_kitty_image(&self) -> bool {
        self.use_kitty
    }

    /// The prepared compressed kitty image for the current crop, if built.
    pub fn kitty_image_ref(&self) -> Option<&crate::preview::kitty::KittyImage> {
        self.kitty_image.as_ref()
    }

    /// Page the text preview by one page (dir: +1=next page / -1=previous page).
    /// Overlaps one row to keep context. The upper bound is clamped at render time.
    pub fn preview_page(&mut self, dir: i32) {
        let page = self.preview_viewport.saturating_sub(1).max(1) as i32;
        self.preview_scroll(dir * page);
    }

    /// Half-page the text preview (vim: Ctrl-d/Ctrl-u, less: d/u).
    pub fn preview_half_page(&mut self, dir: i32) {
        let half = (self.preview_viewport / 2).max(1) as i32;
        self.preview_scroll(dir * half);
    }

    /// To the top of the preview.
    pub fn preview_to_top(&mut self) {
        if self.is_windowed() {
            self.preview_cursor_line = 0;
            self.preview_byte_top = 0;
            self.preview_top_line = 0;
        } else {
            self.preview_scroll = 0;
        }
    }

    /// To the bottom of the preview. The actual maximum is clamped at render time, when content and screen size are known.
    /// When windowed, moves to the line-head byte of the last page (found by a backward seek, without scanning the whole file).
    /// If line numbers are ON, the bottom line number is also corrected from the total line count.
    pub fn preview_to_bottom(&mut self) {
        if !self.is_windowed() {
            self.preview_scroll = u16::MAX;
            return;
        }
        let vh = self.preview_viewport.max(1) as usize;
        // 行カーソルの末尾クランプに総行数が要るので常に求める(キャッシュされる)。
        let total = self.win_total();
        let cur = self.preview_top_line;
        if let Some(b) = self
            .preview_win
            .as_mut()
            .map(|w| w.last_page_top(vh).unwrap_or(0))
        {
            self.preview_byte_top = b;
            self.preview_top_line = total.map(|t| t.saturating_sub(vh)).unwrap_or(cur);
        }
        if let Some(t) = total {
            self.preview_cursor_line = t.saturating_sub(1);
        }
    }

    /// Total line count (computed and cached only when line numbers are ON). Scans the whole file, so call it minimally.
    fn win_total(&mut self) -> Option<usize> {
        if let Some(t) = self.preview_total_lines {
            return Some(t);
        }
        let t = self.preview_win.as_mut()?.count_lines().ok()?;
        self.preview_total_lines = Some(t);
        Some(t)
    }

    /// Apply a re-encode result from the worker to the current image state. Returns true if applied.
    pub fn apply_image_resize(&mut self, resp: Result<ResizeResponse, Errors>) -> bool {
        let Ok(resp) = resp else {
            return false; // エンコード失敗は無視(クラッシュさせない)
        };
        match self.image.as_mut() {
            Some(state) => state.update_resized_protocol(resp),
            None => false,
        }
    }

    pub fn preview_scroll(&mut self, delta: i32) {
        if self.is_windowed() {
            // windowed(Code/Text)は行カーソルを動かし、窓を追従させる(常時カーソルモデル)。
            self.preview_cursor_move(delta);
            return;
        }
        let next = self.preview_scroll as i32 + delta;
        // 下限のみここで。上限 (末尾) は内容・画面サイズが判る描画時にクランプする。
        self.preview_scroll = next.max(0) as u16;
    }

    /// Move the windowed line cursor by `delta` (clamped to the file), then scroll the window to keep it visible.
    /// In visual mode the anchor stays fixed, so moving the cursor extends the selection.
    fn preview_cursor_move(&mut self, delta: i32) {
        let total = self.win_total().unwrap_or(usize::MAX);
        let maxl = total.saturating_sub(1) as i64;
        let next = (self.preview_cursor_line as i64 + delta as i64).clamp(0, maxl.max(0)) as usize;
        self.preview_cursor_line = next;
        self.follow_cursor();
    }

    /// Scroll the window (byte-based) just enough that the line cursor is on screen.
    fn follow_cursor(&mut self) {
        let vh = self.preview_viewport.max(1) as usize;
        let top = self.preview_top_line;
        let cur = self.preview_cursor_line;
        if cur < top {
            self.win_scroll_lines(-((top - cur) as i32));
        } else if cur >= top + vh {
            self.win_scroll_lines((cur + 1 - (top + vh)) as i32);
        }
    }

    /// Windowed scroll (delta lines). Computes the surrounding line-head bytes each time to move preview_byte_top, and
    /// updates preview_top_line (the line number) by the actual number of moved lines. Downward is clamped so as not to pass the last page.
    /// On end-clamp, the line number is corrected from the total line count when line numbers are ON.
    fn win_scroll_lines(&mut self, delta: i32) {
        let vh = self.preview_viewport.max(1) as usize;
        let top = self.preview_byte_top;
        let line = self.preview_top_line;
        // 行番号 ON、または(行カーソルのため)総行数が既にキャッシュされていれば末尾クランプに使う。
        let total = if self.cfg.ui.line_numbers || self.preview_total_lines.is_some() {
            self.win_total()
        } else {
            None
        };
        let result = self.preview_win.as_mut().map(|w| {
            if delta > 0 {
                let (adv, moved) = w.advance(top, delta as usize).unwrap_or((top, 0));
                let maxt = w.last_page_top(vh).unwrap_or(top);
                if adv >= maxt {
                    // 末尾ページ到達: 行番号は総行数から(無ければ素朴に加算)。
                    let bl = total.map(|t| t.saturating_sub(vh)).unwrap_or(line + moved);
                    (maxt, bl)
                } else {
                    (adv, line + moved)
                }
            } else if delta < 0 {
                let (ret, moved) = w.retreat(top, (-delta) as usize).unwrap_or((0, 0));
                (ret, line.saturating_sub(moved))
            } else {
                (top, line)
            }
        });
        if let Some((nt, nl)) = result {
            self.preview_byte_top = nt;
            self.preview_top_line = nl;
        }
    }

    /// For windowed display, read the current window (from the top byte for the height), highlight Code with syntect
    /// / leave Text plain, and return it as a list of ratatui Lines. Cached by (path, top byte, height),
    /// re-read only on scroll/resize. If the top exceeds the last page, it is clamped.
    pub fn windowed_lines(&mut self, height: u16, width: u16) -> Vec<Line<'static>> {
        let _ = width; // 行内容は幅に依存しない(折返しは描画側)。将来用に受けておく。
        let h = height.max(1) as usize;
        // リサイズ等で末尾を超えていたらクランプ(行番号も総行数から補正)。
        let top0 = self.preview_byte_top;
        let maxt = self
            .preview_win
            .as_mut()
            .and_then(|w| w.last_page_top(h).ok());
        if let Some(maxt) = maxt {
            if top0 > maxt {
                self.preview_byte_top = maxt;
                // 行番号ガター OFF でも検索の現在一致(橙)が abs=preview_top_line+i で
                // 参照するため、末尾ページへのクランプ時は line_numbers の有無に関わらず
                // 常に preview_top_line を総行数から補正する(#5)。
                if let Some(t) = self.win_total() {
                    self.preview_top_line = t.saturating_sub(h);
                }
            }
        }
        let top = self.preview_byte_top;
        let path = self.preview_path.clone().unwrap_or_default();
        // syntax を着けるか: ハイライト無効(off-switch) / progressive で待ち中(hl_pending)なら素。
        // Code は常に対象。Text は「拡張子/ファイル名から実在の文法が解決できる時だけ」対象にする=
        // .bashrc/Makefile/Dockerfile 等の設定ファイルを着色しつつ、本当に素のテキストは無色のまま保つ。
        // progressive 待ち中だけは「差し替え前の素テキスト」なのでキャッシュしない(後で着色版に替わる)。
        let syntax_kind = match &self.preview_kind {
            Some(PreviewKind::Code(_)) => true,
            Some(PreviewKind::Text(p)) => crate::preview::code::has_named_syntax(p),
            // raw ソース表示(`R`)の Markdown/Mermaid はファイルの文法(.md→Markdown 等)で着色する。
            Some(PreviewKind::Markdown(p)) | Some(PreviewKind::Mermaid(p)) if self.md_raw => {
                crate::preview::code::has_named_syntax(p)
            }
            _ => false,
        };
        let want_syntax = self.cfg.ui.syntax_highlight
            && syntax_kind
            && (!self.hl_pending || self.loading_is_indicator());
        // progressive 待ち中の素テキストだけはキャッシュしない(後で着色版に差し替わるため)。
        // それ以外は素テキストでも (path, top, height) でキャッシュする=毎フレームのファイル
        // 読み直しをしない。`styled` をキーに含め、着色版と素版を取り違えない。
        let cacheable = want_syntax || !(self.cfg.ui.syntax_highlight && syntax_kind);
        let mut content: Vec<Line<'static>> = if cacheable {
            let hit = matches!(
                &self.win_cache,
                Some(c) if c.path == path && c.byte_top == top && c.height == height
                    && c.styled == want_syntax
            );
            if !hit {
                let raw = self
                    .preview_win
                    .as_mut()
                    .and_then(|w| w.read_lines(top, h).ok())
                    .unwrap_or_default();
                let lines = if want_syntax {
                    let src = raw.join("\n");
                    crate::preview::code::highlight(&src, &path, &self.cfg.ui.theme.code_theme)
                } else {
                    raw.into_iter().map(Line::from).collect()
                };
                self.win_cache = Some(WinCache {
                    path,
                    byte_top: top,
                    height,
                    styled: want_syntax,
                    lines,
                });
            }
            self.win_cache
                .as_ref()
                .map(|c| c.lines.clone())
                .unwrap_or_default()
        } else {
            // progressive 待ち中の素テキスト(キャッシュしない=着色完了で差し替わる)。
            let raw = self
                .preview_win
                .as_mut()
                .and_then(|w| w.read_lines(top, h).ok())
                .unwrap_or_default();
            raw.into_iter().map(Line::from).collect()
        };
        // タブを可視マーカー(→)+タブストップ空白へ展開する(端末はタブを桁揃えしないため)。
        // 行番号ガター/検索強調の前に行う=桁追跡が本文の先頭(0桁)基準になる。窓の可視行のみ=軽い。
        content = crate::preview::code::expand_tabs(content, self.cfg.ui.tab_width);
        // 検索中は一致箇所(クエリ)を強調する(ガターより先=本文だけ強調)。
        // 現在の出現(search_idx)1箇所だけオレンジ、他は黄色。表示行 i の絶対行 = preview_top_line + i。
        // その行が現在の出現の行なら、その列(col)の出現だけオレンジにする(同一行に複数あっても1つ)。
        if let Some(q) = self.preview_search.clone() {
            // 現在一致(search_idx)の行と、その「行内での出現順位」(0始まり)を求める。
            // タブ展開でバイト列がずれるため、列(バイト位置)ではなく出現順位で
            // 現在一致を同定する(#14)。同一行の一致は search_matches 内で連続・列昇順。
            let (cur_line, cur_rank) = match self.search_matches.get(self.search_idx).copied() {
                Some((_, line, _)) => {
                    let rank = self.search_matches[..self.search_idx]
                        .iter()
                        .filter(|(_, l, _)| *l == line)
                        .count();
                    (Some(line), Some(rank))
                }
                None => (None, None),
            };
            let top_line = self.preview_top_line;
            content = content
                .into_iter()
                .enumerate()
                .map(|(i, l)| {
                    let abs = top_line + i;
                    let rank = if cur_line == Some(abs) {
                        cur_rank
                    } else {
                        None
                    };
                    highlight_query_in_line(l, &q, rank)
                })
                .collect();
        }
        let top_line = self.preview_top_line;
        // 2D キャレット列を可視のカーソル行の実長さにクランプし、書き戻す(`l`/`$` の行き過ぎ補正)。
        // キャレット行はビューポート追従で常に可視なので、ここで content から実長を取得できる。
        if self.preview_cursor_line >= top_line
            && self.preview_cursor_line < top_line + content.len()
        {
            let ln = &content[self.preview_cursor_line - top_line];
            let len: usize = ln.spans.iter().map(|s| s.content.chars().count()).sum();
            // 読み取り専用キャレットは常に実在の文字の上に置く(空行は 0)。$ は最後の文字へ。
            self.preview_cursor_col = self.preview_cursor_col.min(len.saturating_sub(1));
        }
        // 行カーソル/選択範囲のハイライト(ガター前=列インデックスが本文先頭 0 基準に揃う)。
        let content = apply_preview_caret(
            content,
            top_line,
            self.preview_cursor_line,
            self.preview_cursor_col,
            self.preview_selection(),
        );
        // 行番号ガター(設定 ON のときだけ)。先頭行番号 = preview_top_line。
        let content = if self.cfg.ui.line_numbers {
            with_line_numbers(content, top_line)
        } else {
            content
        };
        // git 変更ガター(設定 ON・変更のあるファイルのみ)。行番号の左に 1 セルのマーカーを前置する。
        let marks = self.git_gutter_marks();
        with_git_gutter(content, top_line, &marks)
    }

    /// Git gutter marks (per 1-based new-file line) for the current code/text preview, cached per path.
    /// Empty when the gutter is disabled, outside a repo, or the file is unchanged (→ no gutter column).
    /// Called from `windowed_lines`, which only runs for code/text previews, so no kind check is needed.
    fn git_gutter_marks(&mut self) -> std::collections::HashMap<u32, GutterMark> {
        if !self.cfg.ui.git_gutter {
            return std::collections::HashMap::new();
        }
        let Some(path) = self.preview_path.clone() else {
            return std::collections::HashMap::new();
        };
        let hit = matches!(&self.gutter_cache, Some(c) if c.path == path);
        if !hit {
            let diff = crate::git::file_diff(&self.root, &path);
            let marks = gutter_marks(&diff);
            self.gutter_cache = Some(GutterCache {
                path: path.clone(),
                marks,
            });
        }
        self.gutter_cache
            .as_ref()
            .map(|c| c.marks.clone())
            .unwrap_or_default()
    }

    /// Windowed scroll progress (0..=100 %). For the title display. None if not windowed.
    pub fn window_progress(&self) -> Option<u16> {
        let w = self.preview_win.as_ref()?;
        let len = w.len();
        if len == 0 {
            return Some(0);
        }
        Some((self.preview_byte_top.min(len) * 100 / len) as u16)
    }

    /// Whether in-preview search input mode is active (intercepting keys).
    pub fn is_searching(&self) -> bool {
        self.search_input.is_some()
    }

    /// The active search query (for highlighting).
    pub fn preview_search_query(&self) -> Option<&str> {
        self.preview_search.as_deref()
    }

    /// The search input being edited (for the footer prompt).
    pub fn search_input(&self) -> Option<&str> {
        self.search_input.as_deref()
    }

    /// Search status (current/total). Some((1-based, total)) when active and there are matches.
    pub fn search_status(&self) -> Option<(usize, usize)> {
        if self.preview_search.is_some() && !self.search_matches.is_empty() {
            Some((self.search_idx + 1, self.search_matches.len()))
        } else {
            None
        }
    }

    /// Which preview the in-preview search (`/`) runs against. Each target has its own way of
    /// locating matches and of moving to one, so `search_commit` / `jump_to_match` branch on this.
    fn search_target(&self) -> SearchTarget {
        if self.preview_win.is_some() {
            // Code/Text と `R` の生 Markdown(バイトオフセットで窓を動かす)。
            SearchTarget::Windowed
        } else if self.table_data.is_some() {
            SearchTarget::Table
        } else if self.md_cache.is_some() {
            // 装飾 Markdown / Mermaid。検索対象は**画面に出ている装飾行**であって
            // ソースではない(装飾は行を増減させるので、ソース行番号では位置を指せない)。
            SearchTarget::Markdown
        } else {
            SearchTarget::Unsupported
        }
    }

    /// Case-insensitive scan of the **decorated** Markdown lines — the same lines the renderer
    /// slices from — so a hit is always something visible on screen. Positions are
    /// `(0, logical line, byte column)`; `n`/`N` then scroll that line into view.
    ///
    /// Non-ASCII queries whose byte length changes under `to_lowercase` are skipped for that line,
    /// matching `highlight_query_in_line` so the highlight and the match list never disagree.
    fn md_search_scan(&mut self, q: &str) {
        self.search_matches.clear();
        let needle = q.to_lowercase();
        let Some(c) = self.md_cache.as_ref() else {
            return;
        };
        for (li, line) in c.lines.iter().enumerate() {
            let full: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            let lower = full.to_lowercase();
            if lower.len() != full.len() {
                continue;
            }
            let mut i = 0usize;
            while let Some(rel) = lower[i..].find(&needle) {
                let s = i + rel;
                self.search_matches.push((0, li, s));
                i = s + needle.len().max(1);
                if i >= lower.len() {
                    break;
                }
            }
        }
    }

    /// Scroll the decorated Markdown view to a search hit on logical line `line`.
    ///
    /// A hit that is already fully on screen does not move the view (searching for something you
    /// can see should not jolt the page). Otherwise the line is placed near the top with a few
    /// lines of context above — the same affordance as `follow_scroll_to_first_change`. Note this
    /// deliberately differs from `md_focus_move`'s minimal-scroll rule: with minimal scrolling the
    /// same hit lands at the top or the bottom depending on which way you arrived, so `n` `n` `n`
    /// wrapping back around would not return to the same view.
    fn md_scroll_line_into_view(&mut self, line: usize) {
        const CONTEXT_ROWS: usize = 3;
        let (top, height) = self.md_visual_span(line);
        let vh = self.preview_viewport.max(1) as usize;
        let scroll = self.preview_scroll as usize;
        let fully_visible = top >= scroll && top + height <= scroll + vh;
        if fully_visible {
            return;
        }
        self.preview_scroll = top.saturating_sub(CONTEXT_ROWS) as u16;
    }

    /// Start a search (`/`). Supported in Code/Text (windowed) and table previews. Enters input mode.
    pub fn start_search(&mut self) {
        if matches!(self.search_target(), SearchTarget::Unsupported) {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::SearchCodeTextOnly).into());
            return;
        }
        self.search_input = Some(String::new());
    }

    /// Case-insensitive cell scan for a table preview, in reading order (row-major).
    /// Only data cells are searched: the cell cursor addresses data rows, so a header-only hit
    /// would have nowhere to jump to.
    fn table_search_scan(&mut self, q: &str) {
        self.table_search_hits.clear();
        self.search_matches.clear();
        let needle = q.to_lowercase();
        let Some(t) = self.table_data.as_ref() else {
            return;
        };
        for r in 0..t.nrows() {
            for c in 0..t.ncols {
                if t.cell(r, c).to_lowercase().contains(&needle) {
                    self.search_matches.push((0, r, c));
                    self.table_search_hits.insert((r, c));
                }
            }
        }
    }

    /// Whether this data cell matched the active search (renderer lookup — O(1) per cell).
    pub fn table_cell_is_hit(&self, row: usize, col: usize) -> bool {
        self.table_search_hits.contains(&(row, col))
    }

    pub fn search_input_push(&mut self, c: char) {
        if let Some(s) = self.search_input.as_mut() {
            s.push(c);
        }
    }

    pub fn search_input_backspace(&mut self) {
        if let Some(s) = self.search_input.as_mut() {
            s.pop();
        }
    }

    /// Confirm input (Enter): run the query (collect all matching lines) and jump to the first match at or after the current position.
    pub fn search_commit(&mut self) {
        let q = self.search_input.take().unwrap_or_default();
        if q.is_empty() {
            self.preview_search = None;
            self.search_matches.clear();
            self.table_search_hits.clear();
            return;
        }
        const CAP: usize = 5000;
        let target = self.search_target();
        match target {
            SearchTarget::Table => self.table_search_scan(&q),
            SearchTarget::Markdown => {
                self.table_search_hits.clear();
                self.md_search_scan(&q);
            }
            _ => {
                self.table_search_hits.clear();
                self.search_matches = self
                    .preview_win
                    .as_mut()
                    .and_then(|w| w.find_all_matches(&q, CAP).ok())
                    .unwrap_or_default();
            }
        }
        self.preview_search = Some(q);
        if self.search_matches.is_empty() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoMatch).into());
            return;
        }
        self.search_idx = match target {
            // 表: いま居るセル以降の最初の一致へ(読み順)。無ければ先頭へ巡回。
            SearchTarget::Table => {
                let (cr, cc) = (self.table_cur_row, self.table_cur_col);
                self.search_matches
                    .iter()
                    .position(|(_, r, c)| (*r, *c) >= (cr, cc))
                    .unwrap_or(0)
            }
            // 装飾 md: いま見えている先頭の論理行以降の最初の一致へ。無ければ先頭へ巡回。
            SearchTarget::Markdown => {
                let from = self.md_top_logical_line().unwrap_or(0);
                self.search_matches
                    .iter()
                    .position(|(_, line, _)| *line >= from)
                    .unwrap_or(0)
            }
            // 窓読み: 現在の表示位置(byte_top)以降の最初の出現へ。無ければ先頭へ巡回。
            _ => {
                let top = self.preview_byte_top;
                self.search_matches
                    .iter()
                    .position(|(off, _, _)| *off >= top)
                    .unwrap_or(0)
            }
        };
        self.jump_to_match();
    }

    /// `n`/`N`: to the next/previous match (cyclic).
    pub fn search_next(&mut self, dir: i32) {
        if self.search_matches.is_empty() {
            return;
        }
        let n = self.search_matches.len() as i32;
        self.search_idx = (self.search_idx as i32 + dir).rem_euclid(n) as usize;
        self.jump_to_match();
    }

    /// Clear the search (Esc).
    pub fn search_clear(&mut self) {
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.table_search_hits.clear();
        self.search_idx = 0;
    }

    /// Bring the line of the current occurrence to the top of the display (updates the line-head byte and line number). For moves within the same line,
    /// the top does not change, and only the highlight color (orange) moves to that occurrence (the column is referenced by the render side).
    fn jump_to_match(&mut self) {
        let Some(&(off, a, b)) = self.search_matches.get(self.search_idx) else {
            return;
        };
        match self.search_target() {
            // 表: (行, 列) はセル座標。カーソルを移すと描画側がスクロールして追従する。
            SearchTarget::Table => {
                self.table_cur_row = a;
                self.table_cur_col = b;
            }
            // 装飾 md: 一致した論理行を可視域へ(装飾表示のまま=raw に切替えない)。
            SearchTarget::Markdown => self.md_scroll_line_into_view(a),
            _ => {
                self.preview_byte_top = off;
                self.preview_top_line = a;
            }
        }
    }

    pub fn preview_hscroll(&mut self, delta: i32) {
        let next = self.preview_hscroll as i32 + delta;
        self.preview_hscroll = next.max(0) as u16;
    }
    /// Reset horizontal scroll to the line start (left edge) in one step. `0`. When wrapping, it is already 0, so no effect.
    pub fn preview_hscroll_home(&mut self) {
        self.preview_hscroll = 0;
    }
    /// Send horizontal scroll to the line end (right edge) in one step. `$`. The actual maximum is clamped to the longest line width at render time
    /// (here we set the upper bound, and the render side's `.min(max_h)` settles it at the correct right edge).
    pub fn preview_hscroll_end(&mut self) {
        self.preview_hscroll = u16::MAX;
    }

    /// Arrange the links in decorated Markdown lines to "show label only", build `md_items` (links +
    /// task checkboxes), and return the line list with the focused item rendered inverted (called just
    /// before rendering). Since tui-markdown outputs the "label (URL)" form, `collapse_links` folds the
    /// accompanying URL (the URL is the hidden destination) and styles the label as a link plus (when
    /// configured) an icon. Checkbox markers are recognized by their dedicated style (`is_task_span`).
    /// Test-only equivalent of the production path (`ensure_md_cache` + `md_slice`) over caller-
    /// supplied lines: collapse links, rebuild `md_items`, and invert the focused item. Shares
    /// `build_md_items` / `invert_focused_line` with the cache path so the two cannot drift.
    /// Post-process decorated Markdown lines just before caching/rendering: collapse the `label
    /// (URL)` links tui-markdown emits, then (when `ui.md_autolink`) auto-link bare URLs/emails, then
    /// (when `ui.md_emoji`) convert `:shortcode:` emoji. Shared by the cache build (`ensure_md_cache`)
    /// and the test-only decorate path so link/emoji collection cannot drift between them. Emoji runs
    /// last so width-affecting substitutions are reflected in the caller's reflow/`row_prefix`.
    fn postprocess_md(&self, lines: Vec<Line<'static>>) -> (Vec<Line<'static>>, Vec<String>) {
        let (lines, targets) = collapse_links(lines, self.cfg.ui.icons);
        let (lines, targets) = if self.cfg.ui.md_autolink {
            autolink_bare_urls(lines, targets)
        } else {
            (lines, targets)
        };
        let lines = if self.cfg.ui.md_emoji {
            substitute_emoji(lines)
        } else {
            lines
        };
        (lines, targets)
    }

    #[cfg(test)]
    pub fn decorate_md_items(&mut self, lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
        let (lines, targets) = self.postprocess_md(lines);
        let items = build_md_items(&lines, &targets, &[]);
        // フォーカス添字を範囲内にクランプ。
        match self.focused_item {
            Some(_) if items.is_empty() => self.focused_item = None,
            Some(f) if f >= items.len() => self.focused_item = Some(items.len() - 1),
            _ => {}
        }
        self.md_items = items;

        let Some(target_idx) = self.focused_item else {
            return lines;
        };
        let (target_line, whole_line) = {
            let it = &self.md_items[target_idx];
            (it.line, matches!(it.kind, MdItemKind::CodeBlock))
        };
        let first_on_line = self.md_items.partition_point(|x| x.line < target_line);
        let ordinal = target_idx - first_on_line;
        lines
            .into_iter()
            .enumerate()
            .map(|(li, line)| {
                if li == target_line {
                    invert_focused_line(&line, ordinal, whole_line)
                } else {
                    line
                }
            })
            .collect()
    }

    /// Move the item focus of the Markdown preview (dir: +1=next / -1=previous, cyclic over links and
    /// checkboxes in document order). If the focused line is off-screen, scroll until it is visible.
    pub fn md_focus_move(&mut self, dir: i32) {
        if self.md_items.is_empty() {
            return;
        }
        let n = self.md_items.len() as i32;
        let next = match self.focused_item {
            Some(f) => (f as i32 + dir).rem_euclid(n),
            None if dir >= 0 => 0,
            None => n - 1,
        } as usize;
        if self.focused_item != Some(next) {
            // フォーカスが移ったらインライン図のズーム/パンは初期化(前の図の状態を持ち越さない)。
            self.fence_zoom = 1.0;
            self.fence_center = (0.5, 0.5);
        }
        self.focused_item = Some(next);
        // フォーカス行を表示範囲に収める。preview_scroll は**表示行(折返し後)**の座標系
        // (描画側が para.line_count でクランプしている)なので、アイテムの論理行も
        // 表示行へ変換してから比較する(論理行のままだと折返しで乖離し、画面外の
        // フォーカスに追従しない — 2026-07-08 ユーザー報告)。
        let line = self.md_items[next].line;
        let (top, mut height) = self.md_visual_span(line);
        // フェンス図: キャプションだけでなく**図ブロック全体**(キャプション+予約行+下マージン)を
        // 可視域へ入れる(図が下に見切れたまま「フォーカスしたのに見えない」を防ぐ=ユーザー要望)。
        if let MdItemKind::MermaidFence { ordinal } = self.md_items[next].kind {
            if let Some((pl, pr)) = self.mermaid_placement(ordinal) {
                let last = pl + pr as usize; // 下マージン行(placement.line + rows)
                let (bt, bh) = self.md_visual_span(last);
                height = (bt + bh).saturating_sub(top).max(height);
            }
        }
        let vh = self.preview_viewport.max(1) as usize;
        let scroll = self.preview_scroll as usize;
        if height >= vh || top < scroll {
            // ブロックが画面より大きい(先頭を出す) or 上に見切れている。
            self.preview_scroll = top as u16;
        } else if top + height > scroll + vh {
            self.preview_scroll = (top + height).saturating_sub(vh) as u16;
        }
    }

    /// (line, rows) of the inline mermaid placement whose **source ordinal** is `ordinal`
    /// (placements carry it in `fence_ord`; counting rendered placements would drift as soon as
    /// an earlier fence has no placement — loading or degraded to text).
    fn mermaid_placement(&self, ordinal: usize) -> Option<(usize, u16)> {
        let cache = self.md_cache.as_ref()?;
        cache
            .images
            .iter()
            .find(|p| p.fence_ord == Some(ordinal))
            .map(|p| (p.line, p.rows))
    }

    /// Ordinal of the focused inline mermaid diagram, if the focus is on one (border cue in the renderer).
    pub fn focused_mermaid_ordinal(&self) -> Option<usize> {
        let f = self.focused_item?;
        match self.md_items.get(f)?.kind {
            MdItemKind::MermaidFence { ordinal } => Some(ordinal),
            _ => None,
        }
    }

    /// Visual (post-wrap) row offset of decorated line `line` plus its own wrapped height.
    /// With wrap off this is just (line, 1). Reads the cached per-line reflow prefix sums
    /// (ratatui's own `line_count`, computed once at cache build), so the numbers match what
    /// the renderer draws exactly — and the lookup is O(1) instead of re-flowing the document.
    pub(crate) fn md_visual_span(&self, line: usize) -> (usize, usize) {
        if !self.cfg.ui.wrap {
            return (line, 1);
        }
        let Some(cache) = &self.md_cache else {
            return (line, 1);
        };
        if cache.width == 0
            || line >= cache.lines.len()
            || cache.row_prefix.len() != cache.lines.len() + 1
        {
            return (line, 1);
        }
        let top = cache.row_prefix[line];
        let height = (cache.row_prefix[line + 1] - top).max(1);
        (top, height)
    }

    /// Activate the focused item: a link opens (URLs externally, local paths within konoma),
    /// a task checkbox toggles.
    pub fn md_activate_focused(&mut self) -> Result<()> {
        let Some(f) = self.focused_item else {
            return Ok(());
        };
        match self.md_items.get(f) {
            Some(MdItem {
                kind: MdItemKind::Link { target },
                ..
            }) => {
                let target = target.clone();
                self.open_link_target(&target)
            }
            Some(MdItem {
                kind: MdItemKind::Task { .. },
                ..
            }) => {
                self.md_toggle_focused_task();
                Ok(())
            }
            // コードブロックは「開く/トグル」対象が無いので Enter では何もしない。
            // コピーは他のコピー操作と揃えて `y`(コピーリーダー)で行う(main.rs で先取り)。
            Some(MdItem {
                kind: MdItemKind::CodeBlock,
                ..
            }) => Ok(()),
            // インライン mermaid 図: 全画面(ズーム/パン付き)で開く。
            Some(MdItem {
                kind: MdItemKind::MermaidFence { ordinal },
                ..
            }) => {
                let ord = *ordinal;
                self.open_mermaid_fence(ord);
                Ok(())
            }
            // <details> の summary: 折りたたみをトグル。
            Some(MdItem {
                kind: MdItemKind::Details { ordinal },
                ..
            }) => {
                let ord = *ordinal;
                self.toggle_details(ord);
                Ok(())
            }
            None => Ok(()),
        }
    }

    /// Open the Nth ```mermaid fence of the current Markdown preview full screen (Enter on a
    /// Tab-focused inline diagram). The Markdown view's scroll/focus are stashed so `q` returns
    /// exactly where the reader was. Count-guarded re-extraction: if the file changed and the
    /// fence is gone, flash instead of rendering a stale diagram (principle #3).
    fn open_mermaid_fence(&mut self, ordinal: usize) {
        let Some(md) = self.preview_path.clone() else {
            return;
        };
        if self.mermaid_fence_code(&md, ordinal).is_none() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::DiagramOpenFailed).into());
            return;
        }
        self.fence_return = Some((self.preview_scroll, self.focused_item));
        self.clear_image();
        let kind = PreviewKind::MermaidFence(ordinal);
        self.start_media_load(&kind, &md);
        self.preview_kind = Some(kind);
    }

    /// Raw source of the focused code block, matched by ordinal against the on-screen headers. The
    /// block text is re-scanned from the file; `None` when the focused item is not a code block,
    /// there is no path, the read fails, or the counts disagree (file changed / pathological doc) —
    /// the caller then flashes instead of copying garbage (safe fallback, #3). Also used by tests
    /// to assert the copied value without a clipboard round-trip.
    fn focused_code_source(&self) -> Option<String> {
        let f = self.focused_item?;
        if !matches!(
            self.md_items.get(f),
            Some(MdItem {
                kind: MdItemKind::CodeBlock,
                ..
            })
        ) {
            return None;
        }
        // 文書内で何番目のコードブロックか(リンク/タスクを除いた序数)。
        let ordinal = self.md_items[..=f]
            .iter()
            .filter(|it| matches!(it.kind, MdItemKind::CodeBlock))
            .count()
            .saturating_sub(1);
        let total = self
            .md_items
            .iter()
            .filter(|it| matches!(it.kind, MdItemKind::CodeBlock))
            .count();
        let src = std::fs::read_to_string(self.preview_path.as_ref()?).ok()?;
        let blocks = crate::preview::markdown::code_block_source_locs(&src);
        // 画面上のヘッダ数とソースのブロック数が一致するときだけ信頼して写す。
        (blocks.len() == total)
            .then(|| blocks.get(ordinal).cloned())
            .flatten()
    }

    /// Copy the focused code block's raw source to the clipboard, or flash a safe notice when it
    /// cannot be resolved (`focused_code_source` = None). Triggered by the copy leader (`y`) in a
    /// Markdown preview when a code block is focused (pre-empted in `handle_key`).
    pub fn md_copy_focused_code(&mut self) {
        let Some(text) = self.focused_code_source() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::CodeBlockCopyUnavailable).into());
            return;
        };
        match set_clipboard(&text) {
            Ok(()) => self.flash = Some(tr(self.lang, crate::i18n::Msg::CopiedCodeBlock).into()),
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::CopyFailed)
                ))
            }
        }
    }

    /// Test-only: the exact text `Enter` would copy for the focused code block (no clipboard).
    #[cfg(test)]
    pub fn focused_code_text(&self) -> Option<String> {
        self.focused_code_source()
    }

    /// Whether the currently focused Markdown item is a code block (drives the footer hint:
    /// `Enter` copies the block).
    pub fn md_focused_code(&self) -> bool {
        !self.is_raw_source()
            && self
                .focused_item
                .and_then(|f| self.md_items.get(f))
                .is_some_and(|it| matches!(it.kind, MdItemKind::CodeBlock))
    }

    /// Whether the currently focused Markdown item is a task checkbox (drives the Space fixed key:
    /// only then does Space toggle instead of falling through to the keymap).
    pub fn md_focused_task(&self) -> bool {
        !self.is_raw_source()
            && self
                .focused_item
                .and_then(|f| self.md_items.get(f))
                .is_some_and(|it| matches!(it.kind, MdItemKind::Task { .. }))
    }

    /// The ordinal of the focused `<details>` summary, if one is focused (drives the Space fixed key
    /// and the footer hint). None when not focused on a details summary.
    pub fn md_focused_details(&self) -> Option<usize> {
        if self.is_raw_source() {
            return None;
        }
        match self.focused_item.and_then(|f| self.md_items.get(f)) {
            Some(MdItem {
                kind: MdItemKind::Details { ordinal },
                ..
            }) => Some(*ordinal),
            _ => None,
        }
    }

    /// Whether the rendered Markdown preview has any task checkboxes (drives the footer hint).
    pub fn md_has_tasks(&self) -> bool {
        self.md_items
            .iter()
            .any(|it| matches!(it.kind, MdItemKind::Task { .. }))
    }

    /// Open a link target. `scheme://`/`mailto:`, etc. are delegated externally; local paths open in konoma
    /// (file=preview / directory=make it the new root and Tree).
    fn open_link_target(&mut self, target: &str) -> Result<()> {
        let t = target.trim();
        if t.contains("://") || t.starts_with("mailto:") || t.starts_with("tel:") {
            return self.open_external(t);
        }
        if let Some(anchor) = t.strip_prefix('#') {
            if !self.md_scroll_to_anchor(anchor) {
                self.flash = Some(format!(
                    "{}{}",
                    tr(self.lang, crate::i18n::Msg::AnchorNotFound),
                    t
                ));
            }
            return Ok(());
        }
        let path_part = t.split('#').next().unwrap_or(t);
        let resolved = self.resolve_link_local(t);
        if resolved.is_dir() {
            self.back_to_tree();
            // root を変えるので旧 root の選択/ビジュアル/絞り込み/検索を破棄する(持ち越さない)。
            self.clear_for_root_change();
            self.root = resolved;
            self.open_dir = self.root.clone();
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        } else if resolved.is_file() {
            self.enter_preview(&resolved);
        } else {
            self.flash = Some(format!(
                "{}{}",
                tr(self.lang, crate::i18n::Msg::NotFound),
                path_part
            ));
        }
        Ok(())
    }

    /// Resolve a local (non-URL, non-anchor) Markdown link target to an absolute path (existence not
    /// guaranteed), relative to the current preview file's directory. A `#anchor` suffix is dropped.
    fn resolve_link_local(&self, target: &str) -> PathBuf {
        let t = target.trim();
        let path_part = t.split('#').next().unwrap_or(t);
        let base = self
            .preview_path
            .as_ref()
            .and_then(|p| p.parent())
            .map(Path::to_path_buf)
            .unwrap_or_else(|| self.root.clone());
        let p = Path::new(path_part);
        let resolved = if p.is_absolute() {
            p.to_path_buf()
        } else {
            base.join(p)
        };
        std::fs::canonicalize(&resolved).unwrap_or(resolved)
    }

    /// `Ctrl-t`: open the focused Markdown link in a **new tab** (the current doc's tab stays intact).
    /// URLs still go to the browser (a tab makes no sense for them); a local file/dir opens in a fresh
    /// foreground tab via the shared paste-jump navigation (reveal + root-switch-if-outside + preview).
    /// No-op when the focused item is not a link (task/code) or nothing is focused.
    pub fn md_open_focused_link_new_tab(&mut self) -> Result<()> {
        let Some(f) = self.focused_item else {
            return Ok(());
        };
        let target = match self.md_items.get(f) {
            Some(MdItem {
                kind: MdItemKind::Link { target },
                ..
            }) => target.clone(),
            _ => return Ok(()),
        };
        let t = target.trim();
        // URL/mailto/tel はタブにできないので、Enter と同じく外部(ブラウザ等)で開く。
        if t.contains("://") || t.starts_with("mailto:") || t.starts_with("tel:") {
            return self.open_external(t);
        }
        if t.starts_with('#') {
            // A same-document anchor makes no sense in a new tab — scroll in place instead.
            return self.open_link_target(t);
        }
        // タブを作る前に、現在の md ファイルの位置基準でローカルパスを解決しておく。
        let resolved = self.resolve_link_local(t);
        if !resolved.exists() {
            self.flash = Some(format!(
                "{}{}",
                tr(self.lang, crate::i18n::Msg::NotFound),
                t.split('#').next().unwrap_or(t)
            ));
            return Ok(());
        }
        // 新規タブ(前面)を作り、その中でジャンプする。元のドキュメントのタブは save_active で保持済み。
        self.tab_new()?;
        self.paste_jump_to(&resolved, None);
        Ok(())
    }

    /// Open a URL/file with an external command (macOS `open`). The result is reported via flash.
    fn open_external(&mut self, url: &str) -> Result<()> {
        match std::process::Command::new("open").arg(url).spawn() {
            Ok(_) => self.flash = Some(format!("{}{url}", tr(self.lang, crate::i18n::Msg::Opened))),
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::OpenFailed)
                ))
            }
        }
        Ok(())
    }

    pub fn cycle_path_style(&mut self) {
        self.path_style = self.path_style.next();
    }

    /// Toggle the `?` help. When opening, reset scroll to the top.
    pub fn toggle_help(&mut self) {
        self.show_help = !self.show_help;
        self.help_scroll = 0;
    }

    /// Toggle the `i` file-info popup. Does not open if there is no target.
    pub fn toggle_info(&mut self) {
        if self.show_info {
            self.show_info = false;
        } else if self.info_target().is_some() {
            self.show_info = true;
        } else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
        }
    }
    /// Whether the file-info popup is showing.
    pub fn is_info(&self) -> bool {
        self.show_info
    }
    /// The target path for the info display: Tree=the cursor item / Preview=the file being previewed.
    pub fn info_target(&self) -> Option<PathBuf> {
        match self.mode {
            Mode::Tree => self.entries.get(self.selected).map(|e| e.path.clone()),
            Mode::Preview => self.preview_path.clone(),
        }
    }

    /// Scroll within the help. The upper bound is clamped at render time (since content and screen size are then known).
    pub fn help_scroll_by(&mut self, delta: i32) {
        self.help_scroll = (self.help_scroll as i32 + delta).max(0) as u16;
    }

    /// The path to copy. In Preview it is the preview target; in Tree it is the entry selected in the tree.
    fn copy_target(&self) -> Option<PathBuf> {
        // Git 変更ハブ表示中は、ツリーの選択ではなく**変更ファイル**のパスをコピー対象にする。
        #[cfg(feature = "git")]
        if self.surface() == crate::keymap::Surface::GitChanges {
            return self.git_view_selected();
        }
        match self.mode {
            Mode::Preview => self.preview_path.clone(),
            Mode::Tree => self.entries.get(self.selected).map(|e| e.path.clone()),
        }
    }

    /// Copy the selected path to the clipboard according to the kind, and show the result in flash (FR-6).
    pub fn copy_path(&mut self, kind: CopyKind) {
        let Some(path) = self.copy_target() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        let text = copy_text(&path, &self.open_dir, kind);
        match set_clipboard(&text) {
            Ok(()) => {
                self.flash = Some(format!(
                    "{}{text}",
                    tr(self.lang, crate::i18n::Msg::CopiedPrefix)
                ))
            }
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::CopyFailed)
                ))
            }
        }
    }

    /// Test-only: the exact string `copy_path(kind)` would place on the clipboard for the current
    /// copy target (tree selection / preview path / git-changes selection). `None` when there is no
    /// target — the same gate as `copy_path`. Lets E2E assert copy values without the (headless-flaky)
    /// clipboard round-trip.
    #[cfg(test)]
    pub fn copy_string_for(&self, kind: CopyKind) -> Option<String> {
        let path = self.copy_target()?;
        Some(copy_text(&path, &self.open_dir, kind))
    }

    /// Test-only: the exact `@path#L..` string that `preview_copy_selection_ref` (`Y`) would copy.
    #[cfg(test)]
    pub fn selection_ref_string(&self) -> Option<String> {
        self.preview_selection_ref_text()
    }

    /// Get metadata for the selected commit in log/graph/detail. detail uses the already-loaded data, while log/graph
    /// fetch `commit_meta` from the selected commit id. None for non-commits (uncommitted rows, etc.) or out-of-scope surfaces.
    #[cfg(feature = "git")]
    fn current_commit_meta(&self) -> Option<crate::git::CommitMeta> {
        use crate::keymap::Surface;
        match self.surface() {
            Surface::GitDetail => self.git_detail_meta.clone(),
            Surface::GitLog => {
                let id = self.git_log_selected_id()?;
                crate::git::commit_meta(&self.root, &id)
            }
            Surface::GitGraph => {
                let id = self
                    .git_graph_selected_row()
                    .and_then(|r| r.commit.clone())?;
                crate::git::commit_meta(&self.root, &id)
            }
            _ => None,
        }
    }

    /// git log/graph/detail: copy the selected commit's info (short/full hash, subject, full message, author, date)
    /// to the clipboard. If there is no commit, notify via flash.
    #[cfg(feature = "git")]
    pub fn git_copy(&mut self, kind: GitCopyKind) {
        let Some(meta) = self.current_commit_meta() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCommitToCopy).into());
            return;
        };
        let text = match kind {
            GitCopyKind::ShortHash => meta.short,
            GitCopyKind::FullHash => meta.id,
            GitCopyKind::Subject => meta.message.lines().next().unwrap_or("").to_string(),
            GitCopyKind::Message => meta.message,
            GitCopyKind::Author => meta.author,
            GitCopyKind::Date => meta.date,
        };
        self.set_clipboard_flash(&text);
    }

    /// branches view: copy the selected branch name to the clipboard.
    #[cfg(feature = "git")]
    pub fn git_copy_branch_name(&mut self) {
        let Some(b) = self.git_branch_selected() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        let name = b.name;
        self.set_clipboard_flash(&name);
    }

    /// Write to the clipboard and flash success/failure (common processing for copy operations). On success, shows a one-line preview
    /// (multi-line content such as a full message is rounded to the first line + `…` so the footer does not overflow).
    fn set_clipboard_flash(&mut self, text: &str) {
        match set_clipboard(text) {
            Ok(()) => {
                let first = text.lines().next().unwrap_or("");
                let mut preview: String = first.chars().take(60).collect();
                if first.chars().count() > 60 || text.lines().nth(1).is_some() {
                    preview.push('');
                }
                self.flash = Some(format!(
                    "{}{preview}",
                    tr(self.lang, crate::i18n::Msg::CopiedPrefix)
                ));
            }
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::CopyFailed)
                ))
            }
        }
    }

    // ---- タブ (FR-5) ----

    /// Snapshot the current tree working state.
    fn snapshot_tab(&self) -> TabState {
        TabState {
            root: self.root.clone(),
            open_dir: self.open_dir.clone(),
            entries: self.entries.clone(),
            selected: self.selected,
            show_hidden: self.show_hidden,
            tree_viewport: self.tree_viewport,
            mode: self.mode,
            preview_path: self.preview_path.clone(),
            preview_kind: self.preview_kind.clone(),
            preview_scroll: self.preview_scroll,
            preview_hscroll: self.preview_hscroll,
            preview_viewport: self.preview_viewport,
            preview_byte_top: self.preview_byte_top,
            preview_top_line: self.preview_top_line,
            image_zoom: self.image_zoom,
            image_center: self.image_center,
            pdf_page: self.pdf_page,
            pdf_pages: self.pdf_pages,
            table_cur_row: self.table_cur_row,
            table_cur_col: self.table_cur_col,
            table_top_row: self.table_top_row,
            table_left_col: self.table_left_col,
            preview_cursor_line: self.preview_cursor_line,
            preview_cursor_col: self.preview_cursor_col,
            md_raw: self.md_raw,
            focused_item: self.focused_item,
            fence_zoom: self.fence_zoom,
            fence_center: self.fence_center,
            fence_return: self.fence_return,
            git_view: self.git_view,
            git_view_sel: self.git_view_sel,
            git_view_entries: self.git_view_entries.clone(),
            came_from_git_view: self.came_from_git_view,
            git_log: self.git_log.clone(),
            git_log_sel: self.git_log_sel,
            git_detail: self.git_detail.clone(),
            git_detail_meta: self.git_detail_meta.clone(),
            git_detail_title: self.git_detail_title.clone(),
            git_detail_scroll: self.git_detail_scroll,
            git_detail_hscroll: self.git_detail_hscroll,
            git_detail_viewport: self.git_detail_viewport,
            git_detail_total: self.git_detail_total,
            git_branches: self.git_branches.clone(),
            git_branch_sel: self.git_branch_sel,
            git_branch_filter: self.git_branch_filter.clone(),
            git_branch_filtering: self.git_branch_filtering,
            git_graph: self.git_graph.clone(),
            git_graph_sel: self.git_graph_sel,
            git_graph_base: self.git_graph_base.clone(),
            git_graph_base_label: self.git_graph_base_label.clone(),
            git_graph_visible: self.git_graph_visible.clone(),
            git_graph_legend: self.git_graph_legend.clone(),
            git_graph_hidden: self.git_graph_hidden,
            git_graph_order: self.git_graph_order.clone(),
            // 選択 / 絞り込み / プレビュー検索もタブ毎に保存する(切替で旧タブへ持ち越さない)。
            selection: self.selection.clone(),
            visual_anchor: self.visual_anchor,
            tree_filter: self.tree_filter.clone(),
            filter_input: self.filter_input.clone(),
            filter_pool: self.filter_pool.clone(),
            changed_filter: self.changed_filter,
            preview_search: self.preview_search.clone(),
            search_input: self.search_input.clone(),
            search_matches: self.search_matches.clone(),
            search_idx: self.search_idx,
        }
    }

    /// Save the current working state to the active tab.
    fn save_active(&mut self) {
        let snap = self.snapshot_tab();
        self.tabs[self.active_tab] = snap;
    }

    /// Load the active tab's snapshot into the working fields.
    /// **Also restores that tab's mode/preview** (does not drop to Tree). Images are restored by reloading.
    /// The snapshot is **moved** out of the slot (no deep clone of entries/filter_pool/git vectors):
    /// while a tab is active its slot is never read (tab_label/tab_root use the live App fields)
    /// and every switch path calls save_active before the slot is needed again.
    fn load_active(&mut self) {
        let t = std::mem::take(&mut self.tabs[self.active_tab]);
        self.root = t.root;
        self.open_dir = t.open_dir;
        self.entries = t.entries;
        self.selected = t.selected;
        self.show_hidden = t.show_hidden;
        self.tree_viewport = t.tree_viewport;
        self.mode = t.mode;
        self.preview_path = t.preview_path;
        self.preview_kind = t.preview_kind;
        self.preview_scroll = t.preview_scroll;
        self.preview_hscroll = t.preview_hscroll;
        self.preview_viewport = t.preview_viewport;
        self.preview_byte_top = t.preview_byte_top;
        self.preview_top_line = t.preview_top_line;
        // git オーバーレイもそのタブの状態を復元する(タブごとに git モードを保持)。
        self.git_view = t.git_view;
        self.git_view_sel = t.git_view_sel;
        self.git_view_entries = t.git_view_entries;
        self.came_from_git_view = t.came_from_git_view;
        self.git_log = t.git_log;
        self.git_log_sel = t.git_log_sel;
        self.git_detail = t.git_detail;
        self.git_detail_meta = t.git_detail_meta;
        self.git_detail_title = t.git_detail_title;
        self.git_detail_scroll = t.git_detail_scroll;
        self.git_detail_hscroll = t.git_detail_hscroll;
        self.git_detail_viewport = t.git_detail_viewport;
        self.git_detail_total = t.git_detail_total;
        self.git_branches = t.git_branches;
        self.git_branch_sel = t.git_branch_sel;
        self.git_branch_filter = t.git_branch_filter;
        self.git_branch_filtering = t.git_branch_filtering;
        self.git_graph = t.git_graph;
        self.git_graph_sel = t.git_graph_sel;
        self.git_graph_base = t.git_graph_base;
        self.git_graph_base_label = t.git_graph_base_label;
        self.git_graph_visible = t.git_graph_visible;
        self.git_graph_legend = t.git_graph_legend;
        self.git_graph_hidden = t.git_graph_hidden;
        self.git_graph_order = t.git_graph_order;
        // グラフのブランチ可視ピッカー(モーダル)はタブ跨ぎで持ち越さない: 復元時は閉じておく。
        self.git_graph_picker = false;
        self.git_graph_picker_sel = 0;
        self.git_graph_picker_set.clear();
        self.git_graph_reordered = false;
        // 見出しアウトラインオーバーレイもタブ跨ぎで持ち越さない。
        self.outline_open = false;
        // <details> の開閉状態も文書ごと=タブ跨ぎで持ち越さない。
        self.details_open.clear();
        // 選択 / 絞り込み / プレビュー検索もそのタブの状態を復元する(entries も同時に復元するため
        // visual_anchor(entries 添字)は整合する)。load_active は rebuild_tree を呼ばない。
        self.selection = t.selection;
        self.visual_anchor = t.visual_anchor;
        self.tree_filter = t.tree_filter;
        self.filter_input = t.filter_input;
        self.filter_pool = t.filter_pool;
        self.changed_filter = t.changed_filter;
        self.preview_search = t.preview_search;
        self.search_input = t.search_input;
        self.search_matches = t.search_matches;
        self.search_idx = t.search_idx;
        // `table_search_hits` は `search_matches` から導出される描画用の集合。TabState には持たず
        // (二重管理を避ける)、復元した search_matches から作り直す。表以外は空にする — さもないと
        // 別タブの一致セル座標が居残り、表 renderer(`table_cell_is_hit` を無条件参照)が誤って強調する。
        self.table_search_hits = if matches!(self.preview_kind, Some(PreviewKind::Table { .. })) {
            self.search_matches
                .iter()
                .map(|&(_, r, c)| (r, c))
                .collect()
        } else {
            std::collections::HashSet::new()
        };
        // 装飾キャッシュは持ち越さない (decorated_lines が再生成)。
        self.md_cache = None;
        // 復元した diff プレビューはフォロー由来の印を持ち越さない(セッションはタブ横断の概念でない)。
        self.diff_follow_scope = false;
        // 画像は重い状態(protocol/元画像/GIFフレーム)を持ち越さず、画像系プレビューなら再読込で復元する。
        self.clear_image();
        if let (Some(kind), Some(path)) = (self.preview_kind.clone(), self.preview_path.clone()) {
            // Mermaid(.mmd 画像モード)/全画面フェンスも媒体復元の対象(kind_loads_media)。
            // 漏れると clear_image 後に誰も start_media_load を呼ばず、reload_media_if_changed も
            // mtime 一致で早期 return するため、タブ復帰でテキスト図/偽エラーに劣化していた。
            if self.kind_loads_media(&kind) {
                // SVG/動画サムネ/GIF は別スレッドで読み込み開始(set_* は zoom/center を触らない)。
                // 保存値を即セットしておけば、後から結果が届いても復元したズーム/中心が保たれる。
                // GIF は先頭フレームから再生。
                // PDF は保存ページを start_media_load の前に戻す(その世代でそのページをラスタライズする)。
                self.pdf_page = t.pdf_page.max(1);
                self.pdf_pages = t.pdf_pages;
                self.start_media_load(&kind, &path);
                self.image_zoom = t.image_zoom;
                self.image_center = t.image_center;
                self.image_crop = None;
            }
        }
        // raw ソース表示状態を復元してから windowed を張り直す(raw md は窓読みにするため順序が重要)。
        self.md_raw = t.md_raw;
        // Tab フォーカス/インライン図のズーム/全画面復帰情報はこのタブの保存値へ(前タブの値を
        // 別文書に適用しない)。md_items は次描画の ensure_md_cache がこのタブの文書で再構築し、
        // focused_item はその時に範囲へクランプされる(それまで旧文書の items を参照しないよう空に)。
        self.md_items.clear();
        self.focused_item = t.focused_item;
        self.fence_zoom = t.fence_zoom;
        self.fence_center = t.fence_center;
        self.fence_return = t.fence_return;
        // 大きい Code/Text(+raw の Markdown/Mermaid)なら ウィンドウ読みリーダを張り直す(byte_top は上で復元済み)。
        self.setup_windowed();
        // windowed プレビューの 2D キャレットを復元(選択は持ち越さない)。範囲は次描画/移動でクランプされる。
        self.preview_cursor_line = t.preview_cursor_line;
        self.preview_cursor_col = t.preview_cursor_col;
        self.preview_visual_anchor = None;
        self.preview_visual_linewise = false;
        // CSV/TSV テーブルは本体を再パースし、保存済みカーソル/スクロールを復元してクランプする。
        self.load_table();
        self.table_cur_row = t.table_cur_row;
        self.table_cur_col = t.table_cur_col;
        self.table_top_row = t.table_top_row;
        self.table_left_col = t.table_left_col;
        self.clamp_table_cursor();

        // 切替でアクティブになったタブを**ディスクから再読み込み**する。ファイル監視はアクティブな
        // root しか見ていない(rewatch)ため、裏に居た間の外部変更(ファイルの作成/削除/リネーム・git
        // 状態・変更ガター/diff)がスナップショットのまま古い。fs イベント時と同じ refresh_fs 経路を
        // 通して、ツリー再構築・git status・diff/gutter キャッシュ・変更フィルタ・git ビュー・プレビュー
        // 再読込を一括で追従させる。`false`=重い ignore セット(gitignore)は作り直さずキャッシュ保持
        // (root が変われば次の描画の refresh_git_if_needed が workdir 単位キャッシュで面倒を見る=
        // 巨大 repo の性能対策[[git-watch-feedback-loop-perf]]を壊さない)。プレビューの表示位置は
        // reload_preview が保持する(スクロール/ズーム/テーブルカーソル)。
        // タブは背面に居た間 fs 監視の対象外なので、そのタブの git status は外部変更を取りこぼして
        // いる可能性がある(同一 repo の別タブなら workdir 単位キャッシュで流用され陳腐化が居残る)。
        // 切替=再検証の節目として dirty を立て、次の描画の refresh_git_if_needed に取り直させる
        // (back_to_tree と同型。h/l 連打は dirty を立てないので最適化は保たれる)。
        self.git_status_dirty = true;
        let _ = self.refresh_fs(false);
    }

    pub fn tab_count(&self) -> usize {
        self.tabs.len()
    }

    pub fn active_tab_index(&self) -> usize {
        self.active_tab
    }

    /// Display name of tab `i`. While showing Tree, the **root directory name**; while showing Preview/image, etc.,
    /// the **preview target's file name**. The active tab references the latest working state (App fields),
    /// while inactive tabs reference the snapshot (`TabState`) (since saving happens only on switch).
    pub fn tab_label(&self, i: usize) -> String {
        // (mode, root, preview_path) をアクティブ/非アクティブで使い分ける。
        let (mode, root, preview) = if i == self.active_tab {
            (self.mode, self.root.as_path(), self.preview_path.as_deref())
        } else if let Some(t) = self.tabs.get(i) {
            (t.mode, t.root.as_path(), t.preview_path.as_deref())
        } else {
            return String::new();
        };
        let path = match mode {
            Mode::Preview => preview.unwrap_or(root), // 念のため preview 無しは root へ
            Mode::Tree => root,
        };
        path.file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string())
    }

    /// New tab. Create another tree context starting from the current root and switch to it.
    /// The new tab starts in Tree (since it has no preview target). The source tab's preview is
    /// preserved by `save_active`, so it is not lost.
    pub fn tab_new(&mut self) -> Result<()> {
        self.save_active();
        // 見出しアウトラインオーバーレイは新タブへ持ち越さない(空タブ上の空オーバーレイを防ぐ)。
        self.outline_open = false;
        let root = self.root.clone();
        self.open_dir = root.clone();
        self.root = root;
        self.selected = 0;
        self.entries.clear();
        self.rebuild_tree()?;
        // snapshot 前に Tree へリセットする (snapshot がプレビュー状態も取り込むため順序が重要)。
        self.mode = Mode::Tree;
        self.clear_image();
        self.preview_path = None;
        self.preview_kind = None;
        self.preview_scroll = 0;
        self.preview_hscroll = 0;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        self.md_cache = None;
        // 新規タブは md フォーカス/インライン図ズームも素の状態から(TabState 複製対象)。
        self.md_items.clear();
        self.focused_item = None;
        self.fence_zoom = 1.0;
        self.fence_center = (0.5, 0.5);
        self.fence_return = None;
        // 新規タブは git オーバーレイ無しの素の Tree から始める(現タブの git 状態は save_active で保持済み)。
        self.git_view = false;
        self.git_view_sel = 0;
        self.git_view_entries.clear();
        self.came_from_git_view = false;
        self.git_log = None;
        self.git_log_sel = 0;
        self.git_detail = None;
        self.git_detail_meta = None;
        self.git_detail_title = None;
        self.git_detail_scroll = 0;
        self.git_detail_hscroll = 0;
        self.git_detail_viewport = 0;
        self.git_detail_total = 0;
        self.git_branches = None;
        self.git_branch_sel = 0;
        self.git_branch_filter.clear();
        self.git_branch_filtering = false;
        self.git_graph = None;
        self.git_graph_sel = 0;
        // 新規タブはグラフの装飾状態(基準/凡例/表示ブランチ/優先順)とピッカーも素から始める
        // (現タブのこれらは直前の save_active で TabState に保持済み)。次に開くとき再導出される。
        self.git_graph_base = None;
        self.git_graph_base_label = None;
        self.git_graph_visible.clear();
        self.git_graph_legend.clear();
        self.git_graph_hidden = 0;
        self.git_graph_order.clear();
        self.git_graph_picker = false;
        self.git_graph_picker_sel = 0;
        self.git_graph_picker_set.clear();
        self.git_graph_reordered = false;
        // 新規タブは選択 / 絞り込み / プレビュー検索を空から始める
        // (現タブのこれらは直前の save_active で TabState に保持済み)。
        self.selection.clear();
        self.visual_anchor = None;
        self.clear_filter_state();
        self.search_clear();
        self.tabs.push(self.snapshot_tab());
        self.active_tab = self.tabs.len() - 1;
        // タブ集合が変わる節目でセッションを保存する(異常終了でも直近のタブ構成が残る)。
        self.save_session();
        Ok(())
    }

    /// `Ctrl-t` in the tree: open the entry under the cursor in a new (foreground) tab, leaving the
    /// current tab untouched. A file opens as a preview; a directory becomes the new tab's root
    /// (mirroring `l`). No-op when the tree is empty.
    pub fn tab_new_from_selection(&mut self) -> Result<()> {
        let Some(entry) = self.entries.get(self.selected).cloned() else {
            return Ok(());
        };
        self.tab_new()?; // fresh Tree tab at the current root, now active
        if entry.is_dir {
            // Descend into the folder in the new tab (same as `l`); root changes, so drop stale state.
            self.clear_for_root_change();
            self.root = entry.path;
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        } else {
            // Reveal the file (so returning with `q` lands on it), then preview it.
            let _ = self.reveal_path_deep(&entry.path);
            self.enter_preview(&entry.path);
        }
        self.save_session();
        Ok(())
    }

    /// Close the active tab. The last one is not closed.
    pub fn tab_close(&mut self) {
        if self.tabs.len() <= 1 {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::CantCloseLastTab).into());
            return;
        }
        self.tabs.remove(self.active_tab);
        if self.active_tab >= self.tabs.len() {
            self.active_tab = self.tabs.len() - 1;
        }
        self.load_active();
        self.save_session();
    }

    /// Move tabs relatively (dir: +1=next / -1=previous). Wraps at the ends.
    pub fn tab_cycle(&mut self, dir: i32) {
        self.tab_list = false; // 一覧から [/] で切替えた場合も一覧は用済み
        if self.tabs.len() <= 1 {
            return;
        }
        self.save_active();
        let n = self.tabs.len() as i32;
        self.active_tab = (self.active_tab as i32 + dir).rem_euclid(n) as usize;
        self.load_active();
        self.save_session();
    }

    /// Select a tab by number (0-based). Out-of-range or the same tab is ignored.
    pub fn tab_goto(&mut self, i: usize) {
        self.tab_list = false; // 一覧(1-9/Enter)からの切替で一覧を閉じる
        if i >= self.tabs.len() || i == self.active_tab {
            return;
        }
        self.save_active();
        self.active_tab = i;
        self.load_active();
        self.save_session();
    }

    // --- 見出しアウトラインオーバーレイ (`o` in a Markdown preview) --------
    pub fn is_outline(&self) -> bool {
        self.outline_open
    }

    /// Heading outline of the current Markdown preview: `(level, text, decorated-line-index)` in
    /// document order. Built from the decorated cache, so it reflects exactly what is on screen
    /// (front matter stripped, footnotes/inline-HTML processed). Empty for non-Markdown previews.
    pub(crate) fn md_outline(&self) -> Vec<(u8, String, usize)> {
        let Some(c) = &self.md_cache else {
            return Vec::new();
        };
        c.anchors
            .iter()
            .filter_map(|(_slug, line)| {
                let l = c.lines.get(*line)?;
                let text = crate::preview::markdown::heading_text(l)?;
                let level = crate::preview::markdown::heading_level_hint(l, c.lines.get(*line + 1));
                Some((level, text, *line))
            })
            .collect()
    }

    /// `o`: open/close the heading outline. Opening selects the heading of the current section
    /// (the last one at or above the viewport top). Flashes and stays closed if there are no
    /// headings (e.g. a non-Markdown preview or a document without any).
    pub fn toggle_outline(&mut self) {
        if self.outline_open {
            self.outline_open = false;
            return;
        }
        let items = self.md_outline();
        if items.is_empty() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::OutlineEmpty).into());
            return;
        }
        // Select the current section: the last heading at or above the top of the view.
        let top = self.md_top_logical_line().unwrap_or(0);
        self.outline_sel = items
            .iter()
            .rposition(|(_, _, line)| *line <= top)
            .unwrap_or(0);
        self.outline_open = true;
    }

    pub fn outline_sel(&self) -> usize {
        self.outline_sel
    }

    pub fn outline_move(&mut self, delta: i32) {
        let n = self.md_outline().len();
        if n == 0 {
            return;
        }
        self.outline_sel = (self.outline_sel as i32 + delta).rem_euclid(n as i32) as usize;
    }

    /// Enter in the outline: scroll the preview to the selected heading and close the overlay.
    pub fn outline_jump(&mut self) {
        let line = self.md_outline().get(self.outline_sel).map(|(_, _, l)| *l);
        self.outline_open = false;
        if let Some(line) = line {
            let (row, _) = self.md_visual_span(line);
            self.preview_scroll = row.min(u16::MAX as usize) as u16;
        }
    }

    // --- タブ一覧オーバーレイ (`T`) ----------------------------------------
    pub fn is_tab_list(&self) -> bool {
        self.tab_list
    }
    /// `T`: open/close the tab list. Opening puts the selection on the active tab.
    pub fn toggle_tab_list(&mut self) {
        self.tab_list = !self.tab_list;
        if self.tab_list {
            self.tab_list_sel = self.active_tab;
        }
    }
    pub fn tab_list_sel(&self) -> usize {
        self.tab_list_sel
    }
    pub fn tab_list_move(&mut self, delta: i32) {
        let n = self.tabs.len();
        if n == 0 {
            return;
        }
        self.tab_list_sel = (self.tab_list_sel as i32 + delta).rem_euclid(n as i32) as usize;
    }
    /// Enter in the list: switch to the selected tab (closing the list; same tab = just close).
    pub fn tab_list_activate(&mut self) {
        let i = self.tab_list_sel;
        self.tab_list = false;
        self.tab_goto(i);
    }
    /// `w` in the list: close the **selected** tab (the list stays open, like the bookmark list).
    /// Closing the active tab switches to a neighbor; the last tab refuses with a flash.
    pub fn tab_list_close_selected(&mut self) {
        if self.tabs.len() <= 1 {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::CantCloseLastTab).into());
            return;
        }
        let i = self.tab_list_sel;
        if i == self.active_tab {
            self.tab_close();
        } else {
            self.tabs.remove(i);
            if self.active_tab > i {
                self.active_tab -= 1;
            }
        }
        self.tab_list_sel = self.tab_list_sel.min(self.tabs.len() - 1);
        self.save_session();
    }
    /// Root directory of tab `i` (for the tab list's path column).
    pub fn tab_root(&self, i: usize) -> std::path::PathBuf {
        if i == self.active_tab {
            self.root.clone()
        } else {
            self.tabs
                .get(i)
                .map(|t| t.root.clone())
                .unwrap_or_else(|| self.root.clone())
        }
    }

    /// Format a path into a display string using the current path_style (shared by the tree/preview title).
    pub fn format_path(&self, path: &Path) -> String {
        match self.path_style {
            PathStyle::Full => path.display().to_string(),
            PathStyle::Home => home_relative(path),
            PathStyle::Relative => rel_to_open(&self.open_dir, path),
        }
    }
}

/// Common helper that moves a list cursor by delta and returns it clamped to `[0, len-1]`.
/// Even if the caller (`g`/`G`/Home/End) passes `delta=i32::MIN/MAX`, the computation is done in i64, so it
/// does not panic on overflow (the plain `as i32 + delta` addition used to crash in debug).
/// `len==0` returns 0. The behavior is unchanged from the previous `(cur as i32 + delta).clamp(0, len-1)`.
fn clamp_cursor(cur: usize, delta: i32, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let last = len.saturating_sub(1) as i64;
    (cur as i64).saturating_add(delta as i64).clamp(0, last) as usize
}

/// Whether a span is a Markdown link (blue underline). Since konoma's StyleSheet.link()=underline+blue draws them,
/// these two conditions decide it (code/headings/rules have different colors, so no false positives).
fn is_link_span(span: &Span<'static>) -> bool {
    use ratatui::style::{Color, Modifier};
    span.style.add_modifier.contains(Modifier::UNDERLINED) && span.style.fg == Some(Color::Blue)
}

/// Scan collapsed decorated lines for Tab-cycle items (links / task checkboxes / code-block
/// headers) in document order. `targets` are the link URLs recovered by `collapse_links`, in the
/// same order the link spans appear. `fence_ords` are the **source** ordinals of the rendered
/// mermaid placements in order (from `ImagePlacement::fence_ord`) — the k-th sentinel takes the
/// k-th value. Shared by the cache build and the test-only decorate path.
/// Slugify a heading's text the way GitHub does for `#anchor` links: lowercase, drop punctuation
/// except `-`/`_`, spaces → `-` (consecutive spaces → consecutive `-`, not collapsed). Unicode
/// letters/digits are kept (CJK headings anchor too). Used to match `[x](#slug)` link targets.
fn github_slug(text: &str) -> String {
    let mut s = String::new();
    for c in text.trim().chars() {
        if c.is_alphanumeric() {
            s.extend(c.to_lowercase());
        } else if c == ' ' {
            s.push('-');
        } else if c == '-' || c == '_' {
            s.push(c);
        }
    }
    s
}

/// Build the in-page anchor map (slug → decorated logical-line index) from the rendered lines, in
/// document order, with GitHub's duplicate-slug disambiguation (`slug`, `slug-1`, `slug-2`, …).
fn compute_md_anchors(lines: &[Line<'static>]) -> Vec<(String, usize)> {
    use std::collections::HashMap;
    let mut anchors = Vec::new();
    let mut counts: HashMap<String, usize> = HashMap::new();
    for (i, line) in lines.iter().enumerate() {
        let Some(text) = crate::preview::markdown::heading_text(line) else {
            continue;
        };
        let base = github_slug(&text);
        if base.is_empty() {
            continue;
        }
        let n = counts.entry(base.clone()).or_insert(0);
        let slug = if *n == 0 {
            base.clone()
        } else {
            format!("{base}-{n}")
        };
        *n += 1;
        anchors.push((slug, i));
    }
    anchors
}

fn build_md_items(
    lines: &[Line<'static>],
    targets: &[String],
    fence_ords: &[usize],
) -> Vec<MdItem> {
    let mut items = Vec::new();
    let mut k = 0usize;
    for (li, line) in lines.iter().enumerate() {
        for span in &line.spans {
            if is_link_span(span) {
                let target = targets.get(k).cloned().unwrap_or_default();
                items.push(MdItem {
                    line: li,
                    kind: MdItemKind::Link { target },
                });
                k += 1;
            } else if crate::preview::markdown::is_task_span(span) {
                if let Some(state) =
                    crate::preview::markdown::task_span_state(span.content.as_ref())
                {
                    items.push(MdItem {
                        line: li,
                        kind: MdItemKind::Task { state },
                    });
                }
            } else if crate::preview::markdown::is_code_header_span(span) {
                items.push(MdItem {
                    line: li,
                    kind: MdItemKind::CodeBlock,
                });
            } else if crate::preview::markdown::is_mermaid_header_span(span) {
                let seen = items
                    .iter()
                    .filter(|it| matches!(it.kind, MdItemKind::MermaidFence { .. }))
                    .count();
                // 序数は placement 由来の**ソース順**(loading/失敗フェンス込みの通し番号)。
                // 描画済み番兵の個数で代用すると、上流に番兵を出さないフェンス(テキスト降格/
                // loading 中)があるとき Enter のソース再抽出とずれて**別の図**が開く。
                // fence_ords が無い経路(テスト互換)のみ従来の計数にフォールバック。
                let ordinal = fence_ords.get(seen).copied().unwrap_or(seen);
                items.push(MdItem {
                    line: li,
                    kind: MdItemKind::MermaidFence { ordinal },
                });
            } else if crate::preview::markdown::is_details_header_span(span) {
                let ordinal = items
                    .iter()
                    .filter(|it| matches!(it.kind, MdItemKind::Details { .. }))
                    .count();
                items.push(MdItem {
                    line: li,
                    kind: MdItemKind::Details { ordinal },
                });
            }
        }
    }
    items
}

/// Apply the focus inversion to one decorated line. `ordinal` = index of the focused marker span
/// within this line (counting link/task/code-header spans in order); `whole_line`=code-block
/// header (all spans inverted — one line, a clear focus cue). Other lines pass through untouched.
fn invert_focused_line(line: &Line<'static>, ordinal: usize, whole_line: bool) -> Line<'static> {
    use ratatui::style::Modifier;
    let style = line.style;
    let mut seen = 0usize;
    let spans = line
        .spans
        .iter()
        .cloned()
        .map(|mut span| {
            if whole_line {
                span.style = span.style.add_modifier(Modifier::REVERSED);
            } else if is_link_span(&span)
                || crate::preview::markdown::is_task_span(&span)
                || crate::preview::markdown::is_code_header_span(&span)
                || crate::preview::markdown::is_mermaid_header_span(&span)
                || crate::preview::markdown::is_details_header_span(&span)
            {
                if seen == ordinal {
                    span.style = span.style.add_modifier(Modifier::REVERSED);
                }
                seen += 1;
            }
            span
        })
        .collect::<Vec<_>>();
    Line::from(spans).style(style)
}

/// Fold the accompanying URL of the "label (URL)" that tui-markdown emits, leaving **only the label** in link style (blue underline,
/// with a leading link icon when `icons=true`). The URLs are collected in order into `targets` and returned (hidden destinations).
/// Pattern: `[label]` `" ("` `[URL(blue underline)]` `")"`. Spans that do not match are passed through unchanged.
fn collapse_links(lines: Vec<Line<'static>>, icons: bool) -> (Vec<Line<'static>>, Vec<String>) {
    use ratatui::style::{Color, Modifier, Style};
    let link_style = Style::new()
        .fg(Color::Blue)
        .add_modifier(Modifier::UNDERLINED);
    let mut out = Vec::with_capacity(lines.len());
    let mut targets = Vec::new();
    for line in lines {
        let style = line.style;
        let spans = line.spans;
        let n = spans.len();
        let mut new: Vec<Span<'static>> = Vec::with_capacity(n);
        let mut i = 0;
        while i < n {
            // 表セル由来の「ラベル+隠しターゲット」ペア(markdown::render_table が生成):
            // ラベルはそのまま残し(幅を変えない=表の桁揃え維持のためアイコンも付けない)、
            // 隠しスパンを取り除いて URL を targets へ回収する(Tab/Enter は通常リンクと同じ)。
            if i + 1 < n
                && is_link_span(&spans[i])
                && crate::preview::markdown::is_hidden_link_target(&spans[i + 1])
            {
                targets.push(spans[i + 1].content.to_string());
                new.push(spans[i].clone());
                i += 2;
                continue;
            }
            let is_link_pattern = i + 2 < n
                && spans[i + 1].content.as_ref() == " ("
                && is_link_span(&spans[i + 2])
                && spans.get(i + 3).is_some_and(|s| s.content.starts_with(')'));
            if is_link_pattern {
                let label = spans[i].content.as_ref();
                targets.push(spans[i + 2].content.to_string());
                let text = if icons {
                    format!("{} {label}", crate::ui::icons::link_icon())
                } else {
                    label.to_string()
                };
                new.push(Span::styled(text, link_style));
                // 閉じ括弧 ")" の後ろに続く文字(句読点等)は保持する。
                let closer = spans[i + 3].content.as_ref();
                if closer.len() > 1 {
                    new.push(Span::styled(closer[1..].to_string(), spans[i + 3].style));
                }
                i += 4;
            } else {
                new.push(spans[i].clone());
                i += 1;
            }
        }
        out.push(Line::from(new).style(style));
    }
    (out, targets)
}

/// Trim trailing punctuation from a matched URL run, GFM-style: drop a trailing run of
/// `? ! . , : * _ ~ ' "` and any `)` that has no matching `(` inside the run (iteratively).
fn trim_url_end(s: &str) -> &str {
    let mut end = s.len();
    loop {
        let sub = &s[..end];
        let Some(last) = sub.chars().last() else {
            break;
        };
        if "?!.,:*_~'\"".contains(last) {
            end -= last.len_utf8();
            continue;
        }
        if last == ')' && sub.matches(')').count() > sub.matches('(').count() {
            end -= 1;
            continue;
        }
        break;
    }
    &s[..end]
}

/// A character that ends a bare-URL run: whitespace, `<`, or CJK/fullwidth punctuation. The last set
/// matters for konoma's CJK audience — Japanese text often abuts a URL with no ASCII space
/// (`https://x.example、と`), and GFM's "stop only at whitespace/`<`" would swallow the trailing
/// characters into the link. Stopping at these keeps the URL clean.
fn is_url_stop(c: char) -> bool {
    c.is_whitespace()
        || c == '<'
        || matches!(
            c,
            '' | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
        )
}

/// Match a bare URL autolink at the start of `rest` (`http://…`, `https://…`, or `www.…`). Returns
/// the matched byte length and the target to open (`www.` gains an `http://` prefix). The run stops
/// at whitespace / `<` / CJK punctuation (`is_url_stop`), then trailing punctuation is trimmed. None
/// if `rest` does not start a URL.
fn match_bare_url(rest: &str) -> Option<(usize, String)> {
    let is_www = rest.starts_with("www.");
    if !(is_www || rest.starts_with("http://") || rest.starts_with("https://")) {
        return None;
    }
    let run_end = rest.find(is_url_stop).unwrap_or(rest.len());
    let run = trim_url_end(&rest[..run_end]);
    // Need a host after the scheme (or after `www.` a further alphanumeric char).
    let valid = if is_www {
        run.len() > 4 && run[4..].contains(|c: char| c.is_ascii_alphanumeric())
    } else {
        run.find("://").is_some_and(|p| run.len() > p + 3)
    };
    if !valid {
        return None;
    }
    let target = if is_www {
        format!("http://{run}")
    } else {
        run.to_string()
    };
    Some((run.len(), target))
}

fn is_email_local(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '%' | '+' | '-')
}
fn is_email_domain(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '-')
}

/// Match a bare email autolink at the start of `rest` (`local@domain.tld`). Returns the matched byte
/// length and a `mailto:` target. Requires a non-empty local part, an `@`, and a domain with a dot
/// whose last label is ≥2 ASCII letters. Trailing `.`/`-` are trimmed from the domain.
fn match_bare_email(rest: &str) -> Option<(usize, String)> {
    let local_len: usize = rest
        .chars()
        .take_while(|&c| is_email_local(c))
        .map(char::len_utf8)
        .sum();
    if local_len == 0 || !rest[local_len..].starts_with('@') {
        return None;
    }
    let after_at = &rest[local_len + 1..];
    let mut dom_len: usize = after_at
        .chars()
        .take_while(|&c| is_email_domain(c))
        .map(char::len_utf8)
        .sum();
    // Trim trailing '.'/'-' from the domain.
    while dom_len > 0 && matches!(after_at.as_bytes()[dom_len - 1], b'.' | b'-') {
        dom_len -= 1;
    }
    let domain = &after_at[..dom_len];
    let tld_ok = domain
        .rsplit_once('.')
        .is_some_and(|(_, tld)| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()));
    if !tld_ok {
        return None;
    }
    let end = local_len + 1 + dom_len;
    Some((end, format!("mailto:{}", &rest[..end])))
}

/// Find bare autolinkable spans (GFM autolink literals) in `text`: `http(s)://…`, `www.…`, and
/// `local@domain.tld` emails. Returns `(start_byte, end_byte, target)` in document order,
/// non-overlapping. A pragmatic subset of GFM §6.9: a match may start only at the beginning or after
/// a non-alphanumeric byte, the run stops at whitespace/`<`, and trailing punctuation (plus
/// unbalanced `)`) is trimmed. `www.` gets an `http://` prefix; emails a `mailto:` prefix.
fn find_bare_links(text: &str) -> Vec<(usize, usize, String)> {
    let bytes = text.as_bytes();
    let n = bytes.len();
    let mut out: Vec<(usize, usize, String)> = Vec::new();
    let mut i = 0usize;
    while i < n {
        let boundary_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
        if boundary_ok {
            let rest = &text[i..];
            if let Some((len, target)) = match_bare_url(rest).or_else(|| match_bare_email(rest)) {
                out.push((i, i + len, target));
                i += len.max(1);
                continue;
            }
        }
        i += text[i..].chars().next().map_or(1, char::len_utf8);
    }
    out
}

/// Post-pass over collapsed lines: turn bare URLs/emails in plain-text spans into link spans, and
/// interleave their targets into `targets` in document order (so `build_md_items` pairs each link
/// span with the right URL). Skips spans that already carry a link, a background (inline code / code
/// fence content), or a konoma sentinel (task / code-header / mermaid / hidden-target) — matching
/// GitHub, which never auto-links inside code.
fn autolink_bare_urls(
    lines: Vec<Line<'static>>,
    in_targets: Vec<String>,
) -> (Vec<Line<'static>>, Vec<String>) {
    use ratatui::style::{Color, Modifier, Style};
    let link_style = Style::new()
        .fg(Color::Blue)
        .add_modifier(Modifier::UNDERLINED);
    let mut out_lines = Vec::with_capacity(lines.len());
    let mut out_targets = Vec::new();
    let mut ti = 0usize;
    for line in lines {
        // Code-block lines never auto-link (a URL in a fence stays literal). Keep as-is; for any
        // existing link span (none in practice) carry its target through 1:1 so the k-th link span
        // in `out_lines` still maps to `out_targets[k]` — no drift if a code line ever holds a link.
        if crate::preview::markdown::is_code_line(&line) {
            for span in &line.spans {
                if is_link_span(span) {
                    out_targets.push(in_targets.get(ti).cloned().unwrap_or_default());
                    ti += 1;
                }
            }
            out_lines.push(line);
            continue;
        }
        let style = line.style;
        let mut new: Vec<Span<'static>> = Vec::with_capacity(line.spans.len());
        for span in line.spans {
            // Existing link span → keep as-is; it owns the next input target (preserve order).
            if is_link_span(&span) {
                out_targets.push(in_targets.get(ti).cloned().unwrap_or_default());
                ti += 1;
                new.push(span);
                continue;
            }
            // Never auto-link inside code (inline code / bg-filled code) or over a konoma sentinel.
            if span.style.bg.is_some()
                || crate::preview::markdown::is_inline_code_span(&span)
                || crate::preview::markdown::is_task_span(&span)
                || crate::preview::markdown::is_code_header_span(&span)
                || crate::preview::markdown::is_mermaid_header_span(&span)
                || crate::preview::markdown::is_hidden_link_target(&span)
            {
                new.push(span);
                continue;
            }
            let text = span.content.into_owned();
            let matches = find_bare_links(&text);
            if matches.is_empty() {
                new.push(Span::styled(text, span.style));
                continue;
            }
            let mut pos = 0usize;
            for (s, e, url) in matches {
                if s > pos {
                    new.push(Span::styled(text[pos..s].to_string(), span.style));
                }
                new.push(Span::styled(text[s..e].to_string(), link_style));
                out_targets.push(url);
                pos = e;
            }
            if pos < text.len() {
                new.push(Span::styled(text[pos..].to_string(), span.style));
            }
        }
        out_lines.push(Line::from(new).style(style));
    }
    (out_lines, out_targets)
}

/// Replace `:shortcode:` runs in `text` with Unicode emoji (gemoji names, e.g. `:rocket:` → 🚀).
/// Returns `None` when nothing changed (so the caller reuses the original span untouched). A
/// shortcode with no Unicode mapping (GitHub-custom like `:shipit:`) and non-shortcode `:` (times,
/// ratios) are left exactly as they were.
fn replace_emoji_shortcodes(text: &str) -> Option<String> {
    if !text.contains(':') {
        return None;
    }
    let mut out = String::new();
    let mut changed = false;
    let mut rest = text;
    while let Some(start) = rest.find(':') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        if let Some(end) = after.find(':') {
            let code = &after[..end];
            let looks_like_code = !code.is_empty()
                && code
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-'));
            if looks_like_code {
                if let Some(e) = emojis::get_by_shortcode(code) {
                    out.push_str(e.as_str());
                    changed = true;
                    rest = &after[end + 1..];
                    continue;
                }
            }
            // Not a known shortcode: keep this `:` and resume scanning right after it.
            out.push(':');
            rest = after;
        } else {
            out.push(':');
            out.push_str(after);
            rest = "";
        }
    }
    out.push_str(rest);
    changed.then_some(out)
}

/// Post-pass over decorated Markdown lines: convert `:shortcode:` emoji to Unicode in plain-text
/// spans. Skips spans that carry a background (inline code / code fence), a link, or a konoma
/// sentinel (task / code-header / mermaid / hidden-target) — matching GitHub, which never converts
/// shortcodes inside code, and keeping Tab-item spans byte-stable.
fn substitute_emoji(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
    lines
        .into_iter()
        .map(|line| {
            // Code-block lines keep their `:shortcode:` literal (a fence is verbatim).
            if crate::preview::markdown::is_code_line(&line) {
                return line;
            }
            let style = line.style;
            let spans = line
                .spans
                .into_iter()
                .map(|span| {
                    if span.style.bg.is_some()
                        || is_link_span(&span)
                        || crate::preview::markdown::is_inline_code_span(&span)
                        || crate::preview::markdown::is_task_span(&span)
                        || crate::preview::markdown::is_code_header_span(&span)
                        || crate::preview::markdown::is_mermaid_header_span(&span)
                        || crate::preview::markdown::is_hidden_link_target(&span)
                    {
                        return span;
                    }
                    match replace_emoji_shortcodes(span.content.as_ref()) {
                        Some(new) => Span::styled(new, span.style),
                        None => span,
                    }
                })
                .collect::<Vec<_>>();
            Line::from(spans).style(style)
        })
        .collect()
}

/// Within line `line` (multiple colored spans), highlight the parts matching `query` (substring, case-insensitive)
/// in a highlighter style (background color + black text + bold). Even for matches crossing span boundaries, each span is split at the
/// match boundaries and the background is applied (the original fg/bold/italic are kept). If the byte length changes when lowercasing
/// (multibyte), it does nothing to avoid mis-slicing.
/// When `current_occurrence`=Some(occurrence rank within the line, 0-based), **only that one occurrence is orange**, and
/// the others are yellow (vim's CurSearch/Search style; `n`/`N` change the color of only the selected occurrence). None means all yellow.
/// Since occurrences are identified by rank rather than column (byte position), the current match stays stable even if the byte sequence shifts from tab expansion (#14).
fn highlight_query_in_line(
    line: Line<'static>,
    query: &str,
    current_occurrence: Option<usize>,
) -> Line<'static> {
    use ratatui::style::{Color, Modifier};
    if query.is_empty() {
        return line;
    }
    let full: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
    let lower = full.to_lowercase();
    let q = query.to_lowercase();
    if lower.len() != full.len() {
        return line; // 非 ASCII でバイト長が変わる場合は安全側で強調なし
    }
    // 一致バイト範囲を収集。
    let mut ranges: Vec<(usize, usize)> = Vec::new();
    let mut i = 0;
    while let Some(rel) = lower[i..].find(&q) {
        let s = i + rel;
        let e = s + q.len();
        ranges.push((s, e));
        i = e;
    }
    if ranges.is_empty() {
        return line;
    }
    let style = line.style;
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut pos = 0usize; // full 内のバイト位置
    for span in line.spans {
        let text = span.content.into_owned();
        let span_start = pos;
        let span_end = pos + text.len();
        // この span 内の分割点(span 端+一致境界)。
        let mut points = vec![span_start, span_end];
        for (s, e) in &ranges {
            if *s > span_start && *s < span_end {
                points.push(*s);
            }
            if *e > span_start && *e < span_end {
                points.push(*e);
            }
        }
        points.sort_unstable();
        points.dedup();
        for w in points.windows(2) {
            let (a, b) = (w[0], w[1]);
            if let Some(seg) = text.get(a - span_start..b - span_start) {
                if seg.is_empty() {
                    continue;
                }
                // この区間が属する一致範囲の出現順位(あれば)。その順位が current_occurrence
                // なら現在の出現=オレンジ、他の一致は黄色。範囲外は素のまま。
                let hit = ranges.iter().position(|(s, e)| a >= *s && b <= *e);
                let st = if let Some(idx) = hit {
                    let bg = if current_occurrence == Some(idx) {
                        Color::Rgb(0xff, 0x8c, 0x00) // 現在の出現
                    } else {
                        Color::Yellow // 他の出現
                    };
                    span.style
                        .bg(bg)
                        .fg(Color::Black)
                        .add_modifier(Modifier::BOLD)
                } else {
                    span.style
                };
                out.push(Span::styled(seg.to_string(), st));
            }
        }
        pos = span_end;
    }
    Line::from(out).style(style)
}

/// Editor-style git change status of one line in the previewed (working-tree) file, for the left gutter.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum GutterMark {
    /// Newly inserted line (no matching removal): green bar.
    Added,
    /// Line replaced/edited (part of a hunk that also removed lines): blue bar.
    Modified,
    /// One or more lines were removed just above this line: red boundary marker.
    Deleted,
}

// Gutter marker colors, matching Zed: green added, amber modified, red deleted.
const GUTTER_ADDED: ratatui::style::Color = ratatui::style::Color::Rgb(87, 171, 90);
const GUTTER_MODIFIED: ratatui::style::Color = ratatui::style::Color::Rgb(216, 166, 74);
const GUTTER_DELETED: ratatui::style::Color = ratatui::style::Color::Rgb(199, 84, 80);

/// Derive a per-new-line git gutter map from a file's working-tree diff. Keyed by 1-based new-file line
/// number. A change block is a maximal run of Added/Removed lines (Context breaks it): with additions it
/// marks each added line Modified (if the block also removed lines) or Added (pure insertion); a
/// pure-deletion block marks the following line Deleted (or the preceding line if the deletion is at EOF).
fn gutter_marks(diff: &[crate::git::DiffLine]) -> std::collections::HashMap<u32, GutterMark> {
    use crate::git::DiffLineKind;
    let mut marks = std::collections::HashMap::new();
    let mut i = 0;
    while i < diff.len() {
        if diff[i].kind == DiffLineKind::Context {
            i += 1;
            continue;
        }
        let start = i;
        let mut removed = 0usize;
        let mut added: Vec<u32> = Vec::new();
        while i < diff.len() && diff[i].kind != DiffLineKind::Context {
            match diff[i].kind {
                DiffLineKind::Removed => removed += 1,
                DiffLineKind::Added => {
                    if let Some(n) = diff[i].new_no {
                        added.push(n);
                    }
                }
                DiffLineKind::Context => {}
            }
            i += 1;
        }
        if !added.is_empty() {
            let mark = if removed > 0 {
                GutterMark::Modified
            } else {
                GutterMark::Added
            };
            for n in added {
                marks.insert(n, mark);
            }
        } else if removed > 0 {
            // Pure deletion: anchor the marker to the line just below the removed block; if the block is
            // at EOF, anchor to the last real line above it (deletion below).
            let anchor = diff
                .get(i)
                .and_then(|d| d.new_no)
                .or_else(|| diff[..start].iter().rev().find_map(|d| d.new_no));
            if let Some(a) = anchor {
                marks.entry(a).or_insert(GutterMark::Deleted);
            }
        }
    }
    marks
}

/// Prepend a one-cell git change marker to each line (before the line-number gutter, Zed-style). Only
/// applied when the file has changes (`marks` non-empty) — unchanged files / non-repos keep their layout.
/// The displayed line `i` maps to 1-based file line `top_line + i + 1`; unchanged lines get a blank cell.
fn with_git_gutter(
    lines: Vec<Line<'static>>,
    top_line: usize,
    marks: &std::collections::HashMap<u32, GutterMark>,
) -> Vec<Line<'static>> {
    use ratatui::style::{Color, Style};
    if marks.is_empty() {
        return lines;
    }
    lines
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            let n = (top_line + i + 1) as u32;
            let (glyph, color) = match marks.get(&n) {
                Some(GutterMark::Added) => ("", GUTTER_ADDED),
                Some(GutterMark::Modified) => ("", GUTTER_MODIFIED),
                // Thin bar hugging the TOP edge of the line below a deletion, so it
                // sits on the seam between the two lines instead of looking like the
                // line itself was removed. (A terminal cell can't draw in the inter-row
                // gap, so the top edge is the closest we can get without adding a row.)
                Some(GutterMark::Deleted) => ("", GUTTER_DELETED),
                None => (" ", Color::Reset),
            };
            let style = line.style;
            let mut spans = Vec::with_capacity(line.spans.len() + 1);
            spans.push(Span::styled(glyph, Style::new().fg(color)));
            spans.extend(line.spans);
            Line::from(spans).style(style)
        })
        .collect()
}

/// The active visual selection in a windowed preview, normalized so `start ≤ end`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewSelection {
    /// Not selecting (only the block caret is drawn).
    None,
    /// Charwise (`v`): an inclusive `(line, col)` character range across one or more lines.
    Char {
        start: (usize, usize),
        end: (usize, usize),
    },
    /// Linewise (`V`): whole logical lines `lo..=hi`.
    Line { lo: usize, hi: usize },
}

/// Extract the text of a charwise selection from the file's logical lines (`start`/`end` end-inclusive,
/// columns are char indices). Slicing by chars (not bytes) keeps multibyte/CJK content intact.
fn selection_char_text(lines: &[&str], start: (usize, usize), end: (usize, usize)) -> String {
    let (sl, sc) = start;
    let (el, ec) = end;
    if sl >= lines.len() {
        return String::new();
    }
    let el = el.min(lines.len() - 1);
    if sl == el {
        // 単一行: [sc..=ec](正規化済みで sc ≤ ec)
        lines[sl]
            .chars()
            .skip(sc)
            .take((ec + 1).saturating_sub(sc))
            .collect()
    } else {
        let mut out = String::new();
        out.push_str(&lines[sl].chars().skip(sc).collect::<String>());
        for l in &lines[sl + 1..el] {
            out.push('\n');
            out.push_str(l);
        }
        out.push('\n');
        out.push_str(&lines[el].chars().take(ec + 1).collect::<String>());
        out
    }
}

/// The character range `[lo, hi)` to highlight on absolute line `abs` for a charwise selection, or None.
/// `usize::MAX` for `hi` means "to end of line". End is inclusive, so the last covered char is `end.1`.
fn char_range_for_line(
    abs: usize,
    start: (usize, usize),
    end: (usize, usize),
) -> Option<(usize, usize)> {
    if abs < start.0 || abs > end.0 {
        return None;
    }
    let lo = if abs == start.0 { start.1 } else { 0 };
    let hi = if abs == end.0 {
        end.1.saturating_add(1)
    } else {
        usize::MAX
    };
    Some((lo, hi))
}

/// Paint the 2D caret and selection onto the visible content lines (char-column based, applied BEFORE the
/// line-number/git gutters so column indices align with the file text). The whole-line cases also set the
/// line's base style so the gutter cells inherit the tint; charwise partial ranges tint only the spanned chars.
fn apply_preview_caret(
    lines: Vec<Line<'static>>,
    top_line: usize,
    cursor_line: usize,
    cursor_col: usize,
    sel: PreviewSelection,
) -> Vec<Line<'static>> {
    use ratatui::style::Color;
    // 暗色テーマ向け: 控えめな現在行背景と、選択範囲の少し強い青系背景。
    const CURSOR_BG: Color = Color::Rgb(55, 60, 74);
    const SEL_BG: Color = Color::Rgb(40, 66, 104);
    lines
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            let abs = top_line + i;
            let caret = if abs == cursor_line {
                Some(cursor_col)
            } else {
                None
            };
            let (range, whole): (Option<(usize, usize, Color)>, bool) = match sel {
                PreviewSelection::None => {
                    if abs == cursor_line {
                        (Some((0, usize::MAX, CURSOR_BG)), true)
                    } else {
                        (None, false)
                    }
                }
                PreviewSelection::Line { lo, hi } => {
                    if abs >= lo && abs <= hi {
                        (Some((0, usize::MAX, SEL_BG)), true)
                    } else {
                        (None, false)
                    }
                }
                PreviewSelection::Char { start, end } => match char_range_for_line(abs, start, end)
                {
                    Some((lo, hi)) => (Some((lo, hi, SEL_BG)), lo == 0 && hi == usize::MAX),
                    None => (None, false),
                },
            };
            if range.is_none() && caret.is_none() {
                return line;
            }
            restyle_line(line, range, whole, caret)
        })
        .collect()
}

/// Rebuild a line applying a background to chars in `range` `(lo, hi, color)` and the REVERSED modifier to the
/// `caret` char. When `whole` is set, the line's base style also gets the bg (so gutters inherit it). Consecutive
/// chars with the same resulting style are coalesced into one span to keep the span count low.
fn restyle_line(
    line: Line<'static>,
    range: Option<(usize, usize, ratatui::style::Color)>,
    whole: bool,
    caret: Option<usize>,
) -> Line<'static> {
    use ratatui::style::Modifier;
    let base = line.style;
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut idx = 0usize; // char index within the line content
    let mut cur = String::new();
    let mut cur_style: Option<ratatui::style::Style> = None;
    for span in line.spans.into_iter() {
        for ch in span.content.chars() {
            let mut style = span.style;
            if let Some((lo, hi, color)) = range {
                if idx >= lo && idx < hi {
                    style = style.bg(color);
                }
            }
            if caret == Some(idx) {
                style = style.add_modifier(Modifier::REVERSED);
            }
            if cur_style != Some(style) {
                if !cur.is_empty() {
                    out.push(Span::styled(std::mem::take(&mut cur), cur_style.unwrap()));
                }
                cur_style = Some(style);
            }
            cur.push(ch);
            idx += 1;
        }
    }
    if !cur.is_empty() {
        out.push(Span::styled(cur, cur_style.unwrap_or(base)));
    }
    let mut line = Line::from(out);
    line.style = if whole {
        if let Some((_, _, color)) = range {
            base.bg(color)
        } else {
            base
        }
    } else {
        base
    };
    line
}

/// Prepend a line-number gutter (right-aligned + a space) to each line. The first line's number is `top_line+1` (1-based).
/// A dim color (DarkGray) distinguishes it from the body. The original line style (background, etc.) is kept.
fn with_line_numbers(lines: Vec<Line<'static>>, top_line: usize) -> Vec<Line<'static>> {
    use ratatui::style::{Color, Style};
    let last = top_line + lines.len().max(1);
    let width = last.to_string().len().max(3); // 最低 3 桁ぶんの幅を確保
    lines
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            let n = top_line + i + 1;
            let gutter = Span::styled(format!("{n:>width$} "), Style::new().fg(Color::DarkGray));
            let style = line.style;
            let mut spans = Vec::with_capacity(line.spans.len() + 1);
            spans.push(gutter);
            spans.extend(line.spans);
            Line::from(spans).style(style)
        })
        .collect()
}

/// The rectangle that centers an image of size `cells` (natural size) within `inner` while preserving the aspect ratio.
/// With `allow_upscale=false`, downscale only (scale<=1=fit behavior); with `true`, it may upscale to fill the area.
fn centered_rect(cells: (u16, u16), inner: Rect, allow_upscale: bool) -> Rect {
    let (cw, ch) = cells;
    if cw == 0 || ch == 0 || inner.width == 0 || inner.height == 0 {
        return inner;
    }
    let mut scale = (inner.width as f64 / cw as f64).min(inner.height as f64 / ch as f64);
    if !allow_upscale {
        scale = scale.min(1.0);
    }
    let w = ((cw as f64 * scale).round() as u16).clamp(1, inner.width);
    let h = ((ch as f64 * scale).round() as u16).clamp(1, inner.height);
    let x = inner.x + (inner.width - w) / 2;
    let y = inner.y + (inner.height - h) / 2;
    Rect {
        x,
        y,
        width: w,
        height: h,
    }
}

/// Max reserved rows for one inline Markdown image; a taller image is scaled down (keeping aspect) so it never dominates the viewport.
const MD_IMAGE_MAX_ROWS: u16 = 24;

/// Resolve a Markdown image URL to a local file path. A remote (`http(s)://`) URL resolves to its
/// download-cache path, but only once it has been fetched (so callers treat a cached remote image
/// exactly like a local one). `data:` URLs return None. Relative paths are resolved against the
/// Markdown file's directory. Returns the path only if the file exists.
fn resolve_md_image_path(url: &str, base: Option<&Path>) -> Option<PathBuf> {
    let u = url.trim();
    if u.is_empty() {
        return None;
    }
    if crate::preview::markdown::is_remote_image_url(u) {
        let p = md_remote_cache_path(u)?;
        return p.is_file().then_some(p);
    }
    let lower = u.to_ascii_lowercase();
    if lower.starts_with("data:") {
        return None;
    }
    let u = u.strip_prefix("file://").unwrap_or(u);
    let p = PathBuf::from(u);
    let p = if p.is_absolute() {
        p
    } else if let Some(b) = base {
        b.join(p)
    } else {
        p
    };
    p.is_file().then_some(p)
}

/// Pixel dimensions of a cached inline-image file, accepting both raster formats and SVG (parsed cheaply
/// via usvg, without rasterizing). None if the file is neither a known raster image nor an SVG.
fn md_image_dims(path: &Path) -> Option<(u32, u32)> {
    crate::preview::image::dimensions(path).or_else(|| crate::preview::svg::intrinsic_size(path))
}

/// Decode a cached inline-image file to an image, rasterizing SVG (at `svg_max_px`) when the raster
/// decoders reject it (GitHub READMEs are full of SVG badges/logos). None if it is not a decodable image.
fn md_decode_image(path: &Path, svg_max_px: u32) -> Option<image::DynamicImage> {
    crate::preview::image::decode_static(path)
        .or_else(|| crate::preview::svg::rasterize(path, svg_max_px))
}

/// The source-pixel band `(y0, height)` of an image `dh` pixels tall that corresponds to the visible
/// cell rows `[row_off, row_off + vis_rows)` out of `full_rows` total. The result is always within
/// `[0, dh]` (so `crop_imm(0, y0, _, height)` never exceeds the image and never panics), and the height
/// is at least 1.
fn md_band_pixels(full_rows: u16, row_off: u16, vis_rows: u16, dh: u32) -> (u32, u32) {
    let fr = full_rows.max(1) as u32;
    let y0 = (row_off as u32 * dh) / fr;
    let y1 = ((row_off as u32 + vis_rows as u32).min(fr) * dh) / fr;
    (y0, y1.saturating_sub(y0).max(1))
}

/// Root of konoma's on-disk cache (`$XDG_CACHE_HOME` or `~/.cache`). None if neither is available.
fn cache_root() -> Option<PathBuf> {
    if let Some(x) = std::env::var_os("XDG_CACHE_HOME") {
        if !x.is_empty() {
            return Some(PathBuf::from(x));
        }
    }
    let home = std::env::var_os("HOME")?;
    if home.is_empty() {
        return None;
    }
    Some(PathBuf::from(home).join(".cache"))
}

/// Deterministic cache path for a remote image URL: `<cache>/konoma/remote-images/<hash>`. The file is
/// stored without an extension (the content type is unknown until fetched) and read via content sniffing.
fn md_remote_cache_path(url: &str) -> Option<PathBuf> {
    use std::hash::{Hash, Hasher};
    let root = cache_root()?;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    url.trim().hash(&mut hasher);
    Some(
        root.join("konoma")
            .join("remote-images")
            .join(format!("{:016x}", hasher.finish())),
    )
}

/// Maximum bytes to download for one remote image (guards against huge / hostile responses).
const MD_REMOTE_MAX_BYTES: u64 = 25 * 1024 * 1024;

/// Download a remote image with `curl` into `dest` (atomically, via a temp file), validating that the
/// bytes decode as an image before committing. Returns whether a valid image now exists at `dest`.
/// Runs on a background thread. Uses the system `curl` (always present on macOS) to avoid adding a
/// TLS/HTTP dependency — consistent with konoma's external-tool delegation model (PRD §5).
fn fetch_remote_image(url: &str, dest: &Path) -> bool {
    use std::process::{Command, Stdio};
    let Some(parent) = dest.parent() else {
        return false;
    };
    if std::fs::create_dir_all(parent).is_err() {
        return false;
    }
    let tmp = dest.with_extension("part");
    let status = Command::new("curl")
        .args([
            "-sSL", // silent, show errors, follow redirects (GitHub proxies images via camo)
            "--fail",
            "--max-time",
            "20",
            "--max-filesize",
            &MD_REMOTE_MAX_BYTES.to_string(),
            "-A",
            "konoma image preview",
            "-o",
        ])
        .arg(&tmp)
        .arg(url)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    let downloaded = matches!(status, Ok(s) if s.success());
    if !downloaded {
        let _ = std::fs::remove_file(&tmp);
        return false;
    }
    // Reject non-images (e.g. an HTML error page served with 200) before caching them (accepts SVG).
    if md_image_dims(&tmp).is_none() {
        let _ = std::fs::remove_file(&tmp);
        return false;
    }
    let ok = std::fs::rename(&tmp, dest).is_ok();
    if ok {
        prune_remote_cache(parent, MD_REMOTE_CACHE_MAX);
    }
    ok
}

/// Keep at most `keep` files in the remote-image cache directory, deleting the oldest (by mtime).
/// The cache is content-addressed (one file per distinct URL) with no cleanup, so without this it
/// grows unbounded over a machine's lifetime. Runs only after a **new** download (rare), so the
/// directory scan is cheap. Best-effort: any IO error just leaves the cache as-is.
fn prune_remote_cache(dir: &Path, keep: usize) {
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    let mut files: Vec<(std::time::SystemTime, PathBuf)> = rd
        .flatten()
        .filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
        .filter_map(|e| {
            let p = e.path();
            // 進行中の一時ファイル(.part)は対象外。
            if p.extension().is_some_and(|x| x == "part") {
                return None;
            }
            let mtime = e.metadata().and_then(|m| m.modified()).ok()?;
            Some((mtime, p))
        })
        .collect();
    if files.len() <= keep {
        return;
    }
    files.sort_by_key(|(t, _)| *t); // oldest first
    for (_, p) in files.iter().take(files.len() - keep) {
        let _ = std::fs::remove_file(p);
    }
}

/// Max files kept in the remote-image disk cache (`~/.cache/konoma/remote-images`).
const MD_REMOTE_CACHE_MAX: usize = 256;

/// Compute the display size in terminal cells for an image of `pw`x`ph` pixels, given the terminal
/// font cell size (`fw`x`fh` px). The image is fit to `avail_cols` (never upscaled beyond its natural
/// cell size) and then capped to `max_rows`, preserving aspect ratio in both steps.
fn md_image_cells(
    pw: u32,
    ph: u32,
    fw: u16,
    fh: u16,
    avail_cols: u16,
    max_rows: u16,
) -> (u16, u16) {
    let fw = (fw.max(1)) as f64;
    let fh = (fh.max(1)) as f64;
    let nat_cols = (pw as f64 / fw).ceil().max(1.0);
    let nat_rows = (ph as f64 / fh).ceil().max(1.0);
    let avail = avail_cols.max(1) as f64;
    let (mut cols, mut rows) = if nat_cols <= avail {
        (nat_cols, nat_rows)
    } else {
        let s = avail / nat_cols;
        (avail, (nat_rows * s).round().max(1.0))
    };
    let maxr = max_rows.max(1) as f64;
    if rows > maxr {
        let s = maxr / rows;
        rows = maxr;
        cols = (cols * s).round().max(1.0);
    }
    (cols as u16, rows as u16)
}

/// Cell box for an inline mermaid diagram: **fill to `target_rows`** (up- or downscale, keeping
/// the aspect from the layout pixels), clamped by the available width. Unlike raster images
/// (`md_image_cells`, never upscaled), diagrams are vector-backed — the raster follows the
/// display size via sharpening re-rasters, so growing beyond the natural size stays crisp.
fn mermaid_cells(pw: u32, ph: u32, fw: u16, fh: u16, avail: u16, target_rows: u16) -> (u16, u16) {
    let (fw, fh) = (fw.max(1) as f64, fh.max(1) as f64);
    let ar = (pw.max(1) as f64) / (ph.max(1) as f64); // px アスペクト
    let mut rows = target_rows.max(1) as f64;
    let mut cols = (rows * fh * ar / fw).round().max(1.0);
    let avail = avail.max(1) as f64;
    if cols > avail {
        cols = avail;
        rows = (cols * fw / ar / fh).round().max(1.0);
    }
    (cols as u16, rows as u16)
}

/// Cell box for an inline math image, sized proportionally from the SVG's intrinsic **em** units
/// (RaTeX renders at 40 units/em) so equations sit at roughly text scale: em-height → rows, intrinsic
/// aspect → cols. Display math gets a touch more height than inline. Clamped to the available width
/// (aspect preserved) and a sane row cap. Vector-backed, so the once-rendered raster is fit crisply.
fn math_cells(uw: u32, uh: u32, fw: u16, fh: u16, avail: u16, display: bool) -> (u16, u16) {
    let (fw, fh) = (fw.max(1) as f64, fh.max(1) as f64);
    let em_h = (uh.max(1) as f64) / 40.0;
    let rows_per_em = if display { 1.5 } else { 1.3 };
    let mut rows = (em_h * rows_per_em).round().max(1.0);
    let ar = (uw.max(1) as f64) / (uh.max(1) as f64);
    let mut cols = (rows * fh * ar / fw).round().max(1.0);
    let avail = avail.max(1) as f64;
    if cols > avail {
        cols = avail;
        rows = (cols * fw / ar / fh).round().max(1.0);
    }
    // 極端に高い式(行列など)が画面を埋め尽くさないための上限。
    let maxr = 24.0;
    if rows > maxr {
        let s = maxr / rows;
        rows = maxr;
        cols = (cols * s).round().max(1.0);
    }
    (cols as u16, rows as u16)
}

/// Source-pixel crop rectangle (x, y, w, h).
type PxRect = (u32, u32, u32, u32);

/// Crop window for the in-place zoom of an inline diagram. `f` is the visible fraction, i.e.
/// 1/zoom, of the source; `center` is clamped so the window stays inside the image. Returns the
/// crop px rect plus the clamped center. Fractions are scale-free, so the same zoom and center
/// map onto a sharper re-raster unchanged.
fn fence_crop(dims: (u32, u32), f: f64, center: (f64, f64)) -> (PxRect, (f64, f64)) {
    let (sw, sh) = dims;
    let f = f.clamp(0.0, 1.0);
    let cx = center.0.clamp(f / 2.0, 1.0 - f / 2.0);
    let cy = center.1.clamp(f / 2.0, 1.0 - f / 2.0);
    let cw = ((sw as f64 * f).round() as u32).clamp(1, sw);
    let ch = ((sh as f64 * f).round() as u32).clamp(1, sh);
    let x0 = ((cx * sw as f64) as i64 - cw as i64 / 2).clamp(0, (sw - cw) as i64) as u32;
    let y0 = ((cy * sh as f64) as i64 - ch as i64 / 2).clamp(0, (sh - ch) as i64) as u32;
    ((x0, y0, cw, ch), (cx, cy))
}

/// Compute the display layout for an image/GIF frame (a pure function shared by prepare_image / prepare_gif).
/// From (source image src, font_size, zoom, center[0,1], display area inner, render_scale), returns
/// `(target, crop_rect, center, frac)` (None if size 0).
///
/// - `target`  : the render-target rectangle (centered; z=1=fit, grows when zooming, clips when exceeding the viewport)
/// - `crop_rect`: the source-image window of the visible portion (px: x,y,w,h)
/// - `center`  : the center clamped to where the visible window fits within the image [0,1]
/// - `frac`    : the visible fraction per axis (<1=clipped=pan possible)
#[allow(clippy::type_complexity)]
fn image_layout(
    src: &image::DynamicImage,
    font_size: ratatui_image::FontSize,
    zoom: f64,
    center: (f64, f64),
    inner: Rect,
    render_scale: f64,
    logical: Option<(u32, u32)>,
) -> Option<(Rect, PxRect, (f64, f64), (f64, f64))> {
    use image::GenericImageView;
    let (sw, sh) = src.dimensions();
    if sw == 0 || sh == 0 || inner.width == 0 || inner.height == 0 {
        return None;
    }
    // z=1 のフィット表示サイズ(セル, 拡大しない)。ベクタ由来のプレビューは **論理サイズ**
    // (初回ラスタの寸法) で計るので、シャープなラスタへ差し替えても画面上の大きさ・切り出し窓は
    // 一切動かない(HiDPI のバッキングストア方式。切り出し自体は比率で実ピクセルに写像される)。
    let (nw, nh) = match logical {
        Some((lw, lh)) if lw > 0 && lh > 0 => (
            (lw as u16).div_ceil(font_size.width.max(1)),
            (lh as u16).div_ceil(font_size.height.max(1)),
        ),
        _ => {
            let n = Resize::natural_size(src, font_size);
            (n.width, n.height)
        }
    };
    let base = centered_rect((nw, nh), inner, false);
    // ズーム後の論理表示サイズ。
    let disp_w = (base.width as f64 * zoom).max(1.0);
    let disp_h = (base.height as f64 * zoom).max(1.0);
    // 画面に出る大きさ = min(表示サイズ, 表示領域)。
    let tw = (disp_w.min(inner.width as f64).round() as u16).max(1);
    let th = (disp_h.min(inner.height as f64).round() as u16).max(1);
    // 各軸の可視率(<1 なら見切れ=パン可能)。
    let fw = (tw as f64 / disp_w).min(1.0);
    let fh = (th as f64 / disp_h).min(1.0);
    // 中心を可視窓が画像内に収まる範囲へクランプ。
    let cx = center.0.clamp(fw / 2.0, 1.0 - fw / 2.0);
    let cy = center.1.clamp(fh / 2.0, 1.0 - fh / 2.0);
    // 元画像から見える窓を切り出す(px)。
    let cw = ((sw as f64 * fw).round() as u32).clamp(1, sw);
    let ch = ((sh as f64 * fh).round() as u32).clamp(1, sh);
    let x0 = ((cx * sw as f64) as i64 - cw as i64 / 2).clamp(0, (sw - cw) as i64) as u32;
    let y0 = ((cy * sh as f64) as i64 - ch as i64 / 2).clamp(0, (sh - ch) as i64) as u32;
    let crop_rect = (x0, y0, cw, ch);
    // 表示矩形(中央寄せ)。任意で render_scale により縮小(転送量=描画待ち削減)。
    let scale = render_scale.clamp(0.1, 1.0);
    let (tw, th) = if scale >= 0.999 {
        (tw, th)
    } else {
        (
            ((tw as f64 * scale).round() as u16).max(1),
            ((th as f64 * scale).round() as u16).max(1),
        )
    };
    let target = Rect {
        x: inner.x + (inner.width - tw.min(inner.width)) / 2,
        y: inner.y + (inner.height - th.min(inner.height)) / 2,
        width: tw.min(inner.width),
        height: th.min(inner.height),
    };
    Some((target, crop_rect, (cx, cy), (fw, fh)))
}

/// The modification time of `path`, or None if it cannot be read. Used by the FS-driven media auto-reload guard.
fn file_mtime(path: &Path) -> Option<std::time::SystemTime> {
    std::fs::metadata(path).and_then(|m| m.modified()).ok()
}

/// Assemble the copy string (a pure function; does not touch the clipboard).
/// `open_dir` is the base for relative paths (the launch directory).
fn copy_text(path: &Path, open_dir: &Path, kind: CopyKind) -> String {
    match kind {
        CopyKind::Name => path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default(),
        CopyKind::Full => path.display().to_string(),
        CopyKind::Parent => path
            .parent()
            .map(|p| p.display().to_string())
            .unwrap_or_default(),
        // 左上のタイトル表示 (format_path の Relative) と完全に同じ基準にする。
        CopyKind::Relative => rel_to_open(open_dir, path),
        CopyKind::AtRef => at_ref_text(open_dir, path),
    }
}

/// `@path` reference for AI agents (Claude Code's `@file` context syntax). Under `open_dir` the path is
/// strictly relative to it (`src/app.rs` — no leading dir name, unlike `rel_to_open`); outside it is
/// `..`-relative; if neither works, absolute. Prefixed with `@`.
fn at_ref_text(open_dir: &Path, path: &Path) -> String {
    let rel = match path.strip_prefix(open_dir) {
        Ok(r) if !r.as_os_str().is_empty() => r.display().to_string(),
        _ => match rel_from(open_dir, path) {
            Some(r) if !r.as_os_str().is_empty() => r.display().to_string(),
            _ => path.display().to_string(),
        },
    };
    format!("@{rel}")
}

/// A relative display string based on `open_dir` (the launch directory). For paths underneath, it puts the launch directory name first (e.g. `A/sub/x`),
/// and for things outside open_dir (siblings/ancestors) it relativizes with `..` (e.g. `../B/aaa.md`, `..`). If it cannot be relativized, `~/...`.
/// A shared function to guarantee the **same base** for the top-left path display (`format_path`'s Relative) and path copy (`cr`/`yr`).
fn rel_to_open(open_dir: &Path, path: &Path) -> String {
    if path.starts_with(open_dir) {
        // open_dir 配下: 起動ディレクトリ名を先頭に出すため、その親を基準に相対化 (例: A/sub/x)。
        let base = open_dir.parent().unwrap_or(open_dir);
        match path.strip_prefix(base) {
            Ok(rel) if !rel.as_os_str().is_empty() => rel.display().to_string(),
            _ => home_relative(path),
        }
    } else {
        // open_dir の外(兄弟/上位など): open_dir 基準の相対パスを `..` 込みで表示 (例: ../B/aaa.md)。
        // これが無いと兄弟 B のファイルが `B/aaa.md` のように見え、配下にあるかのように誤解される。
        match rel_from(open_dir, path) {
            Some(rel) if !rel.as_os_str().is_empty() => rel.display().to_string(),
            _ => home_relative(path),
        }
    }
}

/// Write to the clipboard. Returns Err on environments where arboard is unavailable (the caller shows a flash).
fn set_clipboard(text: &str) -> Result<()> {
    let mut cb = arboard::Clipboard::new()?;
    cb.set_text(text.to_string())?;
    Ok(())
}

/// `~/...` if under HOME, otherwise the full path.
pub(crate) fn home_relative(path: &Path) -> String {
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        if let Ok(rel) = path.strip_prefix(&home) {
            if rel.as_os_str().is_empty() {
                return "~".to_string();
            }
            return format!("~/{}", rel.display());
        }
    }
    path.display().to_string()
}

/// Resolve a dropped (=pasted) string into a list of **existing paths**. Terminals (Ghostty, etc.) pass a drop
/// as shell-escaped text (spaces as `\ `; multiple files separated by unescaped spaces).
/// Undo the backslash escapes, split on unescaped whitespace/newlines, and return only the tokens that **exist on disk**
/// (= safely excludes plain text pastes, junk, and control-character mixes).
fn parse_dropped_paths(text: &str) -> Vec<PathBuf> {
    let mut tokens: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut escaped = false;
    for c in text.chars() {
        if escaped {
            cur.push(c); // 直前が `\` = この文字はリテラル(空白入りパス名等)
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else if c.is_whitespace() {
            if !cur.is_empty() {
                tokens.push(std::mem::take(&mut cur));
            }
        } else {
            cur.push(c);
        }
    }
    if !cur.is_empty() {
        tokens.push(cur);
    }
    tokens
        .into_iter()
        .map(PathBuf::from)
        .filter(|p| p.exists()) // 実在パスのみ採用(テキストペースト/不正入力を弾く安全網)
        .collect()
}

/// Build a plan for sequential rename. Number `targets` **in display order** as `{n}`=1,2,…,
/// expand the template, and create each (old, new) path. If the template has no extension, the original extension is kept automatically.
/// **Pre-validates** collisions: an empty name / a `/` mixed in / duplicate final names / a collision with an existing file (not vacated within the batch) is an Err.
fn build_rename_plan(targets: &[PathBuf], template: &str) -> Result<Vec<(PathBuf, PathBuf)>> {
    let mut plan: Vec<(PathBuf, PathBuf)> = Vec::with_capacity(targets.len());
    for (idx, src) in targets.iter().enumerate() {
        let n = idx + 1;
        let stem = src.file_stem().and_then(|s| s.to_str()).unwrap_or("");
        let ext = src.extension().and_then(|s| s.to_str()).unwrap_or("");
        let rendered = crate::fileops::render_rename_template(template, n, stem, ext);
        let rendered = rendered.trim().to_string();
        if rendered.is_empty() {
            anyhow::bail!("空の名前になります (n={n})");
        }
        if rendered.contains('/') {
            anyhow::bail!("名前に / は使えません: {rendered}");
        }
        // 拡張子: テンプレ結果に拡張子が無ければ元拡張子を自動付与(ユーザ決定)。
        let has_ext = Path::new(&rendered)
            .extension()
            .filter(|e| !e.is_empty())
            .is_some();
        let new_name = if !has_ext && !ext.is_empty() {
            format!("{rendered}.{ext}")
        } else {
            rendered
        };
        let dst = src
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(&new_name);
        plan.push((src.clone(), dst));
    }
    // 最終名の重複検証。
    let mut seen = BTreeSet::new();
    for (_, dst) in &plan {
        if !seen.insert(dst.clone()) {
            anyhow::bail!("リネーム先が重複: {}", dst.display());
        }
    }
    // 既存ファイルとの衝突検証(バッチ内で「移動して空く」元パスは除外)。
    let vacated: BTreeSet<PathBuf> = plan
        .iter()
        .filter(|(s, d)| s != d)
        .map(|(s, _)| s.clone())
        .collect();
    for (src, dst) in &plan {
        // 名前据え置き(src == dst)は自分自身の存在を衝突と誤検出しないよう除外する(#11)。
        // 真の衝突=別ファイルと被る場合のみ、最終名重複検証(上)で弾く。
        if src == dst {
            continue;
        }
        if dst.exists() && !vacated.contains(dst) {
            anyhow::bail!("既に存在します: {}", dst.display());
        }
    }
    Ok(plan)
}

/// Return the byte position in `s` corresponding to character index `char_idx` (past the end gives `s.len()`).
/// A conversion to safely compute insertion/deletion positions even for multibyte text (e.g. Japanese file names).
fn char_byte(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(b, _)| b)
        .unwrap_or(s.len())
}

/// Compute the relative path from `base` to `target`, including `..` (equivalent to pathdiff). It removes the common leading components and
/// pushes one `..` for each remaining level on the base side. None if the root kinds (absolute/drive) disagree and it cannot be relativized.
fn rel_from(base: &Path, target: &Path) -> Option<PathBuf> {
    use std::path::Component;
    let bc: Vec<Component> = base.components().collect();
    let tc: Vec<Component> = target.components().collect();
    let mut i = 0;
    while i < bc.len() && i < tc.len() && bc[i] == tc[i] {
        i += 1;
    }
    // 共通成分が無く、かつ一方がルート(絶対/Prefix)で始まる=相対化不能。
    if i == 0 {
        let is_root = |c: Option<&Component>| {
            matches!(c, Some(Component::Prefix(_)) | Some(Component::RootDir))
        };
        if is_root(bc.first()) || is_root(tc.first()) {
            return None;
        }
    }
    let mut rel = PathBuf::new();
    for _ in i..bc.len() {
        rel.push("..");
    }
    for c in &tc[i..] {
        rel.push(c.as_os_str());
    }
    Some(rel)
}

/// Append one directory's worth of entries to out. Recurse into expanded subdirectories.
/// Bundles the decision info for one entry for sorting. Lowercased sort keys are precomputed
/// once per entry (sort_by runs O(n log n) comparisons — lowercasing inside the comparator
/// allocated two Strings per comparison). The stat is taken only when the sort key needs
/// size/mtime, or when the entry is a symlink (is_dir must follow the link like fs::metadata).
struct ChildMeta {
    path: PathBuf,
    /// Lowercased file name (also the stable tiebreak for every sort key).
    name_lower: String,
    /// Lowercased extension; filled only when sorting by extension.
    ext_lower: String,
    is_dir: bool,
    size: u64,
    mtime: Option<std::time::SystemTime>,
}

fn child_meta(path: PathBuf, ft: Option<std::fs::FileType>, sort: Sort) -> ChildMeta {
    let need_stat = matches!(sort.key, SortKey::Size | SortKey::Modified);
    let is_symlink = ft.map(|t| t.is_symlink()).unwrap_or(true);
    let (is_dir, size, mtime) = if need_stat || is_symlink {
        // fs::metadata follows symlinks, so a symlink to a directory stays expandable.
        let md = std::fs::metadata(&path).ok();
        (
            md.as_ref().map(|m| m.is_dir()).unwrap_or(false),
            md.as_ref().map(|m| m.len()).unwrap_or(0),
            md.as_ref().and_then(|m| m.modified().ok()),
        )
    } else {
        // DirEntry::file_type is free on macOS (readdir d_type) — no extra syscall.
        (ft.map(|t| t.is_dir()).unwrap_or(false), 0, None)
    };
    let name_lower = path
        .file_name()
        .map(|s| s.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    let ext_lower = if matches!(sort.key, SortKey::Ext) {
        path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase()
    } else {
        String::new()
    };
    ChildMeta {
        path,
        name_lower,
        ext_lower,
        is_dir,
        size,
        mtime,
    }
}

/// Compare two entries according to the settings. dirs_first → key → reverse, finally stabilized by name.
fn sort_cmp(a: &ChildMeta, b: &ChildMeta, sort: Sort) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    if sort.dirs_first {
        let d = b.is_dir.cmp(&a.is_dir); // ディレクトリ(true)を先頭に
        if d != Ordering::Equal {
            return d;
        }
    }
    let mut ord = match sort.key {
        SortKey::Name => a.name_lower.cmp(&b.name_lower),
        SortKey::Size => a.size.cmp(&b.size),
        SortKey::Modified => a.mtime.cmp(&b.mtime),
        SortKey::Ext => a.ext_lower.cmp(&b.ext_lower),
    };
    if sort.reverse {
        ord = ord.reverse();
    }
    // 同値は名前(昇順)で安定化して並びがブレないようにする。
    ord.then_with(|| a.name_lower.cmp(&b.name_lower))
}

/// Take the title label for the graph base from refs (`%D`). From `(HEAD -> main, origin/main)`, etc.,
/// pick one branch name (strip the HEAD-> and skip tag:). If there is no branch ref, the short hash.
#[cfg_attr(not(feature = "git"), allow(dead_code))]
fn base_label_from(refs: &str, short: &str) -> String {
    for part in refs.split(',').map(str::trim) {
        let p = part.strip_prefix("HEAD -> ").unwrap_or(part);
        if p.is_empty() || p.starts_with("tag:") {
            continue;
        }
        return p.to_string();
    }
    short.to_string()
}

fn build_dir(
    dir: &Path,
    depth: usize,
    expanded_dirs: &std::collections::HashSet<PathBuf>,
    show_hidden: bool,
    sort: Sort,
    out: &mut Vec<Entry>,
) -> Result<()> {
    let mut children: Vec<ChildMeta> = std::fs::read_dir(dir)?
        .filter_map(|r| r.ok())
        .map(|e| {
            let ft = e.file_type().ok();
            (e.path(), ft)
        })
        .filter(|(p, _)| {
            if show_hidden {
                return true;
            }
            !p.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(false)
        })
        .map(|(p, ft)| child_meta(p, ft, sort))
        .collect();

    children.sort_by(|a, b| sort_cmp(a, b, sort));

    for c in children {
        let expanded = c.is_dir && expanded_dirs.contains(&c.path);
        out.push(Entry {
            path: c.path.clone(),
            is_dir: c.is_dir,
            depth,
            expanded,
        });
        if expanded {
            build_dir(&c.path, depth + 1, expanded_dirs, show_hidden, sort, out)?;
        }
    }
    Ok(())
}

/// Recursively collect files/directories under `root` (the population for filtering). Hidden ones are excluded via `show_hidden`,
/// and symlink directories are not descended into (to prevent loops). The scan count is capped as a cost limit.
/// The return value is in ascending path order (grouped per directory). Each Entry is flat with depth=0 and expanded=false.
fn collect_all(root: &Path, show_hidden: bool) -> Vec<Entry> {
    const CAP: usize = 50_000;
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        if out.len() >= CAP {
            break;
        }
        let Ok(rd) = std::fs::read_dir(&dir) else {
            continue;
        };
        for path in rd.filter_map(|r| r.ok()).map(|e| e.path()) {
            if out.len() >= CAP {
                break;
            }
            let hidden = path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(false);
            if hidden && !show_hidden {
                continue;
            }
            // シンボリックリンクの dir には潜らない(循環回避)。is_dir はリンク先を辿るので別途判定。
            let is_symlink = std::fs::symlink_metadata(&path)
                .map(|m| m.file_type().is_symlink())
                .unwrap_or(false);
            let is_dir = path.is_dir();
            out.push(Entry {
                path: path.clone(),
                is_dir,
                depth: 0,
                expanded: false,
            });
            if is_dir && !is_symlink {
                stack.push(path);
            }
        }
    }
    out.sort_by(|a, b| a.path.cmp(&b.path));
    out
}

#[cfg(test)]
mod tests;