aboutsummaryrefslogtreecommitdiff
path: root/src/ecex.c
blob: 7206b96ac8b2ee840ed1fd1e1ad9de00f8aa953c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
#include "ecex.h"
#include "media.h"

#include "ccdjit.h"
#include "common.h"
#include "config.h"
#include "util.h"
#include "path.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

extern FILE *popen(const char *command, const char *type);
extern int pclose(FILE *stream);
extern int kill(pid_t pid, int sig);

#define ECEX_INITIAL_BUFFER_CAP 8
#define ECEX_INITIAL_COMMAND_CAP 32
#define ECEX_INITIAL_KEYBIND_CAP 32
#define ECEX_INITIAL_WINDOW_CAP 4
#define ECEX_INITIAL_MODE_CAP 8
#define ECEX_INITIAL_MODE_KEYBIND_CAP 16
#define ECEX_INITIAL_HOOK_CAP 8

ecex_window_t *ecex_current_window(ecex_t *ed);
static void ecex_clear_command_hooks(ecex_t *ed);
static void ecex_clear_prefix_hooks(ecex_t *ed);
static void ecex_clear_buffer_hooks(ecex_t *ed);
static void ecex_clear_completion_providers(ecex_t *ed);
static int ecex_complete_at_point_direction(ecex_t *ed, int direction);
static int ecex_indent_for_tab(ecex_t *ed);


void *ecex_config_alloc(size_t size) {
    return malloc(size ? size : 1);
}

void *ecex_config_calloc(size_t count, size_t size) {
    if (count == 0) count = 1;
    if (size == 0) size = 1;
    return calloc(count, size);
}

void ecex_config_free(void *ptr) {
    free(ptr);
}

double ecex_time_seconds(void) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
}

void ecex_mem_zero(void *ptr, size_t size) {
    if (!ptr || size == 0) return;
    memset(ptr, 0, size);
}


int ecex_i32_get(const int *items, size_t index) {
    if (!items) return 0;
    return items[index];
}

void ecex_i32_set(int *items, size_t index, int value) {
    if (!items) return;
    items[index] = value;
}

int ecex_run_plugin_file_handlers(ecex_t *ed, buffer_t *buffer) {
    return ecex_plugin_file_handlers_run(ed, buffer);
}

int ecex_prng_next_bounded(unsigned int *state, int bound) {
    unsigned int x;
    unsigned int limit;

    if (!state || bound <= 0) return 0;

    x = *state;
    if (x == 0u) x = 0x6d2b79f5u;

    /* Xorshift32. Keep this host-side so CCDJIT plugins do not depend on
     * unsigned multiply/divide lowering details for game logic randomness. */
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    if (x == 0u) x = 0xa5a5a5a5u;
    *state = x;

    /* Avoid modulo bias enough for tiny bounds without libc. */
    limit = 0xffffffffu - (0xffffffffu % (unsigned int)bound);
    while (x >= limit) {
        x ^= x << 13;
        x ^= x >> 17;
        x ^= x << 5;
        if (x == 0u) x = 0x9e3779b9u;
        *state = x;
    }

    return (int)(x % (unsigned int)bound);
}


int ecex_random_bounded(int bound) {
    static unsigned int state = 0x7f4a7c15u;
    unsigned int mix;

    if (bound <= 0) return 0;
    /* Host-owned PRNG for plugins that should not pass writable state pointers
     * through the JIT ABI. Stir in a stack address so separate launches differ
     * enough for games/demos without requiring libc time calls from plugins. */
    mix = (unsigned int)(size_t)&bound;
    state ^= mix + 0x9e3779b9u + (state << 6) + (state >> 2);
    return ecex_prng_next_bounded(&state, bound);
}

static int ecex_file_browser_preview_current(ecex_t *ed);
static int ecex_file_browser_update_preview_if_enabled(ecex_t *ed);

static ecex_color_t ecex_color(float r, float g, float b) {
    ecex_color_t c = {r, g, b};
    return c;
}

static void ecex_mark_ui_changed(ecex_t *ed) {
    if (!ed) return;
    ed->ui_revision++;
}

static void ecex_mark_font_changed(ecex_t *ed) {
    if (!ed) return;
    ed->font_revision++;
    ecex_mark_ui_changed(ed);
}

static void ecex_theme_set_defaults(ecex_t *ed) {
    if (!ed) return;

    ed->theme.font_path = NULL;
    ed->theme.font_size = 22.0f;

    ed->theme.bg = ecex_color(0.08f, 0.09f, 0.11f);
    ed->theme.fg = ecex_color(0.88f, 0.88f, 0.86f);

    ed->theme.status_bg = ecex_color(0.15f, 0.15f, 0.18f);
    ed->theme.status_fg = ecex_color(0.86f, 0.86f, 0.84f);
    ed->theme.status_border = ecex_color(0.28f, 0.28f, 0.32f);

    ed->theme.cursor = ecex_color(1.0f, 1.0f, 1.0f);
    ed->theme.region_bg = ecex_color(0.22f, 0.34f, 0.48f);

    ed->theme.minibuffer_bg = ecex_color(0.10f, 0.11f, 0.14f);
    ed->theme.minibuffer_fg = ecex_color(0.95f, 0.95f, 0.90f);

    ed->theme.completion_fg = ecex_color(0.45f, 0.45f, 0.45f);
    ed->theme.completion_enabled = 1;

    ed->theme.interactive_highlight_bg = ecex_color(0.18f, 0.20f, 0.24f);
    ed->theme.interactive_highlight_fg = ecex_color(1.0f, 1.0f, 1.0f);
    ed->theme.current_line_bg = ecex_color(0.12f, 0.13f, 0.16f);
    ed->theme.search_bg = ecex_color(0.55f, 0.42f, 0.12f);
    ed->theme.line_numbers_enabled = 1;
    ed->theme.current_line_enabled = 1;
}

#define ECEX_COMMAND(name, fn) \
    do { \
        if (ecex_register_command(ed, (name), (fn)) != ECEX_OK) return ECEX_ERR; \
    } while (0)

#define ECEX_BIND(key, command) \
    do { \
        if (ecex_bind_key(ed, (key), (command)) != ECEX_OK) return ECEX_ERR; \
    } while (0)

#define CURRENT_BUFFER_OR_ERR(ed) \
    buffer_t *buf = ecex_current_buffer(ed); \
    if (!buf) return ECEX_ERR

static int cmd_quit(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    if (ecex_has_modified_buffers(ed)) {
        fprintf(stderr, "ecex: refusing to quit; modified buffers exist. Save or use force-quit.\n");
        return ECEX_ERR;
    }
    ed->should_quit = 1;
    return ECEX_OK;
}

static int cmd_force_quit(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    ed->should_quit = 1;
    return ECEX_OK;
}

static int cmd_next_buffer(ecex_t *ed) { return ecex_next_buffer(ed); }
static int cmd_previous_buffer(ecex_t *ed) { return ecex_previous_buffer(ed); }
static int cmd_split_window_right(ecex_t *ed) { return ecex_split_window_vertically(ed); }
static int cmd_split_window_below(ecex_t *ed) { return ecex_split_window_horizontally(ed); }
static int cmd_other_window(ecex_t *ed) { return ecex_other_window(ed); }
static int cmd_previous_window(ecex_t *ed) { return ecex_previous_window(ed); }
static int cmd_delete_window(ecex_t *ed) { return ecex_delete_window(ed); }
static int cmd_delete_other_windows(ecex_t *ed) { return ecex_delete_other_windows(ed); }
static int cmd_balance_windows(ecex_t *ed) { return ecex_balance_windows(ed); }

static int cmd_move_left(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_left(buf); return ECEX_OK; }
static int cmd_move_right(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_right(buf); return ECEX_OK; }
static int cmd_move_up(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    buffer_move_up(buf);
    ecex_file_browser_update_preview_if_enabled(ed);
    return ECEX_OK;
}
static int cmd_move_down(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    buffer_move_down(buf);
    ecex_file_browser_update_preview_if_enabled(ed);
    return ECEX_OK;
}
static int cmd_move_word_left(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_word_left(buf); return ECEX_OK; }
static int cmd_move_word_right(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_word_right(buf); return ECEX_OK; }
static int cmd_beginning_of_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_beginning_of_line(buf); return ECEX_OK; }
static int cmd_end_of_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_end_of_line(buf); return ECEX_OK; }
static int cmd_beginning_of_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_beginning_of_buffer(buf); return ECEX_OK; }
static int cmd_end_of_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_end_of_buffer(buf); return ECEX_OK; }

static int cmd_undo(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_undo(buf); }
static int cmd_redo(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_redo(buf); }
static int cmd_backspace(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_backspace(buf); }
static int cmd_delete_forward(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_delete_forward(buf); }
static int cmd_newline(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    if (buffer_is_interactive(buf)) {
        return ecex_interactive_activate_current_line(ed);
    }
    return buffer_insert_char(buf, '\n');
}
static int cmd_kill_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_kill_line(buf); }
static int cmd_clear_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_clear(buf); }
static int cmd_set_mark(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_set_mark(buf, buf->point); return ECEX_OK; }
static int cmd_clear_mark(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_clear_mark(buf); return ECEX_OK; }


static int cmd_yank(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    const char *text = ecex_clipboard_get(ed);
    if (!text || !text[0]) return ECEX_OK;
    return buffer_replace_selection(buf, text);
}

static int cmd_copy_region(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    if (!buffer_has_selection(buf)) return ECEX_OK;

    size_t start = 0;
    size_t end = 0;
    buffer_selection_range(buf, &start, &end);

    char *text = buffer_substring(buf, start, end);
    if (!text) return ECEX_ERR;

    int result = ecex_clipboard_set(ed, text);
    free(text);
    return result;
}

static int cmd_kill_region(ecex_t *ed) {
    CURRENT_BUFFER_OR_ERR(ed);
    if (!buffer_has_selection(buf)) return ECEX_OK;

    size_t start = 0;
    size_t end = 0;
    buffer_selection_range(buf, &start, &end);

    char *text = buffer_substring(buf, start, end);
    if (!text) return ECEX_ERR;

    int result = ecex_clipboard_set(ed, text);
    free(text);
    if (result != ECEX_OK) return result;

    return buffer_delete_selection(buf);
}

static int cmd_list_commands(ecex_t *ed) { return ecex_list_commands(ed); }
static int cmd_list_buffers(ecex_t *ed) { return ecex_list_buffers(ed); }
static int cmd_switch_buffer(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_SWITCH_BUFFER, "Switch buffer: "); return ECEX_OK; }
static int cmd_kill_buffer_command(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_KILL_BUFFER, "Kill buffer: "); return ECEX_OK; }
static int cmd_force_kill_buffer_command(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_FORCE_KILL_BUFFER, "Force kill buffer: "); return ECEX_OK; }
static int cmd_compile(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_COMPILE, "Compile: "); return ECEX_OK; }
static int cmd_grep(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_GREP, "Grep: "); return ECEX_OK; }
static int cmd_recompile(ecex_t *ed) { return ecex_rerun_compile(ed); }
static int cmd_regrep(ecex_t *ed) { return ecex_rerun_grep(ed); }
static int cmd_next_error(ecex_t *ed) { return ecex_next_interactive_action(ed); }
static int cmd_previous_error(ecex_t *ed) { return ecex_previous_interactive_action(ed); }
static int cmd_comment_region(ecex_t *ed) { return ecex_comment_region(ed); }
static int cmd_uncomment_region(ecex_t *ed) { return ecex_uncomment_region(ed); }
static int cmd_toggle_line_numbers(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    ecex_set_line_numbers_enabled(ed, !ed->theme.line_numbers_enabled);
    return ECEX_OK;
}

static int cmd_toggle_current_line(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    ecex_set_current_line_enabled(ed, !ed->theme.current_line_enabled);
    return ECEX_OK;
}
static int cmd_isearch_forward(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_ISEARCH_FORWARD, "I-search: "); return ECEX_OK; }
static int cmd_isearch_backward(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_ISEARCH_BACKWARD, "I-search backward: "); return ECEX_OK; }

static int cmd_find_file(ecex_t *ed) {
    ecex_request_prompt(ed, ECEX_PROMPT_FIND_FILE, "Find file: ");
    return ECEX_OK;
}

static int cmd_write_file(ecex_t *ed) {
    ecex_request_prompt(ed, ECEX_PROMPT_WRITE_FILE, "Write file: ");
    return ECEX_OK;
}

static int cmd_save_buffer(ecex_t *ed) {
    if (!ed) return ECEX_ERR;

    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf) return ECEX_ERR;

    if (!buf->path) {
        ecex_request_prompt(ed, ECEX_PROMPT_WRITE_FILE, "Write file: ");
        return ECEX_OK;
    }

    return ecex_save_current_buffer(ed);
}

static int cmd_eval_buffer(ecex_t *ed) {
    return ecex_eval_current_buffer(ed);
}

static int cmd_eval_line(ecex_t *ed) {
    return ecex_eval_current_line(ed);
}

static int cmd_eval_region(ecex_t *ed) {
    return ecex_eval_current_region(ed);
}

static int cmd_eval_file(ecex_t *ed) {
    ecex_request_prompt(ed, ECEX_PROMPT_EVAL_FILE, "Eval file: ");
    return ECEX_OK;
}

static int cmd_eval_rerun_last(ecex_t *ed) {
    return ecex_eval_rerun_last(ed);
}

static int cmd_quit_window(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    if (ecex_window_count(ed) > 1) return ecex_delete_window(ed);
    return ecex_previous_buffer(ed);
}

static int cmd_reload_config(ecex_t *ed) {
    return ecex_reload_config(ed);
}

static int cmd_indent_for_tab(ecex_t *ed) {
    return ecex_indent_for_tab(ed);
}

static int cmd_complete_at_point(ecex_t *ed) {
    return ecex_complete_at_point(ed);
}

static int cmd_complete_at_point_previous(ecex_t *ed) {
    return ecex_complete_at_point_direction(ed, -1);
}


/* Built-in file browser -------------------------------------------------- */

typedef struct ecex_file_entry {
    char *name;
    char *path;
    int is_dir;
    int is_image;
    long long size;
} ecex_file_entry_t;

static char ecex_fb_cwd[4096] = ".";
static char ecex_fb_history[64][4096];
static size_t ecex_fb_history_count = 0;
static size_t ecex_fb_history_index = 0;
static int ecex_fb_preview_expanded = 0;

static void ecex_file_entry_free(ecex_file_entry_t *entries, size_t count) {
    if (!entries) return;
    for (size_t i = 0; i < count; i++) {
        free(entries[i].name);
        free(entries[i].path);
    }
    free(entries);
}

static int ecex_file_entry_compare(const void *a, const void *b) {
    const ecex_file_entry_t *ea = (const ecex_file_entry_t *)a;
    const ecex_file_entry_t *eb = (const ecex_file_entry_t *)b;
    if (ea->is_dir != eb->is_dir) return eb->is_dir - ea->is_dir;
    return strcmp(ea->name ? ea->name : "", eb->name ? eb->name : "");
}

static int ecex_file_browser_collect(const char *dir, ecex_file_entry_t **out_entries, size_t *out_count) {
    if (out_entries) *out_entries = NULL;
    if (out_count) *out_count = 0;
    if (!dir || !out_entries || !out_count) return ECEX_ERR;

    DIR *d = opendir(dir);
    if (!d) return ECEX_ERR;

    size_t cap = 64;
    size_t count = 0;
    ecex_file_entry_t *entries = calloc(cap, sizeof(*entries));
    if (!entries) { closedir(d); return ECEX_ERR; }

    struct dirent *entry;
    while ((entry = readdir(d)) != NULL) {
        const char *name = entry->d_name;
        if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue;

        if (count == cap) {
            size_t new_cap = cap * 2;
            ecex_file_entry_t *grown = realloc(entries, new_cap * sizeof(*entries));
            if (!grown) break;
            memset(grown + cap, 0, (new_cap - cap) * sizeof(*grown));
            entries = grown;
            cap = new_cap;
        }

        char *path = ecex_path_join(dir, name);
        if (!path) continue;
        char *name_copy = ecex_strdup(name);
        if (!name_copy) { free(path); continue; }

        entries[count].name = name_copy;
        entries[count].path = path;
        entries[count].is_dir = ecex_path_is_dir(path);
        entries[count].is_image = ecex_path_is_image(path);
        entries[count].size = ecex_path_file_size(path);
        count++;
    }

    closedir(d);
    qsort(entries, count, sizeof(*entries), ecex_file_entry_compare);
    *out_entries = entries;
    *out_count = count;
    return ECEX_OK;
}

static void ecex_file_browser_push_history(const char *dir) {
    if (!dir || !dir[0]) return;
    if (ecex_fb_history_count > 0 && strcmp(ecex_fb_history[ecex_fb_history_index], dir) == 0) return;

    if (ecex_fb_history_index + 1 < ecex_fb_history_count) {
        ecex_fb_history_count = ecex_fb_history_index + 1;
    }

    if (ecex_fb_history_count == 64) {
        memmove(ecex_fb_history, ecex_fb_history + 1, sizeof(ecex_fb_history[0]) * 63);
        ecex_fb_history_count = 63;
        if (ecex_fb_history_index > 0) ecex_fb_history_index--;
    }

    ecex_path_copy(ecex_fb_history[ecex_fb_history_count], sizeof(ecex_fb_history[0]), dir);
    ecex_fb_history_index = ecex_fb_history_count;
    ecex_fb_history_count++;
}

static int ecex_file_browser_populate(ecex_t *ed, const char *dir, int push_history);
static int ecex_file_browser_move_to_action(buffer_t *buf, size_t action_index);

static int ecex_file_browser_open_action(ecex_t *ed,
                                         buffer_t *buffer,
                                         size_t line,
                                         const char *payload,
                                         void *userdata) {
    (void)buffer;
    (void)line;
    (void)userdata;
    if (!ed || !payload) return ECEX_ERR;

    char selected[4096];
    ecex_path_copy(selected, sizeof(selected), payload);

    if (ecex_path_is_dir(selected)) return ecex_file_browser_populate(ed, selected, 1);
    if (ecex_path_is_file(selected) && ecex_path_is_media(selected)) return ecex_media_open(ed, selected);
    if (ecex_path_is_file(selected)) return ecex_find_file(ed, selected);
    return ECEX_ERR;
}

static int ecex_file_browser_populate(ecex_t *ed, const char *dir, int push_history) {
    if (!ed) return ECEX_ERR;

    char *normalized = ecex_path_normalize((dir && dir[0]) ? dir : ecex_fb_cwd);
    if (!normalized) return ECEX_ERR;
    if (!ecex_path_is_dir(normalized)) {
        char *parent = ecex_path_dirname(normalized);
        free(normalized);
        normalized = parent;
        if (!normalized) return ECEX_ERR;
    }

    ecex_path_copy(ecex_fb_cwd, sizeof(ecex_fb_cwd), normalized);
    if (push_history) ecex_file_browser_push_history(ecex_fb_cwd);

    buffer_t *buf = ecex_find_buffer(ed, "*file-browser*");
    if (!buf) buf = ecex_create_interactive_buffer(ed, "*file-browser*");
    if (!buf) { free(normalized); return ECEX_ERR; }

    buffer_clear(buf);
    buffer_set_interactive(buf, 1);
    ecex_buffer_set_major_mode_by_name(ed, buf, "file-browser-mode");

    char line[8192];
    snprintf(line, sizeof(line),
             "File browser: %s\n\nKeys: RET/l open, h parent, g refresh, b/f history, v preview, m toggle preview, q quit.\n\n",
             ecex_fb_cwd);
    buffer_append(buf, line);

    char *parent = ecex_path_dirname(ecex_fb_cwd);
    if (parent) {
        ecex_interactive_append_line(ed, buf, "[..] parent", ecex_file_browser_open_action, parent, NULL);
        free(parent);
    }

    ecex_file_entry_t *entries = NULL;
    size_t count = 0;
    if (ecex_file_browser_collect(ecex_fb_cwd, &entries, &count) != ECEX_OK) {
        buffer_append(buf, "\nCould not read directory.\n");
    } else {
        for (size_t i = 0; i < count; i++) {
            const char *tag = entries[i].is_dir ? "[D]" : (entries[i].is_image ? "[I]" : (ecex_path_is_video(entries[i].path) ? "[V]" : "   "));
            if (entries[i].is_dir) {
                snprintf(line, sizeof(line), "%s %s/", tag, entries[i].name);
            } else if (entries[i].size >= 0) {
                snprintf(line, sizeof(line), "%s %s  (%lld bytes)", tag, entries[i].name, entries[i].size);
            } else {
                snprintf(line, sizeof(line), "%s %s", tag, entries[i].name);
            }
            ecex_interactive_append_line(ed, buf, line, ecex_file_browser_open_action, entries[i].path, NULL);
        }
    }
    ecex_file_entry_free(entries, count);

    if (ecex_fb_preview_expanded) {
        buffer_append(buf, "\nPreview pane is active: move up/down to update it, v refreshes, m closes it.\n");
    }

    buf->point = 0;
    buf->scroll_line = 0;
    buf->scroll_col = 0;
    if (buf->interactive_action_count > 0) {
        /* Start on the first actual directory entry instead of the [..] parent row.
         * That makes pressing m/v immediately show a useful preview. */
        ecex_file_browser_move_to_action(buf, buf->interactive_action_count > 1 ? 1 : 0);
    }
    buf->modified = 0;
    free(normalized);
    int result = ecex_switch_buffer(ed, "*file-browser*");
    if (result == ECEX_OK && ecex_fb_preview_expanded) {
        ecex_file_browser_update_preview_if_enabled(ed);
    }
    return result;
}

static int ecex_file_browser_current_payload(ecex_t *ed, char *out, size_t out_size) {
    if (!ed || !out || out_size == 0) return ECEX_ERR;
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf || !buffer_is_interactive(buf)) return ECEX_ERR;
    size_t line = buffer_current_line_number(buf);
    if (line > 0) line--;
    ecex_interactive_line_action_t *action = buffer_interactive_action_at_line(buf, line);
    if ((!action || !action->payload) && buf->interactive_action_count > 0) {
        action = &buf->interactive_actions[0];
    }
    if (!action || !action->payload) return ECEX_ERR;
    return ecex_path_copy(out, out_size, action->payload) == 0 ? ECEX_OK : ECEX_ERR;
}

static int ecex_file_browser_move_to_action(buffer_t *buf, size_t action_index) {
    if (!buf || !buffer_is_interactive(buf) || buf->interactive_action_count == 0) return ECEX_ERR;
    if (action_index >= buf->interactive_action_count) action_index = buf->interactive_action_count - 1;
    size_t target_line = buf->interactive_actions[action_index].line;
    size_t pos = 0;
    for (size_t line = 0; line < target_line && pos < buf->len; pos++) {
        if (buf->data[pos] == '\n') line++;
    }
    buffer_set_point(buf, pos);
    return ECEX_OK;
}

static buffer_t *ecex_file_preview_buffer(ecex_t *ed) {
    if (!ed) return NULL;
    buffer_t *preview = ecex_find_buffer(ed, "*file-preview*");
    if (!preview) preview = ecex_create_buffer(ed, "*file-preview*", NULL, 0);
    return preview;
}

static int ecex_file_browser_show_preview_pane(ecex_t *ed, buffer_t *preview) {
    if (!ed || !preview || ed->window_count == 0) return ECEX_ERR;

    size_t browser_window = ed->current_window_index;
    if (ed->window_count == 1) {
        if (ecex_split_window_vertically(ed) != ECEX_OK) return ECEX_ERR;
        ed->windows[ed->current_window_index].buffer = preview;
        ed->current_window_index = browser_window;
        return ecex_sync_current_buffer(ed);
    }

    size_t preview_window = (browser_window + 1) % ed->window_count;
    if (preview_window == browser_window && ed->window_count > 1) preview_window = 1;
    ed->windows[preview_window].buffer = preview;
    ed->current_window_index = browser_window;
    return ecex_sync_current_buffer(ed);
}

static int ecex_file_browser_close_preview_pane(ecex_t *ed) {
    if (!ed || ed->window_count <= 1) return ECEX_OK;
    buffer_t *preview = ecex_find_buffer(ed, "*file-preview*");
    if (!preview) return ECEX_OK;

    for (size_t i = 0; i < ed->window_count; i++) {
        if (ed->windows[i].buffer != preview) continue;
        memmove(&ed->windows[i], &ed->windows[i + 1], (ed->window_count - i - 1) * sizeof(ed->windows[0]));
        ed->window_count--;
        if (ed->current_window_index >= ed->window_count) ed->current_window_index = ed->window_count - 1;
        ecex_balance_windows(ed);
        return ecex_sync_current_buffer(ed);
    }
    return ECEX_OK;
}

static int ecex_file_browser_fill_preview(ecex_t *ed, buffer_t *preview, const char *path) {
    if (!ed || !preview || !path) return ECEX_ERR;

    if (ecex_path_is_media(path)) {
        return ecex_media_load_into_buffer(ed, path, preview);
    }

    ecex_media_buffer_clear(preview);
    ecex_buffer_set_major_mode_by_name(ed, preview, "special-mode");
    preview->read_only = 0;
    buffer_clear(preview);
    char line[8192];
    snprintf(line, sizeof(line), "Preview: %s\n\n", path);
    buffer_append(preview, line);

    if (ecex_path_is_dir(path)) {
        buffer_append(preview, "Directory. Press RET/l in *file-browser* to open it.\n");
    } else if (ecex_path_is_file(path)) {
        long long size = ecex_path_file_size(path);
        snprintf(line, sizeof(line), "File size: %lld bytes.\n\n", size);
        buffer_append(preview, line);
        FILE *f = fopen(path, "rb");
        if (f) {
            char chunk[8193];
            size_t n = fread(chunk, 1, sizeof(chunk) - 1, f);
            fclose(f);
            chunk[n] = '\0';
            int binary = 0;
            for (size_t i = 0; i < n; i++) {
                unsigned char c = (unsigned char)chunk[i];
                if (c == 0 || (c < 8) || (c > 13 && c < 32)) { binary = 1; break; }
            }
            if (binary) buffer_append(preview, "Binary file; text preview suppressed.\n");
            else buffer_append(preview, chunk);
        }
    }

    preview->modified = 0;
    preview->read_only = 1;
    return ECEX_OK;
}

static int ecex_file_browser_preview_current(ecex_t *ed) {
    char path[4096];
    if (ecex_file_browser_current_payload(ed, path, sizeof(path)) != ECEX_OK) return ECEX_ERR;

    buffer_t *preview = ecex_file_preview_buffer(ed);
    if (!preview) return ECEX_ERR;

    int result = ecex_file_browser_fill_preview(ed, preview, path);
    ecex_file_browser_show_preview_pane(ed, preview);
    return result;
}

static int ecex_file_browser_update_preview_if_enabled(ecex_t *ed) {
    if (!ed || !ecex_fb_preview_expanded) return ECEX_OK;
    buffer_t *buf = ecex_current_buffer(ed);
    const char *mode = buf ? ecex_buffer_major_mode_name(ed, buf) : NULL;
    if (!mode || strcmp(mode, "file-browser-mode") != 0) return ECEX_OK;
    return ecex_file_browser_preview_current(ed);
}

static int cmd_file_browser(ecex_t *ed) {
    char cwd[4096];
    ecex_path_cwd(cwd, sizeof(cwd));
    return ecex_file_browser_populate(ed, cwd, 1);
}

static int cmd_file_browser_here(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    if (buf && buf->path && buf->path[0]) {
        char *dir = ecex_path_dirname(buf->path);
        if (!dir) return ECEX_ERR;
        int result = ecex_file_browser_populate(ed, dir, 1);
        free(dir);
        return result;
    }
    return cmd_file_browser(ed);
}

static int cmd_file_browser_refresh(ecex_t *ed) { return ecex_file_browser_populate(ed, ecex_fb_cwd, 0); }

static int cmd_file_browser_parent(ecex_t *ed) {
    char *parent = ecex_path_dirname(ecex_fb_cwd);
    if (!parent) return ECEX_ERR;
    int result = ecex_file_browser_populate(ed, parent, 1);
    free(parent);
    return result;
}

static int cmd_file_browser_open(ecex_t *ed) { return ecex_interactive_activate_current_line(ed); }
static int cmd_file_browser_preview(ecex_t *ed) { return ecex_file_browser_preview_current(ed); }

static int cmd_file_browser_toggle_preview(ecex_t *ed) {
    ecex_fb_preview_expanded = !ecex_fb_preview_expanded;
    if (!ecex_fb_preview_expanded) {
        ecex_file_browser_close_preview_pane(ed);
        return ecex_file_browser_populate(ed, ecex_fb_cwd, 0);
    }
    int result = ecex_file_browser_populate(ed, ecex_fb_cwd, 0);
    if (result == ECEX_OK) ecex_file_browser_preview_current(ed);
    return result;
}

static int cmd_file_browser_history_back(ecex_t *ed) {
    if (ecex_fb_history_count == 0 || ecex_fb_history_index == 0) return ECEX_ERR;
    ecex_fb_history_index--;
    return ecex_file_browser_populate(ed, ecex_fb_history[ecex_fb_history_index], 0);
}

static int cmd_file_browser_history_forward(ecex_t *ed) {
    if (ecex_fb_history_count == 0 || ecex_fb_history_index + 1 >= ecex_fb_history_count) return ECEX_ERR;
    ecex_fb_history_index++;
    return ecex_file_browser_populate(ed, ecex_fb_history[ecex_fb_history_index], 0);
}

static int cmd_media_play_pause(ecex_t *ed) { return ecex_media_toggle_playback(ed); }

static int ecex_register_builtins(ecex_t *ed) {
    ECEX_COMMAND("quit", cmd_quit);
    ECEX_COMMAND("force-quit", cmd_force_quit);
    ECEX_COMMAND("find-file", cmd_find_file);
    ECEX_COMMAND("file-browser", cmd_file_browser);
    ECEX_COMMAND("file-browser-here", cmd_file_browser_here);
    ECEX_COMMAND("file-browser-refresh", cmd_file_browser_refresh);
    ECEX_COMMAND("file-browser-parent", cmd_file_browser_parent);
    ECEX_COMMAND("file-browser-open", cmd_file_browser_open);
    ECEX_COMMAND("file-browser-preview", cmd_file_browser_preview);
    ECEX_COMMAND("file-browser-toggle-preview", cmd_file_browser_toggle_preview);
    ECEX_COMMAND("file-browser-history-back", cmd_file_browser_history_back);
    ECEX_COMMAND("file-browser-history-forward", cmd_file_browser_history_forward);
    ECEX_COMMAND("media-play-pause", cmd_media_play_pause);
    ECEX_COMMAND("save-buffer", cmd_save_buffer);
    ECEX_COMMAND("write-file", cmd_write_file);
    ECEX_COMMAND("eval-buffer", cmd_eval_buffer);
    ECEX_COMMAND("eval-line", cmd_eval_line);
    ECEX_COMMAND("eval-region", cmd_eval_region);
    ECEX_COMMAND("eval-selection", cmd_eval_region);
    ECEX_COMMAND("eval-file", cmd_eval_file);
    ECEX_COMMAND("eval-rerun-last", cmd_eval_rerun_last);
    ECEX_COMMAND("revert-eval-buffer", cmd_eval_rerun_last);
    ECEX_COMMAND("quit-window", cmd_quit_window);
    ECEX_COMMAND("reload-config", cmd_reload_config);
    ECEX_COMMAND("list-commands", cmd_list_commands);
    ECEX_COMMAND("list-buffers", cmd_list_buffers);
    ECEX_COMMAND("switch-buffer", cmd_switch_buffer);
    ECEX_COMMAND("kill-buffer", cmd_kill_buffer_command);
    ECEX_COMMAND("force-kill-buffer", cmd_force_kill_buffer_command);
    ECEX_COMMAND("compile", cmd_compile);
    ECEX_COMMAND("recompile", cmd_recompile);
    ECEX_COMMAND("grep", cmd_grep);
    ECEX_COMMAND("regrep", cmd_regrep);
    ECEX_COMMAND("next-error", cmd_next_error);
    ECEX_COMMAND("previous-error", cmd_previous_error);
    ECEX_COMMAND("comment-region", cmd_comment_region);
    ECEX_COMMAND("uncomment-region", cmd_uncomment_region);
    ECEX_COMMAND("toggle-line-numbers", cmd_toggle_line_numbers);
    ECEX_COMMAND("toggle-current-line", cmd_toggle_current_line);
    ECEX_COMMAND("isearch-forward", cmd_isearch_forward);
    ECEX_COMMAND("isearch-backward", cmd_isearch_backward);
    ECEX_COMMAND("indent-for-tab-command", cmd_indent_for_tab);
    ECEX_COMMAND("complete-at-point", cmd_complete_at_point);
    ECEX_COMMAND("complete-at-point-previous", cmd_complete_at_point_previous);

    ECEX_COMMAND("next-buffer", cmd_next_buffer);
    ECEX_COMMAND("previous-buffer", cmd_previous_buffer);
    ECEX_COMMAND("split-window-right", cmd_split_window_right);
    ECEX_COMMAND("split-window-vertically", cmd_split_window_right);
    ECEX_COMMAND("split-window-below", cmd_split_window_below);
    ECEX_COMMAND("split-window-horizontally", cmd_split_window_below);
    ECEX_COMMAND("other-window", cmd_other_window);
    ECEX_COMMAND("previous-window", cmd_previous_window);
    ECEX_COMMAND("delete-window", cmd_delete_window);
    ECEX_COMMAND("delete-other-windows", cmd_delete_other_windows);
    ECEX_COMMAND("balance-windows", cmd_balance_windows);

    ECEX_COMMAND("move-left", cmd_move_left);
    ECEX_COMMAND("move-right", cmd_move_right);
    ECEX_COMMAND("move-up", cmd_move_up);
    ECEX_COMMAND("move-down", cmd_move_down);
    ECEX_COMMAND("move-word-left", cmd_move_word_left);
    ECEX_COMMAND("move-word-right", cmd_move_word_right);
    ECEX_COMMAND("beginning-of-line", cmd_beginning_of_line);
    ECEX_COMMAND("end-of-line", cmd_end_of_line);
    ECEX_COMMAND("beginning-of-buffer", cmd_beginning_of_buffer);
    ECEX_COMMAND("end-of-buffer", cmd_end_of_buffer);

    ECEX_COMMAND("undo", cmd_undo);
    ECEX_COMMAND("redo", cmd_redo);
    ECEX_COMMAND("backspace", cmd_backspace);
    ECEX_COMMAND("delete-forward", cmd_delete_forward);
    ECEX_COMMAND("newline", cmd_newline);
    ECEX_COMMAND("kill-line", cmd_kill_line);
    ECEX_COMMAND("clear-buffer", cmd_clear_buffer);
    ECEX_COMMAND("set-mark", cmd_set_mark);
    ECEX_COMMAND("clear-mark", cmd_clear_mark);
    ECEX_COMMAND("yank", cmd_yank);
    ECEX_COMMAND("paste", cmd_yank);
    ECEX_COMMAND("clipboard-yank", cmd_yank);
    ECEX_COMMAND("copy", cmd_copy_region);
    ECEX_COMMAND("copy-region", cmd_copy_region);
    ECEX_COMMAND("copy-region-as-kill", cmd_copy_region);
    ECEX_COMMAND("cut", cmd_kill_region);
    ECEX_COMMAND("kill-region", cmd_kill_region);
    ECEX_COMMAND("clipboard-kill-region", cmd_kill_region);

    ECEX_BIND("LEFT", "move-left");
    ECEX_BIND("RIGHT", "move-right");
    ECEX_BIND("UP", "move-up");
    ECEX_BIND("DOWN", "move-down");
    ECEX_BIND("HOME", "beginning-of-line");
    ECEX_BIND("END", "end-of-line");
    ECEX_BIND("C-HOME", "beginning-of-buffer");
    ECEX_BIND("C-END", "end-of-buffer");

    ECEX_BIND("C-b", "move-left");
    ECEX_BIND("C-f", "move-right");
    ECEX_BIND("C-p", "move-up");
    ECEX_BIND("C-n", "move-down");
    ECEX_BIND("M-b", "move-word-left");
    ECEX_BIND("M-f", "move-word-right");
    ECEX_BIND("C-a", "beginning-of-line");
    ECEX_BIND("C-e", "end-of-line");
    ECEX_BIND("M-<", "beginning-of-buffer");
    ECEX_BIND("M->", "end-of-buffer");
    ECEX_BIND("C-k", "kill-line");
    ECEX_BIND("C-SPC", "set-mark");
    ECEX_BIND("C-y", "yank");
    ECEX_BIND("C-v", "paste");
    ECEX_BIND("C-S-v", "paste");
    ECEX_BIND("C-c", "copy-region");
    ECEX_BIND("C-S-c", "copy-region");
    ECEX_BIND("C-S-x", "kill-region");
    ECEX_BIND("M-w", "copy-region-as-kill");
    ECEX_BIND("C-w", "kill-region");
    ECEX_BIND("C-s", "isearch-forward");
    ECEX_BIND("C-r", "isearch-backward");
    ECEX_BIND("C-/", "undo");
    ECEX_BIND("C-?", "undo");
    ECEX_BIND("C-_", "undo");
    ECEX_BIND("C-z", "undo");
    ECEX_BIND("C-S-z", "redo");
    ECEX_BIND("C-x u", "undo");
    ECEX_BIND("C-x C-u", "undo");

    ECEX_BIND("C-x C-f", "find-file");
    ECEX_BIND("C-x f", "find-file");
    ECEX_BIND("C-x d", "file-browser");
    ECEX_BIND("C-x C-d", "file-browser-here");
    ECEX_BIND("C-x C-s", "save-buffer");
    ECEX_BIND("C-x C-w", "write-file");
    ECEX_BIND("C-x C-b", "list-buffers");
    ECEX_BIND("C-x b", "switch-buffer");
    ECEX_BIND("C-x k", "kill-buffer");
    ECEX_BIND("C-x K", "force-kill-buffer");
    ECEX_BIND("C-x 2", "split-window-below");
    ECEX_BIND("C-x 3", "split-window-right");
    ECEX_BIND("C-x o", "other-window");
    ECEX_BIND("C-x O", "previous-window");
    ECEX_BIND("C-x 0", "delete-window");
    ECEX_BIND("C-x 1", "delete-other-windows");
    ECEX_BIND("C-x +", "balance-windows");
    ECEX_BIND("C-x C-c", "quit");
    ECEX_BIND("C-x C-S-c", "force-quit");
    ECEX_BIND("C-x e b", "eval-buffer");
    ECEX_BIND("C-x e l", "eval-line");
    ECEX_BIND("C-x C-e", "eval-line");
    ECEX_BIND("C-x e r", "eval-region");
    ECEX_BIND("C-x e f", "eval-file");
    ECEX_BIND("C-x C-r", "reload-config");
    ECEX_BIND("F5", "reload-config");
    ECEX_BIND("M-g n", "next-error");
    ECEX_BIND("M-g p", "previous-error");
    ECEX_BIND("M-;", "comment-region");

    ECEX_BIND("BACKSPACE", "backspace");
    ECEX_BIND("DELETE", "delete-forward");
    ECEX_BIND("ENTER", "newline");
    ECEX_BIND("TAB", "indent-for-tab-command");
    ECEX_BIND("C-TAB", "complete-at-point");
    ECEX_BIND("C-S-TAB", "complete-at-point-previous");

    ecex_define_major_mode(ed, "fundamental-mode");
    ecex_define_major_mode(ed, "eval-output-mode");
    ecex_define_major_mode(ed, "special-mode");
    ecex_define_major_mode(ed, "file-browser-mode");
    ecex_define_major_mode(ed, "media-preview-mode");
    ecex_define_major_mode(ed, "markdown-mode");
    ecex_bind_mode_key(ed, "eval-output-mode", "g", "eval-rerun-last");
    ecex_bind_mode_key(ed, "eval-output-mode", "q", "quit-window");
    ecex_bind_mode_key(ed, "eval-output-mode", "r", "eval-rerun-last");
    ecex_bind_mode_key(ed, "special-mode", "q", "quit-window");

    ecex_bind_mode_key(ed, "file-browser-mode", "g", "file-browser-refresh");
    ecex_bind_mode_key(ed, "file-browser-mode", "r", "file-browser-refresh");
    ecex_bind_mode_key(ed, "file-browser-mode", "h", "file-browser-parent");
    ecex_bind_mode_key(ed, "file-browser-mode", "l", "file-browser-open");
    ecex_bind_mode_key(ed, "file-browser-mode", "v", "file-browser-preview");
    ecex_bind_mode_key(ed, "file-browser-mode", "m", "file-browser-toggle-preview");
    ecex_bind_mode_key(ed, "file-browser-mode", "b", "file-browser-history-back");
    ecex_bind_mode_key(ed, "file-browser-mode", "f", "file-browser-history-forward");
    ecex_bind_mode_key(ed, "file-browser-mode", "q", "quit-window");
    ecex_bind_mode_key(ed, "media-preview-mode", "SPC", "media-play-pause");
    ecex_bind_mode_key(ed, "media-preview-mode", "p", "media-play-pause");
    ecex_bind_mode_key(ed, "media-preview-mode", "q", "quit-window");
    ecex_bind_mode_key(ed, "special-mode", "g", "recompile");
    ecex_bind_mode_key(ed, "special-mode", "n", "next-error");
    ecex_bind_mode_key(ed, "special-mode", "p", "previous-error");

    return ECEX_OK;
}

#undef ECEX_COMMAND
#undef ECEX_BIND
#undef CURRENT_BUFFER_OR_ERR

ecex_t *ecex_new(void) {
    ecex_t *ed = calloc(1, sizeof(*ed));
    if (!ed) return NULL;

    ed->plugins = ecex_plugin_runtime_new();
    if (!ed->plugins) {
        ecex_free(ed);
        return NULL;
    }

    ecex_theme_set_defaults(ed);

    buffer_t *scratch = buffer_new("*scratch*", NULL, 0);
    if (!scratch || ecex_add_buffer(ed, scratch) != ECEX_OK) {
        buffer_free(scratch);
        ecex_free(ed);
        return NULL;
    }

    ed->current_buffer_index = 0;
    ed->current_buffer = scratch;
    ed->next_major_mode_id = 1;

    ed->window_cap = ECEX_INITIAL_WINDOW_CAP;
    ed->windows = calloc(ed->window_cap, sizeof(*ed->windows));
    if (!ed->windows) {
        ecex_free(ed);
        return NULL;
    }
    ed->window_count = 1;
    ed->current_window_index = 0;
    ed->windows[0].buffer = scratch;
    ed->windows[0].x = 0.0f;
    ed->windows[0].y = 0.0f;
    ed->windows[0].w = 1.0f;
    ed->windows[0].h = 1.0f;

    if (ecex_register_builtins(ed) != ECEX_OK) {
        ecex_free(ed);
        return NULL;
    }

    ecex_buffer_set_major_mode_by_name(ed, scratch, "fundamental-mode");

    return ed;
}

void ecex_free(ecex_t *ed) {
    if (!ed) return;

    /* Buffers may hold renderer/animation callbacks and userdata destructors
     * compiled by CCDJIT config modules. Run those destructors while their JIT
     * modules are still alive; freeing modules first leaves callback pointers
     * dangling and can segfault during buffer teardown. */
    for (size_t i = 0; i < ed->buffer_count; i++) {
        buffer_free(ed->buffers[i]);
    }

    ecex_clear_command_hooks(ed);
    ecex_clear_prefix_hooks(ed);
    ecex_clear_buffer_hooks(ed);
    ecex_clear_completion_providers(ed);

    for (size_t i = 0; i < ed->jit_module_count; i++) {
        ccdjit_module_free((ccdjit_module *)ed->jit_modules[i]);
    }

    ecex_plugin_runtime_free(ed->plugins);
    ed->plugins = NULL;

    for (size_t i = 0; i < ed->command_count; i++) {
        free(ed->commands[i].name);
    }

    for (size_t i = 0; i < ed->keybind_count; i++) {
        free(ed->keybinds[i].key);
        free(ed->keybinds[i].command);
    }

    for (size_t i = 0; i < ed->mode_keybind_count; i++) {
        free(ed->mode_keybinds[i].key);
        free(ed->mode_keybinds[i].command);
    }

    for (size_t i = 0; i < ed->major_mode_count; i++) {
        free(ed->major_modes[i].name);
    }

    free(ed->jit_modules);
    free(ed->windows);
    free(ed->buffers);
    free(ed->commands);
    free(ed->keybinds);
    free(ed->mode_keybinds);
    free(ed->command_hooks);
    free(ed->prefix_hooks);
    free(ed->buffer_hooks);
    free(ed->completion_providers);
    free(ed->major_modes);
    free(ed->last_eval_source);
    free(ed->last_eval_filename);
    free(ed->last_compile_command);
    free(ed->last_grep_command);
    free(ed->config_path);
    free(ed->clipboard_text);
    free(ed->theme.font_path);
    free(ed);
    ecex_log_flush();
}

int ecex_reserve_buffers(ecex_t *ed, size_t needed) {
    ECEX_RETURN_ERR_IF_NULL(ed);
    if (needed <= ed->buffer_cap) return ECEX_OK;

    while (ed->buffer_cap < needed) {
        if (ECEX_GROW_ARRAY(ed->buffers,
                            ed->buffer_count,
                            ed->buffer_cap,
                            ECEX_INITIAL_BUFFER_CAP) != ECEX_OK) {
            return ECEX_ERR;
        }
    }

    return ECEX_OK;
}

int ecex_add_buffer(ecex_t *ed, buffer_t *buffer) {
    if (!ed || !buffer) return ECEX_ERR;

    if (ecex_reserve_buffers(ed, ed->buffer_count + 1) != ECEX_OK) return ECEX_ERR;

    ed->buffers[ed->buffer_count++] = buffer;

    if (!ed->current_buffer) {
        ed->current_buffer_index = 0;
        ed->current_buffer = buffer;
    }

    return ECEX_OK;
}

buffer_t *ecex_create_buffer(ecex_t *ed,
                             const char *name,
                             const char *path,
                             int read_only) {
    if (!ed || !name) return NULL;

    buffer_t *buffer = buffer_new(name, path, read_only);
    if (!buffer) return NULL;

    if (ecex_add_buffer(ed, buffer) != ECEX_OK) {
        buffer_free(buffer);
        return NULL;
    }

    ecex_notify_buffer_hooks(ed, buffer, ECEX_BUFFER_HOOK_CREATE);
    return buffer;
}

buffer_t *ecex_find_buffer(ecex_t *ed, const char *name) {
    if (!ed || !name) return NULL;

    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (strcmp(ed->buffers[i]->name, name) == 0) {
            return ed->buffers[i];
        }
    }

    return NULL;
}


static int ecex_buffer_index_of(ecex_t *ed, buffer_t *buffer, size_t *out_index) {
    if (!ed || !buffer) return ECEX_ERR;
    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (ed->buffers[i] == buffer) {
            if (out_index) *out_index = i;
            return ECEX_OK;
        }
    }
    return ECEX_ERR;
}

static int ecex_set_current_buffer_index(ecex_t *ed, size_t index) {
    if (!ed || index >= ed->buffer_count) return ECEX_ERR;

    buffer_t *next = ed->buffers[index];
    if (ed->current_buffer && ed->current_buffer != next) {
        ed->previous_buffer = ed->current_buffer;
    }

    ed->current_buffer_index = index;
    ed->current_buffer = next;
    ecex_window_t *win = ecex_current_window(ed);
    if (win) win->buffer = ed->current_buffer;
    ecex_notify_buffer_hooks(ed, next, ECEX_BUFFER_HOOK_SWITCH);
    return ECEX_OK;
}

int ecex_sync_current_buffer(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    ecex_window_t *win = ecex_current_window(ed);
    if (!win || !win->buffer) return ECEX_ERR;

    buffer_t *next = win->buffer;
    if (ed->current_buffer && ed->current_buffer != next) {
        ed->previous_buffer = ed->current_buffer;
    }

    ed->current_buffer = next;
    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (ed->buffers[i] == next) {
            ed->current_buffer_index = i;
            ecex_notify_buffer_hooks(ed, next, ECEX_BUFFER_HOOK_SWITCH);
            return ECEX_OK;
        }
    }
    return ECEX_ERR;
}

int ecex_switch_buffer(ecex_t *ed, const char *name) {
    if (!ed) return ECEX_ERR;

    if (!name || name[0] == '\0') {
        buffer_t *other = ecex_other_buffer(ed);
        size_t index = 0;
        if (!other || ecex_buffer_index_of(ed, other, &index) != ECEX_OK) return ECEX_ERR;
        return ecex_set_current_buffer_index(ed, index);
    }

    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (strcmp(ed->buffers[i]->name, name) == 0) {
            return ecex_set_current_buffer_index(ed, i);
        }
    }

    return ECEX_ERR;
}

buffer_t *ecex_current_buffer(ecex_t *ed) {
    if (!ed) return NULL;
    ecex_window_t *win = ecex_current_window(ed);
    if (win && win->buffer) return win->buffer;
    return ed->current_buffer;
}

buffer_t *ecex_other_buffer(ecex_t *ed) {
    if (!ed || ed->buffer_count == 0) return NULL;

    buffer_t *current = ecex_current_buffer(ed);
    if (ed->previous_buffer && ed->previous_buffer != current &&
        ecex_buffer_index_of(ed, ed->previous_buffer, NULL) == ECEX_OK) {
        return ed->previous_buffer;
    }

    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (ed->buffers[i] && ed->buffers[i] != current) return ed->buffers[i];
    }

    return current;
}

ecex_window_t *ecex_current_window(ecex_t *ed) {
    if (!ed || ed->window_count == 0 || ed->current_window_index >= ed->window_count) return NULL;
    return &ed->windows[ed->current_window_index];
}

size_t ecex_window_count(ecex_t *ed) {
    return ed ? ed->window_count : 0;
}

static int ecex_reserve_windows(ecex_t *ed, size_t needed) {
    if (!ed) return ECEX_ERR;
    if (needed <= ed->window_cap) return ECEX_OK;
    while (ed->window_cap < needed) {
        if (ECEX_GROW_ARRAY(ed->windows,
                            ed->window_count,
                            ed->window_cap,
                            ECEX_INITIAL_WINDOW_CAP) != ECEX_OK) {
            return ECEX_ERR;
        }
    }
    return ECEX_OK;
}

static int ecex_add_window(ecex_t *ed, ecex_window_t win) {
    if (!ed || !win.buffer) return ECEX_ERR;
    if (ecex_reserve_windows(ed, ed->window_count + 1) != ECEX_OK) return ECEX_ERR;
    ed->windows[ed->window_count++] = win;
    return ECEX_OK;
}

int ecex_split_window_vertically(ecex_t *ed) {
    ecex_window_t *active = ecex_current_window(ed);
    if (!active || !active->buffer || active->w < 0.08f) return ECEX_ERR;

    ecex_window_t new_win = *active;
    float half = active->w * 0.5f;
    active->w = half;
    new_win.x = active->x + half;
    new_win.w = half;

    if (ecex_add_window(ed, new_win) != ECEX_OK) return ECEX_ERR;
    ed->current_window_index = ed->window_count - 1;
    return ecex_sync_current_buffer(ed);
}

int ecex_split_window_horizontally(ecex_t *ed) {
    ecex_window_t *active = ecex_current_window(ed);
    if (!active || !active->buffer || active->h < 0.08f) return ECEX_ERR;

    ecex_window_t new_win = *active;
    float half = active->h * 0.5f;
    active->h = half;
    new_win.y = active->y + half;
    new_win.h = half;

    if (ecex_add_window(ed, new_win) != ECEX_OK) return ECEX_ERR;
    ed->current_window_index = ed->window_count - 1;
    return ecex_sync_current_buffer(ed);
}

int ecex_other_window(ecex_t *ed) {
    if (!ed || ed->window_count == 0) return ECEX_ERR;
    ed->current_window_index = (ed->current_window_index + 1) % ed->window_count;
    return ecex_sync_current_buffer(ed);
}

int ecex_previous_window(ecex_t *ed) {
    if (!ed || ed->window_count == 0) return ECEX_ERR;
    if (ed->current_window_index == 0) ed->current_window_index = ed->window_count - 1;
    else ed->current_window_index--;
    return ecex_sync_current_buffer(ed);
}

int ecex_delete_window(ecex_t *ed) {
    if (!ed || ed->window_count <= 1 || ed->current_window_index >= ed->window_count) return ECEX_ERR;

    size_t index = ed->current_window_index;
    for (size_t i = index; i + 1 < ed->window_count; i++) {
        ed->windows[i] = ed->windows[i + 1];
    }
    ed->window_count--;
    if (ed->current_window_index >= ed->window_count) ed->current_window_index = ed->window_count - 1;
    return ecex_sync_current_buffer(ed);
}

int ecex_delete_other_windows(ecex_t *ed) {
    ecex_window_t *active = ecex_current_window(ed);
    if (!ed || !active) return ECEX_ERR;
    ecex_window_t keep = *active;
    keep.x = 0.0f; keep.y = 0.0f; keep.w = 1.0f; keep.h = 1.0f;
    ed->windows[0] = keep;
    ed->window_count = 1;
    ed->current_window_index = 0;
    return ecex_sync_current_buffer(ed);
}

int ecex_balance_windows(ecex_t *ed) {
    if (!ed || ed->window_count == 0) return ECEX_ERR;
    size_t n = ed->window_count;
    size_t cols = 1;
    while (cols * cols < n) cols++;
    size_t rows = (n + cols - 1) / cols;
    for (size_t i = 0; i < n; i++) {
        size_t row = i / cols;
        size_t col = i % cols;
        ed->windows[i].x = (float)col / (float)cols;
        ed->windows[i].y = (float)row / (float)rows;
        ed->windows[i].w = 1.0f / (float)cols;
        ed->windows[i].h = 1.0f / (float)rows;
    }
    return ecex_sync_current_buffer(ed);
}

int ecex_next_buffer(ecex_t *ed) {
    if (!ed || ed->buffer_count == 0) return ECEX_ERR;
    ecex_sync_current_buffer(ed);
    return ecex_set_current_buffer_index(ed, (ed->current_buffer_index + 1) % ed->buffer_count);
}

int ecex_previous_buffer(ecex_t *ed) {
    if (!ed || ed->buffer_count == 0) return ECEX_ERR;
    ecex_sync_current_buffer(ed);

    if (ed->current_buffer_index == 0) {
        ed->current_buffer_index = ed->buffer_count - 1;
    } else {
        ed->current_buffer_index--;
    }

    return ecex_set_current_buffer_index(ed, ed->current_buffer_index);
}

static int ecex_kill_buffer_impl(ecex_t *ed, const char *name, int force) {
    if (!ed || ed->buffer_count == 0) return ECEX_ERR;

    size_t index = ed->buffer_count;
    if (!name || name[0] == '\0') {
        buffer_t *current = ecex_current_buffer(ed);
        if (!current || ecex_buffer_index_of(ed, current, &index) != ECEX_OK) return ECEX_ERR;
    } else {
        for (size_t i = 0; i < ed->buffer_count; i++) {
            if (strcmp(ed->buffers[i]->name, name) == 0) {
                index = i;
                break;
            }
        }
    }

    if (index == ed->buffer_count) return ECEX_ERR;

    buffer_t *victim = ed->buffers[index];
    if (ed->previous_buffer == victim) ed->previous_buffer = NULL;
    if (!force && victim->modified && !victim->read_only) {
        fprintf(stderr,
                "ecex: refusing to kill modified buffer '%s'; save it or use force-kill-buffer.\n",
                victim->name ? victim->name : "<unnamed>");
        return ECEX_ERR;
    }

    for (size_t i = index; i + 1 < ed->buffer_count; i++) ed->buffers[i] = ed->buffers[i + 1];
    ed->buffer_count--;

    buffer_t *fallback = ecex_other_buffer(ed);
    if (fallback == victim) fallback = ed->buffer_count > 0 ? ed->buffers[0] : NULL;
    for (size_t i = 0; i < ed->window_count; i++) {
        if (ed->windows[i].buffer == victim) ed->windows[i].buffer = fallback;
    }

    ecex_notify_buffer_hooks(ed, victim, ECEX_BUFFER_HOOK_KILL);
    buffer_free(victim);

    if (ed->buffer_count == 0) {
        ed->current_buffer = NULL;
        ed->current_buffer_index = 0;
        ed->window_count = 0;
        ed->current_window_index = 0;
        return ECEX_OK;
    }

    if (ed->current_window_index >= ed->window_count) {
        ed->current_window_index = ed->window_count ? ed->window_count - 1 : 0;
    }

    return ecex_sync_current_buffer(ed);
}

int ecex_kill_buffer(ecex_t *ed, const char *name) {
    return ecex_kill_buffer_impl(ed, name, 0);
}

int ecex_kill_buffer_force(ecex_t *ed, const char *name) {
    return ecex_kill_buffer_impl(ed, name, 1);
}

int ecex_has_modified_buffers(ecex_t *ed) {
    if (!ed) return 0;
    for (size_t i = 0; i < ed->buffer_count; i++) {
        buffer_t *buf = ed->buffers[i];
        if (buf && buf->modified && !buf->read_only) return 1;
    }
    return 0;
}

int ecex_keep_jit_module(ecex_t *ed, void *module) {
    if (!ed || !module) return ECEX_ERR;

    if (ECEX_GROW_ARRAY(ed->jit_modules,
                        ed->jit_module_count,
                        ed->jit_module_cap,
                        8) != ECEX_OK) {
        return ECEX_ERR;
    }

    ed->jit_modules[ed->jit_module_count++] = module;
    return ECEX_OK;
}

int ecex_set_config_path(ecex_t *ed, const char *path) {
    if (!ed) return ECEX_ERR;

    char *copy = NULL;
    if (path && path[0]) {
        copy = ecex_strdup(path);
        if (!copy) return ECEX_ERR;
    }

    free(ed->config_path);
    ed->config_path = copy;
    return ECEX_OK;
}

const char *ecex_config_path(ecex_t *ed) {
    if (!ed) return NULL;
    return ed->config_path;
}

static void ecex_clear_commands(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->command_count; i++) {
        free(ed->commands[i].name);
    }
    ed->command_count = 0;
}

static void ecex_clear_keybinds(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->keybind_count; i++) {
        free(ed->keybinds[i].key);
        free(ed->keybinds[i].command);
    }
    ed->keybind_count = 0;
}

static void ecex_clear_mode_keybinds(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->mode_keybind_count; i++) {
        free(ed->mode_keybinds[i].key);
        free(ed->mode_keybinds[i].command);
    }
    ed->mode_keybind_count = 0;
}

static void ecex_command_hook_clear(ecex_command_hook_t *hook) {
    if (!hook) return;
    if (hook->free_fn && hook->userdata) hook->free_fn(hook->userdata);
    free(hook->name);
    memset(hook, 0, sizeof(*hook));
}

static void ecex_prefix_hook_clear(ecex_prefix_hook_t *hook) {
    if (!hook) return;
    if (hook->free_fn && hook->userdata) hook->free_fn(hook->userdata);
    free(hook->name);
    memset(hook, 0, sizeof(*hook));
}

static void ecex_buffer_hook_clear(ecex_buffer_hook_t *hook) {
    if (!hook) return;
    if (hook->free_fn && hook->userdata) hook->free_fn(hook->userdata);
    free(hook->name);
    memset(hook, 0, sizeof(*hook));
}

static void ecex_completion_provider_clear(ecex_completion_provider_t *provider) {
    if (!provider) return;
    if (provider->free_fn && provider->userdata) provider->free_fn(provider->userdata);
    for (size_t i = 0; i < provider->word_count; i++) {
        free(provider->words[i]);
    }
    free(provider->words);
    free(provider->detail);
    free(provider->name);
    memset(provider, 0, sizeof(*provider));
}

static void ecex_clear_command_hooks(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->command_hook_count; i++) {
        ecex_command_hook_clear(&ed->command_hooks[i]);
    }
    ed->command_hook_count = 0;
}

static void ecex_clear_prefix_hooks(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->prefix_hook_count; i++) {
        ecex_prefix_hook_clear(&ed->prefix_hooks[i]);
    }
    ed->prefix_hook_count = 0;
}

static void ecex_clear_buffer_hooks(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->buffer_hook_count; i++) {
        ecex_buffer_hook_clear(&ed->buffer_hooks[i]);
    }
    ed->buffer_hook_count = 0;
}

static void ecex_clear_completion_providers(ecex_t *ed) {
    if (!ed) return;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        ecex_completion_provider_clear(&ed->completion_providers[i]);
    }
    ed->completion_provider_count = 0;
}

typedef struct ecex_binding_snapshot {
    ecex_command_t *commands;
    size_t command_count;
    size_t command_cap;
    ecex_keybind_t *keybinds;
    size_t keybind_count;
    size_t keybind_cap;
    ecex_mode_keybind_t *mode_keybinds;
    size_t mode_keybind_count;
    size_t mode_keybind_cap;
    ecex_command_hook_t *command_hooks;
    size_t command_hook_count;
    size_t command_hook_cap;
    ecex_prefix_hook_t *prefix_hooks;
    size_t prefix_hook_count;
    size_t prefix_hook_cap;
    ecex_buffer_hook_t *buffer_hooks;
    size_t buffer_hook_count;
    size_t buffer_hook_cap;
    ecex_completion_provider_t *completion_providers;
    size_t completion_provider_count;
    size_t completion_provider_cap;
    ecex_theme_t theme;
} ecex_binding_snapshot_t;

static void ecex_theme_snapshot_free(ecex_theme_t *theme) {
    if (!theme) return;
    free(theme->font_path);
    theme->font_path = NULL;
}

static int ecex_theme_clone(ecex_theme_t *out, const ecex_theme_t *in) {
    if (!out || !in) return ECEX_ERR;
    *out = *in;
    out->font_path = NULL;
    if (in->font_path) {
        out->font_path = ecex_strdup(in->font_path);
        if (!out->font_path) return ECEX_ERR;
    }
    return ECEX_OK;
}

static void ecex_snapshot_free(ecex_binding_snapshot_t *snap) {
    if (!snap) return;
    for (size_t i = 0; i < snap->command_count; i++) free(snap->commands[i].name);
    for (size_t i = 0; i < snap->keybind_count; i++) {
        free(snap->keybinds[i].key);
        free(snap->keybinds[i].command);
    }
    for (size_t i = 0; i < snap->mode_keybind_count; i++) {
        free(snap->mode_keybinds[i].key);
        free(snap->mode_keybinds[i].command);
    }
    for (size_t i = 0; i < snap->command_hook_count; i++) {
        ecex_command_hook_clear(&snap->command_hooks[i]);
    }
    for (size_t i = 0; i < snap->prefix_hook_count; i++) {
        ecex_prefix_hook_clear(&snap->prefix_hooks[i]);
    }
    for (size_t i = 0; i < snap->buffer_hook_count; i++) {
        ecex_buffer_hook_clear(&snap->buffer_hooks[i]);
    }
    for (size_t i = 0; i < snap->completion_provider_count; i++) {
        ecex_completion_provider_clear(&snap->completion_providers[i]);
    }
    free(snap->commands);
    free(snap->keybinds);
    free(snap->mode_keybinds);
    free(snap->command_hooks);
    free(snap->prefix_hooks);
    free(snap->buffer_hooks);
    free(snap->completion_providers);
    ecex_theme_snapshot_free(&snap->theme);
    memset(snap, 0, sizeof(*snap));
}

static int ecex_snapshot_clone(ecex_binding_snapshot_t *snap, ecex_t *ed) {
    if (!snap || !ed) return ECEX_ERR;
    memset(snap, 0, sizeof(*snap));

    if (ecex_theme_clone(&snap->theme, &ed->theme) != ECEX_OK) return ECEX_ERR;

    if (ed->command_cap) {
        snap->commands = calloc(ed->command_cap, sizeof(*snap->commands));
        if (!snap->commands) goto fail;
        snap->command_cap = ed->command_cap;
        snap->command_count = ed->command_count;
        for (size_t i = 0; i < ed->command_count; i++) {
            snap->commands[i].fn = ed->commands[i].fn;
            snap->commands[i].name = ecex_strdup(ed->commands[i].name);
            if (!snap->commands[i].name) goto fail;
        }
    }

    if (ed->keybind_cap) {
        snap->keybinds = calloc(ed->keybind_cap, sizeof(*snap->keybinds));
        if (!snap->keybinds) goto fail;
        snap->keybind_cap = ed->keybind_cap;
        snap->keybind_count = ed->keybind_count;
        for (size_t i = 0; i < ed->keybind_count; i++) {
            snap->keybinds[i].key = ecex_strdup(ed->keybinds[i].key);
            snap->keybinds[i].command = ecex_strdup(ed->keybinds[i].command);
            if (!snap->keybinds[i].key || !snap->keybinds[i].command) goto fail;
        }
    }

    if (ed->mode_keybind_cap) {
        snap->mode_keybinds = calloc(ed->mode_keybind_cap, sizeof(*snap->mode_keybinds));
        if (!snap->mode_keybinds) goto fail;
        snap->mode_keybind_cap = ed->mode_keybind_cap;
        snap->mode_keybind_count = ed->mode_keybind_count;
        for (size_t i = 0; i < ed->mode_keybind_count; i++) {
            snap->mode_keybinds[i].mode = ed->mode_keybinds[i].mode;
            snap->mode_keybinds[i].key = ecex_strdup(ed->mode_keybinds[i].key);
            snap->mode_keybinds[i].command = ecex_strdup(ed->mode_keybinds[i].command);
            if (!snap->mode_keybinds[i].key || !snap->mode_keybinds[i].command) goto fail;
        }
    }

    snap->command_hooks = ed->command_hooks;
    snap->command_hook_count = ed->command_hook_count;
    snap->command_hook_cap = ed->command_hook_cap;
    ed->command_hooks = NULL;
    ed->command_hook_count = 0;
    ed->command_hook_cap = 0;

    snap->prefix_hooks = ed->prefix_hooks;
    snap->prefix_hook_count = ed->prefix_hook_count;
    snap->prefix_hook_cap = ed->prefix_hook_cap;
    ed->prefix_hooks = NULL;
    ed->prefix_hook_count = 0;
    ed->prefix_hook_cap = 0;

    snap->buffer_hooks = ed->buffer_hooks;
    snap->buffer_hook_count = ed->buffer_hook_count;
    snap->buffer_hook_cap = ed->buffer_hook_cap;
    ed->buffer_hooks = NULL;
    ed->buffer_hook_count = 0;
    ed->buffer_hook_cap = 0;

    snap->completion_providers = ed->completion_providers;
    snap->completion_provider_count = ed->completion_provider_count;
    snap->completion_provider_cap = ed->completion_provider_cap;
    ed->completion_providers = NULL;
    ed->completion_provider_count = 0;
    ed->completion_provider_cap = 0;

    return ECEX_OK;

fail:
    ecex_snapshot_free(snap);
    return ECEX_ERR;
}

static void ecex_restore_snapshot(ecex_t *ed, ecex_binding_snapshot_t *snap) {
    if (!ed || !snap) return;

    ecex_clear_commands(ed);
    ecex_clear_keybinds(ed);
    ecex_clear_mode_keybinds(ed);
    ecex_clear_command_hooks(ed);
    ecex_clear_prefix_hooks(ed);
    ecex_clear_buffer_hooks(ed);
    ecex_clear_completion_providers(ed);
    free(ed->commands);
    free(ed->keybinds);
    free(ed->mode_keybinds);
    free(ed->command_hooks);
    free(ed->prefix_hooks);
    free(ed->buffer_hooks);
    free(ed->completion_providers);
    free(ed->theme.font_path);

    ed->commands = snap->commands;
    ed->command_count = snap->command_count;
    ed->command_cap = snap->command_cap;
    ed->keybinds = snap->keybinds;
    ed->keybind_count = snap->keybind_count;
    ed->keybind_cap = snap->keybind_cap;
    ed->mode_keybinds = snap->mode_keybinds;
    ed->mode_keybind_count = snap->mode_keybind_count;
    ed->mode_keybind_cap = snap->mode_keybind_cap;
    ed->command_hooks = snap->command_hooks;
    ed->command_hook_count = snap->command_hook_count;
    ed->command_hook_cap = snap->command_hook_cap;
    ed->prefix_hooks = snap->prefix_hooks;
    ed->prefix_hook_count = snap->prefix_hook_count;
    ed->prefix_hook_cap = snap->prefix_hook_cap;
    ed->buffer_hooks = snap->buffer_hooks;
    ed->buffer_hook_count = snap->buffer_hook_count;
    ed->buffer_hook_cap = snap->buffer_hook_cap;
    ed->completion_providers = snap->completion_providers;
    ed->completion_provider_count = snap->completion_provider_count;
    ed->completion_provider_cap = snap->completion_provider_cap;
    ed->theme = snap->theme;

    memset(snap, 0, sizeof(*snap));
}

int ecex_reload_config(ecex_t *ed) {
    if (!ed || !ed->config_path || !ed->config_path[0]) {
        fprintf(stderr, "ecex: no config file to reload; start with --config path/to/ecexrc.c\n");
        return ECEX_ERR;
    }

    char *path = ecex_strdup(ed->config_path);
    if (!path) return ECEX_ERR;

    ecex_binding_snapshot_t snapshot;
    if (ecex_snapshot_clone(&snapshot, ed) != ECEX_OK) {
        free(path);
        fprintf(stderr, "ecex: failed to snapshot config state before reload\n");
        return ECEX_ERR;
    }

    ecex_clear_commands(ed);
    ecex_clear_keybinds(ed);
    ecex_clear_mode_keybinds(ed);

    int result = ECEX_ERR;
    if (ecex_register_builtins(ed) == ECEX_OK) {
        result = ecex_load_c_config(ed, path);
        if (result == ECEX_OK) result = ecex_validate_bindings(ed);
    }

    if (result != ECEX_OK) {
        fprintf(stderr, "ecex: config reload failed; keeping previous config active\n");
        ecex_restore_snapshot(ed, &snapshot);
    } else {
        ecex_snapshot_free(&snapshot);
    }

    free(path);
    return result;
}


int ecex_config_register_commands(ecex_t *ed, const ecex_config_command_t *commands, size_t count) {
    if (!ed || (!commands && count != 0)) return ECEX_ERR;
    for (size_t i = 0; i < count; i++) {
        if (!commands[i].name || !commands[i].fn) return ECEX_ERR;
        if (ecex_register_command(ed, commands[i].name, commands[i].fn) != ECEX_OK) return ECEX_ERR;
    }
    return ECEX_OK;
}

int ecex_config_bind_keys(ecex_t *ed, const ecex_config_keybind_t *bindings, size_t count) {
    if (!ed || (!bindings && count != 0)) return ECEX_ERR;
    for (size_t i = 0; i < count; i++) {
        if (!bindings[i].key || !bindings[i].command) return ECEX_ERR;
        if (ecex_bind_key(ed, bindings[i].key, bindings[i].command) != ECEX_OK) return ECEX_ERR;
    }
    return ECEX_OK;
}

int ecex_config_bind_mode_keys(ecex_t *ed, const ecex_config_mode_keybind_t *bindings, size_t count) {
    if (!ed || (!bindings && count != 0)) return ECEX_ERR;
    for (size_t i = 0; i < count; i++) {
        if (!bindings[i].mode || !bindings[i].key || !bindings[i].command) return ECEX_ERR;
        if (ecex_bind_mode_key(ed, bindings[i].mode, bindings[i].key, bindings[i].command) != ECEX_OK) return ECEX_ERR;
    }
    return ECEX_OK;
}

int ecex_config_define_modes(ecex_t *ed, const char *const *modes, size_t count) {
    if (!ed || (!modes && count != 0)) return ECEX_ERR;
    for (size_t i = 0; i < count; i++) {
        if (!modes[i] || !ecex_define_major_mode(ed, modes[i])) return ECEX_ERR;
    }
    return ECEX_OK;
}

int ecex_apply_theme(ecex_t *ed, const ecex_theme_t *theme) {
    if (!ed || !theme) return ECEX_ERR;
    char *font = NULL;
    if (theme->font_path) {
        font = ecex_strdup(theme->font_path);
        if (!font) return ECEX_ERR;
    }
    int font_changed =
        ed->theme.font_size != theme->font_size ||
        ((ed->theme.font_path || theme->font_path) &&
         (!ed->theme.font_path || !theme->font_path ||
          strcmp(ed->theme.font_path, theme->font_path) != 0));
    free(ed->theme.font_path);
    ed->theme = *theme;
    ed->theme.font_path = font;
    if (font_changed) ecex_mark_font_changed(ed);
    else ecex_mark_ui_changed(ed);
    return ECEX_OK;
}

int ecex_register_command(ecex_t *ed, const char *name, ecex_command_fn fn) {
    if (!ed || !name || !fn) return ECEX_ERR;

    for (size_t i = 0; i < ed->command_count; i++) {
        if (strcmp(ed->commands[i].name, name) == 0) {
            fprintf(stderr, "ecex: command warning: replacing existing command '%s'\n", name);
            ed->commands[i].fn = fn;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->commands,
                        ed->command_count,
                        ed->command_cap,
                        ECEX_INITIAL_COMMAND_CAP) != ECEX_OK) {
        return ECEX_ERR;
    }

    char *copy = ecex_strdup(name);
    if (!copy) return ECEX_ERR;

    ed->commands[ed->command_count].name = copy;
    ed->commands[ed->command_count].fn = fn;
    ed->command_count++;
    return ECEX_OK;
}

int ecex_execute_command(ecex_t *ed, const char *name) {
    if (!ed || !name) return ECEX_ERR;

    for (size_t i = 0; i < ed->command_count; i++) {
        if (strcmp(ed->commands[i].name, name) == 0) {
            ecex_command_fn fn = ed->commands[i].fn;
            for (size_t j = 0; j < ed->command_hook_count; j++) {
                ecex_command_hook_t *hook = &ed->command_hooks[j];
                if (hook->fn) hook->fn(ed, name, ECEX_COMMAND_HOOK_BEFORE, 0, hook->userdata);
            }

            int result = fn(ed);

            for (size_t j = 0; j < ed->command_hook_count; j++) {
                ecex_command_hook_t *hook = &ed->command_hooks[j];
                if (hook->fn) hook->fn(ed, name, ECEX_COMMAND_HOOK_AFTER, result, hook->userdata);
            }

            return result;
        }
    }

    return ECEX_ERR;
}

int ecex_add_command_hook(ecex_t *ed,
                          const char *name,
                          ecex_command_hook_fn fn,
                          void *userdata,
                          ecex_hook_free_fn free_fn) {
    if (!ed || !name || !name[0] || !fn) return ECEX_ERR;

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    for (size_t i = 0; i < ed->command_hook_count; i++) {
        if (strcmp(ed->command_hooks[i].name, name) == 0) {
            ecex_command_hook_clear(&ed->command_hooks[i]);
            ed->command_hooks[i].name = name_copy;
            ed->command_hooks[i].fn = fn;
            ed->command_hooks[i].userdata = userdata;
            ed->command_hooks[i].free_fn = free_fn;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->command_hooks,
                        ed->command_hook_count,
                        ed->command_hook_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_command_hook_t *hook = &ed->command_hooks[ed->command_hook_count++];
    memset(hook, 0, sizeof(*hook));
    hook->name = name_copy;
    hook->fn = fn;
    hook->userdata = userdata;
    hook->free_fn = free_fn;
    return ECEX_OK;
}

int ecex_remove_command_hook(ecex_t *ed, const char *name) {
    if (!ed || !name) return ECEX_ERR;

    for (size_t i = 0; i < ed->command_hook_count; i++) {
        if (strcmp(ed->command_hooks[i].name, name) != 0) continue;
        ecex_command_hook_clear(&ed->command_hooks[i]);
        if (i + 1 < ed->command_hook_count) {
            memmove(&ed->command_hooks[i],
                    &ed->command_hooks[i + 1],
                    (ed->command_hook_count - i - 1) * sizeof(ed->command_hooks[i]));
        }
        ed->command_hook_count--;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

int ecex_add_prefix_hook(ecex_t *ed,
                         const char *name,
                         ecex_prefix_hook_fn fn,
                         void *userdata,
                         ecex_hook_free_fn free_fn) {
    if (!ed || !name || !name[0] || !fn) return ECEX_ERR;

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    for (size_t i = 0; i < ed->prefix_hook_count; i++) {
        if (strcmp(ed->prefix_hooks[i].name, name) == 0) {
            ecex_prefix_hook_clear(&ed->prefix_hooks[i]);
            ed->prefix_hooks[i].name = name_copy;
            ed->prefix_hooks[i].fn = fn;
            ed->prefix_hooks[i].userdata = userdata;
            ed->prefix_hooks[i].free_fn = free_fn;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->prefix_hooks,
                        ed->prefix_hook_count,
                        ed->prefix_hook_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_prefix_hook_t *hook = &ed->prefix_hooks[ed->prefix_hook_count++];
    memset(hook, 0, sizeof(*hook));
    hook->name = name_copy;
    hook->fn = fn;
    hook->userdata = userdata;
    hook->free_fn = free_fn;
    return ECEX_OK;
}

int ecex_remove_prefix_hook(ecex_t *ed, const char *name) {
    if (!ed || !name) return ECEX_ERR;

    for (size_t i = 0; i < ed->prefix_hook_count; i++) {
        if (strcmp(ed->prefix_hooks[i].name, name) != 0) continue;
        ecex_prefix_hook_clear(&ed->prefix_hooks[i]);
        if (i + 1 < ed->prefix_hook_count) {
            memmove(&ed->prefix_hooks[i],
                    &ed->prefix_hooks[i + 1],
                    (ed->prefix_hook_count - i - 1) * sizeof(ed->prefix_hooks[i]));
        }
        ed->prefix_hook_count--;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

void ecex_notify_prefix_hooks(ecex_t *ed, const char *prefix, int event) {
    if (!ed || !prefix) return;

    for (size_t i = 0; i < ed->prefix_hook_count; i++) {
        ecex_prefix_hook_t *hook = &ed->prefix_hooks[i];
        if (hook->fn) hook->fn(ed, prefix, event, hook->userdata);
    }
}

int ecex_add_buffer_hook(ecex_t *ed,
                         const char *name,
                         ecex_buffer_hook_fn fn,
                         void *userdata,
                         ecex_hook_free_fn free_fn) {
    if (!ed || !name || !name[0] || !fn) return ECEX_ERR;

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    for (size_t i = 0; i < ed->buffer_hook_count; i++) {
        if (strcmp(ed->buffer_hooks[i].name, name) == 0) {
            ecex_buffer_hook_clear(&ed->buffer_hooks[i]);
            ed->buffer_hooks[i].name = name_copy;
            ed->buffer_hooks[i].fn = fn;
            ed->buffer_hooks[i].userdata = userdata;
            ed->buffer_hooks[i].free_fn = free_fn;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->buffer_hooks,
                        ed->buffer_hook_count,
                        ed->buffer_hook_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_buffer_hook_t *hook = &ed->buffer_hooks[ed->buffer_hook_count++];
    memset(hook, 0, sizeof(*hook));
    hook->name = name_copy;
    hook->fn = fn;
    hook->userdata = userdata;
    hook->free_fn = free_fn;
    return ECEX_OK;
}

int ecex_remove_buffer_hook(ecex_t *ed, const char *name) {
    if (!ed || !name) return ECEX_ERR;

    for (size_t i = 0; i < ed->buffer_hook_count; i++) {
        if (strcmp(ed->buffer_hooks[i].name, name) != 0) continue;
        ecex_buffer_hook_clear(&ed->buffer_hooks[i]);
        if (i + 1 < ed->buffer_hook_count) {
            memmove(&ed->buffer_hooks[i],
                    &ed->buffer_hooks[i + 1],
                    (ed->buffer_hook_count - i - 1) * sizeof(ed->buffer_hooks[i]));
        }
        ed->buffer_hook_count--;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

void ecex_notify_buffer_hooks(ecex_t *ed, buffer_t *buffer, int event) {
    if (!ed || !buffer) return;

    for (size_t i = 0; i < ed->buffer_hook_count; i++) {
        ecex_buffer_hook_t *hook = &ed->buffer_hooks[i];
        if (hook->fn) hook->fn(ed, buffer, event, hook->userdata);
    }
}

void ecex_message(ecex_t *ed, const char *message) {
    if (!ed) return;
    snprintf(ed->message, sizeof(ed->message), "%s", message ? message : "");
    ed->message_revision++;
    ecex_mark_ui_changed(ed);
}

static int ecex_path_is_executable(const char *path) {
    return path && path[0] && access(path, X_OK) == 0;
}

int ecex_dependency_available(const char *program) {
    if (!program || !program[0]) return 0;
    if (strchr(program, '/')) return ecex_path_is_executable(program);

    const char *path = getenv("PATH");
    if (!path || !path[0]) path = "/bin:/usr/bin:/usr/local/bin";

    const char *start = path;
    while (*start) {
        const char *end = strchr(start, ':');
        size_t dir_len = end ? (size_t)(end - start) : strlen(start);
        if (dir_len == 0) {
            start = end ? end + 1 : start + strlen(start);
            continue;
        }

        char candidate[4096];
        size_t prog_len = strlen(program);
        if (dir_len + 1 + prog_len < sizeof(candidate)) {
            memcpy(candidate, start, dir_len);
            candidate[dir_len] = '/';
            memcpy(candidate + dir_len + 1, program, prog_len + 1);
            if (ecex_path_is_executable(candidate)) return 1;
        }

        if (!end) break;
        start = end + 1;
    }

    return 0;
}

int ecex_plugin_require_dependency(ecex_t *ed, const char *plugin_id, const char *program) {
    if (!program || !program[0]) return ECEX_ERR;
    if (ecex_dependency_available(program)) return ECEX_OK;

    char message[256];
    snprintf(message,
             sizeof(message),
             "%s disabled: missing dependency '%s'",
             plugin_id && plugin_id[0] ? plugin_id : "plugin",
             program);
    ecex_message(ed, message);
    fprintf(stderr, "ecex: %s\n", message);
    return ECEX_ERR;
}

int ecex_add_completion_provider(ecex_t *ed,
                                 const char *name,
                                 const char *mode_name,
                                 ecex_completion_provider_fn fn,
                                 void *userdata,
                                 ecex_hook_free_fn free_fn) {
    if (!ed || !name || !name[0] || !fn) return ECEX_ERR;

    int mode = 0;
    if (mode_name && mode_name[0]) {
        mode = ecex_define_major_mode(ed, mode_name);
        if (mode == 0) return ECEX_ERR;
    }

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        if (strcmp(ed->completion_providers[i].name, name) == 0) {
            ecex_completion_provider_clear(&ed->completion_providers[i]);
            ed->completion_providers[i].name = name_copy;
            ed->completion_providers[i].mode = mode;
            ed->completion_providers[i].fn = fn;
            ed->completion_providers[i].userdata = userdata;
            ed->completion_providers[i].free_fn = free_fn;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->completion_providers,
                        ed->completion_provider_count,
                        ed->completion_provider_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_completion_provider_t *provider =
        &ed->completion_providers[ed->completion_provider_count++];
    memset(provider, 0, sizeof(*provider));
    provider->name = name_copy;
    provider->mode = mode;
    provider->fn = fn;
    provider->userdata = userdata;
    provider->free_fn = free_fn;
    return ECEX_OK;
}

static int ecex_completion_provider_mode(ecex_t *ed, const char *mode_name, int *out_mode) {
    if (!ed || !out_mode) return ECEX_ERR;
    *out_mode = 0;
    if (mode_name && mode_name[0]) {
        *out_mode = ecex_define_major_mode(ed, mode_name);
        if (*out_mode == 0) return ECEX_ERR;
    }
    return ECEX_OK;
}

static char **ecex_completion_words_copy(const char *const *words, size_t count) {
    if (!words || count == 0) return NULL;
    char **copy = calloc(count, sizeof(*copy));
    if (!copy) return NULL;

    for (size_t i = 0; i < count; i++) {
        copy[i] = ecex_strdup(words[i] ? words[i] : "");
        if (!copy[i]) {
            for (size_t j = 0; j < i; j++) free(copy[j]);
            free(copy);
            return NULL;
        }
    }

    return copy;
}

int ecex_define_word_completion_provider(ecex_t *ed,
                                         const char *name,
                                         const char *mode_name,
                                         int flags) {
    if (!ed || !name || !name[0]) return ECEX_ERR;

    int mode = 0;
    if (ecex_completion_provider_mode(ed, mode_name, &mode) != ECEX_OK) return ECEX_ERR;

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        if (strcmp(ed->completion_providers[i].name, name) == 0) {
            ecex_completion_provider_clear(&ed->completion_providers[i]);
            ed->completion_providers[i].name = name_copy;
            ed->completion_providers[i].mode = mode;
            ed->completion_providers[i].flags = flags;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->completion_providers,
                        ed->completion_provider_count,
                        ed->completion_provider_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_completion_provider_t *provider =
        &ed->completion_providers[ed->completion_provider_count++];
    memset(provider, 0, sizeof(*provider));
    provider->name = name_copy;
    provider->mode = mode;
    provider->flags = flags;
    return ECEX_OK;
}

int ecex_completion_provider_add_word(ecex_t *ed, const char *name, const char *word) {
    if (!ed || !name || !word || !word[0]) return ECEX_ERR;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        ecex_completion_provider_t *provider = &ed->completion_providers[i];
        if (strcmp(provider->name, name) != 0) continue;

        char **grown = realloc(provider->words,
                               (provider->word_count + 1) * sizeof(*provider->words));
        if (!grown) return ECEX_ERR;
        provider->words = grown;

        provider->words[provider->word_count] = ecex_strdup(word);
        if (!provider->words[provider->word_count]) return ECEX_ERR;
        provider->word_count++;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

int ecex_completion_provider_add_words(ecex_t *ed, const char *name, const char *words) {
    if (!ed || !name || !words) return ECEX_ERR;

    const char *p = words;
    while (*p) {
        while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++;
        if (!*p) break;

        char word[256];
        size_t len = 0;
        while (*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') {
            if (len + 1 < sizeof(word)) word[len++] = *p;
            p++;
        }
        word[len] = '\0';

        if (len > 0 && ecex_completion_provider_add_word(ed, name, word) != ECEX_OK) {
            return ECEX_ERR;
        }
    }

    return ECEX_OK;
}

int ecex_completion_provider_set_detail(ecex_t *ed, const char *name, const char *detail) {
    if (!ed || !name || !name[0]) return ECEX_ERR;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        ecex_completion_provider_t *provider = &ed->completion_providers[i];
        if (strcmp(provider->name, name) != 0) continue;

        char *copy = NULL;
        if (detail && detail[0]) {
            copy = ecex_strdup(detail);
            if (!copy) return ECEX_ERR;
        }

        free(provider->detail);
        provider->detail = copy;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

int ecex_add_word_completion_provider(ecex_t *ed,
                                      const char *name,
                                      const char *mode_name,
                                      const char *const *words,
                                      size_t word_count,
                                      int flags) {
    if (!ed || !name || !name[0] || !words || word_count == 0) return ECEX_ERR;

    int mode = 0;
    if (ecex_completion_provider_mode(ed, mode_name, &mode) != ECEX_OK) return ECEX_ERR;

    char *name_copy = ecex_strdup(name);
    if (!name_copy) return ECEX_ERR;

    char **words_copy = ecex_completion_words_copy(words, word_count);
    if (!words_copy) {
        free(name_copy);
        return ECEX_ERR;
    }

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        if (strcmp(ed->completion_providers[i].name, name) == 0) {
            ecex_completion_provider_clear(&ed->completion_providers[i]);
            ed->completion_providers[i].name = name_copy;
            ed->completion_providers[i].mode = mode;
            ed->completion_providers[i].words = words_copy;
            ed->completion_providers[i].word_count = word_count;
            ed->completion_providers[i].flags = flags;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->completion_providers,
                        ed->completion_provider_count,
                        ed->completion_provider_cap,
                        ECEX_INITIAL_HOOK_CAP) != ECEX_OK) {
        for (size_t i = 0; i < word_count; i++) free(words_copy[i]);
        free(words_copy);
        free(name_copy);
        return ECEX_ERR;
    }

    ecex_completion_provider_t *provider =
        &ed->completion_providers[ed->completion_provider_count++];
    memset(provider, 0, sizeof(*provider));
    provider->name = name_copy;
    provider->mode = mode;
    provider->words = words_copy;
    provider->word_count = word_count;
    provider->flags = flags;
    return ECEX_OK;
}

int ecex_remove_completion_provider(ecex_t *ed, const char *name) {
    if (!ed || !name) return ECEX_ERR;

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        if (strcmp(ed->completion_providers[i].name, name) != 0) continue;
        ecex_completion_provider_clear(&ed->completion_providers[i]);
        if (i + 1 < ed->completion_provider_count) {
            memmove(&ed->completion_providers[i],
                    &ed->completion_providers[i + 1],
                    (ed->completion_provider_count - i - 1) * sizeof(ed->completion_providers[i]));
        }
        ed->completion_provider_count--;
        return ECEX_OK;
    }

    return ECEX_ERR;
}

void ecex_set_clipboard_callbacks(ecex_t *ed,
                                  ecex_clipboard_get_fn get_fn,
                                  ecex_clipboard_set_fn set_fn,
                                  void *userdata) {
    if (!ed) return;
    ed->clipboard_get = get_fn;
    ed->clipboard_set = set_fn;
    ed->clipboard_userdata = userdata;
}

const char *ecex_clipboard_get(ecex_t *ed) {
    if (!ed) return NULL;

    if (ed->clipboard_get) {
        const char *external = ed->clipboard_get(ed->clipboard_userdata);
        if (external) {
            if (!ed->clipboard_text || strcmp(ed->clipboard_text, external) != 0) {
                char *copy = ecex_strdup(external);
                if (copy) {
                    free(ed->clipboard_text);
                    ed->clipboard_text = copy;
                }
            }
        }
    }

    return ed->clipboard_text;
}

int ecex_clipboard_set(ecex_t *ed, const char *text) {
    if (!ed || !text) return ECEX_ERR;

    char *copy = ecex_strdup(text);
    if (!copy) return ECEX_ERR;

    free(ed->clipboard_text);
    ed->clipboard_text = copy;

    if (ed->clipboard_set) {
        ed->clipboard_set(ed->clipboard_userdata, text);
    }

    return ECEX_OK;
}

static int ecex_command_exists(ecex_t *ed, const char *name) {
    if (!ed || !name) return 0;
    for (size_t i = 0; i < ed->command_count; i++) {
        if (ed->commands[i].name && strcmp(ed->commands[i].name, name) == 0) return 1;
    }
    return 0;
}

static int ecex_key_is_prefix_of(const char *prefix, const char *key) {
    if (!prefix || !key) return 0;
    size_t n = strlen(prefix);
    return strncmp(prefix, key, n) == 0 && key[n] == ' ';
}

static void ecex_warn_keybind_issue(const char *scope, const char *key, const char *detail) {
    if (scope && scope[0]) {
        fprintf(stderr,
                "ecex: keybind warning [%s]: %s%s%s\n",
                scope,
                key ? key : "<null>",
                detail && detail[0] ? " " : "",
                detail ? detail : "");
    } else {
        fprintf(stderr,
                "ecex: keybind warning: %s%s%s\n",
                key ? key : "<null>",
                detail && detail[0] ? " " : "",
                detail ? detail : "");
    }
}

static void ecex_warn_keybind_conflicts(ecex_t *ed, const char *scope, const char *key, int mode) {
    if (!ed || !key) return;

    for (size_t i = 0; i < ed->keybind_count; i++) {
        if (mode != 0) break;
        const char *existing = ed->keybinds[i].key;
        if (existing && ecex_key_is_prefix_of(key, existing)) ecex_warn_keybind_issue(scope, key, "is a prefix of an existing binding");
        if (existing && ecex_key_is_prefix_of(existing, key)) ecex_warn_keybind_issue(scope, key, "extends an existing complete binding");
    }

    for (size_t i = 0; i < ed->mode_keybind_count; i++) {
        if (mode != ed->mode_keybinds[i].mode) continue;
        const char *existing = ed->mode_keybinds[i].key;
        if (existing && ecex_key_is_prefix_of(key, existing)) ecex_warn_keybind_issue(scope, key, "is a prefix of an existing mode binding");
        if (existing && ecex_key_is_prefix_of(existing, key)) ecex_warn_keybind_issue(scope, key, "extends an existing complete mode binding");
    }
}

int ecex_bind_key(ecex_t *ed, const char *key, const char *command) {
    if (!ed || !key || !command) return ECEX_ERR;

    if (!ecex_command_exists(ed, command)) {
        ecex_warn_keybind_issue("global", key, "targets a command that is not registered yet");
    }
    ecex_warn_keybind_conflicts(ed, "global", key, 0);

    for (size_t i = 0; i < ed->keybind_count; i++) {
        if (strcmp(ed->keybinds[i].key, key) == 0) {
            fprintf(stderr, "ecex: keybind warning [global]: replacing %s from %s to %s\n", key, ed->keybinds[i].command, command);
            char *new_command = ecex_strdup(command);
            if (!new_command) return ECEX_ERR;

            free(ed->keybinds[i].command);
            ed->keybinds[i].command = new_command;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->keybinds,
                        ed->keybind_count,
                        ed->keybind_cap,
                        ECEX_INITIAL_KEYBIND_CAP) != ECEX_OK) {
        return ECEX_ERR;
    }

    char *key_copy = ecex_strdup(key);
    char *command_copy = ecex_strdup(command);
    if (!key_copy || !command_copy) {
        free(key_copy);
        free(command_copy);
        return ECEX_ERR;
    }

    ed->keybinds[ed->keybind_count].key = key_copy;
    ed->keybinds[ed->keybind_count].command = command_copy;
    ed->keybind_count++;
    return ECEX_OK;
}

const char *ecex_lookup_key(ecex_t *ed, const char *key) {
    if (!ed || !key) return NULL;

    for (size_t i = 0; i < ed->keybind_count; i++) {
        if (strcmp(ed->keybinds[i].key, key) == 0) {
            return ed->keybinds[i].command;
        }
    }

    return NULL;
}

int ecex_define_major_mode(ecex_t *ed, const char *name) {
    if (!ed || !name || !name[0]) return 0;

    for (size_t i = 0; i < ed->major_mode_count; i++) {
        if (strcmp(ed->major_modes[i].name, name) == 0) {
            return ed->major_modes[i].id;
        }
    }

    if (ECEX_GROW_ARRAY(ed->major_modes,
                        ed->major_mode_count,
                        ed->major_mode_cap,
                        ECEX_INITIAL_MODE_CAP) != ECEX_OK) {
        return 0;
    }

    char *copy = ecex_strdup(name);
    if (!copy) return 0;

    int id = ed->next_major_mode_id++;
    ed->major_modes[ed->major_mode_count].id = id;
    ed->major_modes[ed->major_mode_count].name = copy;
    ed->major_mode_count++;
    return id;
}

int ecex_major_mode_by_name(ecex_t *ed, const char *name) {
    if (!ed || !name) return 0;
    for (size_t i = 0; i < ed->major_mode_count; i++) {
        if (strcmp(ed->major_modes[i].name, name) == 0) return ed->major_modes[i].id;
    }
    return 0;
}

const char *ecex_major_mode_name(ecex_t *ed, int mode) {
    if (!ed || mode == 0) return "fundamental-mode";
    for (size_t i = 0; i < ed->major_mode_count; i++) {
        if (ed->major_modes[i].id == mode) return ed->major_modes[i].name;
    }
    return "unknown-mode";
}

int ecex_buffer_set_major_mode(buffer_t *buffer, int mode) {
    if (!buffer) return ECEX_ERR;
    buffer->major_mode = mode;
    return ECEX_OK;
}

int ecex_buffer_set_major_mode_by_name(ecex_t *ed, buffer_t *buffer, const char *name) {
    if (!ed || !buffer || !name) return ECEX_ERR;
    int mode = ecex_define_major_mode(ed, name);
    if (!mode) return ECEX_ERR;
    int old_mode = buffer->major_mode;
    int result = ecex_buffer_set_major_mode(buffer, mode);
    if (result == ECEX_OK && old_mode != mode) {
        ecex_notify_buffer_hooks(ed, buffer, ECEX_BUFFER_HOOK_MODE_CHANGE);
    }
    return result;
}

const char *ecex_buffer_major_mode_name(ecex_t *ed, buffer_t *buffer) {
    if (!buffer) return "fundamental-mode";
    return ecex_major_mode_name(ed, buffer->major_mode);
}

int ecex_bind_mode_key(ecex_t *ed, const char *mode_name, const char *key, const char *command) {
    if (!ed || !mode_name || !key || !command) return ECEX_ERR;

    int mode = ecex_define_major_mode(ed, mode_name);
    if (!mode) return ECEX_ERR;

    if (!ecex_command_exists(ed, command)) {
        ecex_warn_keybind_issue(mode_name, key, "targets a command that is not registered yet");
    }
    ecex_warn_keybind_conflicts(ed, mode_name, key, mode);

    for (size_t i = 0; i < ed->mode_keybind_count; i++) {
        if (ed->mode_keybinds[i].mode == mode && strcmp(ed->mode_keybinds[i].key, key) == 0) {
            fprintf(stderr, "ecex: keybind warning [%s]: replacing %s from %s to %s\n", mode_name, key, ed->mode_keybinds[i].command, command);
            char *new_command = ecex_strdup(command);
            if (!new_command) return ECEX_ERR;
            free(ed->mode_keybinds[i].command);
            ed->mode_keybinds[i].command = new_command;
            return ECEX_OK;
        }
    }

    if (ECEX_GROW_ARRAY(ed->mode_keybinds,
                        ed->mode_keybind_count,
                        ed->mode_keybind_cap,
                        ECEX_INITIAL_MODE_KEYBIND_CAP) != ECEX_OK) {
        return ECEX_ERR;
    }

    char *key_copy = ecex_strdup(key);
    char *command_copy = ecex_strdup(command);
    if (!key_copy || !command_copy) {
        free(key_copy);
        free(command_copy);
        return ECEX_ERR;
    }

    ed->mode_keybinds[ed->mode_keybind_count].mode = mode;
    ed->mode_keybinds[ed->mode_keybind_count].key = key_copy;
    ed->mode_keybinds[ed->mode_keybind_count].command = command_copy;
    ed->mode_keybind_count++;
    return ECEX_OK;
}

int ecex_validate_bindings(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    int ok = ECEX_OK;

    for (size_t i = 0; i < ed->keybind_count; i++) {
        const char *command = ed->keybinds[i].command;
        if (!ecex_command_exists(ed, command)) {
            ecex_warn_keybind_issue("global", ed->keybinds[i].key, "targets a missing command");
            ok = ECEX_ERR;
        }
        for (size_t j = i + 1; j < ed->keybind_count; j++) {
            if (ecex_key_is_prefix_of(ed->keybinds[i].key, ed->keybinds[j].key) ||
                ecex_key_is_prefix_of(ed->keybinds[j].key, ed->keybinds[i].key)) {
                ecex_warn_keybind_issue("global", ed->keybinds[i].key, "has a prefix conflict");
            }
        }
    }

    for (size_t i = 0; i < ed->mode_keybind_count; i++) {
        const char *command = ed->mode_keybinds[i].command;
        const char *mode = ecex_major_mode_name(ed, ed->mode_keybinds[i].mode);
        if (!ecex_command_exists(ed, command)) {
            ecex_warn_keybind_issue(mode, ed->mode_keybinds[i].key, "targets a missing command");
            ok = ECEX_ERR;
        }
        for (size_t j = i + 1; j < ed->mode_keybind_count; j++) {
            if (ed->mode_keybinds[i].mode != ed->mode_keybinds[j].mode) continue;
            if (ecex_key_is_prefix_of(ed->mode_keybinds[i].key, ed->mode_keybinds[j].key) ||
                ecex_key_is_prefix_of(ed->mode_keybinds[j].key, ed->mode_keybinds[i].key)) {
                ecex_warn_keybind_issue(mode, ed->mode_keybinds[i].key, "has a mode prefix conflict");
            }
        }
    }

    return ok;
}

const char *ecex_lookup_key_for_buffer(ecex_t *ed, buffer_t *buffer, const char *key) {
    if (!ed || !key) return NULL;

    int mode = buffer ? buffer->major_mode : 0;
    if (mode) {
        for (size_t i = 0; i < ed->mode_keybind_count; i++) {
            if (ed->mode_keybinds[i].mode == mode && strcmp(ed->mode_keybinds[i].key, key) == 0) {
                return ed->mode_keybinds[i].command;
            }
        }
    }

    return ecex_lookup_key(ed, key);
}

int ecex_key_sequence_has_prefix_for_buffer(ecex_t *ed, buffer_t *buffer, const char *prefix) {
    if (!ed || !prefix) return 0;
    size_t prefix_len = strlen(prefix);
    int mode = buffer ? buffer->major_mode : 0;

    if (mode) {
        for (size_t i = 0; i < ed->mode_keybind_count; i++) {
            const char *key = ed->mode_keybinds[i].key;
            if (ed->mode_keybinds[i].mode == mode &&
                strncmp(key, prefix, prefix_len) == 0 && key[prefix_len] == ' ') {
                return 1;
            }
        }
    }

    for (size_t i = 0; i < ed->keybind_count; i++) {
        const char *key = ed->keybinds[i].key;
        if (strncmp(key, prefix, prefix_len) == 0 && key[prefix_len] == ' ') return 1;
    }

    return 0;
}

typedef struct ecex_key_prefix_item {
    char key[64];
    char command[128];
    int has_children;
} ecex_key_prefix_item_t;

static int ecex_key_prefix_item_exists(ecex_key_prefix_item_t *items,
                                       size_t count,
                                       const char *key) {
    for (size_t i = 0; i < count; i++) {
        if (strcmp(items[i].key, key) == 0) return 1;
    }
    return 0;
}

static void ecex_key_prefix_collect_binding(ecex_key_prefix_item_t *items,
                                            size_t *count,
                                            size_t cap,
                                            const char *prefix,
                                            const char *binding,
                                            const char *command) {
    if (!items || !count || *count >= cap || !prefix || !binding || !command) return;

    size_t prefix_len = strlen(prefix);
    if (strncmp(binding, prefix, prefix_len) != 0 || binding[prefix_len] != ' ') return;

    const char *rest = binding + prefix_len + 1;
    if (!rest[0]) return;

    const char *space = strchr(rest, ' ');
    size_t key_len = space ? (size_t)(space - rest) : strlen(rest);
    if (key_len == 0) return;

    char key[64];
    if (key_len >= sizeof(key)) key_len = sizeof(key) - 1;
    memcpy(key, rest, key_len);
    key[key_len] = '\0';

    if (ecex_key_prefix_item_exists(items, *count, key)) return;

    ecex_key_prefix_item_t *item = &items[(*count)++];
    memset(item, 0, sizeof(*item));
    snprintf(item->key, sizeof(item->key), "%s", key);
    item->has_children = space ? 1 : 0;
    snprintf(item->command,
             sizeof(item->command),
             "%s",
             item->has_children ? "prefix" : command);
}

int ecex_describe_key_prefix(ecex_t *ed,
                             buffer_t *buffer,
                             const char *prefix,
                             char *out,
                             size_t out_size,
                             size_t max_items) {
    if (out && out_size) out[0] = '\0';
    if (!ed || !prefix || !prefix[0] || !out || out_size == 0) return ECEX_ERR;

    ecex_key_prefix_item_t items[64];
    size_t count = 0;
    int mode = buffer ? buffer->major_mode : 0;

    if (mode) {
        for (size_t i = 0; i < ed->mode_keybind_count; i++) {
            if (ed->mode_keybinds[i].mode != mode) continue;
            ecex_key_prefix_collect_binding(items,
                                            &count,
                                            ECEX_ARRAY_LEN(items),
                                            prefix,
                                            ed->mode_keybinds[i].key,
                                            ed->mode_keybinds[i].command);
        }
    }

    for (size_t i = 0; i < ed->keybind_count; i++) {
        ecex_key_prefix_collect_binding(items,
                                        &count,
                                        ECEX_ARRAY_LEN(items),
                                        prefix,
                                        ed->keybinds[i].key,
                                        ed->keybinds[i].command);
    }

    if (count == 0) {
        snprintf(out, out_size, "%s: no continuations", prefix);
        return 0;
    }

    if (max_items == 0 || max_items > count) max_items = count;

    size_t used = (size_t)snprintf(out, out_size, "%s: ", prefix);
    if (used >= out_size) {
        out[out_size - 1] = '\0';
        return (int)count;
    }

    size_t items_per_row = max_items > 8 ? 4 : max_items + 1;
    for (size_t i = 0; i < max_items; i++) {
        const char *sep = "";
        if (i > 0) sep = (i % items_per_row) == 0 ? "\n  " : "  |  ";

        int n = snprintf(out + used,
                         out_size - used,
                         "%s%s %s",
                         sep,
                         items[i].key,
                         items[i].command);
        if (n < 0) break;
        if ((size_t)n >= out_size - used) {
            used = out_size - 1;
            out[used] = '\0';
            break;
        }
        used += (size_t)n;
    }

    if (max_items < count && used + 16 < out_size) {
        snprintf(out + used, out_size - used, "  |  +%zu more", count - max_items);
    }

    return (int)count;
}

int ecex_auto_set_major_mode(ecex_t *ed, buffer_t *buffer) {
    if (!ed || !buffer) return ECEX_ERR;

    const char *name = "fundamental-mode";

    if (buffer_is_interactive(buffer) && buffer->name && buffer->name[0] == '*') {
        name = "special-mode";
    }

    return ecex_buffer_set_major_mode_by_name(ed, buffer, name);
}

int ecex_list_commands(ecex_t *ed) {
    if (!ed) return ECEX_ERR;

    buffer_t *buf = ecex_find_buffer(ed, "*commands*");
    if (!buf) {
        buf = ecex_create_buffer(ed, "*commands*", NULL, 0);
        if (!buf) return ECEX_ERR;
    }

    if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR;
    buffer_append(buf, "Commands:\n\n");

    for (size_t i = 0; i < ed->command_count; i++) {
        const char *command_name = ed->commands[i].name;
        int first_key = 1;

        buffer_append(buf, "  ");
        buffer_append(buf, command_name);

        for (size_t j = 0; j < ed->keybind_count; j++) {
            if (strcmp(ed->keybinds[j].command, command_name) == 0) {
                buffer_append(buf, first_key ? "    [" : ", ");
                buffer_append(buf, ed->keybinds[j].key);
                first_key = 0;
            }
        }

        for (size_t j = 0; j < ed->mode_keybind_count; j++) {
            if (strcmp(ed->mode_keybinds[j].command, command_name) == 0) {
                buffer_append(buf, first_key ? "    [" : ", ");
                buffer_append(buf, ecex_major_mode_name(ed, ed->mode_keybinds[j].mode));
                buffer_append(buf, ":");
                buffer_append(buf, ed->mode_keybinds[j].key);
                first_key = 0;
            }
        }

        if (!first_key) buffer_append(buf, "]");
        buffer_append(buf, "\n");
    }

    buf->point = 0;
    buf->modified = 0;
    return ecex_switch_buffer(ed, "*commands*");
}



static int ecex_interactive_switch_buffer_action(ecex_t *ed,
                                                 buffer_t *buffer,
                                                 size_t line,
                                                 const char *payload,
                                                 void *userdata) {
    (void)buffer;
    (void)line;
    (void)userdata;

    if (!ed || !payload) return ECEX_ERR;
    return ecex_switch_buffer(ed, payload);
}

int ecex_list_buffers(ecex_t *ed) {
    if (!ed) return ECEX_ERR;

    buffer_t *buf = ecex_find_buffer(ed, "*buffers*");
    if (!buf) {
        buf = ecex_create_interactive_buffer(ed, "*buffers*");
        if (!buf) return ECEX_ERR;
    }

    buffer_set_interactive(buf, 1);
    if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR;
    buffer_set_interactive(buf, 1);

    buffer_append(buf, "Buffers:\n");
    buffer_append(buf, "Press ENTER on a buffer to switch to it.\n\n");

    for (size_t i = 0; i < ed->buffer_count; i++) {
        buffer_t *b = ed->buffers[i];
        char line[1024];

        snprintf(line,
                 sizeof(line),
                 "%s %s %-24s %-18s size:%zu%s%s",
                 b == ed->current_buffer ? "*" : " ",
                 b->modified ? "+" : " ",
                 b->name ? b->name : "(unnamed)",
                 ecex_buffer_major_mode_name(ed, b),
                 b->len,
                 b->path ? "    " : "",
                 b->path ? b->path : "");

        if (ecex_interactive_append_line(ed,
                                         buf,
                                         line,
                                         ecex_interactive_switch_buffer_action,
                                         b->name,
                                         NULL) != ECEX_OK) {
            return ECEX_ERR;
        }
    }

    buf->point = 0;
    buf->modified = 0;
    return ecex_switch_buffer(ed, "*buffers*");
}

buffer_t *ecex_create_interactive_buffer(ecex_t *ed, const char *name) {
    if (!ed || !name) return NULL;

    buffer_t *buffer = ecex_find_buffer(ed, name);
    if (!buffer) {
        buffer = ecex_create_buffer(ed, name, NULL, 0);
        if (!buffer) return NULL;
    }

    buffer_set_interactive(buffer, 1);
    if (buffer->major_mode == 0) ecex_buffer_set_major_mode_by_name(ed, buffer, "special-mode");
    return buffer;
}

int ecex_interactive_append_line(ecex_t *ed,
                                 buffer_t *buffer,
                                 const char *text,
                                 ecex_interactive_line_fn fn,
                                 const char *payload,
                                 void *userdata) {
    (void)ed;

    if (!buffer || !text) return ECEX_ERR;

    size_t line = buffer_line_count(buffer);
    if (line > 0) line--;

    if (fn) {
        if (buffer_add_interactive_action(buffer, line, fn, payload, userdata) != ECEX_OK) {
            return ECEX_ERR;
        }
    }

    if (buffer_append(buffer, text) != ECEX_OK) return ECEX_ERR;
    if (buffer_append(buffer, "\n") != ECEX_OK) return ECEX_ERR;

    buffer_set_interactive(buffer, 1);
    return ECEX_OK;
}

int ecex_interactive_activate_current_line(ecex_t *ed) {
    if (!ed) return ECEX_ERR;

    buffer_t *buffer = ecex_current_buffer(ed);
    if (!buffer || !buffer_is_interactive(buffer)) return ECEX_ERR;

    size_t line = buffer_current_line_number(buffer);
    if (line > 0) line--;

    ecex_interactive_line_action_t *action =
        buffer_interactive_action_at_line(buffer, line);

    if (!action || !action->fn) return ECEX_ERR;
    return action->fn(ed, buffer, line, action->payload, action->userdata);
}

static int ecex_buffer_path_equal(buffer_t *buffer, const char *path) {
    return buffer && buffer->path && path && strcmp(buffer->path, path) == 0;
}

int ecex_find_file(ecex_t *ed, const char *path) {
    if (!ed || !path || !path[0]) return ECEX_ERR;

    char *normal_path = ecex_path_normalize(path);
    if (!normal_path) return ECEX_ERR;

    if (ecex_path_is_dir(normal_path)) {
        int result = ecex_file_browser_populate(ed, normal_path, 1);
        free(normal_path);
        return result;
    }

    if (ecex_path_is_file(normal_path) && ecex_path_is_media(normal_path)) {
        int result = ecex_media_open(ed, normal_path);
        free(normal_path);
        return result;
    }

    for (size_t i = 0; i < ed->buffer_count; i++) {
        if (ecex_buffer_path_equal(ed->buffers[i], normal_path)) {
            int result;
            free(normal_path);
            result = ecex_set_current_buffer_index(ed, i);
            if (result == ECEX_OK && !ecex_buffer_has_renderer(ed->buffers[i])) ecex_run_plugin_file_handlers(ed, ed->buffers[i]);
            return result;
        }
    }

    char *name = ecex_path_basename_dup(normal_path);
    if (!name) { free(normal_path); return ECEX_ERR; }
    buffer_t *buf = ecex_create_buffer(ed, name, NULL, 0);
    free(name);
    if (!buf) { free(normal_path); return ECEX_ERR; }

    if (ecex_file_exists(normal_path)) {
        if (buffer_load_file(buf, normal_path) != ECEX_OK) {
            ecex_kill_buffer_force(ed, buf->name);
            free(normal_path);
            return ECEX_ERR;
        }
    } else {
        free(buf->path);
        buf->path = normal_path;
        normal_path = NULL;
        buf->modified = 0;
    }

    free(normal_path);
    ecex_auto_set_major_mode(ed, buf);
    int switch_result = ecex_set_current_buffer_index(ed, ed->buffer_count ? ed->buffer_count - 1 : 0);
    if (switch_result == ECEX_OK) ecex_run_plugin_file_handlers(ed, buf);
    return switch_result;
}

int ecex_save_current_buffer(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf) return ECEX_ERR;
    int result = buffer_save(buf);
    if (result == ECEX_OK) ecex_notify_buffer_hooks(ed, buf, ECEX_BUFFER_HOOK_SAVE);
    return result;
}

int ecex_write_current_buffer(ecex_t *ed, const char *path) {
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf || !path || !path[0]) return ECEX_ERR;
    char *normal_path = ecex_path_normalize(path);
    if (!normal_path) return ECEX_ERR;
    int result = buffer_save_as(buf, normal_path);
    free(normal_path);
    if (result == ECEX_OK) {
        ecex_notify_buffer_hooks(ed, buf, ECEX_BUFFER_HOOK_SAVE);
        ecex_auto_set_major_mode(ed, buf);
    }
    return result;
}

void ecex_request_prompt(ecex_t *ed,
                         ecex_prompt_request_t request,
                         const char *message) {
    if (!ed) return;

    ed->prompt_request = request;
    snprintf(ed->prompt_message,
             sizeof(ed->prompt_message),
             "%s",
             message ? message : "");
}

void ecex_clear_prompt_request(ecex_t *ed) {
    if (!ed) return;
    ed->prompt_request = ECEX_PROMPT_NONE;
    ed->prompt_message[0] = '\0';
}

int ecex_indent_line_to(buffer_t *buffer, int target_cols) {
    if (!buffer || buffer->read_only || buffer_is_interactive(buffer)) return ECEX_ERR;
    if (target_cols < 0) target_cols = 0;
    if (target_cols > 240) target_cols = 240;

    size_t line_start = buffer_current_line_start(buffer);
    size_t line_end = buffer_current_line_end(buffer);
    size_t first = line_start;
    while (first < line_end && (buffer->data[first] == ' ' || buffer->data[first] == '\t')) first++;

    size_t point = buffer->point;
    size_t point_after_indent = point > first ? point - first : 0;

    char spaces[256];
    memset(spaces, ' ', (size_t)target_cols);
    spaces[target_cols] = '\0';

    if (buffer_delete_range(buffer, line_start, first) != ECEX_OK) return ECEX_ERR;
    if (target_cols > 0 && buffer_insert_at(buffer, line_start, spaces) != ECEX_OK) return ECEX_ERR;

    size_t new_first = line_start + (size_t)target_cols;
    if (point <= first) {
        buffer_set_point(buffer, new_first);
    } else {
        buffer_set_point(buffer, new_first + point_after_indent);
    }

    return ECEX_OK;
}

static int ecex_indent_for_tab(ecex_t *ed) {
    if (!ed) return ECEX_ERR;
    buffer_t *buffer = ecex_current_buffer(ed);
    if (!buffer || buffer->read_only || buffer_is_interactive(buffer)) return ECEX_ERR;

    size_t col = buffer_current_column(buffer);
    size_t spaces = 4 - (col % 4);
    if (spaces == 0) spaces = 4;

    char text[5];
    memset(text, ' ', spaces);
    text[spaces] = '\0';
    return buffer_insert(buffer, text);
}

static int ecex_fuzzy_score(const char *candidate, const char *query) {
    if (!candidate || !query) return -1;
    if (query[0] == '\0') return 0;

    int score = 0;
    int consecutive = 0;
    int last_match = -1;
    size_t ci = 0;
    size_t qi = 0;

    while (candidate[ci] && query[qi]) {
        char c = candidate[ci];
        char q = query[qi];

        if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
        if (q >= 'A' && q <= 'Z') q = (char)(q - 'A' + 'a');

        if (c == q) {
            score += 10;

            if ((int)ci == last_match + 1) {
                consecutive++;
                score += 5 * consecutive;
            } else {
                consecutive = 0;
            }

            if (ci == 0) score += 20;
            if (ci > 0 && (candidate[ci - 1] == '-' ||
                           candidate[ci - 1] == '_' ||
                           candidate[ci - 1] == ' ')) {
                score += 15;
            }

            last_match = (int)ci;
            qi++;
        }

        ci++;
    }

    if (query[qi] != '\0') return -1;

    score -= (int)strlen(candidate);
    if (strncmp(candidate, query, strlen(query)) == 0) score += 100;
    return score;
}

#define ECEX_COMPLETION_MAX_CANDIDATES 96

typedef struct ecex_completion_candidate {
    char text[256];
    char detail[256];
    int score;
} ecex_completion_candidate_t;

static void ecex_completion_cycle_reset(ecex_t *ed) {
    if (!ed) return;
    ed->completion_cycle_active = 0;
    ed->completion_cycle_buffer = NULL;
    ed->completion_cycle_start = 0;
    ed->completion_cycle_index = 0;
    ed->completion_cycle_prefix[0] = '\0';
    ed->completion_cycle_current[0] = '\0';
}

static int ecex_completion_candidates_add(ecex_completion_candidate_t *items,
                                          size_t cap,
                                          size_t *count,
                                          const char *text,
                                          const char *detail,
                                          int score) {
    if (!items || !count || *count >= cap || !text || !text[0] || score < 0) return ECEX_ERR;

    for (size_t i = 0; i < *count; i++) {
        if (strcmp(items[i].text, text) == 0) {
            if (score > items[i].score) items[i].score = score;
            if ((!items[i].detail[0]) && detail && detail[0]) {
                snprintf(items[i].detail, sizeof(items[i].detail), "%s", detail);
            }
            return ECEX_OK;
        }
    }

    ecex_completion_candidate_t *item = &items[(*count)++];
    memset(item, 0, sizeof(*item));
    snprintf(item->text, sizeof(item->text), "%s", text);
    if (detail && detail[0]) snprintf(item->detail, sizeof(item->detail), "%s", detail);
    item->score = score;
    return ECEX_OK;
}

static int ecex_completion_candidate_compare(const void *a, const void *b) {
    const ecex_completion_candidate_t *ca = (const ecex_completion_candidate_t *)a;
    const ecex_completion_candidate_t *cb = (const ecex_completion_candidate_t *)b;
    if (ca->score != cb->score) return cb->score - ca->score;
    size_t la = strlen(ca->text);
    size_t lb = strlen(cb->text);
    if (la != lb) return la < lb ? -1 : 1;
    return strcmp(ca->text, cb->text);
}

#define ECEX_CLANGD_TIMEOUT_MS 4500
#define ECEX_CLANGD_MAX_MESSAGES 96

typedef struct ecex_lsp_process {
    pid_t pid;
    int in_fd;
    int out_fd;
} ecex_lsp_process_t;

static char *ecex_lsp_format(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int needed = vsnprintf(NULL, 0, fmt, ap);
    va_end(ap);
    if (needed < 0) return NULL;

    char *out = malloc((size_t)needed + 1);
    if (!out) return NULL;

    va_start(ap, fmt);
    vsnprintf(out, (size_t)needed + 1, fmt, ap);
    va_end(ap);
    return out;
}

static int ecex_lsp_write_all(int fd, const char *data, size_t len) {
    size_t written = 0;
    while (written < len) {
        ssize_t n = write(fd, data + written, len - written);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) return ECEX_ERR;
        written += (size_t)n;
    }
    return ECEX_OK;
}

static int ecex_lsp_send(int fd, const char *json) {
    if (!json) return ECEX_ERR;
    char header[80];
    int n = snprintf(header, sizeof(header), "Content-Length: %zu\r\n\r\n", strlen(json));
    if (n <= 0 || (size_t)n >= sizeof(header)) return ECEX_ERR;
    if (ecex_lsp_write_all(fd, header, (size_t)n) != ECEX_OK) return ECEX_ERR;
    return ecex_lsp_write_all(fd, json, strlen(json));
}

static int ecex_lsp_wait_readable(int fd, int timeout_ms) {
    struct pollfd pfd;
    pfd.fd = fd;
    pfd.events = POLLIN;
    pfd.revents = 0;

    for (;;) {
        int rc = poll(&pfd, 1, timeout_ms);
        if (rc < 0 && errno == EINTR) continue;
        if (rc <= 0) return ECEX_ERR;
        if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) return ECEX_ERR;
        if (pfd.revents & POLLIN) return ECEX_OK;
    }
}

static int ecex_lsp_read_byte(int fd, char *out, int timeout_ms) {
    if (!out) return ECEX_ERR;
    if (ecex_lsp_wait_readable(fd, timeout_ms) != ECEX_OK) return ECEX_ERR;

    for (;;) {
        ssize_t n = read(fd, out, 1);
        if (n < 0 && errno == EINTR) continue;
        if (n == 1) return ECEX_OK;
        return ECEX_ERR;
    }
}

static int ecex_lsp_read_line(int fd, char *out, size_t out_size, int timeout_ms) {
    if (!out || out_size == 0) return ECEX_ERR;
    size_t used = 0;

    for (;;) {
        char ch = '\0';
        if (ecex_lsp_read_byte(fd, &ch, timeout_ms) != ECEX_OK) return ECEX_ERR;
        if (ch == '\n') break;
        if (used + 1 < out_size) out[used++] = ch;
    }

    if (used > 0 && out[used - 1] == '\r') used--;
    out[used] = '\0';
    return ECEX_OK;
}

static int ecex_lsp_read_exact(int fd, char *out, size_t len, int timeout_ms) {
    if (!out) return ECEX_ERR;
    size_t got = 0;

    while (got < len) {
        if (ecex_lsp_wait_readable(fd, timeout_ms) != ECEX_OK) return ECEX_ERR;
        ssize_t n = read(fd, out + got, len - got);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) return ECEX_ERR;
        got += (size_t)n;
    }

    return ECEX_OK;
}

static int ecex_lsp_read_message(int fd, char **out_body, int timeout_ms) {
    if (!out_body) return ECEX_ERR;
    *out_body = NULL;

    size_t content_len = 0;
    int have_content_len = 0;

    for (int i = 0; i < 64; i++) {
        char line[256];
        if (ecex_lsp_read_line(fd, line, sizeof(line), timeout_ms) != ECEX_OK) return ECEX_ERR;
        if (line[0] == '\0') break;

        if (strncmp(line, "Content-Length:", 15) == 0) {
            char *end = NULL;
            unsigned long n = strtoul(line + 15, &end, 10);
            if (n > 0) {
                content_len = (size_t)n;
                have_content_len = 1;
            }
        }
    }

    if (!have_content_len || content_len == 0 || content_len > 32u * 1024u * 1024u) {
        return ECEX_ERR;
    }

    char *body = malloc(content_len + 1);
    if (!body) return ECEX_ERR;
    if (ecex_lsp_read_exact(fd, body, content_len, timeout_ms) != ECEX_OK) {
        free(body);
        return ECEX_ERR;
    }
    body[content_len] = '\0';
    *out_body = body;
    return ECEX_OK;
}

static int ecex_json_has_id(const char *json, int id) {
    if (!json) return 0;
    const char *p = json;
    while ((p = strstr(p, "\"id\"")) != NULL) {
        p += 4;
        while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
        if (*p != ':') continue;
        p++;
        while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
        char *end = NULL;
        long value = strtol(p, &end, 10);
        if (end != p && value == id) return 1;
    }
    return 0;
}

static int ecex_lsp_read_response(int fd, int id, char **out_body) {
    if (!out_body) return ECEX_ERR;
    *out_body = NULL;

    for (int i = 0; i < ECEX_CLANGD_MAX_MESSAGES; i++) {
        char *body = NULL;
        if (ecex_lsp_read_message(fd, &body, ECEX_CLANGD_TIMEOUT_MS) != ECEX_OK) return ECEX_ERR;
        if (ecex_json_has_id(body, id)) {
            *out_body = body;
            return ECEX_OK;
        }
        free(body);
    }

    return ECEX_ERR;
}

static int ecex_lsp_start_clangd(ecex_lsp_process_t *proc) {
    if (!proc) return ECEX_ERR;
    memset(proc, 0, sizeof(*proc));
    proc->pid = -1;
    proc->in_fd = -1;
    proc->out_fd = -1;
    signal(SIGPIPE, SIG_IGN);

    int in_pipe[2];
    int out_pipe[2];
    if (pipe(in_pipe) != 0) return ECEX_ERR;
    if (pipe(out_pipe) != 0) {
        close(in_pipe[0]);
        close(in_pipe[1]);
        return ECEX_ERR;
    }

    pid_t pid = fork();
    if (pid < 0) {
        close(in_pipe[0]);
        close(in_pipe[1]);
        close(out_pipe[0]);
        close(out_pipe[1]);
        return ECEX_ERR;
    }

    if (pid == 0) {
        dup2(in_pipe[0], STDIN_FILENO);
        dup2(out_pipe[1], STDOUT_FILENO);

        int null_fd = open("/dev/null", O_WRONLY);
        if (null_fd >= 0) {
            dup2(null_fd, STDERR_FILENO);
            close(null_fd);
        }

        close(in_pipe[0]);
        close(in_pipe[1]);
        close(out_pipe[0]);
        close(out_pipe[1]);

        execlp("clangd", "clangd", "--log=error", "--pretty=false", (char *)NULL);
        _exit(127);
    }

    close(in_pipe[0]);
    close(out_pipe[1]);

    proc->pid = pid;
    proc->in_fd = in_pipe[1];
    proc->out_fd = out_pipe[0];
    return ECEX_OK;
}

static void ecex_lsp_finish(ecex_lsp_process_t *proc) {
    if (!proc || proc->pid <= 0) return;

    if (proc->in_fd >= 0) {
        const char *shutdown = "{\"jsonrpc\":\"2.0\",\"id\":99,\"method\":\"shutdown\",\"params\":null}";
        const char *exit_msg = "{\"jsonrpc\":\"2.0\",\"method\":\"exit\",\"params\":{}}";
        ecex_lsp_send(proc->in_fd, shutdown);
        ecex_lsp_send(proc->in_fd, exit_msg);
        close(proc->in_fd);
        proc->in_fd = -1;
    }

    if (proc->out_fd >= 0) {
        close(proc->out_fd);
        proc->out_fd = -1;
    }

    for (int i = 0; i < 50; i++) {
        int status = 0;
        pid_t rc = waitpid(proc->pid, &status, WNOHANG);
        if (rc == proc->pid) {
            proc->pid = -1;
            return;
        }
        if (rc < 0 && errno != EINTR) break;
        poll(NULL, 0, 10);
    }

    kill(proc->pid, SIGKILL);
    waitpid(proc->pid, NULL, 0);
    proc->pid = -1;
}

static char *ecex_json_escape_len(const char *text, size_t len) {
    if (!text && len != 0) return NULL;

    size_t cap = len * 6 + 1;
    char *out = malloc(cap);
    if (!out) return NULL;

    size_t used = 0;
    static const char hex[] = "0123456789abcdef";
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)text[i];
        if (c == '"' || c == '\\') {
            out[used++] = '\\';
            out[used++] = (char)c;
        } else if (c == '\n') {
            out[used++] = '\\';
            out[used++] = 'n';
        } else if (c == '\r') {
            out[used++] = '\\';
            out[used++] = 'r';
        } else if (c == '\t') {
            out[used++] = '\\';
            out[used++] = 't';
        } else if (c < 0x20) {
            out[used++] = '\\';
            out[used++] = 'u';
            out[used++] = '0';
            out[used++] = '0';
            out[used++] = hex[(c >> 4) & 0x0f];
            out[used++] = hex[c & 0x0f];
        } else {
            out[used++] = (char)c;
        }
    }
    out[used] = '\0';
    return out;
}

static char *ecex_json_escape(const char *text) {
    return ecex_json_escape_len(text ? text : "", text ? strlen(text) : 0);
}

static int ecex_uri_unreserved(unsigned char c) {
    return (c >= 'a' && c <= 'z') ||
           (c >= 'A' && c <= 'Z') ||
           (c >= '0' && c <= '9') ||
           c == '-' || c == '_' || c == '.' || c == '~' || c == '/';
}

static char *ecex_lsp_file_uri(const char *path) {
    if (!path || !path[0]) return NULL;
    char *normal = ecex_path_normalize(path);
    if (!normal) return NULL;

    size_t len = strlen(normal);
    char *out = malloc(7 + len * 3 + 1);
    if (!out) {
        free(normal);
        return NULL;
    }

    memcpy(out, "file://", 7);
    size_t used = 7;
    static const char hex[] = "0123456789ABCDEF";
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)normal[i];
        if (ecex_uri_unreserved(c)) {
            out[used++] = (char)c;
        } else {
            out[used++] = '%';
            out[used++] = hex[(c >> 4) & 0x0f];
            out[used++] = hex[c & 0x0f];
        }
    }
    out[used] = '\0';
    free(normal);
    return out;
}

static const char *ecex_lsp_language_id(const char *path) {
    if (!path) return "c";
    const char *dot = strrchr(path, '.');
    if (!dot) return "c";
    if (strcmp(dot, ".cc") == 0 ||
        strcmp(dot, ".cpp") == 0 ||
        strcmp(dot, ".cxx") == 0 ||
        strcmp(dot, ".hh") == 0 ||
        strcmp(dot, ".hpp") == 0 ||
        strcmp(dot, ".hxx") == 0) {
        return "cpp";
    }
    return "c";
}

static void ecex_buffer_lsp_position(buffer_t *buffer, int *out_line, int *out_character) {
    int line = 0;
    int character = 0;
    if (buffer && buffer->data) {
        size_t point = buffer->point > buffer->len ? buffer->len : buffer->point;
        for (size_t i = 0; i < point; i++) {
            if (buffer->data[i] == '\n') {
                line++;
                character = 0;
            } else {
                character++;
            }
        }
    }
    if (out_line) *out_line = line;
    if (out_character) *out_character = character;
}

static int ecex_json_hex_value(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    return -1;
}

static const char *ecex_json_decode_string(const char *p, char *out, size_t out_size) {
    if (!p || *p != '"' || !out || out_size == 0) return NULL;
    p++;
    size_t used = 0;

    while (*p && *p != '"') {
        unsigned char c = (unsigned char)*p++;
        if (c == '\\') {
            char esc = *p++;
            if (esc == '"' || esc == '\\' || esc == '/') c = (unsigned char)esc;
            else if (esc == 'b') c = '\b';
            else if (esc == 'f') c = '\f';
            else if (esc == 'n') c = '\n';
            else if (esc == 'r') c = '\r';
            else if (esc == 't') c = '\t';
            else if (esc == 'u') {
                int h1 = ecex_json_hex_value(p[0]);
                int h2 = ecex_json_hex_value(p[1]);
                int h3 = ecex_json_hex_value(p[2]);
                int h4 = ecex_json_hex_value(p[3]);
                if (h1 < 0 || h2 < 0 || h3 < 0 || h4 < 0) return NULL;
                unsigned int code = (unsigned int)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
                p += 4;
                c = code < 0x80 ? (unsigned char)code : '?';
            } else {
                return NULL;
            }
        }

        if (used + 1 < out_size) out[used++] = (char)c;
    }

    if (*p != '"') return NULL;
    out[used] = '\0';
    return p + 1;
}

static int ecex_json_string_between(const char *start,
                                    const char *end,
                                    const char *key,
                                    char *out,
                                    size_t out_size) {
    if (out && out_size) out[0] = '\0';
    if (!start || !end || !key || !out || out_size == 0 || start >= end) return 0;

    char pattern[64];
    snprintf(pattern, sizeof(pattern), "\"%s\"", key);
    const char *p = start;
    while ((p = strstr(p, pattern)) != NULL && p < end) {
        p += strlen(pattern);
        while (p < end && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) p++;
        if (p >= end || *p != ':') continue;
        p++;
        while (p < end && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) p++;
        if (p >= end || *p != '"') continue;
        return ecex_json_decode_string(p, out, out_size) ? 1 : 0;
    }

    return 0;
}

static void ecex_trim_in_place(char *text) {
    if (!text) return;
    char *start = text;
    while (*start == ' ' || *start == '\t' || *start == '\r' || *start == '\n') start++;
    if (start != text) memmove(text, start, strlen(start) + 1);

    size_t len = strlen(text);
    while (len > 0 &&
           (text[len - 1] == ' ' ||
            text[len - 1] == '\t' ||
            text[len - 1] == '\r' ||
            text[len - 1] == '\n')) {
        text[--len] = '\0';
    }
}

static void ecex_lsp_completion_detail(const char *label,
                                       const char *item_start,
                                       const char *item_end,
                                       char *out,
                                       size_t out_size) {
    if (out && out_size) out[0] = '\0';
    if (!label || !item_start || !item_end || !out || out_size == 0) return;

    char detail[192];
    char description[128];
    char documentation[192];
    detail[0] = '\0';
    description[0] = '\0';
    documentation[0] = '\0';

    ecex_json_string_between(item_start, item_end, "detail", detail, sizeof(detail));
    ecex_json_string_between(item_start, item_end, "description", description, sizeof(description));
    ecex_json_string_between(item_start, item_end, "documentation", documentation, sizeof(documentation));
    ecex_trim_in_place(detail);
    ecex_trim_in_place(description);
    ecex_trim_in_place(documentation);

    if (detail[0] == '(') {
        snprintf(out,
                 out_size,
                 "%s%s%s%s",
                 label,
                 detail,
                 description[0] ? " -> " : "",
                 description);
    } else if (detail[0] && description[0]) {
        snprintf(out, out_size, "%s; %s", detail, description);
    } else if (detail[0]) {
        snprintf(out, out_size, "%s", detail);
    } else if (description[0]) {
        snprintf(out, out_size, "%s", description);
    } else if (documentation[0]) {
        snprintf(out, out_size, "%s", documentation);
    }
}

static int ecex_lsp_collect_completions(const char *json,
                                        const char *prefix,
                                        ecex_completion_candidate_t *items,
                                        size_t cap,
                                        size_t *count) {
    if (!json || !prefix || !items || !count) return ECEX_ERR;

    const char *p = json;
    while ((p = strstr(p, "\"label\"")) != NULL) {
        const char *item_start = p;
        p += 7;
        while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
        if (*p != ':') continue;
        p++;
        while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
        if (*p != '"') continue;

        char label[256];
        const char *next = ecex_json_decode_string(p, label, sizeof(label));
        if (!next) {
            p++;
            continue;
        }
        p = next;

        char *trimmed = label;
        while (*trimmed == ' ' || *trimmed == '\t' || *trimmed == '\r' || *trimmed == '\n') trimmed++;
        size_t trimmed_len = strlen(trimmed);
        while (trimmed_len > 0 &&
               (trimmed[trimmed_len - 1] == ' ' ||
                trimmed[trimmed_len - 1] == '\t' ||
                trimmed[trimmed_len - 1] == '\r' ||
                trimmed[trimmed_len - 1] == '\n')) {
            trimmed[--trimmed_len] = '\0';
        }
        if (trimmed_len == 0) continue;

        int score = ecex_fuzzy_score(trimmed, prefix);
        if (score < 0) continue;
        score += 7000;

        const char *item_end = strstr(p, "\"label\"");
        if (!item_end) item_end = json + strlen(json);

        char detail[256];
        ecex_lsp_completion_detail(trimmed, item_start, item_end, detail, sizeof(detail));

        ecex_completion_candidates_add(items, cap, count, trimmed, detail, score);
    }

    return *count > 0 ? ECEX_OK : ECEX_ERR;
}

static int ecex_clangd_collect_candidates(buffer_t *buffer,
                                          const char *prefix,
                                          ecex_completion_candidate_t *items,
                                          size_t cap,
                                          size_t *count) {
    if (!buffer || !buffer->path || !buffer->path[0] || !prefix || !items || !count) return ECEX_ERR;

    char *uri = ecex_lsp_file_uri(buffer->path);
    char *root_path = ecex_path_dirname(buffer->path);
    char *root_uri = root_path ? ecex_lsp_file_uri(root_path) : NULL;
    char *escaped_uri = ecex_json_escape(uri);
    char *escaped_root_uri = ecex_json_escape(root_uri ? root_uri : uri);
    char *escaped_text = ecex_json_escape_len(buffer->data ? buffer->data : "", buffer->len);
    if (!uri || !escaped_uri || !escaped_root_uri || !escaped_text) {
        free(uri);
        free(root_path);
        free(root_uri);
        free(escaped_uri);
        free(escaped_root_uri);
        free(escaped_text);
        return ECEX_ERR;
    }

    int line = 0;
    int character = 0;
    ecex_buffer_lsp_position(buffer, &line, &character);

    const char *language_id = ecex_lsp_language_id(buffer->path);
    char *initialize = ecex_lsp_format(
        "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\","
        "\"params\":{\"processId\":null,\"rootUri\":\"%s\","
        "\"capabilities\":{\"textDocument\":{\"completion\":{\"completionItem\":{"
        "\"snippetSupport\":false,\"labelDetailsSupport\":true,"
        "\"documentationFormat\":[\"plaintext\"]}}}},"
        "\"clientInfo\":{\"name\":\"ecex\",\"version\":\"0\"}}}",
        escaped_root_uri);
    char *initialized = ecex_lsp_format(
        "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}");
    char *did_open = ecex_lsp_format(
        "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\","
        "\"params\":{\"textDocument\":{\"uri\":\"%s\",\"languageId\":\"%s\","
        "\"version\":1,\"text\":\"%s\"}}}",
        escaped_uri,
        language_id,
        escaped_text);
    char *completion = ecex_lsp_format(
        "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"textDocument/completion\","
        "\"params\":{\"textDocument\":{\"uri\":\"%s\"},"
        "\"position\":{\"line\":%d,\"character\":%d},"
        "\"context\":{\"triggerKind\":1}}}",
        escaped_uri,
        line,
        character);

    free(uri);
    free(root_path);
    free(root_uri);
    free(escaped_uri);
    free(escaped_root_uri);
    free(escaped_text);

    if (!initialize || !initialized || !did_open || !completion) {
        free(initialize);
        free(initialized);
        free(did_open);
        free(completion);
        return ECEX_ERR;
    }

    int result = ECEX_ERR;
    ecex_lsp_process_t proc;
    if (ecex_lsp_start_clangd(&proc) == ECEX_OK) {
        char *response = NULL;
        if (ecex_lsp_send(proc.in_fd, initialize) == ECEX_OK &&
            ecex_lsp_read_response(proc.out_fd, 1, &response) == ECEX_OK) {
            free(response);
            response = NULL;
            if (ecex_lsp_send(proc.in_fd, initialized) == ECEX_OK &&
                ecex_lsp_send(proc.in_fd, did_open) == ECEX_OK &&
                ecex_lsp_send(proc.in_fd, completion) == ECEX_OK &&
                ecex_lsp_read_response(proc.out_fd, 2, &response) == ECEX_OK) {
                result = ecex_lsp_collect_completions(response, prefix, items, cap, count);
            }
        }
        free(response);
        ecex_lsp_finish(&proc);
    }

    free(initialize);
    free(initialized);
    free(did_open);
    free(completion);
    return result;
}

static int ecex_clangd_completion_provider(ecex_t *ed,
                                           buffer_t *buffer,
                                           const char *prefix,
                                           char *out,
                                           size_t out_size,
                                           void *userdata) {
    (void)ed;
    (void)userdata;
    if (out && out_size) out[0] = '\0';
    if (!buffer || !prefix || !out || out_size == 0) return -1;

    ecex_completion_candidate_t items[ECEX_COMPLETION_MAX_CANDIDATES];
    size_t count = 0;
    memset(items, 0, sizeof(items));

    if (ecex_clangd_collect_candidates(buffer,
                                       prefix,
                                       items,
                                       ECEX_COMPLETION_MAX_CANDIDATES,
                                       &count) != ECEX_OK ||
        count == 0) {
        return -1;
    }

    qsort(items, count, sizeof(items[0]), ecex_completion_candidate_compare);
    snprintf(out, out_size, "%s", items[0].text);
    return items[0].score;
}

int ecex_add_clangd_completion_provider(ecex_t *ed, const char *name, const char *mode_name) {
    return ecex_add_completion_provider(ed,
                                        name,
                                        mode_name,
                                        ecex_clangd_completion_provider,
                                        NULL,
                                        NULL);
}

const char *ecex_complete_command(ecex_t *ed, const char *query) {
    if (!ed || !query || !ed->theme.completion_enabled) return NULL;

    const char *best = NULL;
    int best_score = -1;

    for (size_t i = 0; i < ed->command_count; i++) {
        const char *name = ed->commands[i].name;
        int score = ecex_fuzzy_score(name, query);

        if (score > best_score) {
            best_score = score;
            best = name;
        }
    }

    return best;
}

static int ecex_identifier_char(int c) {
    return (c >= 'a' && c <= 'z') ||
           (c >= 'A' && c <= 'Z') ||
           (c >= '0' && c <= '9') ||
           c == '_';
}

static size_t ecex_buffer_identifier_start(buffer_t *buffer) {
    if (!buffer || !buffer->data) return 0;
    size_t pos = buffer->point > buffer->len ? buffer->len : buffer->point;
    while (pos > 0 && ecex_identifier_char((unsigned char)buffer->data[pos - 1])) {
        pos--;
    }
    return pos;
}

int ecex_buffer_identifier_prefix(buffer_t *buffer, char *out, size_t out_size) {
    if (out && out_size) out[0] = '\0';
    if (!buffer || !out || out_size == 0) return ECEX_ERR;

    size_t end = buffer->point > buffer->len ? buffer->len : buffer->point;
    size_t start = ecex_buffer_identifier_start(buffer);
    size_t len = end > start ? end - start : 0;

    if (len >= out_size) len = out_size - 1;
    if (len > 0) memcpy(out, buffer->data + start, len);
    out[len] = '\0';
    return (int)len;
}

static int ecex_buffer_ed_arrow_context(buffer_t *buffer, const char *prefix) {
    if (!buffer || !buffer->data || !prefix) return 0;

    size_t prefix_len = strlen(prefix);
    size_t point = buffer->point > buffer->len ? buffer->len : buffer->point;
    if (point < prefix_len + 2) return 0;

    size_t start = point - prefix_len;
    if (buffer->data[start - 2] != '-' || buffer->data[start - 1] != '>') return 0;

    size_t name_end = start - 2;
    size_t name_start = name_end;
    while (name_start > 0 && ecex_identifier_char((unsigned char)buffer->data[name_start - 1])) {
        name_start--;
    }

    return name_end - name_start == 2 &&
           buffer->data[name_start] == 'e' &&
           buffer->data[name_start + 1] == 'd';
}

static int ecex_completion_provider_context_matches(ecex_completion_provider_t *provider,
                                                    int ed_arrow_context) {
    if (!provider) return 0;
    if (ed_arrow_context) return (provider->flags & ECEX_COMPLETION_ED_ARROW) != 0;
    return (provider->flags & ECEX_COMPLETION_ED_ARROW) == 0;
}

static const char *ecex_completion_provider_detail(ecex_completion_provider_t *provider) {
    if (!provider || !provider->name) return "";
    if (provider->detail && provider->detail[0]) return provider->detail;
    return provider->name;
}

static void ecex_completion_collect_from_provider(ecex_t *ed,
                                                  buffer_t *buffer,
                                                  ecex_completion_provider_t *provider,
                                                  const char *prefix,
                                                  ecex_completion_candidate_t *items,
                                                  size_t cap,
                                                  size_t *count) {
    if (!ed || !buffer || !provider || !prefix || !items || !count) return;

    const char *detail = ecex_completion_provider_detail(provider);

    if (provider->word_count > 0) {
        for (size_t i = 0; i < provider->word_count; i++) {
            int score = ecex_fuzzy_score(provider->words[i], prefix);
            if (score < 0) continue;
            ecex_completion_candidates_add(items, cap, count, provider->words[i], detail, score);
        }
        return;
    }

    if (provider->fn == ecex_clangd_completion_provider) {
        ecex_clangd_collect_candidates(buffer, prefix, items, cap, count);
        return;
    }

    if (provider->fn) {
        char candidate[256];
        candidate[0] = '\0';
        int score = provider->fn(ed,
                                 buffer,
                                 prefix,
                                 candidate,
                                 sizeof(candidate),
                                 provider->userdata);
        if (score == 0) score = ecex_fuzzy_score(candidate, prefix);
        if (score >= 0 && candidate[0]) {
            ecex_completion_candidates_add(items, cap, count, candidate, detail, score);
        }
    }
}

static int ecex_completion_cycle_valid(ecex_t *ed, buffer_t *buffer) {
    if (!ed || !buffer || !ed->completion_cycle_active) return 0;
    if (ed->completion_cycle_buffer != buffer) return 0;

    size_t len = strlen(ed->completion_cycle_current);
    size_t start = ed->completion_cycle_start;
    if (start + len > buffer->len || start + len != buffer->point) return 0;
    return strncmp(buffer->data + start, ed->completion_cycle_current, len) == 0;
}

static void ecex_completion_describe(ecex_t *ed,
                                     const ecex_completion_candidate_t *item,
                                     size_t index,
                                     size_t count) {
    if (!ed || !item) return;

    char message[700];
    if (item->detail[0]) {
        size_t text_len = strlen(item->text);
        if (strncmp(item->detail, item->text, text_len) == 0) {
            snprintf(message,
                     sizeof(message),
                     "Completion %zu/%zu: %s",
                     index + 1,
                     count,
                     item->detail);
        } else {
            snprintf(message,
                     sizeof(message),
                     "Completion %zu/%zu: %s - %s",
                     index + 1,
                     count,
                     item->text,
                     item->detail);
        }
    } else {
        snprintf(message,
                 sizeof(message),
                 "Completion %zu/%zu: %s",
                 index + 1,
                 count,
                 item->text);
    }
    ecex_message(ed, message);
}

static int ecex_complete_at_point_direction(ecex_t *ed, int direction) {
    if (!ed) return ECEX_ERR;

    buffer_t *buffer = ecex_current_buffer(ed);
    if (!buffer || buffer->read_only || buffer_is_interactive(buffer)) return ECEX_ERR;

    char prefix[256];
    size_t start = 0;
    size_t end = buffer->point > buffer->len ? buffer->len : buffer->point;
    int cycling = ecex_completion_cycle_valid(ed, buffer);

    if (cycling) {
        snprintf(prefix, sizeof(prefix), "%s", ed->completion_cycle_prefix);
        start = ed->completion_cycle_start;
    } else {
        int prefix_len = ecex_buffer_identifier_prefix(buffer, prefix, sizeof(prefix));
        if (prefix_len <= 0) {
            ecex_completion_cycle_reset(ed);
            ecex_message(ed, "No completion prefix");
            return ECEX_OK;
        }
        start = ecex_buffer_identifier_start(buffer);
    }

    if (!prefix[0]) {
        ecex_completion_cycle_reset(ed);
        ecex_message(ed, "No completion prefix");
        return ECEX_OK;
    }

    ecex_completion_candidate_t items[ECEX_COMPLETION_MAX_CANDIDATES];
    size_t count = 0;
    memset(items, 0, sizeof(items));

    int mode = buffer->major_mode;
    int ed_arrow_context = ecex_buffer_ed_arrow_context(buffer, prefix);

    for (size_t i = 0; i < ed->completion_provider_count; i++) {
        ecex_completion_provider_t *provider = &ed->completion_providers[i];
        if (provider->mode != 0 && provider->mode != mode) continue;
        if (!ecex_completion_provider_context_matches(provider, ed_arrow_context)) continue;
        ecex_completion_collect_from_provider(ed,
                                              buffer,
                                              provider,
                                              prefix,
                                              items,
                                              ECEX_COMPLETION_MAX_CANDIDATES,
                                              &count);
    }

    if (count == 0) {
        ecex_completion_cycle_reset(ed);
        ecex_message(ed, "No completion");
        return ECEX_OK;
    }

    qsort(items, count, sizeof(items[0]), ecex_completion_candidate_compare);

    size_t index = direction < 0 ? count - 1 : 0;
    if (cycling) {
        size_t current = count;
        for (size_t i = 0; i < count; i++) {
            if (strcmp(items[i].text, ed->completion_cycle_current) == 0) {
                current = i;
                break;
            }
        }

        if (current < count) {
            if (direction < 0) index = current == 0 ? count - 1 : current - 1;
            else index = (current + 1) % count;
        }
    }

    ecex_completion_candidate_t *choice = &items[index];
    size_t current_len = end >= start ? end - start : 0;
    if (current_len == strlen(choice->text) &&
        strncmp(buffer->data + start, choice->text, current_len) == 0) {
        ed->completion_cycle_active = 1;
        ed->completion_cycle_buffer = buffer;
        ed->completion_cycle_start = start;
        ed->completion_cycle_index = index;
        snprintf(ed->completion_cycle_prefix, sizeof(ed->completion_cycle_prefix), "%s", prefix);
        snprintf(ed->completion_cycle_current, sizeof(ed->completion_cycle_current), "%s", choice->text);
        ecex_completion_describe(ed, choice, index, count);
        return ECEX_OK;
    }

    if (buffer_delete_range(buffer, start, end) != ECEX_OK) return ECEX_ERR;
    if (buffer_insert_at(buffer, start, choice->text) != ECEX_OK) return ECEX_ERR;

    ed->completion_cycle_active = 1;
    ed->completion_cycle_buffer = buffer;
    ed->completion_cycle_start = start;
    ed->completion_cycle_index = index;
    snprintf(ed->completion_cycle_prefix, sizeof(ed->completion_cycle_prefix), "%s", prefix);
    snprintf(ed->completion_cycle_current, sizeof(ed->completion_cycle_current), "%s", choice->text);

    ecex_completion_describe(ed, choice, index, count);
    return ECEX_OK;
}

int ecex_complete_at_point(ecex_t *ed) {
    return ecex_complete_at_point_direction(ed, 1);
}


static int ecex_set_owned_string(char **slot, const char *value) {
    if (!slot) return ECEX_ERR;
    char *copy = NULL;
    if (value && value[0]) {
        copy = ecex_strdup(value);
        if (!copy) return ECEX_ERR;
    }
    free(*slot);
    *slot = copy;
    return ECEX_OK;
}

static int ecex_parse_file_line(const char *text, char *path, size_t path_size, size_t *out_line) {
    if (!text || !path || path_size == 0 || !out_line) return ECEX_ERR;
    const char *colon = strchr(text, ':');
    if (!colon || colon == text) return ECEX_ERR;
    char *end = NULL;
    long line = strtol(colon + 1, &end, 10);
    if (line <= 0 || end == colon + 1) return ECEX_ERR;
    size_t len = (size_t)(colon - text);
    if (len >= path_size) len = path_size - 1;
    memcpy(path, text, len);
    path[len] = '\0';
    *out_line = (size_t)line;
    return ECEX_OK;
}

static int ecex_goto_file_line_action(ecex_t *ed, buffer_t *buffer, size_t line, const char *payload, void *userdata) {
    (void)buffer;
    (void)line;
    (void)userdata;
    if (!ed || !payload) return ECEX_ERR;
    char path[1024];
    size_t target_line = 1;
    if (ecex_parse_file_line(payload, path, sizeof(path), &target_line) != ECEX_OK) return ECEX_ERR;
    if (ecex_find_file(ed, path) != ECEX_OK) return ECEX_ERR;
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf) return ECEX_ERR;
    size_t pos = 0;
    for (size_t l = 1; l < target_line && pos < buf->len; pos++) {
        if (buf->data[pos] == '\n') l++;
    }
    buffer_set_point(buf, pos);
    return ECEX_OK;
}

static int ecex_append_shell_output(ecex_t *ed, const char *name, const char *command) {
    if (!ed || !name || !command || !command[0]) return ECEX_ERR;
    buffer_t *buf = ecex_create_interactive_buffer(ed, name);
    if (!buf) return ECEX_ERR;
    buffer_set_interactive(buf, 1);
    if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR;
    buffer_set_interactive(buf, 1);
    ecex_buffer_set_major_mode_by_name(ed, buf, "special-mode");

    char header[2048];
    snprintf(header, sizeof(header), "%s\n\nKeys: g/r rerun, n/p next/previous result, RET jump, q quit.\n\n", command);
    buffer_append(buf, header);

    char shell_command[4096];
    snprintf(shell_command, sizeof(shell_command), "%s 2>&1", command);
    FILE *pipe = popen(shell_command, "r");
    if (!pipe) {
        buffer_append(buf, "Failed to start command.\n");
        return ecex_switch_buffer(ed, name);
    }

    char line[4096];
    while (fgets(line, sizeof(line), pipe)) {
        size_t len = strlen(line);
        while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0';
        char path[1024];
        size_t target = 0;
        ecex_interactive_line_fn fn = NULL;
        char payload[1200];
        payload[0] = '\0';
        if (ecex_parse_file_line(line, path, sizeof(path), &target) == ECEX_OK) {
            snprintf(payload, sizeof(payload), "%s:%zu", path, target);
            fn = ecex_goto_file_line_action;
        }
        ecex_interactive_append_line(ed, buf, line, fn, payload[0] ? payload : NULL, NULL);
    }

    int status = pclose(pipe);
    char footer[128];
    snprintf(footer, sizeof(footer), "\n[process exited: %d]\n", status);
    buffer_append(buf, footer);
    buf->point = 0;
    buf->modified = 0;
    return ecex_switch_buffer(ed, name);
}

int ecex_compile(ecex_t *ed, const char *command) {
    if (!ed || !command || !command[0]) return ECEX_ERR;
    if (ecex_set_owned_string(&ed->last_compile_command, command) != ECEX_OK) return ECEX_ERR;
    return ecex_append_shell_output(ed, "*compilation*", command);
}

int ecex_grep(ecex_t *ed, const char *command) {
    if (!ed || !command || !command[0]) return ECEX_ERR;
    if (ecex_set_owned_string(&ed->last_grep_command, command) != ECEX_OK) return ECEX_ERR;
    return ecex_append_shell_output(ed, "*grep*", command);
}

int ecex_rerun_compile(ecex_t *ed) {
    if (!ed || !ed->last_compile_command) return ECEX_ERR;
    return ecex_append_shell_output(ed, "*compilation*", ed->last_compile_command);
}

int ecex_rerun_grep(ecex_t *ed) {
    if (!ed || !ed->last_grep_command) return ECEX_ERR;
    return ecex_append_shell_output(ed, "*grep*", ed->last_grep_command);
}

int ecex_next_interactive_action(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf || !buffer_is_interactive(buf) || buf->interactive_action_count == 0) return ECEX_ERR;
    size_t current = buffer_current_line_number(buf);
    if (current > 0) current--;
    size_t best = (size_t)-1;
    for (size_t i = 0; i < buf->interactive_action_count; i++) {
        size_t line = buf->interactive_actions[i].line;
        if (line > current && (best == (size_t)-1 || line < best)) best = line;
    }
    if (best == (size_t)-1) best = buf->interactive_actions[0].line;
    size_t pos = 0;
    for (size_t l = 0; l < best && pos < buf->len; pos++) if (buf->data[pos] == '\n') l++;
    buffer_set_point(buf, pos);
    return ECEX_OK;
}

int ecex_previous_interactive_action(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    if (!buf || !buffer_is_interactive(buf) || buf->interactive_action_count == 0) return ECEX_ERR;
    size_t current = buffer_current_line_number(buf);
    if (current > 0) current--;
    size_t best = (size_t)-1;
    for (size_t i = 0; i < buf->interactive_action_count; i++) {
        size_t line = buf->interactive_actions[i].line;
        if (line < current && (best == (size_t)-1 || line > best)) best = line;
    }
    if (best == (size_t)-1) best = buf->interactive_actions[buf->interactive_action_count - 1].line;
    size_t pos = 0;
    for (size_t l = 0; l < best && pos < buf->len; pos++) if (buf->data[pos] == '\n') l++;
    buffer_set_point(buf, pos);
    return ECEX_OK;
}

static int ecex_region_lines(buffer_t *buf, size_t *out_start, size_t *out_end) {
    if (!buf || !buffer_has_selection(buf)) return ECEX_ERR;
    size_t start = 0, end = 0;
    buffer_selection_range(buf, &start, &end);
    start = buffer_line_start_at(buf, start);
    end = buffer_line_end_at(buf, end);
    if (end < buf->len) end++;
    if (out_start) *out_start = start;
    if (out_end) *out_end = end;
    return ECEX_OK;
}

int ecex_comment_region(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    size_t start = 0, end = 0;
    if (!buf || ecex_region_lines(buf, &start, &end) != ECEX_OK) return ECEX_ERR;
    size_t pos = start;
    while (pos <= end && pos <= buf->len) {
        if (buffer_insert_at(buf, pos, "// ") != ECEX_OK) return ECEX_ERR;
        pos += 3;
        end += 3;
        size_t eol = buffer_line_end_at(buf, pos);
        if (eol >= end || eol >= buf->len) break;
        pos = eol + 1;
    }
    return ECEX_OK;
}

int ecex_uncomment_region(ecex_t *ed) {
    buffer_t *buf = ecex_current_buffer(ed);
    size_t start = 0, end = 0;
    if (!buf || ecex_region_lines(buf, &start, &end) != ECEX_OK) return ECEX_ERR;
    size_t pos = start;
    while (pos < end && pos < buf->len) {
        if (pos + 2 <= buf->len && memcmp(buf->data + pos, "//", 2) == 0) {
            size_t del = (pos + 3 <= buf->len && buf->data[pos + 2] == ' ') ? 3 : 2;
            if (buffer_delete_range(buf, pos, pos + del) != ECEX_OK) return ECEX_ERR;
            end = end > del ? end - del : 0;
        }
        size_t eol = buffer_line_end_at(buf, pos);
        if (eol >= end || eol >= buf->len) break;
        pos = eol + 1;
    }
    return ECEX_OK;
}

int ecex_set_font(ecex_t *ed, const char *path) {
    if (!ed || !path) return ECEX_ERR;
    if (ed->theme.font_path && strcmp(ed->theme.font_path, path) == 0) return ECEX_OK;

    char *copy = ecex_strdup(path);
    if (!copy) return ECEX_ERR;

    free(ed->theme.font_path);
    ed->theme.font_path = copy;
    ecex_mark_font_changed(ed);
    return ECEX_OK;
}

float ecex_get_font_size(ecex_t *ed) {
    if (!ed) return 0.0f;
    return ed->theme.font_size;
}

int ecex_set_font_size(ecex_t *ed, float size) {
    if (!ed) return ECEX_ERR;
    float clamped = ECEX_CLAMP(size, 8.0f, 96.0f);
    if (ed->theme.font_size == clamped) return ECEX_OK;
    ed->theme.font_size = clamped;
    ecex_mark_font_changed(ed);
    return ECEX_OK;
}

int ecex_adjust_font_size(ecex_t *ed, float delta) {
    if (!ed) return ECEX_ERR;
    return ecex_set_font_size(ed, ed->theme.font_size + delta);
}

void ecex_set_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.fg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_status_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.status_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_status_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.status_fg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_status_border_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.status_border = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_cursor_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.cursor = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_region_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.region_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_minibuffer_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.minibuffer_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_minibuffer_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.minibuffer_fg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_completion_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.completion_fg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_completion_enabled(ecex_t *ed, int enabled) { if (ed) { ed->theme.completion_enabled = enabled ? 1 : 0; ecex_mark_ui_changed(ed); } }
void ecex_set_interactive_highlight_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.interactive_highlight_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_interactive_highlight_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.interactive_highlight_fg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_current_line_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.current_line_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_search_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) { ed->theme.search_bg = ecex_color(r, g, b); ecex_mark_ui_changed(ed); } }
void ecex_set_line_numbers_enabled(ecex_t *ed, int enabled) { if (ed) { ed->theme.line_numbers_enabled = enabled ? 1 : 0; ecex_mark_ui_changed(ed); } }
void ecex_set_current_line_enabled(ecex_t *ed, int enabled) { if (ed) { ed->theme.current_line_enabled = enabled ? 1 : 0; ecex_mark_ui_changed(ed); } }