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
use crate::config::Config;
use crate::keybindings::{Action, KeybindingMode, Keybindings};
use crate::parser::{Document, HeadingNode, Link, extract_links};
use crate::tui::help_text;
use crate::tui::interactive::{ElementType, InteractiveState};
use crate::tui::kitty_animation::{self, KittyAnimation};
use crate::tui::syntax::SyntaxHighlighter;
use crate::tui::terminal_compat::ColorMode;
use crate::tui::theme::{Theme, ThemeName};
use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::widgets::{ListState, ScrollbarState};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::{Duration, Instant};
/// Special marker for the document overview entry (shows entire file content)
pub const DOCUMENT_OVERVIEW: &str = "(Document)";
/// Result of executing an action
#[derive(Debug)]
pub enum ActionResult {
/// Continue the main loop
Continue,
/// Exit the application
Quit,
/// Run an editor on a file, optionally at a specific line
RunEditor(PathBuf, Option<u32>),
/// Redraw the screen (terminal.clear())
Redraw,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Focus {
Outline,
Content,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AppMode {
Normal,
Interactive,
LinkFollow,
Search,
ThemePicker,
Help,
CellEdit,
ConfirmFileCreate,
DocSearch, // In-document search mode (n/N navigation)
CommandPalette, // Fuzzy-searchable command palette
ConfirmSaveWidth, // Modal confirmation for saving outline width
ConfirmSaveBeforeQuit, // Prompt to save unsaved changes before quitting
ConfirmSaveBeforeNav, // Prompt to save unsaved changes before navigating
FilePicker, // File picker modal for switching files
FileSearch, // File picker search/filter mode
}
/// Type of pending navigation when user has unsaved changes
#[derive(Debug, Clone)]
pub enum PendingNavigation {
/// Navigate back in file history
Back,
/// Navigate forward in file history
Forward,
/// Load a file (relative path, optional anchor)
LoadFile(PathBuf, Option<String>),
}
/// Available commands in the command palette
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CommandAction {
SaveWidth,
SaveFile, // Save pending edits to file (:w)
Undo, // Undo last pending edit
ToggleOutline,
ToggleHelp,
ToggleRawSource,
JumpToTop,
JumpToBottom,
CollapseAll,
ExpandAll,
/// Collapse headings at a specific level (parsed from command argument)
CollapseLevel,
/// Expand headings at a specific level (parsed from command argument)
ExpandLevel,
Quit,
}
/// A command in the palette
#[derive(Debug, Clone)]
pub struct PaletteCommand {
pub name: &'static str,
pub aliases: &'static [&'static str],
pub description: &'static str,
pub action: CommandAction,
}
impl PaletteCommand {
const fn new(
name: &'static str,
aliases: &'static [&'static str],
description: &'static str,
action: CommandAction,
) -> Self {
Self {
name,
aliases,
description,
action,
}
}
/// Check if query matches this command (fuzzy match on name or aliases)
pub fn matches(&self, query: &str) -> bool {
if query.is_empty() {
return true;
}
let query_lower = query.to_lowercase();
// Check name
if self.name.to_lowercase().contains(&query_lower) {
return true;
}
// Check aliases
for alias in self.aliases {
if alias.to_lowercase().starts_with(&query_lower) {
return true;
}
}
// Fuzzy match: check if all query chars appear in order in name
let name_lower = self.name.to_lowercase();
let mut name_chars = name_lower.chars().peekable();
for qc in query_lower.chars() {
loop {
match name_chars.next() {
Some(nc) if nc == qc => break,
Some(_) => continue,
None => return false,
}
}
}
true
}
/// Calculate match score (higher = better match)
pub fn match_score(&self, query: &str) -> usize {
if query.is_empty() {
return 100;
}
let query_lower = query.to_lowercase();
// Exact alias match = highest score
for alias in self.aliases {
if alias.to_lowercase() == query_lower {
return 1000;
}
}
// Alias prefix match
for alias in self.aliases {
if alias.to_lowercase().starts_with(&query_lower) {
return 500;
}
}
// Name starts with query
if self.name.to_lowercase().starts_with(&query_lower) {
return 300;
}
// Name contains query
if self.name.to_lowercase().contains(&query_lower) {
return 200;
}
// Fuzzy match score based on how compact the match is
100
}
}
/// All available commands
pub const PALETTE_COMMANDS: &[PaletteCommand] = &[
PaletteCommand::new(
"Save changes",
&["w", "write", "save"],
"Save pending edits to file",
CommandAction::SaveFile,
),
PaletteCommand::new(
"Undo edit",
&["u", "undo"],
"Undo last table cell edit",
CommandAction::Undo,
),
PaletteCommand::new(
"Save width to config",
&["sw", "savewidth"],
"Save current outline width to config file",
CommandAction::SaveWidth,
),
PaletteCommand::new(
"Toggle outline",
&["outline", "sidebar"],
"Show/hide the outline sidebar",
CommandAction::ToggleOutline,
),
PaletteCommand::new(
"Toggle help",
&["help", "?"],
"Show/hide keyboard shortcuts",
CommandAction::ToggleHelp,
),
PaletteCommand::new(
"Toggle raw source",
&["raw", "source"],
"Switch between rendered and raw markdown",
CommandAction::ToggleRawSource,
),
PaletteCommand::new(
"Jump to top",
&["top", "first", "gg"],
"Go to first heading",
CommandAction::JumpToTop,
),
PaletteCommand::new(
"Jump to bottom",
&["bottom", "last", "G"],
"Go to last heading",
CommandAction::JumpToBottom,
),
PaletteCommand::new(
"Collapse all",
&["collapse", "ca"],
"Collapse all headings (or :collapse N for level N)",
CommandAction::CollapseAll,
),
PaletteCommand::new(
"Expand all",
&["expand", "ea"],
"Expand all headings (or :expand N for level N)",
CommandAction::ExpandAll,
),
PaletteCommand::new(
"Collapse level",
&[
"collapse 1",
"collapse 2",
"collapse 3",
"collapse 4",
"collapse 5",
],
"Collapse headings at specific level",
CommandAction::CollapseLevel,
),
PaletteCommand::new(
"Expand level",
&["expand 1", "expand 2", "expand 3", "expand 4", "expand 5"],
"Expand headings at specific level",
CommandAction::ExpandLevel,
),
PaletteCommand::new(
"Quit",
&["q", "quit", "exit"],
"Exit treemd",
CommandAction::Quit,
),
];
/// A match found during search
#[derive(Debug, Clone)]
pub struct SearchMatch {
/// Line number (0-indexed)
pub line: usize,
/// Start column (byte offset in line)
pub col_start: usize,
/// Length of match in bytes
pub len: usize,
}
/// A pending table cell edit that hasn't been saved to file yet
#[derive(Debug, Clone)]
pub struct PendingEdit {
/// Which table in the file (0-indexed)
pub table_index: usize,
/// Row within the table (0 = header, 1+ = data rows, excludes separator)
pub row: usize,
/// Column within the table (0-indexed)
pub col: usize,
/// The original value before editing (for undo)
pub original_value: String,
/// The new value after editing
pub new_value: String,
}
pub struct App {
pub document: Document,
pub filename: String,
pub tree: Vec<HeadingNode>,
pub outline_state: ListState,
pub outline_scroll_state: ScrollbarState,
pub focus: Focus,
pub outline_items: Vec<OutlineItem>,
pub content_scroll: u16,
pub content_scroll_state: ScrollbarState,
pub content_height: usize,
pub content_viewport_height: u16, // Actual viewport height for scroll calculations
pub show_help: bool,
pub help_scroll: u16,
pub show_search: bool,
pub outline_search_active: bool, // Whether search input is active (cursor visible)
pub search_query: String,
pub highlighter: SyntaxHighlighter,
pub show_outline: bool,
pub outline_width: u16, // Percentage: 20, 30, or 40
/// Whether the config file had a custom (non-standard) outline width at startup.
/// Used to protect power users' custom config values from being overwritten.
/// Standard values are 20, 30, 40; anything else is considered custom.
config_has_custom_outline_width: bool,
pub bookmark_position: Option<String>, // Bookmarked heading text (was: outline position)
collapsed_headings: HashSet<String>, // Track which headings are collapsed by text
pub filter_by_todos: bool, // Filter outline to show only headings with open todos
pub current_theme: ThemeName,
pub theme: Theme,
pub show_theme_picker: bool,
pub theme_picker_selected: usize,
pub theme_picker_original: Option<ThemeName>, // Original theme before picker opened (for cancel)
previous_selection: Option<String>, // Track previous selection to detect changes
// Link following state
pub mode: AppMode,
/// Vim-style count prefix for motion commands (e.g., 5j moves down 5)
pub count_prefix: Option<usize>,
pub current_file_path: PathBuf, // Path to current file for resolving relative links
pub file_path_changed: bool, // Flag to signal file watcher needs update
pub suppress_file_watch: bool, // Skip next file watch check (after internal save)
pub links_in_view: Vec<Link>, // Links in currently displayed content
pub filtered_link_indices: Vec<usize>, // Indices into links_in_view after filtering
pub selected_link_idx: Option<usize>, // Currently selected index in filtered list
pub link_search_query: String, // Search query for filtering links
pub link_search_active: bool, // Whether search input is active
// File picker state
pub files_in_directory: Vec<PathBuf>, // All .md files in directory
pub dirs_in_directory: Vec<PathBuf>, // Subdirectories in directory
pub filtered_file_indices: Vec<usize>, // Indices after filtering (files)
pub filtered_dir_indices: Vec<usize>, // Indices after filtering (dirs)
pub selected_file_idx: Option<usize>, // Selected index in combined list
pub file_search_query: String, // Search query for filtering files
pub file_search_active: bool, // Whether search input is active
pub startup_needs_file_picker: bool, // True if started without file arg
pub file_picker_dir: Option<PathBuf>, // Custom directory for file picker
pub show_hidden: bool, // Whether to show hidden (dot) files and directories
pub file_history: Vec<FileState>, // Back navigation stack
pub file_future: Vec<FileState>, // Forward navigation stack (for undo back)
pub status_message: Option<String>, // Temporary status message to display
pub status_message_time: Option<Instant>, // When the status message was set
// Interactive element navigation
pub interactive_state: InteractiveState,
// Cell editing state
pub cell_edit_value: String, // Current value being edited
pub cell_edit_original_value: String, // Original value before editing (for undo)
pub cell_edit_row: usize, // Row being edited
pub cell_edit_col: usize, // Column being edited
// Pending edits buffer (for safe editing with explicit save)
pub pending_edits: Vec<PendingEdit>, // Stack of uncommitted edits
pub has_unsaved_changes: bool, // True if pending_edits is non-empty
// Persistent clipboard for Linux X11 compatibility
// On Linux, the clipboard instance must stay alive to serve paste requests
clipboard: Option<arboard::Clipboard>,
// Configuration persistence
config: Config,
color_mode: ColorMode,
// Pending file to open in external editor (set by link following, consumed by main loop)
pub pending_editor_file: Option<PathBuf>,
// Raw source view toggle
pub show_raw_source: bool,
// Pending file creation (for confirm dialog)
pub pending_file_create: Option<PathBuf>,
pub pending_file_create_message: Option<String>,
// Document search state (for in-document / search with n/N navigation)
pub doc_search_query: String,
pub doc_search_matches: Vec<SearchMatch>,
pub doc_search_current_idx: Option<usize>,
pub doc_search_active: bool, // Whether search input is active
pub doc_search_from_interactive: bool, // Whether search was started from interactive mode
pub doc_search_selected_link_idx: Option<usize>, // Index into links_in_view if match is in a link
// Command palette state
pub command_query: String,
pub command_filtered: Vec<usize>, // Indices into PALETTE_COMMANDS
pub command_selected: usize,
// Customizable keybindings
pub keybindings: Keybindings,
// Pending navigation (for confirm save dialog when navigating with unsaved changes)
pub pending_navigation: Option<PendingNavigation>,
// Terminal graphics protocol picker (with fallback font size)
pub picker: Option<ratatui_image::picker::Picker>,
// Cached image protocols keyed by resolved path (avoids re-decoding from disk every frame)
pub image_protocol_cache: HashMap<PathBuf, ratatui_image::protocol::StatefulProtocol>,
// Image modal viewing state
pub viewing_image_path: Option<std::path::PathBuf>,
pub viewing_image_state: Option<ratatui_image::protocol::StatefulProtocol>,
// GIF animation state for modal
pub modal_gif_frames: Vec<crate::tui::image_cache::GifFrame>,
pub modal_frame_protocols: Vec<ratatui_image::protocol::StatefulProtocol>,
pub modal_frame_index: usize,
pub modal_last_rendered_frame: Option<usize>,
pub modal_last_frame_update: Option<Instant>,
pub modal_animation_paused: bool,
// Native Kitty animation (for flicker-free GIF playback)
pub kitty_animation: Option<KittyAnimation>,
pub use_kitty_animation: bool, // Whether to use native Kitty animation
// Image rendering control (can be disabled via config or CLI)
pub images_enabled: bool,
// Mermaid diagram rendering cache: source hash → rendered protocol
#[cfg(feature = "mermaid")]
pub mermaid_protocol_cache: HashMap<u64, ratatui_image::protocol::StatefulProtocol>,
#[cfg(feature = "mermaid")]
pub mermaid_render_errors: HashMap<u64, String>,
#[cfg(feature = "mermaid")]
pub mermaid_last_render_width: u32,
// LaTeX detection state
pub latex_detected: bool,
pub latex_hint_shown: bool,
}
/// Saved state for file navigation history
#[derive(Debug, Clone)]
pub struct FileState {
pub path: PathBuf,
pub document: Document,
pub filename: String,
pub selected_heading: Option<String>,
pub content_scroll: u16,
pub outline_state_selected: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct OutlineItem {
pub level: usize,
pub text: String,
pub expanded: bool,
pub has_children: bool, // Track if this heading has children in the tree
}
impl App {
pub fn new(
document: Document,
filename: String,
file_path: PathBuf,
config: Config,
color_mode: ColorMode,
images_enabled: bool,
) -> Self {
let tree = document.build_tree();
let collapsed_headings = HashSet::new();
let mut outline_items = Self::flatten_tree(&tree, &collapsed_headings);
// Add document overview entry if there's preamble content or no headings
let has_preamble = Self::has_preamble_content(&document);
if has_preamble || document.headings.is_empty() {
outline_items.insert(
0,
OutlineItem {
level: 0, // Level 0 for document overview (renders without # prefix)
text: DOCUMENT_OVERVIEW.to_string(),
expanded: true,
has_children: !outline_items.is_empty(),
},
);
}
let mut outline_state = ListState::default();
if !outline_items.is_empty() {
outline_state.select(Some(0));
}
let content_lines = document.content.lines().count();
// Load theme from config, apply color mode, then apply custom colors
let current_theme = config.theme_name();
let theme = Theme::from_name(current_theme)
.with_color_mode(color_mode, current_theme)
.with_custom_colors(&config.theme, color_mode);
// Load sublime color scheme directory
let code_theme_dir = config.code_theme_dir_path();
// Load sublime color scheme name (for code highlighting)
let code_theme = config.ui.code_theme.as_str();
// Load outline width from config
let outline_width = config.ui.outline_width;
// Detect if config has a custom (non-standard) outline width
// Standard values: 20, 30, 40 - anything else is a custom power-user setting
let config_has_custom_outline_width =
outline_width != 20 && outline_width != 30 && outline_width != 40;
// Load keybindings from config (before config is moved)
let keybindings = config.keybindings();
Self {
document,
filename,
tree,
outline_state,
outline_scroll_state: ScrollbarState::new(outline_items.len()),
focus: Focus::Outline,
outline_items,
content_scroll: 0,
content_scroll_state: ScrollbarState::new(content_lines),
content_height: content_lines,
content_viewport_height: 20, // Default, will be updated by UI on first render
show_help: false,
help_scroll: 0,
show_search: false,
outline_search_active: false,
search_query: String::new(),
highlighter: SyntaxHighlighter::new(code_theme, code_theme_dir),
show_outline: true,
outline_width,
config_has_custom_outline_width,
bookmark_position: None,
collapsed_headings,
filter_by_todos: false,
current_theme,
theme,
show_theme_picker: false,
theme_picker_selected: 0,
theme_picker_original: None,
previous_selection: None,
// Link following state
mode: AppMode::Normal,
count_prefix: None,
current_file_path: file_path,
file_path_changed: false,
suppress_file_watch: false,
links_in_view: Vec::new(),
filtered_link_indices: Vec::new(),
selected_link_idx: None,
link_search_query: String::new(),
link_search_active: false,
// File picker state
files_in_directory: Vec::new(),
dirs_in_directory: Vec::new(),
filtered_file_indices: Vec::new(),
filtered_dir_indices: Vec::new(),
selected_file_idx: None,
file_search_query: String::new(),
file_search_active: false,
startup_needs_file_picker: false,
file_picker_dir: None,
show_hidden: false,
file_history: Vec::new(),
file_future: Vec::new(),
status_message: None,
status_message_time: None,
// Interactive element navigation
interactive_state: InteractiveState::new(),
// Cell editing state
cell_edit_value: String::new(),
cell_edit_original_value: String::new(),
cell_edit_row: 0,
cell_edit_col: 0,
// Pending edits buffer
pending_edits: Vec::new(),
has_unsaved_changes: false,
// Initialize persistent clipboard (None if unavailable)
clipboard: arboard::Clipboard::new().ok(),
// Configuration persistence
config,
color_mode,
// Pending editor file
pending_editor_file: None,
// Raw source view (off by default)
show_raw_source: false,
// Pending file creation (for confirm dialog)
pending_file_create: None,
pending_file_create_message: None,
// Document search state
doc_search_query: String::new(),
doc_search_matches: Vec::new(),
doc_search_current_idx: None,
doc_search_active: false,
doc_search_from_interactive: false,
doc_search_selected_link_idx: None,
// Command palette state
command_query: String::new(),
command_filtered: (0..PALETTE_COMMANDS.len()).collect(),
command_selected: 0,
// Customizable keybindings (loaded from config)
// Note: keybindings() called before config is moved into struct
keybindings,
// Pending navigation (for confirm save dialog)
pending_navigation: None,
// Terminal graphics protocol picker with fallback (like figif)
// Only initialize if images are enabled
picker: if images_enabled {
Self::init_picker()
} else {
None
},
// Cached image protocols (populated after index_elements)
image_protocol_cache: HashMap::new(),
// Image modal viewing state
viewing_image_path: None,
viewing_image_state: None,
// GIF animation state for modal
modal_gif_frames: Vec::new(),
modal_frame_protocols: Vec::new(),
modal_frame_index: 0,
modal_last_rendered_frame: None,
modal_last_frame_update: None,
modal_animation_paused: false,
// Native Kitty animation
kitty_animation: None,
use_kitty_animation: images_enabled && kitty_animation::is_kitty_terminal(),
// Image rendering control
images_enabled,
// Mermaid diagram cache
#[cfg(feature = "mermaid")]
mermaid_protocol_cache: HashMap::new(),
#[cfg(feature = "mermaid")]
mermaid_render_errors: HashMap::new(),
#[cfg(feature = "mermaid")]
mermaid_last_render_width: 0,
// LaTeX detection
latex_detected: false,
latex_hint_shown: false,
}
}
/// Initialize graphics protocol picker with environment-based protocol detection.
///
/// Checks environment variables (TERM_PROGRAM, KITTY_WINDOW_ID, etc.) to
/// detect the best image protocol, then queries stdio for font/cell dimensions.
/// Falls back to halfblocks if nothing better is available.
fn init_picker() -> Option<ratatui_image::picker::Picker> {
use ratatui_image::picker::Picker;
let env_protocol = Self::detect_image_protocol();
// Query stdio for accurate font/cell dimensions, then override protocol
let mut picker = match Picker::from_query_stdio() {
Ok(picker) => {
let (w, h) = picker.font_size();
if w < 4 || h < 4 {
Picker::halfblocks()
} else {
picker
}
}
Err(_) => Picker::halfblocks(),
};
// Override detected protocol with environment-based detection
if let Some(protocol) = env_protocol {
picker.set_protocol_type(protocol);
}
Some(picker)
}
/// Detect the best image protocol from environment variables.
///
/// Returns None if no specific protocol is detected (use stdio detection).
fn detect_image_protocol() -> Option<ratatui_image::picker::ProtocolType> {
use ratatui_image::picker::ProtocolType;
// Kitty graphics protocol
if std::env::var("KITTY_WINDOW_ID").is_ok() {
return Some(ProtocolType::Kitty);
}
// iTerm2 / WezTerm inline images protocol
if let Ok(term_program) = std::env::var("TERM_PROGRAM")
&& (term_program == "iTerm.app" || term_program == "WezTerm")
{
return Some(ProtocolType::Iterm2);
}
// Ghostty uses Kitty protocol
if let Ok(term) = std::env::var("TERM") {
if term.contains("ghostty") {
return Some(ProtocolType::Kitty);
}
// Sixel support
if term.contains("sixel") || term.contains("foot") {
return Some(ProtocolType::Sixel);
}
}
None
}
/// Populate the image protocol cache from indexed interactive elements.
///
/// Iterates all image elements, resolves paths, decodes images, and creates
/// stateful protocols. Called after every `index_elements()` to keep cache in sync.
pub fn populate_image_cache(&mut self) {
use std::collections::HashSet as ImgSet;
if self.picker.is_none() || !self.images_enabled {
return;
}
// Collect unique image src strings from indexed elements
let mut seen = ImgSet::new();
let srcs: Vec<String> = self
.interactive_state
.elements
.iter()
.filter_map(|elem| {
if let ElementType::Image { src, .. } = &elem.element_type {
if seen.insert(src.clone()) {
Some(src.clone())
} else {
None
}
} else {
None
}
})
.collect();
// Clear old cache entries not in current element set
let valid_paths: HashSet<PathBuf> = srcs
.iter()
.filter_map(|src| self.resolve_image_path(src).ok())
.collect();
self.image_protocol_cache
.retain(|k, _| valid_paths.contains(k));
// Populate cache for new images
for src in &srcs {
let path = match self.resolve_image_path(src) {
Ok(p) => p,
Err(_) => continue,
};
// Skip if already cached
if self.image_protocol_cache.contains_key(&path) {
continue;
}
let img_data = match crate::tui::image_cache::ImageCache::extract_first_frame(&path) {
Ok(data) => data,
Err(_) => continue,
};
let picker = match self.picker.as_mut() {
Some(p) => p,
None => continue,
};
let protocol = picker.new_resize_protocol(img_data);
self.image_protocol_cache.insert(path, protocol);
}
}
/// Render a mermaid diagram and cache the result as a StatefulProtocol.
/// Returns true if a cached protocol is available (either fresh or from prior render).
#[cfg(feature = "mermaid")]
pub fn render_mermaid_if_needed(&mut self, source: &str, width: u16) -> bool {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
source.hash(&mut hasher);
let hash = hasher.finish();
// Use picker's actual font width for accurate pixel calculation
let font_width = self.picker.as_ref().map_or(8u16, |p| {
let (w, _) = p.font_size();
if w < 1 { 8 } else { w }
});
let target_px = (width as u32) * (font_width as u32);
// Clear caches on render width change (re-rasterize at new size)
if target_px != self.mermaid_last_render_width {
self.mermaid_protocol_cache.clear();
self.mermaid_render_errors.clear();
self.mermaid_last_render_width = target_px;
}
// Already cached (success or failure)
if self.mermaid_protocol_cache.contains_key(&hash) {
return true;
}
if self.mermaid_render_errors.contains_key(&hash) {
return false;
}
match crate::tui::mermaid::render_mermaid_to_image(source, target_px) {
Ok(img) => {
if let Some(picker) = self.picker.as_mut() {
let protocol = picker.new_resize_protocol(img);
self.mermaid_protocol_cache.insert(hash, protocol);
return true;
}
false
}
Err(e) => {
self.mermaid_render_errors.insert(hash, e);
false
}
}
}
/// Get the hash for a mermaid source string.
#[cfg(feature = "mermaid")]
pub fn mermaid_source_hash(source: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
source.hash(&mut hasher);
hasher.finish()
}
/// Open image modal for a given image path
pub fn open_image_modal(&mut self, image_src: &str) {
// Skip if images are disabled
if !self.images_enabled {
return;
}
// Try to resolve and load the image
if let Ok(path) = self.resolve_image_path(image_src) {
// Load all frames (for GIF animation)
if let Ok(frames) = crate::tui::image_cache::ImageCache::extract_all_frames(&path)
&& !frames.is_empty()
&& let Some(picker) = &mut self.picker
{
// Create initial protocol for first frame only.
// Subsequent frames will be created on-demand during animation
// to avoid memory overhead of pre-computing all protocols.
let initial_protocol = picker.new_resize_protocol(frames[0].image.clone());
self.viewing_image_path = Some(path);
self.viewing_image_state = Some(initial_protocol);
self.modal_gif_frames = frames;
self.modal_frame_protocols.clear(); // Not used anymore
self.modal_frame_index = 0;
self.modal_last_rendered_frame = Some(0); // Mark first frame as rendered
self.modal_last_frame_update = Some(Instant::now());
}
}
}
/// Close the image modal
pub fn close_image_modal(&mut self) {
// Delete Kitty animation if active
self.stop_kitty_animation();
self.viewing_image_path = None;
self.viewing_image_state = None;
self.modal_gif_frames.clear();
self.modal_frame_protocols.clear();
self.modal_frame_index = 0;
self.modal_last_rendered_frame = None;
self.modal_last_frame_update = None;
self.modal_animation_paused = false;
}
/// Go to previous frame in GIF animation
pub fn modal_prev_frame(&mut self) {
if self.modal_gif_frames.is_empty() {
return;
}
// Stop Kitty animation - it doesn't support frame stepping, so fall back to software
self.stop_kitty_animation();
// Pause animation when manually stepping
self.modal_animation_paused = true;
let len = self.modal_gif_frames.len();
self.modal_frame_index = (self.modal_frame_index + len - 1) % len;
// Force re-render of the new frame
self.modal_last_rendered_frame = None;
}
/// Go to next frame in GIF animation
pub fn modal_next_frame(&mut self) {
if self.modal_gif_frames.is_empty() {
return;
}
// Stop Kitty animation - it doesn't support frame stepping, so fall back to software
self.stop_kitty_animation();
// Pause animation when manually stepping
self.modal_animation_paused = true;
self.modal_frame_index = (self.modal_frame_index + 1) % self.modal_gif_frames.len();
// Force re-render of the new frame
self.modal_last_rendered_frame = None;
}
/// Stop and delete Kitty animation, falling back to software rendering.
/// Called when manual frame control is needed (stepping).
fn stop_kitty_animation(&mut self) {
if let Some(ref anim) = self.kitty_animation {
let mut stdout = std::io::stdout();
let _ = kitty_animation::delete_animation(&mut stdout, anim);
}
self.kitty_animation = None;
}
/// Toggle animation play/pause
pub fn modal_toggle_animation(&mut self) {
self.modal_animation_paused = !self.modal_animation_paused;
// Control Kitty animation if active
if let Some(ref anim) = self.kitty_animation {
let mut stdout = std::io::stdout();
if self.modal_animation_paused {
let _ = kitty_animation::pause_animation(&mut stdout, anim);
} else {
let _ = kitty_animation::resume_animation(&mut stdout, anim);
}
}
if !self.modal_animation_paused {
// Reset the timer when resuming
self.modal_last_frame_update = Some(Instant::now());
}
}
/// Check if image modal is open
pub fn is_image_modal_open(&self) -> bool {
self.viewing_image_path.is_some()
}
/// Start Kitty native animation for GIF playback.
/// Called from render when we know the exact coordinates.
/// Returns true if animation was started successfully.
pub fn start_kitty_animation(&mut self, col: u16, row: u16) -> bool {
// Only start if:
// 1. Use Kitty animation is enabled
// 2. We have multiple frames (GIF)
// 3. Animation hasn't started yet
if !self.use_kitty_animation
|| self.modal_gif_frames.len() <= 1
|| self.kitty_animation.is_some()
{
return false;
}
// Prepare frames for Kitty animation
let frames: Vec<(image::DynamicImage, u32)> = self
.modal_gif_frames
.iter()
.map(|f| (f.image.clone(), f.delay_ms))
.collect();
// Transmit animation to Kitty terminal
let mut stdout = std::io::stdout();
match kitty_animation::transmit_animation(&mut stdout, &frames, col, row) {
Ok(Some(anim)) => {
self.kitty_animation = Some(anim);
true
}
Ok(None) => false,
Err(_) => {
// Fall back to software animation
self.use_kitty_animation = false;
false
}
}
}
/// Check if Kitty animation is active
pub fn has_kitty_animation(&self) -> bool {
self.kitty_animation.is_some()
}
/// Get time until next GIF frame should be displayed.
/// Returns None if not animating, Some(Duration) otherwise.
/// Used by the event loop to optimize poll timeout for smooth animation.
pub fn time_until_next_frame(&self) -> Option<std::time::Duration> {
// Kitty handles animation timing internally - no client-side timing needed
if self.kitty_animation.is_some() {
return None;
}
// Must be in image modal with multiple frames and not paused
if !self.is_image_modal_open()
|| self.modal_gif_frames.len() <= 1
|| self.modal_animation_paused
{
return None;
}
let last_update = self.modal_last_frame_update?;
let current_frame = &self.modal_gif_frames[self.modal_frame_index];
let frame_delay = std::time::Duration::from_millis(current_frame.delay_ms as u64);
let elapsed = last_update.elapsed();
if elapsed >= frame_delay {
// Frame is due now - return minimal duration to trigger immediate redraw
Some(std::time::Duration::from_millis(1))
} else {
Some(frame_delay - elapsed)
}
}
/// Update the content viewport height (called by UI when terminal size is known)
pub fn set_viewport_height(&mut self, height: u16) {
self.content_viewport_height = height.max(1); // Ensure at least 1 to avoid divide-by-zero
}
/// Get the current keybinding mode based on app state
pub fn current_keybinding_mode(&self) -> KeybindingMode {
// Check modal states first
if self.show_help {
return KeybindingMode::Help;
}
if self.show_theme_picker {
return KeybindingMode::ThemePicker;
}
// Then check app mode
match self.mode {
AppMode::Normal => {
if self.show_search && self.outline_search_active {
// Active input mode for typing search query
KeybindingMode::Search
} else {
// Normal mode (including accepted outline search state)
// When show_search=true but outline_search_active=false, we're in
// "accepted search" state - user can navigate filtered results with
// normal keybindings (j/k, n/N for cycling, s to start new search)
KeybindingMode::Normal
}
}
AppMode::Interactive => {
if self.interactive_state.is_in_table_mode() {
KeybindingMode::InteractiveTable
} else {
KeybindingMode::Interactive
}
}
AppMode::LinkFollow => {
if self.link_search_active {
KeybindingMode::LinkSearch
} else {
KeybindingMode::LinkFollow
}
}
AppMode::Search => KeybindingMode::Search,
AppMode::ThemePicker => KeybindingMode::ThemePicker,
AppMode::Help => KeybindingMode::Help,
AppMode::CellEdit => KeybindingMode::CellEdit,
AppMode::ConfirmFileCreate
| AppMode::ConfirmSaveWidth
| AppMode::ConfirmSaveBeforeQuit
| AppMode::ConfirmSaveBeforeNav => KeybindingMode::ConfirmDialog,
AppMode::DocSearch => KeybindingMode::DocSearch,
AppMode::CommandPalette => KeybindingMode::CommandPalette,
AppMode::FilePicker => {
if self.file_search_active {
KeybindingMode::FileSearch
} else {
KeybindingMode::FilePicker
}
}
// FileSearch mode is no longer used - we use FilePicker mode with file_search_active flag
AppMode::FileSearch => KeybindingMode::FileSearch,
}
}
/// Get the action for a key press in the current mode
pub fn get_action_for_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Option<Action> {
use crossterm::event::{KeyEvent, KeyEventKind, KeyEventState};
let mode = self.current_keybinding_mode();
let event = KeyEvent {
code,
modifiers,
kind: KeyEventKind::Press,
state: KeyEventState::NONE,
};
self.keybindings.dispatch(mode, event)
}
/// Execute an action, returning the result type
///
/// Returns:
/// - `ActionResult::Continue` - continue the main loop
/// - `ActionResult::Quit` - exit the application
/// - `ActionResult::RunEditor(PathBuf, Option<u32>)` - run editor on file at optional line
pub fn execute_action(&mut self, action: Action) -> ActionResult {
use Action::*;
match action {
// === Miscellaneous ===
Noop => {}
// === Application ===
Quit => {
// If in accepted outline search state, clear search instead of quitting
if self.show_search {
self.search_query.clear();
self.filter_outline();
self.show_search = false;
self.outline_search_active = false;
} else if self.has_unsaved_changes {
// Prompt to save before quitting
self.mode = AppMode::ConfirmSaveBeforeQuit;
} else {
return ActionResult::Quit;
}
}
Redraw => {
return ActionResult::Redraw;
}
// === Navigation ===
Next => {
let count = self.take_count();
if self.mode == AppMode::FilePicker {
for _ in 0..count {
self.next_file();
}
} else {
for _ in 0..count {
self.next();
}
}
}
Previous => {
let count = self.take_count();
if self.mode == AppMode::FilePicker {
for _ in 0..count {
self.previous_file();
}
} else {
for _ in 0..count {
self.previous();
}
}
}
First => {
self.clear_count();
self.first();
}
Last => {
self.clear_count();
self.last();
}
PageDown => {
self.clear_count();
if self.show_help {
self.scroll_help_page_down();
} else {
self.scroll_page_down();
}
}
PageUp => {
self.clear_count();
if self.show_help {
self.scroll_help_page_up();
} else {
self.scroll_page_up();
}
}
JumpToParent => {
self.clear_count();
self.jump_to_parent();
}
// === Outline ===
Expand => self.expand(),
Collapse => self.collapse(),
ToggleExpand => self.toggle_expand(),
ToggleFocus => self.toggle_focus(),
ToggleFocusBack => self.toggle_focus_back(),
ToggleOutline => self.toggle_outline(),
OutlineWidthIncrease => self.cycle_outline_width(true),
OutlineWidthDecrease => self.cycle_outline_width(false),
ToggleTodoFilter => self.toggle_todo_filter(),
// === Bookmarks ===
SetBookmark => self.set_bookmark(),
JumpToBookmark => self.jump_to_bookmark(),
// === Mode Transitions ===
EnterInteractiveMode => self.enter_interactive_mode(),
ExitInteractiveMode => self.exit_interactive_mode(),
EnterLinkFollowMode => self.enter_link_follow_mode(),
EnterSearchMode => self.toggle_search(),
EnterDocSearch => self.enter_doc_search(),
ToggleSearchMode => self.toggle_search_mode(),
ExitMode => self.exit_current_mode(),
OpenCommandPalette => self.open_command_palette(),
// === Link Navigation ===
NextLink => self.next_link(),
PreviousLink => self.previous_link(),
FollowLink => match self.mode {
AppMode::LinkFollow => {
if let Err(e) = self.follow_selected_link() {
self.status_message = Some(format!("✗ Error: {}", e));
}
self.update_content_metrics();
}
AppMode::FilePicker | AppMode::FileSearch => {
if let Err(e) = self.select_file_from_picker() {
self.status_message = Some(format!("✗ Error: {}", e));
}
self.update_content_metrics();
}
_ => {}
},
LinkSearch => match self.mode {
AppMode::LinkFollow => self.start_link_search(),
AppMode::FilePicker => {
self.file_search_active = true;
}
_ => {}
},
// === Interactive Mode ===
InteractiveNext => {
let count = self.take_count();
if self.interactive_state.is_in_table_mode() {
// In table mode, move down within table
let (rows, cols) = self.get_table_dimensions();
for _ in 0..count {
self.interactive_state.table_move_down(rows);
}
self.status_message =
Some(self.interactive_state.table_status_text(rows + 1, cols));
} else {
// Normal interactive mode, move to next element
for _ in 0..count {
self.interactive_state.next();
}
self.scroll_to_interactive_element(self.content_viewport_height);
self.status_message = Some(self.interactive_state.status_text());
}
}
InteractivePrevious => {
let count = self.take_count();
if self.interactive_state.is_in_table_mode() {
// In table mode, move up within table
let (rows, cols) = self.get_table_dimensions();
for _ in 0..count {
self.interactive_state.table_move_up();
}
self.status_message =
Some(self.interactive_state.table_status_text(rows + 1, cols));
} else {
// Normal interactive mode, move to previous element
for _ in 0..count {
self.interactive_state.previous();
}
self.scroll_to_interactive_element(self.content_viewport_height);
self.status_message = Some(self.interactive_state.status_text());
}
}
InteractiveActivate => {
self.clear_count();
// In table mode, Enter edits the cell; otherwise activate the element
if self.interactive_state.is_in_table_mode() {
if let Err(e) = self.enter_cell_edit_mode() {
self.status_message = Some(format!("✗ Error: {}", e));
}
} else if let Err(e) = self.activate_interactive_element() {
self.status_message = Some(format!("✗ Error: {}", e));
}
self.update_content_metrics();
}
InteractiveNextLink => {
let count = self.take_count();
for _ in 0..count {
self.interactive_state.next();
}
self.scroll_to_interactive_element(self.content_viewport_height);
self.status_message = Some(self.interactive_state.status_text());
}
InteractivePreviousLink => {
let count = self.take_count();
for _ in 0..count {
self.interactive_state.previous();
}
self.scroll_to_interactive_element(self.content_viewport_height);
self.status_message = Some(self.interactive_state.status_text());
}
InteractiveLeft => {
let count = self.take_count();
for _ in 0..count {
self.table_navigate_left();
}
}
InteractiveRight => {
let count = self.take_count();
for _ in 0..count {
self.table_navigate_right();
}
}
// === View ===
ToggleRawSource => self.toggle_raw_source(),
ToggleHelp => self.toggle_help(),
ToggleThemePicker => self.toggle_theme_picker(),
ApplyTheme => self.apply_selected_theme(),
// === Clipboard ===
CopyContent => self.copy_content(),
CopyAnchor => self.copy_anchor(),
// === File Operations ===
GoBack => {
// Check if there's anything to go back to
if self.file_history.is_empty() {
return ActionResult::Continue;
}
// Check for unsaved changes
if self.has_unsaved_changes {
self.pending_navigation = Some(PendingNavigation::Back);
self.mode = AppMode::ConfirmSaveBeforeNav;
} else if self.go_back().is_ok() {
self.update_content_metrics();
}
}
GoForward => {
// Check if there's anything to go forward to
if self.file_future.is_empty() {
return ActionResult::Continue;
}
// Check for unsaved changes
if self.has_unsaved_changes {
self.pending_navigation = Some(PendingNavigation::Forward);
self.mode = AppMode::ConfirmSaveBeforeNav;
} else if self.go_forward().is_ok() {
self.update_content_metrics();
}
}
OpenInEditor => {
let line = if self.mode == AppMode::Interactive {
// In interactive mode, jump to the current element's source line
self.interactive_element_source_line()
.or_else(|| self.selected_heading_source_line())
} else {
self.selected_heading_source_line()
};
return ActionResult::RunEditor(self.current_file_path.clone(), line);
}
UndoEdit => {
self.clear_count();
if let Err(e) = self.undo_last_edit() {
self.status_message = Some(format!("✗ Undo failed: {}", e));
}
}
OpenFilePicker => {
self.enter_file_picker();
}
ParentDirectory => {
self.file_picker_parent_dir();
}
ToggleHidden => {
self.show_hidden = !self.show_hidden;
self.scan_markdown_files();
}
// === Dialog Actions ===
ConfirmAction => {
if let Some(result) = self.handle_confirm_action() {
return result;
}
}
CancelAction => self.handle_cancel_action(),
DiscardAndQuit => {
if let Some(result) = self.handle_discard_and_quit() {
return result;
}
}
DiscardAndContinue => {
self.handle_discard_and_continue();
}
// === Jump to Heading by Number ===
JumpToHeading1 => self.jump_to_heading(0),
JumpToHeading2 => self.jump_to_heading(1),
JumpToHeading3 => self.jump_to_heading(2),
JumpToHeading4 => self.jump_to_heading(3),
JumpToHeading5 => self.jump_to_heading(4),
JumpToHeading6 => self.jump_to_heading(5),
JumpToHeading7 => self.jump_to_heading(6),
JumpToHeading8 => self.jump_to_heading(7),
JumpToHeading9 => self.jump_to_heading(8),
// === Jump to Link by Number ===
JumpToLink1 => self.jump_to_link(0),
JumpToLink2 => self.jump_to_link(1),
JumpToLink3 => self.jump_to_link(2),
JumpToLink4 => self.jump_to_link(3),
JumpToLink5 => self.jump_to_link(4),
JumpToLink6 => self.jump_to_link(5),
JumpToLink7 => self.jump_to_link(6),
JumpToLink8 => self.jump_to_link(7),
JumpToLink9 => self.jump_to_link(8),
// === Scroll (Content pane) ===
ScrollDown => {
let count = self.take_count();
for _ in 0..count {
self.scroll_content_down();
}
}
ScrollUp => {
let count = self.take_count();
for _ in 0..count {
self.scroll_content_up();
}
}
// === Help Navigation ===
HelpScrollDown => {
self.clear_count();
self.scroll_help_down();
}
HelpScrollUp => {
self.clear_count();
self.scroll_help_up();
}
// === Theme Picker Navigation ===
ThemePickerNext => self.theme_picker_next(),
ThemePickerPrevious => self.theme_picker_previous(),
// === Search Input ===
SearchBackspace => self.handle_search_backspace(),
// === Command Palette ===
CommandPaletteNext => self.command_palette_next(),
CommandPalettePrev => self.command_palette_prev(),
CommandPaletteAutocomplete => self.command_palette_autocomplete(),
// === Doc Search Navigation ===
NextMatch => self.next_doc_match(),
PrevMatch => self.prev_doc_match(),
}
ActionResult::Continue
}
/// Exit the current mode based on app state
fn exit_current_mode(&mut self) {
// Close image modal if open
if self.is_image_modal_open() {
self.close_image_modal();
self.status_message = Some("Image modal closed".to_string());
return;
}
// Handle outline search - clear everything
if self.show_search {
self.search_query.clear();
self.filter_outline();
self.show_search = false;
self.outline_search_active = false;
return;
}
match self.mode {
AppMode::Interactive => {
// If in table mode, exit table mode first (stay in interactive)
if self.interactive_state.is_in_table_mode() {
self.interactive_state.exit_table_mode();
self.status_message = Some(self.interactive_state.status_text());
} else {
self.exit_interactive_mode();
}
}
AppMode::LinkFollow => {
if self.link_search_active {
self.stop_link_search();
} else if !self.link_search_query.is_empty() {
self.clear_link_search();
} else {
self.exit_link_follow_mode();
}
}
AppMode::Search => {
self.search_query.clear();
self.filter_outline();
self.show_search = false;
}
AppMode::DocSearch => {
if self.doc_search_active {
self.cancel_doc_search();
} else {
self.clear_doc_search();
}
}
AppMode::CommandPalette => self.close_command_palette(),
AppMode::CellEdit => {
self.mode = AppMode::Interactive;
self.status_message = Some("Editing cancelled".to_string());
}
AppMode::ThemePicker => {
// Close theme picker (restores original theme)
self.toggle_theme_picker();
}
AppMode::Help => {
// Close help
self.show_help = false;
}
AppMode::FileSearch => {
self.file_search_active = false;
self.mode = AppMode::FilePicker;
}
AppMode::FilePicker => {
if self.file_search_active {
// Exit search mode, but stay in file picker
self.file_search_active = false;
self.file_search_query.clear();
} else {
// Exit file picker entirely
self.mode = AppMode::Normal;
self.file_search_query.clear();
self.file_search_active = false;
}
}
AppMode::Normal
| AppMode::ConfirmFileCreate
| AppMode::ConfirmSaveWidth
| AppMode::ConfirmSaveBeforeQuit
| AppMode::ConfirmSaveBeforeNav => {
// In normal mode, show hint for quitting
self.set_status_message("Press q to quit • : for commands • ? for help");
}
}
}
/// Handle confirm action based on current mode
/// Returns Some(ActionResult) if the action should return early (e.g., quit)
fn handle_confirm_action(&mut self) -> Option<ActionResult> {
// Handle outline search - accept and keep filtered results visible
if self.show_search && self.outline_search_active {
// Check if there are any matches (filtered items with matching text)
let has_matches = if self.search_query.is_empty() {
true // Empty query matches everything
} else {
// Check if any outline items match the query
!self.outline_items.is_empty()
};
if has_matches {
// Accept search - deactivate input but keep filter visible
self.outline_search_active = false;
// show_search stays true to keep highlights visible
// User can now navigate with j/k, n/N, or press 's' to start new search
} else {
// No matches - show status message and clear search
self.status_message = Some(format!("Pattern not found: {}", self.search_query));
self.show_search = false;
self.outline_search_active = false;
self.search_query.clear();
self.filter_outline(); // Restore full outline
}
return None;
}
match self.mode {
AppMode::ConfirmFileCreate => {
if let Err(e) = self.confirm_file_create() {
self.status_message = Some(format!("✗ Error: {}", e));
}
}
AppMode::ConfirmSaveWidth => self.confirm_save_outline_width(),
AppMode::ConfirmSaveBeforeQuit => {
// Save pending changes and quit
if let Err(e) = self.save_pending_edits_to_file() {
self.status_message = Some(format!("✗ Save failed: {}", e));
self.mode = AppMode::Normal;
} else {
return Some(ActionResult::Quit);
}
}
AppMode::ConfirmSaveBeforeNav => {
// Save pending changes and then navigate
if let Err(e) = self.save_pending_edits_to_file() {
self.status_message = Some(format!("✗ Save failed: {}", e));
self.mode = AppMode::Normal;
self.pending_navigation = None;
} else {
// Execute the pending navigation
self.execute_pending_navigation();
}
}
AppMode::Search => self.show_search = false,
AppMode::DocSearch => self.accept_doc_search(),
AppMode::CommandPalette => {
// Execute command - Quit is handled separately
let should_quit = self.execute_selected_command();
if should_quit {
return Some(ActionResult::Quit);
}
}
AppMode::CellEdit => {
if let Err(e) = self.save_edited_cell() {
self.status_message = Some(format!("✗ Error saving: {}", e));
} else {
self.mode = AppMode::Interactive;
}
}
_ => {}
}
None
}
/// Handle cancel action based on current mode
fn handle_cancel_action(&mut self) {
match self.mode {
AppMode::ConfirmFileCreate => self.cancel_file_create(),
AppMode::ConfirmSaveWidth => self.cancel_save_width_confirmation(),
AppMode::ConfirmSaveBeforeQuit => {
// Cancel quit - go back to normal mode
self.mode = AppMode::Normal;
self.status_message = Some("Quit cancelled".to_string());
}
AppMode::ConfirmSaveBeforeNav => {
// Cancel navigation - go back to normal mode
self.mode = AppMode::Normal;
self.pending_navigation = None;
self.status_message = Some("Navigation cancelled".to_string());
}
_ => self.exit_current_mode(),
}
}
/// Handle discard and quit action (quit without saving)
fn handle_discard_and_quit(&mut self) -> Option<ActionResult> {
match self.mode {
AppMode::ConfirmSaveBeforeQuit => {
// Discard changes and quit
self.pending_edits.clear();
self.has_unsaved_changes = false;
Some(ActionResult::Quit)
}
AppMode::ConfirmSaveBeforeNav => {
// Discard changes and quit (instead of navigating)
self.pending_edits.clear();
self.has_unsaved_changes = false;
self.pending_navigation = None;
Some(ActionResult::Quit)
}
_ => None,
}
}
/// Handle discard and continue action (discard changes and proceed with navigation)
fn handle_discard_and_continue(&mut self) {
match self.mode {
AppMode::ConfirmSaveBeforeNav => {
// Discard changes and navigate
self.pending_edits.clear();
self.has_unsaved_changes = false;
self.execute_pending_navigation();
}
AppMode::ConfirmSaveBeforeQuit => {
// In quit dialog, 'd' doesn't make sense - ignore or treat as quit
// We'll ignore for now, user should use 'q' for quit without saving
}
_ => {}
}
}
/// Execute the pending navigation action
fn execute_pending_navigation(&mut self) {
let nav = self.pending_navigation.take();
self.mode = AppMode::Normal;
match nav {
Some(PendingNavigation::Back) => {
if self.go_back().is_ok() {
self.update_content_metrics();
}
}
Some(PendingNavigation::Forward) => {
if self.go_forward().is_ok() {
self.update_content_metrics();
}
}
Some(PendingNavigation::LoadFile(path, anchor)) => {
// Call internal load_file_internal that skips the unsaved check
if let Err(e) = self.load_file_internal(&path, anchor.as_deref()) {
self.status_message = Some(format!("✗ {}", e));
}
}
None => {}
}
}
/// Handle backspace in search contexts
fn handle_search_backspace(&mut self) {
// Handle outline search - only if active
if self.show_search && self.outline_search_active {
self.search_backspace();
return;
}
match self.mode {
AppMode::Search => self.search_backspace(),
AppMode::DocSearch => self.doc_search_backspace(),
AppMode::LinkFollow if self.link_search_active => self.link_search_pop(),
AppMode::FilePicker if self.file_search_active => {
if self.file_search_query.is_empty() {
// Empty search query + Backspace => navigate to parent directory
self.file_picker_parent_dir();
} else {
self.file_search_pop();
}
}
AppMode::CommandPalette => self.command_palette_backspace(),
AppMode::CellEdit => {
self.cell_edit_value.pop();
}
_ => {}
}
}
/// Navigate table left
fn table_navigate_left(&mut self) {
if !self.interactive_state.is_in_table_mode() {
return;
}
let (rows, cols) = self.get_table_dimensions();
if cols > 0 {
self.interactive_state.table_move_left();
self.status_message = Some(self.interactive_state.table_status_text(rows + 1, cols));
}
}
/// Navigate table right
fn table_navigate_right(&mut self) {
if !self.interactive_state.is_in_table_mode() {
return;
}
let (rows, cols) = self.get_table_dimensions();
if cols > 0 {
self.interactive_state.table_move_right(cols);
self.status_message = Some(self.interactive_state.table_status_text(rows + 1, cols));
}
}
/// Get table dimensions for current interactive element
fn get_table_dimensions(&self) -> (usize, usize) {
if let Some(element) = self.interactive_state.current_element()
&& let crate::tui::interactive::ElementType::Table { rows, cols, .. } =
&element.element_type
{
return (*rows, *cols);
}
(0, 0)
}
/// Maximum scroll offset: stops when last line is at bottom of viewport
pub fn max_content_scroll(&self) -> u16 {
let viewport = self.content_viewport_height as usize;
self.content_height
.saturating_sub(viewport)
.min(u16::MAX as usize) as u16
}
/// Scroll content down by one line
fn scroll_content_down(&mut self) {
let max_scroll = self.max_content_scroll();
let new_scroll = self.content_scroll.saturating_add(1);
if new_scroll <= max_scroll {
self.content_scroll = new_scroll;
self.content_scroll_state = self.content_scroll_state.position(new_scroll as usize);
}
}
/// Scroll content up by one line
fn scroll_content_up(&mut self) {
let new_scroll = self.content_scroll.saturating_sub(1);
self.content_scroll = new_scroll;
self.content_scroll_state = self.content_scroll_state.position(new_scroll as usize);
}
/// Jump to link by index in filtered list
fn jump_to_link(&mut self, idx: usize) {
if let Some(display_idx) = self.filtered_link_indices.iter().position(|&i| i == idx) {
self.selected_link_idx = Some(display_idx);
}
}
/// Toggle between raw source view and rendered markdown view
pub fn toggle_raw_source(&mut self) {
self.show_raw_source = !self.show_raw_source;
let msg = if self.show_raw_source {
"Raw source view enabled"
} else {
"Rendered view enabled"
};
self.set_status_message(msg);
}
/// Set a status message with automatic timeout tracking
pub fn set_status_message(&mut self, msg: &str) {
self.status_message = Some(msg.to_string());
self.status_message_time = Some(Instant::now());
}
/// Clear status message if it has expired (default 1 second timeout)
pub fn clear_expired_status_message(&mut self) {
const STATUS_MESSAGE_TIMEOUT: Duration = Duration::from_secs(1);
if let Some(time) = self.status_message_time
&& time.elapsed() >= STATUS_MESSAGE_TIMEOUT
{
self.status_message = None;
self.status_message_time = None;
}
}
/// Accumulate a digit into the vim-style count prefix
/// Returns true if the digit was handled as a count prefix
pub fn accumulate_count_digit(&mut self, digit: char) -> bool {
if let Some(d) = digit.to_digit(10) {
let current = self.count_prefix.unwrap_or(0);
// Limit to reasonable count (max 9999)
let new_count = current
.saturating_mul(10)
.saturating_add(d as usize)
.min(9999);
self.count_prefix = Some(new_count);
true
} else {
false
}
}
/// Get and consume the count prefix, returning at least 1
pub fn take_count(&mut self) -> usize {
self.count_prefix.take().unwrap_or(1)
}
/// Clear the count prefix without consuming it
pub fn clear_count(&mut self) {
self.count_prefix = None;
}
/// Check if there's an active count prefix
pub fn has_count(&self) -> bool {
self.count_prefix.is_some()
}
/// Check if the document has non-whitespace content before the first heading
fn has_preamble_content(document: &Document) -> bool {
if document.headings.is_empty() {
// No headings at all - entire document is preamble
return !document.content.trim().is_empty();
}
// Check if there's content before the first heading
let first_heading_offset = document.headings[0].offset;
if first_heading_offset == 0 {
return false;
}
// Check if there's non-whitespace content before the first heading
let preamble = &document.content[..first_heading_offset];
!preamble.trim().is_empty()
}
/// Check if a heading's section contains open todos (- [ ])
fn heading_has_open_todos(&self, heading_text: &str) -> bool {
if let Some(content) = self.document.extract_section(heading_text) {
// Check for unchecked todo pattern: - [ ] or * [ ]
content.contains("- [ ]") || content.contains("* [ ]")
} else {
false
}
}
/// Check if a heading or any of its descendants have open todos
fn heading_tree_has_open_todos(&self, node: &HeadingNode) -> bool {
// Check this heading's direct content
if self.heading_has_open_todos(&node.heading.text) {
return true;
}
// Recursively check children
for child in &node.children {
if self.heading_tree_has_open_todos(child) {
return true;
}
}
false
}
/// Build a set of heading texts that have open todos (directly or in descendants)
fn headings_with_open_todos(&self) -> HashSet<String> {
let mut result = HashSet::new();
for node in &self.tree {
self.collect_headings_with_todos(node, &mut result);
}
result
}
/// Recursively collect headings that should be shown when filtering by todos
fn collect_headings_with_todos(&self, node: &HeadingNode, result: &mut HashSet<String>) {
if self.heading_tree_has_open_todos(node) {
// This heading or a descendant has todos, include it
result.insert(node.heading.text.clone());
// Also recursively add children that have todos
for child in &node.children {
self.collect_headings_with_todos(child, result);
}
}
}
/// Rebuild outline items from the tree, optionally adding document overview
fn rebuild_outline_items(&mut self) {
let mut items = Self::flatten_tree(&self.tree, &self.collapsed_headings);
// Apply todo filter if enabled
if self.filter_by_todos {
let headings_with_todos = self.headings_with_open_todos();
items.retain(|item| headings_with_todos.contains(&item.text));
}
self.outline_items = items;
// Add document overview entry if there's preamble content or no headings
// When filtering by todos, only show overview if it has todos
let has_preamble = Self::has_preamble_content(&self.document);
let preamble_has_todos = self.filter_by_todos
&& self
.document
.content
.split_once("\n#")
.is_some_and(|(preamble, _)| {
preamble.contains("- [ ]") || preamble.contains("* [ ]")
});
let show_preamble = (!self.filter_by_todos
&& (has_preamble || self.document.headings.is_empty()))
|| (self.filter_by_todos && preamble_has_todos);
if show_preamble {
self.outline_items.insert(
0,
OutlineItem {
level: 0,
text: DOCUMENT_OVERVIEW.to_string(),
expanded: true,
has_children: !self.outline_items.is_empty(),
},
);
}
}
fn flatten_tree(
tree: &[HeadingNode],
collapsed_headings: &HashSet<String>,
) -> Vec<OutlineItem> {
let mut items = Vec::new();
fn flatten_recursive(
node: &HeadingNode,
items: &mut Vec<OutlineItem>,
collapsed_headings: &HashSet<String>,
) {
let is_collapsed = collapsed_headings.contains(&node.heading.text);
let expanded = !is_collapsed;
let has_children = !node.children.is_empty();
items.push(OutlineItem {
level: node.heading.level,
text: node.heading.text.clone(),
expanded,
has_children,
});
// Only show children if this node is expanded
if expanded {
for child in &node.children {
flatten_recursive(child, items, collapsed_headings);
}
}
}
for node in tree {
flatten_recursive(node, &mut items, collapsed_headings);
}
items
}
/// Select an outline item by index, updating both selection and scroll state.
fn select_outline_index(&mut self, idx: usize) {
self.outline_state.select(Some(idx));
self.outline_scroll_state = self.outline_scroll_state.position(idx);
}
/// Select a heading by its text. Returns true if found and selected.
fn select_by_text(&mut self, text: &str) -> bool {
for (idx, item) in self.outline_items.iter().enumerate() {
if item.text == text {
self.select_outline_index(idx);
return true;
}
}
false
}
/// Update content height based on current selection and reset scroll if selection changed
pub fn update_content_metrics(&mut self) {
let current_selection = self.selected_heading_text().map(|s| s.to_string());
// Check if selection changed
if current_selection != self.previous_selection {
// Reset content scroll when selection changes
self.content_scroll = 0;
self.previous_selection = current_selection;
// Reindex interactive elements for the new section
let content_text = self.current_section_content();
use crate::parser::content::parse_content;
let blocks = parse_content(&content_text, 0);
self.interactive_state.index_elements(&blocks);
self.populate_image_cache();
}
// Update content height based on current section
let content_text = self.current_section_content();
let content_lines = content_text.lines().count();
self.content_height = content_lines;
self.content_scroll_state =
ScrollbarState::new(content_lines).position(self.content_scroll as usize);
}
pub fn next(&mut self) {
if self.focus == Focus::Outline {
let i = match self.outline_state.selected() {
Some(i) => {
if i >= self.outline_items.len().saturating_sub(1) {
i
} else {
i + 1
}
}
None => 0,
};
self.select_outline_index(i);
} else {
// Scroll content - stop when last line is at viewport bottom
self.scroll_content_down();
}
}
pub fn previous(&mut self) {
if self.focus == Focus::Outline {
let i = match self.outline_state.selected() {
Some(i) => i.saturating_sub(1),
None => 0,
};
self.select_outline_index(i);
} else {
// Scroll content
self.scroll_content_up();
}
}
pub fn first(&mut self) {
if self.mode == AppMode::FilePicker {
let total = self.file_picker_item_count();
if total > 0 {
self.selected_file_idx = Some(0);
}
} else if self.focus == Focus::Outline && !self.outline_items.is_empty() {
self.select_outline_index(0);
} else {
self.content_scroll = 0;
self.content_scroll_state = self.content_scroll_state.position(0);
}
}
pub fn last(&mut self) {
if self.mode == AppMode::FilePicker {
let total = self.file_picker_item_count();
if total > 0 {
self.selected_file_idx = Some(total - 1);
}
} else if self.focus == Focus::Outline && !self.outline_items.is_empty() {
let last = self.outline_items.len() - 1;
self.select_outline_index(last);
} else {
// Scroll to show the last line at the bottom of the viewport
let max_scroll = self.max_content_scroll();
self.content_scroll = max_scroll;
self.content_scroll_state = self.content_scroll_state.position(max_scroll as usize);
}
}
pub fn jump_to_parent(&mut self) {
// Works in both Outline and Content focus
if let Some(current_idx) = self.outline_state.selected()
&& current_idx < self.outline_items.len()
{
let current_level = self.outline_items[current_idx].level;
// Search backwards for a heading with lower level (parent)
for i in (0..current_idx).rev() {
if self.outline_items[i].level < current_level {
self.select_outline_index(i);
return;
}
}
// If no parent found, stay at current position
// (we're already at a top-level heading or first item)
}
}
pub fn toggle_help(&mut self) {
self.show_help = !self.show_help;
if self.show_help {
self.help_scroll = 0; // Reset scroll when opening help
}
}
pub fn scroll_help_down(&mut self) {
let new_scroll = self.help_scroll.saturating_add(1);
let max_scroll = help_text::HELP_LINES.len() as u16;
if new_scroll < max_scroll {
self.help_scroll = new_scroll;
}
}
pub fn scroll_help_up(&mut self) {
self.help_scroll = self.help_scroll.saturating_sub(1);
}
/// Scroll help popup down by a page
pub fn scroll_help_page_down(&mut self) {
let page_size = self.content_viewport_height.saturating_sub(2).max(1);
let new_scroll = self.help_scroll.saturating_add(page_size);
let max_scroll = help_text::HELP_LINES.len() as u16;
if new_scroll < max_scroll {
self.help_scroll = new_scroll;
}
}
/// Scroll help popup up by a page
pub fn scroll_help_page_up(&mut self) {
let page_size = self.content_viewport_height.saturating_sub(2).max(1);
self.help_scroll = self.help_scroll.saturating_sub(page_size);
}
pub fn toggle_search(&mut self) {
if self.show_search && self.outline_search_active {
// If actively typing in search, toggle it off (clear and hide)
self.show_search = false;
self.outline_search_active = false;
self.search_query.clear();
self.filter_outline();
} else if self.show_search {
// In accepted search state (showing filtered results) - start fresh search
self.search_query.clear();
self.filter_outline(); // Restore full outline for new search
self.outline_search_active = true; // Re-enter input mode
} else {
// Enter search mode from normal state
self.show_search = true;
self.outline_search_active = true;
self.search_query.clear();
}
}
/// Toggle between outline search and document search, preserving the query.
/// After search is accepted (Enter pressed), Tab cycles through matches instead.
pub fn toggle_search_mode(&mut self) {
if self.show_search {
// Currently in outline search -> switch to doc search
let query = self.search_query.clone();
let was_active = self.outline_search_active;
self.show_search = false;
self.outline_search_active = false;
self.search_query.clear();
self.filter_outline(); // Reset outline filter
// Enter doc search with the same query
self.mode = AppMode::DocSearch;
self.doc_search_active = was_active; // Preserve active state
self.doc_search_query = query;
self.doc_search_matches.clear();
self.doc_search_current_idx = None;
self.update_doc_search_matches();
} else if self.mode == AppMode::DocSearch {
if self.doc_search_active {
// Still typing -> switch to outline search
let query = self.doc_search_query.clone();
self.mode = AppMode::Normal;
self.doc_search_active = false;
self.doc_search_query.clear();
self.doc_search_matches.clear();
self.doc_search_current_idx = None;
// Enter outline search with the same query
self.show_search = true;
self.outline_search_active = true; // Keep input active
self.search_query = query;
self.filter_outline();
} else {
// Search accepted (after Enter) -> cycle through matches
self.next_doc_match();
}
}
}
/// Maximum search query length to prevent performance issues
const MAX_SEARCH_LEN: usize = 256;
pub fn search_input(&mut self, c: char) {
// Limit search query length
if self.search_query.len() >= Self::MAX_SEARCH_LEN {
return;
}
// Filter control characters (except common ones)
if c.is_control() && c != '\t' {
return;
}
self.search_query.push(c);
self.filter_outline();
}
pub fn search_backspace(&mut self) {
self.search_query.pop();
self.filter_outline();
}
pub fn filter_outline(&mut self) {
// Save current selection text
let current_selection = self.selected_heading_text().map(|s| s.to_string());
if self.search_query.is_empty() {
// Reset to full tree with overview entry
self.rebuild_outline_items();
} else {
// Filter by search query, but always include overview entry if applicable
let query_lower = self.search_query.to_lowercase();
let has_preamble = Self::has_preamble_content(&self.document);
self.outline_items = Self::flatten_tree(&self.tree, &self.collapsed_headings)
.into_iter()
.filter(|item| item.text.to_lowercase().contains(&query_lower))
.collect();
// Add overview entry if it matches the search or if document has preamble
if (has_preamble || self.document.headings.is_empty())
&& DOCUMENT_OVERVIEW.to_lowercase().contains(&query_lower)
{
self.outline_items.insert(
0,
OutlineItem {
level: 0,
text: DOCUMENT_OVERVIEW.to_string(),
expanded: true,
has_children: !self.tree.is_empty(),
},
);
}
}
// Try to restore previous selection, otherwise select first item
if !self.outline_items.is_empty() {
let restored = if let Some(text) = current_selection {
self.select_by_text(&text)
} else {
false
};
if !restored {
self.outline_state.select(Some(0));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(0);
}
}
}
// ========== Document Search Methods ==========
/// Enter document search mode (activated by / when content is focused or in interactive mode)
/// If in accepted outline search state, re-enter outline search input instead
/// If already in accepted doc search state, re-enter doc search input
pub fn enter_doc_search(&mut self) {
// If in accepted outline search state (locked-in filter), re-enter outline search input
if self.show_search && !self.outline_search_active {
// Re-activate outline search input (keep existing query for editing)
self.outline_search_active = true;
return;
}
// If already in accepted doc search state, re-enter input mode (keep existing query)
if self.mode == AppMode::DocSearch && !self.doc_search_active {
self.doc_search_active = true;
return;
}
// Remember if we came from interactive mode to restore it later
self.doc_search_from_interactive = self.mode == AppMode::Interactive;
self.mode = AppMode::DocSearch;
self.doc_search_active = true;
self.doc_search_query.clear();
self.doc_search_matches.clear();
self.doc_search_current_idx = None;
}
/// Add a character to the document search query
pub fn doc_search_input(&mut self, c: char) {
// Limit search query length
if self.doc_search_query.len() >= Self::MAX_SEARCH_LEN {
return;
}
// Filter control characters
if c.is_control() && c != '\t' {
return;
}
self.doc_search_query.push(c);
self.update_doc_search_matches();
}
/// Remove the last character from the document search query
pub fn doc_search_backspace(&mut self) {
self.doc_search_query.pop();
self.update_doc_search_matches();
}
/// Update search matches based on current query (supports fuzzy and exact matching)
pub fn update_doc_search_matches(&mut self) {
self.doc_search_matches.clear();
if self.doc_search_query.is_empty() {
self.doc_search_current_idx = None;
return;
}
// Get current section content
let content = self.current_section_content();
// Convert to plain text using parser (strips links, formatting, etc.)
// This ensures search matches what's visible when rendered
let plain_content = turbovault_parser::to_plain_text(&content);
let query = self.doc_search_query.to_lowercase();
// Find all exact substring matches (case-insensitive)
for (line_num, line) in plain_content.lines().enumerate() {
let line_lower = line.to_lowercase();
let mut search_start = 0;
while let Some(pos) = line_lower[search_start..].find(&query) {
let col_start = search_start + pos;
self.doc_search_matches.push(SearchMatch {
line: line_num,
col_start,
len: query.len(),
});
search_start = col_start + query.len();
}
}
// Select first match if any exist
self.doc_search_current_idx = if self.doc_search_matches.is_empty() {
None
} else {
Some(0)
};
// Scroll to current match
self.scroll_to_doc_search_match();
}
/// Scroll to the current search match and detect if it's inside a link
fn scroll_to_doc_search_match(&mut self) {
// Reset link selection
self.doc_search_selected_link_idx = None;
if let Some(idx) = self.doc_search_current_idx
&& let Some(m) = self.doc_search_matches.get(idx)
{
let match_line = m.line as u16;
// Scroll to bring match line into view (center it if possible)
let half_viewport = self.content_viewport_height / 2;
self.content_scroll = match_line.saturating_sub(half_viewport);
self.content_scroll = self.content_scroll.min(self.max_content_scroll());
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
// Check if this match is inside a link
self.detect_link_at_search_match(m.line, m.col_start, m.len);
}
}
/// Detect if a search match position overlaps with a link and select it
fn detect_link_at_search_match(
&mut self,
match_line: usize,
match_col: usize,
match_len: usize,
) {
use crate::parser::links::extract_links;
// Get current section content
let content = self.current_section_content();
// Convert line/col to byte offset
let mut byte_offset = 0;
for (line_num, line) in content.lines().enumerate() {
if line_num == match_line {
byte_offset += match_col;
break;
}
byte_offset += line.len() + 1; // +1 for newline
}
let match_end = byte_offset + match_len;
// Extract links and populate links_in_view for potential following
self.links_in_view = extract_links(&content);
self.filtered_link_indices = (0..self.links_in_view.len()).collect();
// Find if match overlaps with any link
for (idx, link) in self.links_in_view.iter().enumerate() {
let link_start = link.offset;
// Estimate link end based on its display text length + some syntax overhead
// For markdown: [text](url) - we care about the text portion
// For wikilinks: [[target|text]] - we care about the display text
let link_end = link_start + link.text.len() + 20; // generous estimate for syntax
// Check if match overlaps with link region
if byte_offset < link_end && match_end > link_start {
self.doc_search_selected_link_idx = Some(idx);
self.selected_link_idx = Some(idx); // Also set link mode selection
break;
}
}
}
/// Accept search and exit search input mode (keep matches for n/N navigation)
pub fn accept_doc_search(&mut self) {
self.doc_search_active = false;
// Keep mode as DocSearch for n/N navigation
// If no matches, show status message
if self.doc_search_matches.is_empty() && !self.doc_search_query.is_empty() {
self.status_message = Some(format!("Pattern not found: {}", self.doc_search_query));
}
}
/// Cancel search and return to previous mode (interactive or normal)
pub fn cancel_doc_search(&mut self) {
// Restore interactive mode if that's where we came from
if self.doc_search_from_interactive {
self.mode = AppMode::Interactive;
} else {
self.mode = AppMode::Normal;
}
self.doc_search_active = false;
self.doc_search_from_interactive = false;
self.doc_search_query.clear();
self.doc_search_matches.clear();
self.doc_search_current_idx = None;
self.doc_search_selected_link_idx = None;
// Sync to prevent update_content_metrics() from resetting scroll
self.sync_previous_selection();
}
/// Clear search highlighting and return to previous mode (interactive or normal)
pub fn clear_doc_search(&mut self) {
// Restore interactive mode if that's where we came from
if self.doc_search_from_interactive {
self.mode = AppMode::Interactive;
} else {
self.mode = AppMode::Normal;
}
self.doc_search_from_interactive = false;
self.doc_search_query.clear();
self.doc_search_matches.clear();
self.doc_search_current_idx = None;
self.doc_search_selected_link_idx = None;
// Sync to prevent update_content_metrics() from resetting scroll
self.sync_previous_selection();
}
/// Navigate to next search match
/// Handles both doc search matches and accepted outline search navigation
pub fn next_doc_match(&mut self) {
// Check if in accepted outline search state (filtered outline visible)
if self.show_search && !self.outline_search_active && !self.outline_items.is_empty() {
// Cycle through filtered outline items
let current = self.outline_state.selected().unwrap_or(0);
let next = (current + 1) % self.outline_items.len();
self.select_outline_index(next);
return;
}
if self.doc_search_matches.is_empty() {
return;
}
self.doc_search_current_idx = Some(match self.doc_search_current_idx {
Some(idx) => (idx + 1) % self.doc_search_matches.len(),
None => 0,
});
self.scroll_to_doc_search_match();
}
/// Navigate to previous search match
/// Handles both doc search matches and accepted outline search navigation
pub fn prev_doc_match(&mut self) {
// Check if in accepted outline search state (filtered outline visible)
if self.show_search && !self.outline_search_active && !self.outline_items.is_empty() {
// Cycle through filtered outline items
let current = self.outline_state.selected().unwrap_or(0);
let len = self.outline_items.len();
let prev = (current + len - 1) % len;
self.select_outline_index(prev);
return;
}
if self.doc_search_matches.is_empty() {
return;
}
let len = self.doc_search_matches.len();
self.doc_search_current_idx = Some(match self.doc_search_current_idx {
Some(idx) => (idx + len - 1) % len,
None => len - 1,
});
self.scroll_to_doc_search_match();
}
/// Get document search status text for status bar
pub fn doc_search_status(&self) -> String {
if self.doc_search_matches.is_empty() {
if self.doc_search_query.is_empty() {
"Search: ".to_string()
} else {
format!("Search: {} (no matches)", self.doc_search_query)
}
} else {
let current = self.doc_search_current_idx.unwrap_or(0) + 1;
let total = self.doc_search_matches.len();
let base = format!("Search: {} ({}/{})", self.doc_search_query, current, total);
// Add link indicator if match is inside a link
if let Some(link_idx) = self.doc_search_selected_link_idx {
if let Some(link) = self.links_in_view.get(link_idx) {
format!("{} → [{}] (Enter to follow)", base, link.text)
} else {
base
}
} else {
base
}
}
}
pub fn scroll_page_down(&mut self) {
if self.focus == Focus::Content {
let page = self.content_viewport_height.saturating_sub(2).max(1);
let new_scroll = self.content_scroll.saturating_add(page);
self.content_scroll = new_scroll.min(self.max_content_scroll());
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
}
}
pub fn scroll_page_up(&mut self) {
if self.focus == Focus::Content {
let page = self.content_viewport_height.saturating_sub(2).max(1);
self.content_scroll = self.content_scroll.saturating_sub(page);
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
}
}
/// Scroll page down in interactive mode (bypasses focus check)
pub fn scroll_page_down_interactive(&mut self) {
let page = self.content_viewport_height.saturating_sub(2).max(1);
let new_scroll = self.content_scroll.saturating_add(page);
self.content_scroll = new_scroll.min(self.max_content_scroll());
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
}
/// Scroll page up in interactive mode (bypasses focus check)
pub fn scroll_page_up_interactive(&mut self) {
let page = self.content_viewport_height.saturating_sub(2).max(1);
self.content_scroll = self.content_scroll.saturating_sub(page);
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
}
/// Auto-scroll to keep the selected interactive element in view
/// viewport_height: height of the visible content area (in lines)
pub fn scroll_to_interactive_element(&mut self, viewport_height: u16) {
if let Some((start_line, end_line)) = self.interactive_state.current_element_line_range() {
let start = start_line as u16;
let end = end_line as u16;
let scroll = self.content_scroll;
let viewport_end = scroll.saturating_add(viewport_height);
// Add margin for smoother scrolling - trigger before element goes completely off-screen
let scroll_margin = 2u16.min(viewport_height / 4);
// Element is above viewport (or too close to top margin) - scroll up
if start < scroll.saturating_add(scroll_margin) {
self.content_scroll = start.saturating_sub(scroll_margin);
}
// Element end is below viewport (or within bottom margin) - scroll down
else if end.saturating_add(scroll_margin) > viewport_end {
// Position so element's end is near bottom of viewport with margin
let new_scroll = end
.saturating_add(scroll_margin)
.saturating_sub(viewport_height);
self.content_scroll = new_scroll.min(self.max_content_scroll());
}
// Update scrollbar state
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
}
}
pub fn toggle_expand(&mut self) {
if self.focus == Focus::Outline
&& let Some(i) = self.outline_state.selected()
&& i < self.outline_items.len()
&& self.outline_items[i].has_children
{
let heading_text = self.outline_items[i].text.clone();
// Toggle the collapsed state
if self.collapsed_headings.contains(&heading_text) {
self.collapsed_headings.remove(&heading_text);
} else {
self.collapsed_headings.insert(heading_text.clone());
}
// Rebuild the flattened list with overview entry
self.rebuild_outline_items();
// Restore selection by text (not by index)
if !self.select_by_text(&heading_text) {
// If heading not found (shouldn't happen), clamp to valid index
let safe_idx = i.min(self.outline_items.len().saturating_sub(1));
self.outline_state.select(Some(safe_idx));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(safe_idx);
}
}
}
pub fn expand(&mut self) {
if self.focus == Focus::Outline
&& let Some(i) = self.outline_state.selected()
&& i < self.outline_items.len()
&& self.outline_items[i].has_children
{
let heading_text = self.outline_items[i].text.clone();
// Remove from collapsed set to expand
self.collapsed_headings.remove(&heading_text);
// Rebuild the flattened list with overview entry
self.rebuild_outline_items();
// Restore selection by text (not by index)
if !self.select_by_text(&heading_text) {
// If heading not found (shouldn't happen), clamp to valid index
let safe_idx = i.min(self.outline_items.len().saturating_sub(1));
self.outline_state.select(Some(safe_idx));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(safe_idx);
}
}
}
pub fn collapse(&mut self) {
if self.focus == Focus::Outline
&& let Some(i) = self.outline_state.selected()
&& i < self.outline_items.len()
{
let current_level = self.outline_items[i].level;
let current_text = self.outline_items[i].text.clone();
// If current heading has children, collapse it
if self.outline_items[i].has_children {
self.collapsed_headings.insert(current_text.clone());
// Rebuild the flattened list with overview entry
self.rebuild_outline_items();
// Restore selection by text
if !self.select_by_text(¤t_text) {
let safe_idx = i.min(self.outline_items.len().saturating_sub(1));
self.outline_state.select(Some(safe_idx));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(safe_idx);
}
} else {
// If no children, find parent and collapse it
// Look backwards for first heading with lower level
let mut parent_text: Option<String> = None;
for idx in (0..i).rev() {
if self.outline_items[idx].level < current_level {
// Found parent
parent_text = Some(self.outline_items[idx].text.clone());
break;
}
}
if let Some(parent) = parent_text {
// Collapse the parent
self.collapsed_headings.insert(parent.clone());
// Rebuild and move selection to parent
self.rebuild_outline_items();
// Select the parent by text
if !self.select_by_text(&parent) {
// Fallback: select first item if parent not found
if !self.outline_items.is_empty() {
self.outline_state.select(Some(0));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(0);
}
}
}
// No parent found, do nothing
}
}
}
/// Collapse all headings that have children
pub fn collapse_all(&mut self) {
// Collect all heading texts that have children
let headings_to_collapse: Vec<String> = self
.tree
.iter()
.flat_map(Self::collect_collapsible_headings)
.collect();
for text in headings_to_collapse {
self.collapsed_headings.insert(text);
}
// Rebuild outline and preserve selection
let selected_text = self.selected_heading_text().map(|s| s.to_string());
self.rebuild_outline_items();
// Try to restore selection, or select first item
if let Some(text) = selected_text
&& !self.select_by_text(&text)
{
// Selection collapsed away, select first item
if !self.outline_items.is_empty() {
self.outline_state.select(Some(0));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(0);
}
}
let count = self.collapsed_headings.len();
self.set_status_message(&format!("Collapsed {} headings", count));
}
/// Recursively collect all heading texts that have children
fn collect_collapsible_headings(node: &HeadingNode) -> Vec<String> {
let mut result = Vec::new();
if !node.children.is_empty() {
result.push(node.heading.text.clone());
for child in &node.children {
result.extend(Self::collect_collapsible_headings(child));
}
}
result
}
/// Expand all headings
pub fn expand_all(&mut self) {
let count = self.collapsed_headings.len();
self.collapsed_headings.clear();
// Rebuild outline and preserve selection
let selected_text = self.selected_heading_text().map(|s| s.to_string());
self.rebuild_outline_items();
if let Some(text) = selected_text {
self.select_by_text(&text);
}
self.set_status_message(&format!("Expanded {} headings", count));
}
/// Collapse all headings at a specific level (1-6)
pub fn collapse_level(&mut self, level: usize) {
// Collect all headings at the target level that have children
let headings_to_collapse: Vec<String> = self
.tree
.iter()
.flat_map(|node| Self::collect_headings_at_level_with_children(node, level))
.collect();
let count = headings_to_collapse.len();
for text in headings_to_collapse {
self.collapsed_headings.insert(text);
}
// Rebuild outline and preserve selection
let selected_text = self.selected_heading_text().map(|s| s.to_string());
self.rebuild_outline_items();
if let Some(text) = selected_text
&& !self.select_by_text(&text)
{
// Selection collapsed away, select first item
if !self.outline_items.is_empty() {
self.outline_state.select(Some(0));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(0);
}
}
self.set_status_message(&format!("Collapsed {} h{} headings", count, level));
}
/// Recursively collect headings at a specific level that have children
fn collect_headings_at_level_with_children(
node: &HeadingNode,
target_level: usize,
) -> Vec<String> {
let mut result = Vec::new();
if node.heading.level == target_level && !node.children.is_empty() {
result.push(node.heading.text.clone());
}
// Always recurse to find nested headings at the target level
for child in &node.children {
result.extend(Self::collect_headings_at_level_with_children(
child,
target_level,
));
}
result
}
/// Expand all headings at a specific level (1-6)
pub fn expand_level(&mut self, level: usize) {
let mut count = 0;
// Find all collapsed headings at the specified level and expand them
let headings_at_level: Vec<String> = self
.tree
.iter()
.flat_map(|node| self.collect_headings_at_level(node, level))
.collect();
for heading_text in headings_at_level {
if self.collapsed_headings.remove(&heading_text) {
count += 1;
}
}
// Rebuild outline and preserve selection
let selected_text = self.selected_heading_text().map(|s| s.to_string());
self.rebuild_outline_items();
if let Some(text) = selected_text {
self.select_by_text(&text);
}
self.set_status_message(&format!("Expanded {} h{} headings", count, level));
}
/// Collect heading texts at a specific level
fn collect_headings_at_level(&self, node: &HeadingNode, target_level: usize) -> Vec<String> {
let mut result = Vec::new();
if node.heading.level == target_level {
result.push(node.heading.text.clone());
}
for child in &node.children {
result.extend(self.collect_headings_at_level(child, target_level));
}
result
}
pub fn toggle_focus(&mut self) {
// If in locked-in outline search state, Tab cycles to next filtered item
if self.show_search && !self.outline_search_active && !self.outline_items.is_empty() {
let current = self.outline_state.selected().unwrap_or(0);
let next = (current + 1) % self.outline_items.len();
self.select_outline_index(next);
return;
}
if self.show_outline {
self.focus = match self.focus {
Focus::Outline => Focus::Content,
Focus::Content => Focus::Outline,
};
}
}
/// Toggle focus backwards (Shift+Tab) - cycles to previous item when search is locked in
pub fn toggle_focus_back(&mut self) {
// If in locked-in outline search state, Shift+Tab cycles to previous filtered item
if self.show_search && !self.outline_search_active && !self.outline_items.is_empty() {
let current = self.outline_state.selected().unwrap_or(0);
let len = self.outline_items.len();
let prev = (current + len - 1) % len;
self.select_outline_index(prev);
return;
}
// Same as toggle_focus when not in locked search state
if self.show_outline {
self.focus = match self.focus {
Focus::Outline => Focus::Content,
Focus::Content => Focus::Outline,
};
}
}
pub fn toggle_outline(&mut self) {
self.show_outline = !self.show_outline;
if !self.show_outline {
// When hiding outline, switch focus to content
self.focus = Focus::Content;
} else {
// When showing outline, switch focus back to outline
self.focus = Focus::Outline;
}
}
/// Toggle filtering outline by open todos
pub fn toggle_todo_filter(&mut self) {
self.filter_by_todos = !self.filter_by_todos;
// Rebuild outline with/without filter
let selected_text = self.selected_heading_text().map(|s| s.to_string());
self.rebuild_outline_items();
// Try to restore selection
if let Some(text) = selected_text {
if !self.select_by_text(&text) {
// Selection no longer visible, select first item
if !self.outline_items.is_empty() {
self.outline_state.select(Some(0));
self.outline_scroll_state =
ScrollbarState::new(self.outline_items.len()).position(0);
}
}
} else if !self.outline_items.is_empty() {
self.outline_state.select(Some(0));
self.outline_scroll_state = ScrollbarState::new(self.outline_items.len()).position(0);
}
// Set status message
if self.filter_by_todos {
let count = self.outline_items.len();
self.set_status_message(&format!(
"Todo filter ON: {} heading{} with open todos",
count,
if count == 1 { "" } else { "s" }
));
} else {
self.set_status_message("Todo filter OFF: showing all headings");
}
}
/// Cycle outline width between 20%, 30%, and 40%.
///
/// Behavior depends on user's config:
/// - **New users** (default or standard width in config): Changes are persisted
/// to config file for a seamless experience.
/// - **Power users** (custom width like 25% in config): Changes are session-only
/// to protect their carefully crafted config from accidental overwrites.
/// They can explicitly save with `S` key.
///
/// This respects the principle that user config should always take precedence.
pub fn cycle_outline_width(&mut self, increase: bool) {
if increase {
self.outline_width = match self.outline_width {
20 => 30,
30 => 40,
40 => 20, // Wrap around
// For custom widths, snap to nearest standard value going up
w if w < 25 => 30,
w if w < 35 => 40,
_ => 20,
};
} else {
self.outline_width = match self.outline_width {
40 => 30,
30 => 20,
20 => 40, // Wrap around
// For custom widths, snap to nearest standard value going down
w if w > 35 => 30,
w if w > 25 => 20,
_ => 40,
};
}
// Decide whether to persist based on user's config type
if self.config_has_custom_outline_width {
// Power user: protect their custom config value, offer explicit save
self.set_status_message(&format!("Width: {}% | :w to save", self.outline_width));
} else {
// New user or standard config: safe to persist for better UX
let _ = self.config.set_outline_width(self.outline_width);
self.set_status_message(&format!("Width: {}%", self.outline_width));
}
}
/// Show confirmation modal for saving outline width.
/// Called when user presses `S`.
pub fn show_save_width_confirmation(&mut self) {
self.mode = AppMode::ConfirmSaveWidth;
}
/// Confirm and save outline width to config file.
pub fn confirm_save_outline_width(&mut self) {
match self.config.set_outline_width(self.outline_width) {
Ok(_) => {
// Update the flag since user explicitly chose to save
self.config_has_custom_outline_width = self.outline_width != 20
&& self.outline_width != 30
&& self.outline_width != 40;
self.set_status_message(&format!(
"✓ Width {}% saved to config",
self.outline_width
));
}
Err(e) => {
self.set_status_message(&format!("✗ Failed to save: {}", e));
}
}
self.mode = AppMode::Normal;
}
/// Cancel the save width confirmation modal.
pub fn cancel_save_width_confirmation(&mut self) {
self.mode = AppMode::Normal;
self.set_status_message("Save cancelled");
}
// ========== Command Palette ==========
/// Open command palette (triggered by `:`)
pub fn open_command_palette(&mut self) {
self.mode = AppMode::CommandPalette;
self.command_query.clear();
self.command_filtered = (0..PALETTE_COMMANDS.len()).collect();
self.command_selected = 0;
}
/// Add a character to command palette search
pub fn command_palette_input(&mut self, c: char) {
if self.command_query.len() < 32 {
self.command_query.push(c);
self.filter_commands();
}
}
/// Remove last character from command palette search
pub fn command_palette_backspace(&mut self) {
self.command_query.pop();
self.filter_commands();
}
/// Filter commands based on current query
fn filter_commands(&mut self) {
// Filter matching commands
let mut matches: Vec<(usize, usize)> = PALETTE_COMMANDS
.iter()
.enumerate()
.filter(|(_, cmd)| cmd.matches(&self.command_query))
.map(|(idx, cmd)| (idx, cmd.match_score(&self.command_query)))
.collect();
// Sort by score (highest first)
matches.sort_by(|a, b| b.1.cmp(&a.1));
self.command_filtered = matches.into_iter().map(|(idx, _)| idx).collect();
// Reset selection if it's out of bounds
if self.command_selected >= self.command_filtered.len() {
self.command_selected = 0;
}
}
/// Move selection down in command palette
pub fn command_palette_next(&mut self) {
if !self.command_filtered.is_empty() {
self.command_selected = (self.command_selected + 1) % self.command_filtered.len();
}
}
/// Move selection up in command palette
pub fn command_palette_prev(&mut self) {
if !self.command_filtered.is_empty() {
self.command_selected = if self.command_selected == 0 {
self.command_filtered.len() - 1
} else {
self.command_selected - 1
};
}
}
/// Autocomplete command palette with selected command's alias
pub fn command_palette_autocomplete(&mut self) {
if let Some(&cmd_idx) = self.command_filtered.get(self.command_selected) {
let cmd = &PALETTE_COMMANDS[cmd_idx];
// Use the first alias (typically the shortest canonical form)
if let Some(&alias) = cmd.aliases.first() {
self.command_query = alias.to_string();
// Re-filter with the new query (will likely still match the same command)
self.filter_commands();
}
}
}
/// Close command palette without executing
pub fn close_command_palette(&mut self) {
self.mode = AppMode::Normal;
self.command_query.clear();
}
/// Execute selected command and return whether to quit
pub fn execute_selected_command(&mut self) -> bool {
if let Some(&cmd_idx) = self.command_filtered.get(self.command_selected) {
let action = PALETTE_COMMANDS[cmd_idx].action;
let query = self.command_query.clone(); // Capture query for argument parsing
self.mode = AppMode::Normal;
self.command_query.clear();
self.execute_command_action(action, &query)
} else {
self.mode = AppMode::Normal;
false
}
}
/// Execute a command action, returns true if should quit
fn execute_command_action(&mut self, action: CommandAction, query: &str) -> bool {
match action {
CommandAction::SaveWidth => {
match self.config.set_outline_width(self.outline_width) {
Ok(_) => {
self.config_has_custom_outline_width = self.outline_width != 20
&& self.outline_width != 30
&& self.outline_width != 40;
self.set_status_message(&format!(
"✓ Width {}% saved to config",
self.outline_width
));
}
Err(e) => {
self.set_status_message(&format!("✗ Failed to save: {}", e));
}
}
false
}
CommandAction::ToggleOutline => {
self.toggle_outline();
false
}
CommandAction::ToggleHelp => {
self.toggle_help();
false
}
CommandAction::ToggleRawSource => {
self.toggle_raw_source();
false
}
CommandAction::JumpToTop => {
self.first();
false
}
CommandAction::JumpToBottom => {
self.last();
false
}
CommandAction::CollapseAll => {
self.collapse_all();
false
}
CommandAction::ExpandAll => {
self.expand_all();
false
}
CommandAction::CollapseLevel => {
// Parse level from query (e.g., "collapse 2" -> 2)
if let Some(level) = Self::parse_level_from_query(query) {
self.collapse_level(level);
} else {
self.collapse_all();
}
false
}
CommandAction::ExpandLevel => {
// Parse level from query (e.g., "expand 2" -> 2)
if let Some(level) = Self::parse_level_from_query(query) {
self.expand_level(level);
} else {
self.expand_all();
}
false
}
CommandAction::SaveFile => {
if let Err(e) = self.save_pending_edits_to_file() {
self.set_status_message(&format!("✗ Save failed: {}", e));
}
false
}
CommandAction::Undo => {
if let Err(e) = self.undo_last_edit() {
self.set_status_message(&format!("✗ Undo failed: {}", e));
}
false
}
CommandAction::Quit => {
if self.has_unsaved_changes {
// Show confirmation dialog instead of quitting immediately
self.mode = AppMode::ConfirmSaveBeforeQuit;
false
} else {
true
}
}
}
}
/// Parse a level number from a command query like "collapse 2" or "expand 3"
fn parse_level_from_query(query: &str) -> Option<usize> {
// Find the last word and try to parse it as a number
query
.split_whitespace()
.last()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&n| (1..=6).contains(&n))
}
/// Get selected command for display
pub fn selected_command(&self) -> Option<&'static PaletteCommand> {
self.command_filtered
.get(self.command_selected)
.map(|&idx| &PALETTE_COMMANDS[idx])
}
pub fn jump_to_heading(&mut self, index: usize) {
if index < self.outline_items.len() {
self.select_outline_index(index);
}
}
pub fn set_bookmark(&mut self) {
// Store bookmark as heading text instead of index
self.bookmark_position = self.selected_heading_text().map(|s| s.to_string());
}
pub fn jump_to_bookmark(&mut self) {
// Jump to bookmark by finding the heading text
if let Some(text) = self.bookmark_position.clone() {
self.select_by_text(&text);
}
}
pub fn selected_heading_text(&self) -> Option<&str> {
self.outline_state
.selected()
.and_then(|i| self.outline_items.get(i))
.map(|item| item.text.as_str())
}
/// Get the content for the currently selected section, or the full document if no heading is selected.
fn current_section_content(&self) -> String {
self.selected_heading_text()
.and_then(|text| self.document.extract_section(text))
.unwrap_or_else(|| self.document.content.clone())
}
/// Get the source line number (1-indexed) for the currently selected heading.
///
/// Returns None if no heading is selected or if the selection is the document overview.
pub fn selected_heading_source_line(&self) -> Option<u32> {
let selected_text = self.selected_heading_text()?;
// Document overview doesn't have a source line
if selected_text == DOCUMENT_OVERVIEW {
return Some(1); // Return line 1 for document overview
}
// Find the heading in the document by text
let heading = self
.document
.headings
.iter()
.find(|h| h.text == selected_text)?;
// Convert byte offset to line number (1-indexed)
let offset = heading.offset.min(self.document.content.len());
let before = &self.document.content[..offset];
let line = before.chars().filter(|&c| c == '\n').count() + 1;
Some(line as u32)
}
/// Get the source line number (1-indexed) for the current interactive element.
///
/// Computes the source line by adding the element's rendered line offset
/// to the section's starting line in the source file.
pub fn interactive_element_source_line(&self) -> Option<u32> {
let (element_line, _) = self.interactive_state.current_element_line_range()?;
let selected_text = self.selected_heading_text();
let is_overview = selected_text.is_none_or(|t| t == DOCUMENT_OVERVIEW);
if is_overview {
// Document overview: element lines are relative to full document content
Some((element_line + 1) as u32)
} else {
// Section: element lines are relative to section content (after heading line)
let heading_line = self.selected_heading_source_line().unwrap_or(1) as usize;
Some((heading_line + 1 + element_line) as u32)
}
}
/// Sync previous_selection to current selection (prevents spurious scroll resets)
pub fn sync_previous_selection(&mut self) {
self.previous_selection = self.selected_heading_text().map(|s| s.to_string());
}
pub fn toggle_theme_picker(&mut self) {
if self.show_theme_picker {
// Closing picker - restore original theme if set (user pressed Esc)
if let Some(original) = self.theme_picker_original.take() {
self.apply_theme_preview(original);
}
self.show_theme_picker = false;
} else {
// Opening picker - store current theme and set selection
self.theme_picker_original = Some(self.current_theme);
self.theme_picker_selected = match self.current_theme {
ThemeName::OceanDark => 0,
ThemeName::Nord => 1,
ThemeName::Dracula => 2,
ThemeName::Solarized => 3,
ThemeName::Monokai => 4,
ThemeName::Gruvbox => 5,
ThemeName::TokyoNight => 6,
ThemeName::CatppuccinMocha => 7,
};
self.show_theme_picker = true;
}
}
/// Convert theme picker selection index to ThemeName
fn theme_name_from_index(idx: usize) -> ThemeName {
match idx {
0 => ThemeName::OceanDark,
1 => ThemeName::Nord,
2 => ThemeName::Dracula,
3 => ThemeName::Solarized,
4 => ThemeName::Monokai,
5 => ThemeName::Gruvbox,
6 => ThemeName::TokyoNight,
7 => ThemeName::CatppuccinMocha,
_ => ThemeName::OceanDark,
}
}
/// Apply a theme preview (doesn't save to config)
fn apply_theme_preview(&mut self, theme_name: ThemeName) {
self.current_theme = theme_name;
self.theme = Theme::from_name(theme_name)
.with_color_mode(self.color_mode, theme_name)
.with_custom_colors(&self.config.theme, self.color_mode);
}
pub fn theme_picker_next(&mut self) {
if self.theme_picker_selected < 7 {
self.theme_picker_selected += 1;
// Apply theme preview immediately
let theme_name = Self::theme_name_from_index(self.theme_picker_selected);
self.apply_theme_preview(theme_name);
}
}
pub fn theme_picker_previous(&mut self) {
if self.theme_picker_selected > 0 {
self.theme_picker_selected -= 1;
// Apply theme preview immediately
let theme_name = Self::theme_name_from_index(self.theme_picker_selected);
self.apply_theme_preview(theme_name);
}
}
pub fn apply_selected_theme(&mut self) {
// Theme is already applied via preview, just save to config and close
self.theme_picker_original = None; // Clear so toggle doesn't restore
self.show_theme_picker = false;
// Save to config (silently ignore errors)
let _ = self.config.set_theme(self.current_theme);
}
/// Get the editor configuration for external file editing
pub fn editor_config(&self) -> opensesame::EditorConfig {
self.config.editor.clone()
}
pub fn copy_content(&mut self) {
// Copy the currently selected section's content
if let Some(heading_text) = self.selected_heading_text() {
if let Some(section) = self.document.extract_section(heading_text) {
// Use persistent clipboard for Linux X11 compatibility
if let Some(clipboard) = &mut self.clipboard {
match clipboard.set_text(section) {
Ok(_) => {
self.status_message = Some("✓ Section copied to clipboard".to_string());
}
Err(e) => {
self.status_message = Some(format!("✗ Clipboard error: {}", e));
}
}
} else {
self.status_message = Some("✗ Clipboard not available".to_string());
}
} else {
self.status_message = Some("✗ Could not extract section".to_string());
}
} else {
self.status_message = Some("✗ No heading selected".to_string());
}
}
pub fn copy_anchor(&mut self) {
// Copy the anchor link for the currently selected heading
if let Some(heading_text) = self.selected_heading_text() {
// Convert heading to anchor format (lowercase, replace spaces with dashes)
let anchor = Self::heading_to_anchor(heading_text);
let anchor_link = format!("#{}", anchor);
// Use persistent clipboard for Linux X11 compatibility
if let Some(clipboard) = &mut self.clipboard {
match clipboard.set_text(anchor_link) {
Ok(_) => {
self.status_message = Some(format!("✓ Anchor link copied: #{}", anchor));
}
Err(e) => {
self.status_message = Some(format!("✗ Clipboard error: {}", e));
}
}
} else {
self.status_message = Some("✗ Clipboard not available".to_string());
}
} else {
self.status_message = Some("✗ No heading selected".to_string());
}
}
/// Convert heading text to anchor format using the parser's slugify for consistency
fn heading_to_anchor(heading: &str) -> String {
crate::parser::content::slugify(heading)
}
/// Enter link follow mode - extract links from current section and highlight them
pub fn enter_link_follow_mode(&mut self) {
// Extract content for current section
let content = self.current_section_content();
// Extract all links from the content
self.links_in_view = extract_links(&content);
// Initialize filtered indices to show all links
self.filtered_link_indices = (0..self.links_in_view.len()).collect();
self.link_search_query.clear();
self.link_search_active = false;
// Always enter mode, even if no links (so user sees "no links" message)
self.mode = AppMode::LinkFollow;
// Select first link if any exist
if !self.filtered_link_indices.is_empty() {
self.selected_link_idx = Some(0);
} else {
self.selected_link_idx = None;
}
}
/// Exit link follow mode and return to normal mode
pub fn exit_link_follow_mode(&mut self) {
self.mode = AppMode::Normal;
self.links_in_view.clear();
self.filtered_link_indices.clear();
self.selected_link_idx = None;
self.link_search_query.clear();
self.link_search_active = false;
// Don't clear status message here - let it display for a moment
}
/// Start link search mode
pub fn start_link_search(&mut self) {
if self.mode == AppMode::LinkFollow {
self.link_search_active = true;
}
}
/// Stop link search mode (but keep the filter)
pub fn stop_link_search(&mut self) {
self.link_search_active = false;
}
/// Clear link search and show all links
pub fn clear_link_search(&mut self) {
self.link_search_query.clear();
self.link_search_active = false;
self.update_link_filter();
}
/// Add a character to the link search query
pub fn link_search_push(&mut self, c: char) {
self.link_search_query.push(c);
self.update_link_filter();
}
/// Remove the last character from the link search query
pub fn link_search_pop(&mut self) {
self.link_search_query.pop();
self.update_link_filter();
}
/// Update the filtered link indices based on the search query
fn update_link_filter(&mut self) {
let query = self.link_search_query.to_lowercase();
if query.is_empty() {
// Show all links when no search query
self.filtered_link_indices = (0..self.links_in_view.len()).collect();
} else {
// Filter links by text or URL containing the query
self.filtered_link_indices = self
.links_in_view
.iter()
.enumerate()
.filter(|(_, link)| {
link.text.to_lowercase().contains(&query)
|| link.target.as_str().to_lowercase().contains(&query)
})
.map(|(idx, _)| idx)
.collect();
}
// Update selection to stay within filtered results
if self.filtered_link_indices.is_empty() {
self.selected_link_idx = None;
} else if let Some(idx) = self.selected_link_idx {
if idx >= self.filtered_link_indices.len() {
self.selected_link_idx = Some(0);
}
} else {
self.selected_link_idx = Some(0);
}
}
/// Cycle to the next link (Tab in link follow mode)
pub fn next_link(&mut self) {
if self.mode == AppMode::LinkFollow && !self.filtered_link_indices.is_empty() {
self.selected_link_idx = Some(match self.selected_link_idx {
Some(idx) => {
if idx >= self.filtered_link_indices.len() - 1 {
0 // Wrap to first
} else {
idx + 1
}
}
None => 0,
});
}
}
/// Cycle to the previous link (Shift+Tab in link follow mode)
pub fn previous_link(&mut self) {
if self.mode == AppMode::LinkFollow && !self.filtered_link_indices.is_empty() {
self.selected_link_idx = Some(match self.selected_link_idx {
Some(idx) => {
if idx == 0 {
self.filtered_link_indices.len() - 1 // Wrap to last
} else {
idx - 1
}
}
None => 0,
});
}
}
/// Jump to parent heading while staying in link follow mode
pub fn jump_to_parent_links(&mut self) {
if self.mode == AppMode::LinkFollow {
// First, jump to parent in outline
if let Some(current_idx) = self.outline_state.selected()
&& current_idx < self.outline_items.len()
{
let current_level = self.outline_items[current_idx].level;
// Search backwards for a heading with lower level (parent)
for i in (0..current_idx).rev() {
if self.outline_items[i].level < current_level {
// Jump to parent in outline
self.select_outline_index(i);
// Now extract links from parent's content
let content = self.current_section_content();
self.links_in_view = extract_links(&content);
// Reset link selection
if !self.links_in_view.is_empty() {
self.selected_link_idx = Some(0);
self.status_message = Some(format!(
"✓ Jumped to parent ({} links found)",
self.links_in_view.len()
));
} else {
self.selected_link_idx = None;
self.status_message = Some("⚠ Parent has no links".to_string());
}
return;
}
}
// If no parent found (already at top-level)
self.status_message = Some("⚠ Already at top-level heading".to_string());
}
}
}
// ===== File Picker Methods =====
/// Check if a path has a markdown file extension
fn is_markdown_extension(path: &std::path::Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.map(|ext| {
let ext_lower = ext.to_lowercase();
ext_lower == "md" || ext_lower == "markdown" || ext_lower == "mdown"
})
.unwrap_or(false)
}
/// Get the effective file picker directory (custom or cwd)
pub fn effective_picker_dir(&self) -> PathBuf {
self.file_picker_dir
.clone()
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
}
/// Navigate file picker to the given directory, clearing search and resetting selection
fn navigate_picker_to_dir(&mut self, dir: PathBuf) {
self.file_picker_dir = Some(dir);
self.file_search_query.clear();
self.scan_markdown_files(); // update_file_filter() resets selected_file_idx
}
/// Scan current directory for .md files and subdirectories (non-recursive, alphabetically sorted)
pub fn scan_markdown_files(&mut self) {
use std::fs;
let dir = self.effective_picker_dir();
let mut files = Vec::new();
let mut dirs = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.filter_map(|e| e.ok()) {
let ft = entry.file_type().ok();
let path = entry.path();
let is_visible = path
.file_name()
.and_then(|n| n.to_str())
.map(|name| self.show_hidden || !name.starts_with('.'))
.unwrap_or(false);
if !is_visible {
continue;
}
if ft.map(|t| t.is_file()).unwrap_or(false) && Self::is_markdown_extension(&path) {
files.push(path);
} else if ft.map(|t| t.is_dir()).unwrap_or(false) {
dirs.push(path);
}
}
}
files.sort();
dirs.sort();
self.files_in_directory = files;
self.dirs_in_directory = dirs;
self.update_file_filter();
}
/// Update filtered file and directory lists based on search query
pub fn update_file_filter(&mut self) {
fn filter_by_name(paths: &[PathBuf], query: &str) -> Vec<usize> {
paths
.iter()
.enumerate()
.filter(|(_, path)| {
path.file_name()
.and_then(|n| n.to_str())
.map(|name| name.to_lowercase().contains(query))
.unwrap_or(false)
})
.map(|(idx, _)| idx)
.collect()
}
if self.file_search_query.is_empty() {
self.filtered_file_indices = (0..self.files_in_directory.len()).collect();
self.filtered_dir_indices = (0..self.dirs_in_directory.len()).collect();
} else {
let query_lower = self.file_search_query.to_lowercase();
self.filtered_file_indices = filter_by_name(&self.files_in_directory, &query_lower);
self.filtered_dir_indices = filter_by_name(&self.dirs_in_directory, &query_lower);
}
// Combined count: files + directories
let combined_count = self.filtered_file_indices.len() + self.filtered_dir_indices.len();
// Reset selection if current is out of bounds
if let Some(sel) = self.selected_file_idx {
if sel >= combined_count {
self.selected_file_idx = if combined_count == 0 { None } else { Some(0) };
}
} else if combined_count > 0 {
self.selected_file_idx = Some(0);
}
}
/// Get the total number of items in the file picker (files + dirs)
pub fn file_picker_item_count(&self) -> usize {
self.filtered_file_indices.len() + self.filtered_dir_indices.len()
}
/// Push character to file search query
pub fn file_search_push(&mut self, c: char) {
self.file_search_query.push(c);
self.update_file_filter();
}
/// Pop character from file search query
pub fn file_search_pop(&mut self) {
self.file_search_query.pop();
self.update_file_filter();
}
/// Auto-hide outline when only 0-1 markdown files in directory.
/// User can still toggle outline visibility with keybinding.
pub fn auto_hide_outline_if_single_file(&mut self) {
// Only scan if no data yet (avoids redundant scan after enter_file_picker)
if self.files_in_directory.is_empty() && self.dirs_in_directory.is_empty() {
self.scan_markdown_files();
}
if self.files_in_directory.len() <= 1 {
self.show_outline = false;
}
}
/// Navigate to parent directory in file picker
pub fn file_picker_parent_dir(&mut self) {
let current_dir = self.effective_picker_dir();
if let Some(parent) = current_dir.parent() {
self.navigate_picker_to_dir(parent.to_path_buf());
}
}
/// Enter file picker mode
pub fn enter_file_picker(&mut self) {
self.scan_markdown_files();
// Highlight current file if present
if let Some(current_idx) = self
.files_in_directory
.iter()
.position(|p| p == &self.current_file_path)
{
self.selected_file_idx = Some(current_idx);
} else if !self.filtered_file_indices.is_empty() {
self.selected_file_idx = Some(0);
}
self.mode = AppMode::FilePicker;
}
/// Select file from picker and load it (or navigate into directory)
pub fn select_file_from_picker(&mut self) -> Result<(), String> {
let selected_display_idx = self.selected_file_idx.ok_or("No file selected")?;
let file_count = self.filtered_file_indices.len();
// Check if selection is in the directory range
if selected_display_idx >= file_count {
let dir_display_idx = selected_display_idx - file_count;
let real_dir_idx = self
.filtered_dir_indices
.get(dir_display_idx)
.ok_or("Invalid directory selection")?;
let dir_path = self.dirs_in_directory[*real_dir_idx].clone();
self.navigate_picker_to_dir(dir_path);
return Ok(());
}
let real_idx = self
.filtered_file_indices
.get(selected_display_idx)
.ok_or("Invalid selection")?;
let file_path = self.files_in_directory[*real_idx].clone();
// Don't reload if it's already the current file
if file_path == self.current_file_path {
self.mode = AppMode::Normal;
self.file_search_query.clear();
self.file_search_active = false;
return Ok(());
}
// Save current state to history
let current_state = FileState {
path: self.current_file_path.clone(),
document: self.document.clone(),
filename: self.filename.clone(),
selected_heading: self.selected_heading_text().map(|s| s.to_string()),
content_scroll: self.content_scroll,
outline_state_selected: self.outline_state.selected(),
};
self.file_history.push(current_state);
self.file_future.clear(); // Clear forward history when navigating to new file
// Load new file
let content = std::fs::read_to_string(&file_path)
.map_err(|e| format!("Failed to read file: {}", e))?;
let document = crate::parser::parse_markdown(&content);
let filename = file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown.md")
.to_string();
self.load_document(document, filename, file_path);
// Exit picker mode
self.mode = AppMode::Normal;
self.file_search_query.clear();
self.file_search_active = false;
Ok(())
}
/// Cycle to the next item in file picker (files + dirs)
pub fn next_file(&mut self) {
let total = self.file_picker_item_count();
if self.mode == AppMode::FilePicker && total > 0 {
self.selected_file_idx = Some(match self.selected_file_idx {
Some(idx) => {
if idx >= total - 1 {
0 // Wrap to first
} else {
idx + 1
}
}
None => 0,
});
}
}
/// Cycle to the previous item in file picker (files + dirs)
pub fn previous_file(&mut self) {
let total = self.file_picker_item_count();
if self.mode == AppMode::FilePicker && total > 0 {
self.selected_file_idx = Some(match self.selected_file_idx {
Some(idx) => {
if idx == 0 {
total - 1 // Wrap to last
} else {
idx - 1
}
}
None => 0,
});
}
}
/// Get the currently selected link (from filtered list)
pub fn get_selected_link(&self) -> Option<&Link> {
self.selected_link_idx
.and_then(|idx| self.filtered_link_indices.get(idx))
.and_then(|&real_idx| self.links_in_view.get(real_idx))
}
/// Check if frontmatter should be hidden (from config)
pub fn should_hide_frontmatter(&self) -> bool {
self.config.content.hide_frontmatter
}
/// Check if LaTeX should be hidden (from config)
pub fn should_hide_latex(&self) -> bool {
self.config.content.hide_latex
}
/// Check if aggressive LaTeX filtering is enabled (from config)
pub fn should_latex_aggressive(&self) -> bool {
self.config.content.latex_aggressive
}
/// Handle loading a relative file link, resolving markdown extensions and fallbacks.
///
/// Returns `true` if the caller should exit its current mode (link-follow or interactive).
fn resolve_relative_file_link(
&mut self,
path: &PathBuf,
anchor: &Option<String>,
) -> Result<bool, String> {
let has_md_extension = Self::is_markdown_extension(path);
let current_dir = self
.current_file_path
.parent()
.ok_or("Cannot determine current directory")?;
if has_md_extension {
self.load_file(path, anchor.as_deref())?;
// Only signal exit if we're not prompting for file creation
Ok(self.mode != AppMode::ConfirmFileCreate)
} else {
// No markdown extension — try .md, then as-is, then prompt to create
let md_path = PathBuf::from(format!("{}.md", path.display()));
let absolute_md_path = current_dir.join(&md_path);
if absolute_md_path.exists() && !absolute_md_path.is_symlink() {
self.load_file(&md_path, anchor.as_deref())?;
Ok(true)
} else {
let absolute_path = current_dir.join(path);
if absolute_path.exists() && !absolute_path.is_symlink() {
// Non-markdown file — open in editor
self.pending_editor_file = Some(absolute_path);
Ok(true)
} else {
// File doesn't exist — prompt to create markdown file
let relative_path = if path.extension().is_none() {
PathBuf::from(format!("{}.md", path.display()))
} else {
path.clone()
};
self.load_file(&relative_path, anchor.as_deref())?;
Ok(self.mode != AppMode::ConfirmFileCreate)
}
}
}
}
/// Follow the currently selected link
pub fn follow_selected_link(&mut self) -> Result<(), String> {
let link = match self.get_selected_link() {
Some(link) => link.clone(),
None => return Err("No link selected".to_string()),
};
match link.target {
crate::parser::LinkTarget::Anchor(anchor) => {
// Jump to heading in current document
self.jump_to_anchor(&anchor)?;
self.status_message = Some(format!("✓ Jumped to #{}", anchor));
self.exit_link_follow_mode();
Ok(())
}
crate::parser::LinkTarget::RelativeFile { path, anchor } => {
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
if self.resolve_relative_file_link(&path, &anchor)? {
self.status_message = Some(format!("✓ Opened {}", filename));
self.exit_link_follow_mode();
}
Ok(())
}
crate::parser::LinkTarget::WikiLink { target, .. } => {
// Try to find and load the wikilinked file
self.load_wikilink(&target)?;
// Only exit link follow mode if we're not prompting for file creation
if self.mode != AppMode::ConfirmFileCreate {
self.status_message = Some(format!("✓ Opened [[{}]]", target));
self.exit_link_follow_mode();
}
Ok(())
}
crate::parser::LinkTarget::External(url) => {
// Try to open in default browser
let open_result = open::that(&url);
// Also copy to clipboard as backup
let mut clipboard_success = false;
if let Ok(mut clipboard) = arboard::Clipboard::new() {
clipboard_success = clipboard.set_text(url.clone()).is_ok();
}
// Set status message
self.status_message = match (open_result, clipboard_success) {
(Ok(_), true) => Some(format!(
"✓ Opened {} in browser (also copied to clipboard)",
url
)),
(Ok(_), false) => Some(format!("✓ Opened {} in browser", url)),
(Err(_), true) => Some(format!(
"⚠ Could not open browser, URL copied to clipboard: {}",
url
)),
(Err(_), false) => Some(format!("✗ Failed to open URL: {}", url)),
};
self.exit_link_follow_mode();
Ok(())
}
}
}
/// Jump to a heading by anchor name or heading text.
///
/// Supports two matching strategies (checked per-item, Strategy 1 takes priority):
/// 1. **Normalized anchor match** - compares `heading_to_anchor(item)` with lowercased anchor.
/// Handles markdown links (`#features`, `#mixed-links-test`) and simple wikilinks (`[[#Features]]`).
/// 2. **Heading text match** - case-insensitive comparison of raw heading text.
/// Handles wikilinks preserving spaces (`[[#Mixed Links Test]]`).
fn jump_to_anchor(&mut self, anchor: &str) -> Result<(), String> {
let anchor_lower = anchor.to_lowercase();
for (idx, item) in self.outline_items.iter().enumerate() {
// Strategy 1: Normalized anchor match
// The anchor from markdown links is already normalized (lowercase, dashes),
// so we just lowercase the query and compare with the item's normalized form.
if Self::heading_to_anchor(&item.text) == anchor_lower {
self.select_outline_index(idx);
return Ok(());
}
// Strategy 2: Direct heading text match (case-insensitive)
// Wikilinks like [[#Mixed Links Test]] preserve the original heading text.
if item.text.eq_ignore_ascii_case(anchor) {
self.select_outline_index(idx);
return Ok(());
}
}
Err(format!("Heading '{}' not found", anchor))
}
/// Load a file by relative path (checks for unsaved changes first)
///
/// Security: Validates path to prevent directory traversal attacks.
/// Files must be within the current file's directory or its subdirectories.
fn load_file(&mut self, relative_path: &PathBuf, anchor: Option<&str>) -> Result<(), String> {
// Check for unsaved changes before navigating to a different file
if self.has_unsaved_changes {
self.pending_navigation = Some(PendingNavigation::LoadFile(
relative_path.clone(),
anchor.map(|s| s.to_string()),
));
self.mode = AppMode::ConfirmSaveBeforeNav;
return Ok(()); // Not an error - we're asking user to confirm
}
self.load_file_internal(relative_path, anchor)
}
/// Internal file loading - skips unsaved changes check
///
/// Security: Validates path to prevent directory traversal attacks.
/// Files must be within the current file's directory or its subdirectories.
fn load_file_internal(
&mut self,
relative_path: &PathBuf,
anchor: Option<&str>,
) -> Result<(), String> {
// Reject absolute paths
if relative_path.is_absolute() {
return Err("Absolute paths are not allowed for security reasons".to_string());
}
// Reject paths containing .. components (path traversal)
if relative_path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
{
return Err("Path traversal (..) is not allowed for security reasons".to_string());
}
// Resolve path relative to current file
let current_dir = self
.current_file_path
.parent()
.ok_or("Cannot determine current directory")?;
let absolute_path = current_dir.join(relative_path);
// Verify the resolved path is within allowed boundaries
// (defense in depth - even though we rejected .., canonicalize to be sure)
if let (Ok(canonical_path), Ok(canonical_base)) =
(absolute_path.canonicalize(), current_dir.canonicalize())
&& !canonical_path.starts_with(&canonical_base)
{
return Err("Path escapes document directory boundary".to_string());
}
// Check for symlink (prevent symlink attacks)
if absolute_path.is_symlink() {
return Err("Symlinks are not allowed for security reasons".to_string());
}
// Check if file exists - if not, prompt to create it
if !absolute_path.exists() {
self.pending_file_create = Some(absolute_path.clone());
self.pending_file_create_message = Some(format!(
"File '{}' does not exist. Create it?",
relative_path.display()
));
self.mode = AppMode::ConfirmFileCreate;
return Ok(()); // Not an error - we're asking user to confirm
}
// Parse the new file
let new_document = crate::parser::parse_file(&absolute_path)
.map_err(|e| format!("Failed to load file: {}", e))?;
let new_filename = absolute_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.to_string();
// Save current state to history
self.save_to_history();
// Load new document
self.load_document(new_document, new_filename, absolute_path);
// Jump to anchor if specified
if let Some(anchor_name) = anchor {
let _ = self.jump_to_anchor(anchor_name);
}
Ok(())
}
/// Find and load a wikilinked file
///
/// Supports formats:
/// - `[[filename]]` - load file (tries .md, .markdown extensions)
/// - `[[filename#anchor]]` - load file and jump to anchor
/// - `[[#anchor]]` - jump to anchor in current document
/// - `[[path/to/file]]` - load file with path (e.g., `[[diary/notes.md]]`)
///
/// Security: Path traversal (..) and absolute paths are blocked.
/// The `load_file()` function provides additional security validation.
fn load_wikilink(&mut self, target: &str) -> Result<(), String> {
// Handle anchor-only wikilinks (e.g., [[#section]])
if let Some(anchor) = target.strip_prefix('#') {
// Jump to heading in current document
self.jump_to_anchor(anchor)?;
self.status_message = Some(format!("✓ Jumped to #{}", anchor));
return Ok(());
}
// Split target into file and optional anchor (e.g., "file#section" -> ("file", Some("section")))
let (file_target, anchor) = if let Some((file, anchor)) = target.split_once('#') {
(file, Some(anchor))
} else {
(target, None)
};
// Security: Reject path traversal attempts
if file_target.contains("..") {
return Err("WikiLinks cannot contain path traversal (..)".to_string());
}
// Security: Reject absolute paths
if file_target.starts_with('/') {
return Err("WikiLinks cannot be absolute paths".to_string());
}
// Security: Reject Windows absolute paths (drive letters)
#[cfg(windows)]
if file_target.len() >= 2 && file_target.chars().nth(1) == Some(':') {
return Err("WikiLinks cannot be absolute paths".to_string());
}
// Normalize backslashes to forward slashes for cross-platform compatibility
let file_target = file_target.replace('\\', "/");
// Try to find the file relative to current directory
let current_dir = self
.current_file_path
.parent()
.ok_or("Cannot determine current directory")?;
// Check if target already has a markdown extension
let file_target_lower = file_target.to_lowercase();
let has_md_extension = file_target_lower.ends_with(".md")
|| file_target_lower.ends_with(".markdown")
|| file_target_lower.ends_with(".mdown");
// Try various extensions (only add extensions if target doesn't already have one)
let candidates: Vec<String> = if has_md_extension {
// Already has markdown extension - just try as-is
vec![file_target.to_string()]
} else {
// Try with various extensions
vec![
format!("{}.md", file_target),
format!("{}.markdown", file_target),
file_target.to_string(),
]
};
for candidate in &candidates {
let path = current_dir.join(candidate);
// Check for symlinks
if path.is_symlink() {
continue; // Skip symlinks for security
}
if path.exists() {
return self.load_file(&PathBuf::from(candidate), anchor);
}
}
// File not found - prompt to create it (default to .md extension if not already present)
let default_filename = if has_md_extension {
file_target.to_string()
} else {
format!("{}.md", file_target)
};
let new_path = current_dir.join(&default_filename);
self.pending_file_create = Some(new_path);
self.pending_file_create_message = Some(format!(
"Wikilink '[[{}]]' not found. Create '{}'?",
target, default_filename
));
self.mode = AppMode::ConfirmFileCreate;
Ok(()) // Not an error - we're asking user to confirm
}
/// Save current state to history before navigating away
fn save_to_history(&mut self) {
let state = FileState {
path: self.current_file_path.clone(),
document: self.document.clone(),
filename: self.filename.clone(),
selected_heading: self.selected_heading_text().map(|s| s.to_string()),
content_scroll: self.content_scroll,
outline_state_selected: self.outline_state.selected(),
};
self.file_history.push(state);
// Clear forward history when navigating to a new file
self.file_future.clear();
}
/// Load a new document and update all related state
fn load_document(&mut self, document: Document, filename: String, path: PathBuf) {
// Signal file watcher if path changed
if self.current_file_path != path {
self.file_path_changed = true;
}
self.document = document;
self.filename = filename;
self.current_file_path = path;
// Rebuild tree and outline (with overview entry if applicable)
self.tree = self.document.build_tree();
self.rebuild_outline_items();
// Reset selection to first item
let mut outline_state = ListState::default();
if !self.outline_items.is_empty() {
outline_state.select(Some(0));
}
self.outline_state = outline_state;
self.outline_scroll_state = ScrollbarState::new(self.outline_items.len());
// Reset content scroll
self.content_scroll = 0;
let content_lines = self.document.content.lines().count();
self.content_height = content_lines;
self.content_scroll_state = ScrollbarState::new(content_lines);
// Clear previous selection tracking
self.previous_selection = None;
// Index interactive elements (links, images, etc.) even in normal mode
// This allows inline images to render without entering interactive mode
let content = self.document.content.clone();
use crate::parser::content::parse_content;
let blocks = parse_content(&content, 0);
self.interactive_state.index_elements(&blocks);
self.populate_image_cache();
// Detect LaTeX content for status hint
self.latex_detected = content.contains("\\begin{")
|| content.contains("\\end{")
|| content.contains("\\textbf{")
|| content.contains("\\textit{")
|| content.contains("\\usepackage")
|| content.contains("\\documentclass")
|| content.contains("\\newpage")
|| content.contains("\\section{");
if self.latex_detected && self.should_hide_latex() && !self.latex_hint_shown {
self.latex_hint_shown = true;
self.set_status_message("LaTeX detected · filtered via hide_latex in config");
}
}
/// Navigate back in file history
pub fn go_back(&mut self) -> Result<(), String> {
let previous_state = self
.file_history
.pop()
.ok_or("No previous file in history")?;
// Save current state to future stack
let current_state = FileState {
path: self.current_file_path.clone(),
document: self.document.clone(),
filename: self.filename.clone(),
selected_heading: self.selected_heading_text().map(|s| s.to_string()),
content_scroll: self.content_scroll,
outline_state_selected: self.outline_state.selected(),
};
self.file_future.push(current_state);
// Restore previous state
self.restore_file_state(previous_state);
Ok(())
}
/// Navigate forward in file history
pub fn go_forward(&mut self) -> Result<(), String> {
let next_state = self.file_future.pop().ok_or("No next file in history")?;
// Save current state to history stack
let current_state = FileState {
path: self.current_file_path.clone(),
document: self.document.clone(),
filename: self.filename.clone(),
selected_heading: self.selected_heading_text().map(|s| s.to_string()),
content_scroll: self.content_scroll,
outline_state_selected: self.outline_state.selected(),
};
self.file_history.push(current_state);
// Restore next state
self.restore_file_state(next_state);
Ok(())
}
/// Restore a file state from history
fn restore_file_state(&mut self, state: FileState) {
self.load_document(state.document, state.filename, state.path);
// Restore selection and scroll position
if let Some(selected_idx) = state.outline_state_selected
&& selected_idx < self.outline_items.len()
{
self.select_outline_index(selected_idx);
}
self.content_scroll = state.content_scroll;
self.content_scroll_state = self
.content_scroll_state
.position(state.content_scroll as usize);
}
/// Reload current file from disk (used after external editing)
pub fn reload_current_file(&mut self) -> Result<(), String> {
// Save current state to restore after reload
let current_selection = self.selected_heading_text().map(|s| s.to_string());
let current_scroll = self.content_scroll;
// Reload the file
let content = std::fs::read_to_string(&self.current_file_path)
.map_err(|e| format!("Failed to reload file: {}", e))?;
let document = crate::parser::parse_markdown(&content);
let filename = self
.current_file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("file")
.to_string();
self.load_document(document, filename, self.current_file_path.clone());
// Try to restore selection if the heading still exists
if let Some(heading) = current_selection {
self.select_by_text(&heading);
}
// Restore scroll position (may be adjusted if content changed)
if (current_scroll as usize) < self.content_height {
self.content_scroll = current_scroll;
self.content_scroll_state = self.content_scroll_state.position(current_scroll as usize);
}
Ok(())
}
/// Enter interactive mode - build element index and enter mode
pub fn enter_interactive_mode(&mut self) {
// Exit raw source view if active (interactive elements aren't visible in raw mode)
if self.show_raw_source {
self.show_raw_source = false;
}
// Get current section content to index
let content = self.current_section_content();
// Parse content into blocks
use crate::parser::content::parse_content;
let blocks = parse_content(&content, 0);
// Index interactive elements
self.interactive_state.index_elements(&blocks);
self.populate_image_cache();
// Enter interactive mode at current scroll position (preserve user's view)
self.interactive_state
.enter_at_scroll_position(self.content_scroll as usize);
self.mode = AppMode::Interactive;
// Only scroll if the selected element is not fully visible
self.scroll_to_interactive_element(self.content_viewport_height);
// Set status message
if self.interactive_state.elements.is_empty() {
self.status_message = Some("⚠ No interactive elements in this section".to_string());
} else {
self.status_message = Some(format!(
"✓ Interactive mode: {} elements found (Tab to cycle)",
self.interactive_state.elements.len()
));
}
}
/// Exit interactive mode and return to normal
pub fn exit_interactive_mode(&mut self) {
self.interactive_state.exit();
self.mode = AppMode::Normal;
self.status_message = None;
}
/// Confirm file creation and open the new file
pub fn confirm_file_create(&mut self) -> Result<(), String> {
if let Some(path) = self.pending_file_create.take() {
// Create parent directories if needed
if let Some(parent) = path.parent()
&& !parent.exists()
{
std::fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create directory: {}", e))?;
}
// Create the file with default content
let filename = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("untitled");
let default_content = format!("# {}\n\n", filename);
std::fs::write(&path, &default_content)
.map_err(|e| format!("Failed to create file: {}", e))?;
// Load the new file
let relative_path = path
.file_name()
.map(PathBuf::from)
.unwrap_or_else(|| path.clone());
self.pending_file_create_message = None;
self.mode = AppMode::Normal;
// Load the newly created file
self.load_file(&relative_path, None)?;
self.status_message = Some(format!("✓ Created and opened {}", relative_path.display()));
self.exit_link_follow_mode();
}
Ok(())
}
/// Cancel file creation and return to previous mode
pub fn cancel_file_create(&mut self) {
self.pending_file_create = None;
self.pending_file_create_message = None;
self.mode = AppMode::Normal;
self.status_message = Some("File creation cancelled".to_string());
}
/// Get the currently selected interactive element
pub fn get_selected_interactive_element(
&self,
) -> Option<&crate::tui::interactive::InteractiveElement> {
self.interactive_state.current_element()
}
/// Activate the currently selected interactive element
pub fn activate_interactive_element(&mut self) -> Result<(), String> {
use crate::tui::interactive::ElementType;
let element = match self.interactive_state.current_element() {
Some(elem) => elem.clone(),
None => return Err("No element selected".to_string()),
};
match &element.element_type {
ElementType::Details { .. } => {
// Toggle details expansion
self.interactive_state.toggle_details(element.id);
// Re-index elements since expanded state changed content
self.reindex_interactive_elements();
self.status_message = Some("✓ Toggled details".to_string());
Ok(())
}
ElementType::Checkbox {
checked,
block_idx,
item_idx,
..
} => {
// Toggle checkbox and save to file
self.toggle_checkbox_and_save(*block_idx, *item_idx, *checked)?;
Ok(())
}
ElementType::Link { link, .. } => {
// Follow link using existing link follow logic
self.follow_link_from_interactive(&link.clone())?;
Ok(())
}
ElementType::CodeBlock { content, .. } => {
// Copy code to clipboard
self.copy_to_clipboard(content)?;
self.status_message = Some("✓ Code copied to clipboard".to_string());
Ok(())
}
ElementType::Image { src, alt, .. } => {
if self.images_enabled {
// Open image modal to view the image fullscreen
self.open_image_modal(src);
self.status_message = Some(format!("📸 Viewing: {} (Esc:Close)", alt));
} else {
self.status_message =
Some("Images disabled (use --images or config to enable)".to_string());
}
Ok(())
}
ElementType::Table { rows, cols, .. } => {
// Enter table navigation mode
self.interactive_state.enter_table_mode()?;
self.status_message =
Some(self.interactive_state.table_status_text(rows + 1, *cols));
Ok(())
}
}
}
/// Re-index interactive elements after state changes
pub fn reindex_interactive_elements(&mut self) {
let content = self.current_section_content();
use crate::parser::content::parse_content;
let blocks = parse_content(&content, 0);
self.interactive_state.index_elements(&blocks);
self.populate_image_cache();
}
/// Toggle a checkbox and save changes to the file
fn toggle_checkbox_and_save(
&mut self,
block_idx: usize,
item_idx: usize,
checked: bool,
) -> Result<(), String> {
// Get the checkbox content text to use as identifier
let checkbox_content = {
let content = self.current_section_content();
use crate::parser::content::parse_content;
let blocks = parse_content(&content, 0);
if let Some(crate::parser::output::Block::List { items, .. }) = blocks.get(block_idx) {
items.get(item_idx).map(|item| item.content.clone())
} else {
None
}
};
let checkbox_content =
checkbox_content.ok_or_else(|| "Could not find checkbox content".to_string())?;
// Read the current file
let file_content = std::fs::read_to_string(&self.current_file_path)
.map_err(|e| format!("Failed to read file: {}", e))?;
// Find and toggle the checkbox in the file content
let new_content =
self.toggle_checkbox_by_content(&file_content, &checkbox_content, checked)?;
// Atomic write: write to temp file, then rename (prevents data corruption)
use std::io::Write;
let parent_dir = self
.current_file_path
.parent()
.ok_or("Cannot determine parent directory")?;
let mut temp_file = tempfile::NamedTempFile::new_in(parent_dir)
.map_err(|e| format!("Failed to create temp file: {}", e))?;
temp_file
.write_all(new_content.as_bytes())
.map_err(|e| format!("Failed to write temp file: {}", e))?;
temp_file
.flush()
.map_err(|e| format!("Failed to flush temp file: {}", e))?;
// Atomic rename (same filesystem guarantees atomicity)
temp_file
.persist(&self.current_file_path)
.map_err(|e| format!("Failed to save file: {}", e))?;
// Save scroll position and interactive element index before reload
let saved_scroll = self.content_scroll;
let saved_element_idx = self.interactive_state.current_index;
// Reload the document
self.reload_current_file()?;
// Re-index interactive elements
self.reindex_interactive_elements();
// Restore scroll position (clamped to valid range)
self.content_scroll = saved_scroll.min(self.max_content_scroll());
self.content_scroll_state = self
.content_scroll_state
.position(self.content_scroll as usize);
// Restore interactive element selection if still valid
if let Some(idx) = saved_element_idx
&& idx < self.interactive_state.elements.len()
{
self.interactive_state.current_index = Some(idx);
}
// IMPORTANT: Sync previous_selection to prevent update_content_metrics() from resetting scroll
// After reload, load_document() sets previous_selection = None, but current selection is restored.
// Without this sync, update_content_metrics() thinks selection changed and resets scroll to 0.
self.previous_selection = self.selected_heading_text().map(|s| s.to_string());
// Suppress file watcher for this save - we already reloaded internally
// Without this, file watcher detects our save and triggers a second reload
self.suppress_file_watch = true;
let new_state = if checked { "unchecked" } else { "checked" };
self.status_message = Some(format!("✓ Checkbox {} and saved", new_state));
Ok(())
}
/// Toggle a checkbox in markdown content by matching the content text
fn toggle_checkbox_by_content(
&self,
file_content: &str,
checkbox_text: &str,
current_checked: bool,
) -> Result<String, String> {
let lines: Vec<&str> = file_content.lines().collect();
let mut result = Vec::new();
let mut found = false;
// Clean the checkbox text to match (remove any checkbox markers if present)
let clean_text = checkbox_text
.trim_start()
.trim_start_matches("[x]")
.trim_start_matches("[X]")
.trim_start_matches("[ ]")
.trim();
for line in lines {
let trimmed = line.trim_start();
// Check if this is a checkbox line
if (trimmed.starts_with("- [ ]")
|| trimmed.starts_with("- [x]")
|| trimmed.starts_with("- [X]"))
&& !found
{
// Extract the text after the checkbox marker
let line_text = trimmed
.trim_start_matches("- [ ]")
.trim_start_matches("- [x]")
.trim_start_matches("- [X]")
.trim();
// Check if this matches our target checkbox
let stripped_line_text = crate::parser::utils::strip_markdown_inline(line_text);
if stripped_line_text == clean_text {
// Toggle the checkbox
let new_line = if current_checked {
// Change [x] or [X] to [ ]
line.replacen("[x]", "[ ]", 1).replacen("[X]", "[ ]", 1)
} else {
// Change [ ] to [x]
line.replacen("[ ]", "[x]", 1)
};
result.push(new_line);
found = true;
} else {
result.push(line.to_string());
}
} else {
result.push(line.to_string());
}
}
if !found {
return Err(format!("Checkbox not found in file: '{}'", clean_text));
}
Ok(result.join("\n") + "\n")
}
/// Follow a link from interactive mode
fn follow_link_from_interactive(&mut self, link: &crate::parser::Link) -> Result<(), String> {
use crate::parser::LinkTarget;
match &link.target {
LinkTarget::Anchor(anchor) => {
// Jump to heading in current document
self.jump_to_anchor(anchor)?;
self.exit_interactive_mode();
self.status_message = Some(format!("✓ Jumped to #{}", anchor));
Ok(())
}
LinkTarget::RelativeFile { path, anchor } => {
if self.resolve_relative_file_link(path, anchor)? {
self.exit_interactive_mode();
}
Ok(())
}
LinkTarget::WikiLink { target, .. } => {
// Try to find and load the wikilinked file
self.load_wikilink(target)?;
// Only exit interactive mode if we're not prompting for file creation
if self.mode != AppMode::ConfirmFileCreate {
self.exit_interactive_mode();
}
Ok(())
}
LinkTarget::External(url) => {
// Security: Validate URL scheme (only http/https allowed)
if !url.starts_with("http://") && !url.starts_with("https://") {
return Err(
"Unsafe URL scheme. Only http:// and https:// URLs are allowed."
.to_string(),
);
}
// Use the `open` crate for safe URL opening (no shell injection)
open::that(url).map_err(|e| format!("Failed to open URL: {}", e))?;
self.status_message = Some(format!("✓ Opened {}", url));
Ok(())
}
}
}
/// Copy text to clipboard
fn copy_to_clipboard(&mut self, text: &str) -> Result<(), String> {
if let Some(clipboard) = &mut self.clipboard {
clipboard
.set_text(text.to_string())
.map_err(|e| format!("Clipboard error: {}", e))?;
Ok(())
} else {
Err("Clipboard not available".to_string())
}
}
/// Get table data for current interactive element
fn get_current_table_data(&self) -> Option<(Vec<String>, Vec<Vec<String>>)> {
if let Some(element) = self.interactive_state.current_element()
&& let crate::tui::interactive::ElementType::Table { block_idx, .. } =
&element.element_type
{
// Parse current section to get table data
let content = self.current_section_content();
use crate::parser::content::parse_content;
let blocks = parse_content(&content, 0);
if let Some(crate::parser::output::Block::Table { headers, rows, .. }) =
blocks.get(*block_idx)
{
return Some((headers.clone(), rows.clone()));
}
}
None
}
/// Copy table cell to clipboard
pub fn copy_table_cell(&mut self) -> Result<(), String> {
if let Some((headers, rows)) = self.get_current_table_data()
&& let Some(cell) = self.interactive_state.get_table_cell(&headers, &rows)
{
self.copy_to_clipboard(&cell)?;
self.status_message = Some(format!("✓ Cell copied: {}", cell));
return Ok(());
}
Err("No cell selected".to_string())
}
/// Copy table row to clipboard (tab-separated)
pub fn copy_table_row(&mut self) -> Result<(), String> {
if let Some((headers, rows)) = self.get_current_table_data()
&& let Some(row) = self.interactive_state.get_table_row(&headers, &rows)
{
let row_text = row.join("\t");
self.copy_to_clipboard(&row_text)?;
self.status_message = Some("✓ Row copied (tab-separated)".to_string());
return Ok(());
}
Err("No row selected".to_string())
}
/// Copy entire table as markdown
pub fn copy_table_markdown(&mut self) -> Result<(), String> {
if let Some((headers, rows)) = self.get_current_table_data() {
let mut table_md = String::new();
// Header row
table_md.push_str("| ");
table_md.push_str(&headers.join(" | "));
table_md.push_str(" |\n");
// Separator row
table_md.push_str("| ");
table_md.push_str(&vec!["---"; headers.len()].join(" | "));
table_md.push_str(" |\n");
// Data rows
for row in &rows {
table_md.push_str("| ");
table_md.push_str(&row.join(" | "));
table_md.push_str(" |\n");
}
self.copy_to_clipboard(&table_md)?;
self.status_message = Some("✓ Table copied as markdown".to_string());
Ok(())
} else {
Err("No table data available".to_string())
}
}
/// Enter cell edit mode for the currently selected table cell
pub fn enter_cell_edit_mode(&mut self) -> Result<(), String> {
if let Some((headers, rows)) = self.get_current_table_data()
&& let Some((row, col)) = self.interactive_state.get_table_position()
{
// Get current cell value
let cell_value = if row == 0 {
// Header row
headers.get(col).cloned().unwrap_or_default()
} else {
// Data row
rows.get(row - 1)
.and_then(|r| r.get(col))
.cloned()
.unwrap_or_default()
};
self.cell_edit_value = cell_value.clone();
self.cell_edit_original_value = cell_value; // Store original for undo
self.cell_edit_row = row;
self.cell_edit_col = col;
self.mode = AppMode::CellEdit;
return Ok(());
}
Err("No cell selected for editing".to_string())
}
/// Sanitize table cell content to prevent markdown injection
fn sanitize_table_cell(value: &str) -> String {
value
.replace('|', "\\|") // Escape pipe characters (table delimiters)
.replace(['\n', '\r'], " ") // Replace newlines and carriage returns
}
/// Buffer the edited cell value in memory (does not write to file)
/// Use save_pending_edits_to_file() to write changes to disk
pub fn save_edited_cell(&mut self) -> Result<(), String> {
// Sanitize the cell value to prevent table structure corruption
let sanitized_value = Self::sanitize_table_cell(&self.cell_edit_value);
// Skip if no actual change was made
if sanitized_value == self.cell_edit_original_value {
self.status_message = Some("No changes made".to_string());
return Ok(());
}
// Calculate the table index for this edit
let table_index = self.calculate_current_table_index()?;
// Store the edit in the pending buffer for undo capability
let pending_edit = PendingEdit {
table_index,
row: self.cell_edit_row,
col: self.cell_edit_col,
original_value: self.cell_edit_original_value.clone(),
new_value: sanitized_value.clone(),
};
self.pending_edits.push(pending_edit);
self.has_unsaved_changes = true;
// Apply the edit to the in-memory document content
let new_content = self.replace_table_cell_in_file(
&self.document.content,
table_index,
self.cell_edit_row,
self.cell_edit_col,
&sanitized_value,
)?;
// Update the in-memory document content
self.document.content = new_content;
// Re-parse headings if needed (table edits don't affect heading structure)
// The document tree stays the same, only content changed
let edit_count = self.pending_edits.len();
self.status_message = Some(format!(
"✓ Cell updated ({} unsaved change{})",
edit_count,
if edit_count == 1 { "" } else { "s" }
));
Ok(())
}
/// Calculate the table index for the currently selected table element
fn calculate_current_table_index(&self) -> Result<usize, String> {
use crate::parser::content::parse_content;
use crate::parser::output::Block;
// Get the current section content to find the right table
let section_content = self.current_section_content();
// Parse to find the table block
let blocks = parse_content(§ion_content, 0);
// Find the block index of the current table element
if let Some(element) = self.interactive_state.current_element() {
let block_idx = element.id.block_idx;
if let Some(Block::Table { .. }) = blocks.get(block_idx) {
// Count tables before this one in the section
let tables_before_in_section: usize = blocks[..block_idx]
.iter()
.filter(|b| matches!(b, Block::Table { .. }))
.count();
// Use heading offset to find section start (avoids unreliable string search)
let section_start = self
.selected_heading_text()
.and_then(|text| self.document.find_heading(text))
.map(|h| h.offset)
.unwrap_or(0);
let content_before_section =
&self.document.content[..section_start.min(self.document.content.len())];
// Count tables (groups of | lines) before section
let mut table_count_before = 0;
let mut in_table = false;
for line in content_before_section.lines() {
let trimmed = line.trim();
if trimmed.starts_with('|') && trimmed.ends_with('|') {
if !in_table {
in_table = true;
table_count_before += 1;
}
} else {
in_table = false;
}
}
return Ok(table_count_before + tables_before_in_section);
}
}
Err("Could not locate table".to_string())
}
/// Write all pending edits to the file
pub fn save_pending_edits_to_file(&mut self) -> Result<(), String> {
use std::io::Write;
if !self.has_unsaved_changes {
self.status_message = Some("No changes to save".to_string());
return Ok(());
}
// Atomic write: write to temp file, then rename (prevents data corruption)
let parent_dir = self
.current_file_path
.parent()
.ok_or("Cannot determine parent directory")?;
let mut temp_file = tempfile::NamedTempFile::new_in(parent_dir)
.map_err(|e| format!("Failed to create temp file: {}", e))?;
temp_file
.write_all(self.document.content.as_bytes())
.map_err(|e| format!("Failed to write temp file: {}", e))?;
temp_file
.flush()
.map_err(|e| format!("Failed to flush temp file: {}", e))?;
// Suppress file watcher for our own save
self.suppress_file_watch = true;
// Atomic rename
temp_file
.persist(&self.current_file_path)
.map_err(|e| format!("Failed to save file: {}", e))?;
// Clear the pending edits buffer
let edit_count = self.pending_edits.len();
self.pending_edits.clear();
self.has_unsaved_changes = false;
self.status_message = Some(format!(
"✓ Saved {} change{} to {}",
edit_count,
if edit_count == 1 { "" } else { "s" },
self.filename
));
Ok(())
}
/// Undo the last pending edit
pub fn undo_last_edit(&mut self) -> Result<(), String> {
if let Some(edit) = self.pending_edits.pop() {
// Apply the original value back to the in-memory content
let new_content = self.replace_table_cell_in_file(
&self.document.content,
edit.table_index,
edit.row,
edit.col,
&edit.original_value,
)?;
self.document.content = new_content;
self.has_unsaved_changes = !self.pending_edits.is_empty();
if self.pending_edits.is_empty() {
self.status_message = Some("✓ Undone - no unsaved changes".to_string());
} else {
let remaining = self.pending_edits.len();
self.status_message = Some(format!(
"✓ Undone ({} unsaved change{} remaining)",
remaining,
if remaining == 1 { "" } else { "s" }
));
}
Ok(())
} else {
self.status_message = Some("Nothing to undo".to_string());
Ok(())
}
}
/// Find and replace a cell in a specific table
/// table_index: which table to modify (0-indexed among tables in the content)
fn replace_table_cell_in_file(
&self,
content: &str,
table_index: usize,
row: usize,
col: usize,
new_value: &str,
) -> Result<String, String> {
let lines: Vec<&str> = content.lines().collect();
let mut result = Vec::new();
let mut in_table = false;
let mut table_row_idx = 0;
let mut current_table_index = 0;
let mut modified = false;
for line in lines {
let trimmed = line.trim();
// Detect table start (line starting with |)
if trimmed.starts_with('|') && trimmed.ends_with('|') {
if !in_table {
in_table = true;
table_row_idx = 0;
}
// Skip separator rows (| --- | --- |)
if trimmed.contains("---") {
result.push(line.to_string());
continue;
}
// Only modify the target table at the target row
if current_table_index == table_index && table_row_idx == row && !modified {
// Replace this row's cell
let new_line = self.replace_cell_in_row(line, col, new_value);
result.push(new_line);
modified = true;
} else {
result.push(line.to_string());
}
table_row_idx += 1;
} else {
if in_table {
// Exiting a table - increment table counter
in_table = false;
current_table_index += 1;
}
result.push(line.to_string());
}
}
if modified {
Ok(result.join("\n"))
} else {
Err(format!(
"Table {} not found or row {} not found",
table_index, row
))
}
}
/// Replace a specific cell in a table row line
fn replace_cell_in_row(&self, line: &str, col: usize, new_value: &str) -> String {
// Split by | and reconstruct
let parts: Vec<&str> = line.split('|').collect();
// Table format: | cell0 | cell1 | cell2 |
// After split: ["", " cell0 ", " cell1 ", " cell2 ", ""]
let mut new_parts = Vec::new();
for (i, part) in parts.iter().enumerate() {
if i == 0 || i == parts.len() - 1 {
// Keep empty parts at start/end
new_parts.push(part.to_string());
} else if i - 1 == col {
// This is the cell to replace (accounting for leading empty part)
new_parts.push(format!(" {} ", new_value));
} else {
new_parts.push(part.to_string());
}
}
new_parts.join("|")
}
/// Resolve an image path relative to the current markdown file.
///
/// Supports both relative and absolute paths:
/// - Relative paths are resolved against the current file's directory
/// - Absolute paths are returned as-is
///
/// # Examples
///
/// If current file is `/docs/file.md`:
/// - `./images/photo.png` → `/docs/images/photo.png`
/// - `../assets/logo.png` → `/assets/logo.png`
/// - `/etc/hosts` → `/etc/hosts`
pub fn resolve_image_path(&self, src: &str) -> Result<std::path::PathBuf, String> {
let path = std::path::Path::new(src);
if path.is_absolute() {
return Ok(path.to_path_buf());
}
// Resolve relative to markdown file's directory
let base_dir = self
.current_file_path
.parent()
.ok_or_else(|| "No parent directory for current file".to_string())?;
Ok(base_dir.join(src))
}
}