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
//! Plugin command dispatch and plugin-specific handlers on `Editor`.
//!
//! Three clusters previously inline in mod.rs:
//!
//! - `update_plugin_state_snapshot` — synchronizes the immutable view of
//! editor state plugins observe between commands.
//! - `handle_plugin_command` — the giant match dispatching every
//! PluginCommand variant to a specialized handler. Most arms call
//! methods in app/plugin_commands.rs; the rest live below.
//! - The handle_* family — buffer/path lookups, action execution, plugin
//! lifecycle management, and view-control commands callable from
//! plugin code.
use std::sync::Arc;
use anyhow::Result as AnyhowResult;
use fresh_core::api::{BufferSavedDiff, JsCallbackId, PluginCommand};
use crate::model::event::{BufferId, LeafId, SplitId};
use crate::services::async_bridge::AsyncMessage;
use crate::view::split::SplitViewState;
use super::Editor;
impl Editor {
/// Update the plugin state snapshot with current editor state
#[cfg(feature = "plugins")]
pub(super) fn update_plugin_state_snapshot(&mut self) {
// Update TypeScript plugin manager state
if let Some(snapshot_handle) = self.plugin_manager.state_snapshot_handle() {
use fresh_core::api::{BufferInfo, CursorInfo, ViewportInfo};
let mut snapshot = snapshot_handle.write().unwrap();
// Update grammar info (only rebuild if count changed, cheap check)
let grammar_count = self.grammar_registry.available_syntaxes().len();
if snapshot.available_grammars.len() != grammar_count {
snapshot.available_grammars = self
.grammar_registry
.available_grammar_info()
.into_iter()
.map(|g| fresh_core::api::GrammarInfoSnapshot {
name: g.name,
source: g.source.to_string(),
file_extensions: g.file_extensions,
short_name: g.short_name,
})
.collect();
}
// Update active buffer ID
snapshot.active_buffer_id = self.active_buffer();
// Update active split ID
snapshot.active_split_id = self.split_manager.active_split().0 .0;
// Clear and update buffer info
snapshot.buffers.clear();
snapshot.buffer_saved_diffs.clear();
snapshot.buffer_cursor_positions.clear();
snapshot.buffer_text_properties.clear();
for (buffer_id, state) in &self.buffers {
let is_virtual = self
.buffer_metadata
.get(buffer_id)
.map(|m| m.is_virtual())
.unwrap_or(false);
// Report the ACTIVE split's view_mode so plugins can distinguish
// which mode the user is currently in. Separately, report whether
// ANY split has compose mode so plugins can maintain decorations
// for compose-mode splits even when a source-mode split is active.
let active_split = self.split_manager.active_split();
let active_vs = self.split_view_states.get(&active_split);
let view_mode = active_vs
.and_then(|vs| vs.buffer_state(*buffer_id))
.map(|bs| match bs.view_mode {
crate::state::ViewMode::Source => "source",
crate::state::ViewMode::PageView => "compose",
})
.unwrap_or("source");
let compose_width = active_vs
.and_then(|vs| vs.buffer_state(*buffer_id))
.and_then(|bs| bs.compose_width);
let is_composing_in_any_split = self.split_view_states.values().any(|vs| {
vs.buffer_state(*buffer_id)
.map(|bs| matches!(bs.view_mode, crate::state::ViewMode::PageView))
.unwrap_or(false)
});
let is_preview = self
.buffer_metadata
.get(buffer_id)
.map(|m| m.is_preview)
.unwrap_or(false);
let buffer_info = BufferInfo {
id: *buffer_id,
path: state.buffer.file_path().map(|p| p.to_path_buf()),
modified: state.buffer.is_modified(),
length: state.buffer.len(),
is_virtual,
view_mode: view_mode.to_string(),
is_composing_in_any_split,
compose_width,
language: state.language.clone(),
is_preview,
};
snapshot.buffers.insert(*buffer_id, buffer_info);
let diff = {
let diff = state.buffer.diff_since_saved();
BufferSavedDiff {
equal: diff.equal,
byte_ranges: diff.byte_ranges.clone(),
}
};
snapshot.buffer_saved_diffs.insert(*buffer_id, diff);
// Regular buffers live in exactly one split's keyed_states.
// Panel (hidden) buffers natively live inside a group's inner
// split — but the close-buffer path can leave a *shadow*
// entry in the group's host split (from `switch_buffer`'s
// auto-insert, kept to preserve the
// `active_buffer ∈ keyed_states` invariant). For hidden
// buffers we therefore skip group-host splits and pick the
// inner split, which is the authoritative home.
let is_hidden = self
.buffer_metadata
.get(buffer_id)
.is_some_and(|m| m.hidden_from_tabs);
let source_split = self.split_view_states.iter().find(|(split_id, vs)| {
vs.keyed_states.contains_key(buffer_id)
&& !(is_hidden && self.grouped_subtrees.contains_key(split_id))
});
let cursor_pos = source_split
.and_then(|(_, vs)| vs.buffer_state(*buffer_id))
.map(|bs| bs.cursors.primary().position)
.unwrap_or(0);
tracing::trace!(
"snapshot: buffer {:?} cursor_pos={} (from split {:?})",
buffer_id,
cursor_pos,
source_split.map(|(id, _)| *id),
);
snapshot
.buffer_cursor_positions
.insert(*buffer_id, cursor_pos);
// Store text properties if this buffer has any
if !state.text_properties.is_empty() {
snapshot
.buffer_text_properties
.insert(*buffer_id, state.text_properties.all().to_vec());
}
}
// Update cursor information for active buffer
if let Some(active_vs) = self
.split_view_states
.get(&self.split_manager.active_split())
{
// Primary cursor (from SplitViewState)
let active_cursors = &active_vs.cursors;
let primary = active_cursors.primary();
let primary_position = primary.position;
let primary_selection = primary.selection_range();
snapshot.primary_cursor = Some(CursorInfo {
position: primary_position,
selection: primary_selection.clone(),
});
// All cursors
snapshot.all_cursors = active_cursors
.iter()
.map(|(_, cursor)| CursorInfo {
position: cursor.position,
selection: cursor.selection_range(),
})
.collect();
// Selected text from primary cursor (for clipboard plugin)
if let Some(range) = primary_selection {
if let Some(active_state) = self.buffers.get_mut(&self.active_buffer()) {
snapshot.selected_text =
Some(active_state.get_text_range(range.start, range.end));
}
}
// Viewport - get from SplitViewState (the authoritative source)
let top_line = self.buffers.get(&self.active_buffer()).and_then(|state| {
if state.buffer.line_count().is_some() {
Some(state.buffer.get_line_number(active_vs.viewport.top_byte))
} else {
None
}
});
snapshot.viewport = Some(ViewportInfo {
top_byte: active_vs.viewport.top_byte,
top_line,
left_column: active_vs.viewport.left_column,
width: active_vs.viewport.width,
height: active_vs.viewport.height,
});
} else {
snapshot.primary_cursor = None;
snapshot.all_cursors.clear();
snapshot.viewport = None;
snapshot.selected_text = None;
}
// Update clipboard (provide internal clipboard content to plugins)
snapshot.clipboard = self.clipboard.get_internal().to_string();
// Update working directory (for spawning processes in correct directory)
snapshot.working_dir = self.working_dir.clone();
// Update LSP diagnostics: Arc refcount bump; no clone.
snapshot.diagnostics = Arc::clone(&self.stored_diagnostics);
// Update LSP folding ranges: Arc refcount bump; no clone.
snapshot.folding_ranges = Arc::clone(&self.stored_folding_ranges);
// Update config. Reserialize only when the underlying
// `Arc<Config>` pointer has actually moved since the last
// refresh — `Arc::ptr_eq` vs `config_snapshot_anchor` is a
// sound cache key because the anchor keeps `self.config`'s
// strong count at ≥ 2, forcing every `Arc::make_mut` on the
// editor side to CoW into a new allocation. On idle (no
// config mutation), this branch is skipped entirely and the
// snapshot update is a refcount bump.
if !Arc::ptr_eq(&self.config, &self.config_snapshot_anchor) {
let json = serde_json::to_value(&*self.config).unwrap_or(serde_json::Value::Null);
self.config_cached_json = Arc::new(json);
self.config_snapshot_anchor = Arc::clone(&self.config);
}
snapshot.config = Arc::clone(&self.config_cached_json);
// Update user config (cached raw file contents, not merged with defaults).
// This allows plugins to distinguish between user-set and default values.
// Arc refcount bump; no clone.
snapshot.user_config = Arc::clone(&self.user_config_raw);
// Update editor mode (for vi mode and other modal editing)
snapshot.editor_mode = self.editor_mode.clone();
// Update plugin global states from Rust-side store.
// Merge using or_insert to preserve JS-side write-through entries.
for (plugin_name, state_map) in &self.plugin_global_state {
let entry = snapshot
.plugin_global_states
.entry(plugin_name.clone())
.or_default();
for (key, value) in state_map {
entry.entry(key.clone()).or_insert_with(|| value.clone());
}
}
// Update plugin view states from active split's BufferViewState.plugin_state.
// If the active split changed, fully repopulate. Otherwise, merge using
// or_insert to preserve JS-side write-through entries that haven't
// round-tripped through the command channel yet.
let active_split_id = self.split_manager.active_split().0 .0;
let split_changed = snapshot.plugin_view_states_split != active_split_id;
if split_changed {
snapshot.plugin_view_states.clear();
snapshot.plugin_view_states_split = active_split_id;
}
// Clean up entries for buffers that are no longer open
{
let open_bids: Vec<_> = snapshot.buffers.keys().copied().collect();
snapshot
.plugin_view_states
.retain(|bid, _| open_bids.contains(bid));
}
// Merge from Rust-side plugin_state (source of truth for persisted state)
if let Some(active_vs) = self
.split_view_states
.get(&self.split_manager.active_split())
{
for (buffer_id, buf_state) in &active_vs.keyed_states {
if !buf_state.plugin_state.is_empty() {
let entry = snapshot.plugin_view_states.entry(*buffer_id).or_default();
for (key, value) in &buf_state.plugin_state {
// Use or_insert to preserve JS write-through values
entry.entry(key.clone()).or_insert_with(|| value.clone());
}
}
}
}
}
}
/// Handle a plugin command - dispatches to specialized handlers in plugin_commands module
pub fn handle_plugin_command(&mut self, command: PluginCommand) -> AnyhowResult<()> {
match command {
// ==================== Text Editing Commands ====================
PluginCommand::InsertText {
buffer_id,
position,
text,
} => {
self.handle_insert_text(buffer_id, position, text);
}
PluginCommand::DeleteRange { buffer_id, range } => {
self.handle_delete_range(buffer_id, range);
}
PluginCommand::InsertAtCursor { text } => {
self.handle_insert_at_cursor(text);
}
PluginCommand::DeleteSelection => {
self.handle_delete_selection();
}
// ==================== Overlay Commands ====================
PluginCommand::AddOverlay {
buffer_id,
namespace,
range,
options,
} => {
self.handle_add_overlay(buffer_id, namespace, range, options);
}
PluginCommand::RemoveOverlay { buffer_id, handle } => {
self.handle_remove_overlay(buffer_id, handle);
}
PluginCommand::ClearAllOverlays { buffer_id } => {
self.handle_clear_all_overlays(buffer_id);
}
PluginCommand::ClearNamespace {
buffer_id,
namespace,
} => {
self.handle_clear_namespace(buffer_id, namespace);
}
PluginCommand::ClearOverlaysInRange {
buffer_id,
start,
end,
} => {
self.handle_clear_overlays_in_range(buffer_id, start, end);
}
// ==================== Virtual Text Commands ====================
PluginCommand::AddVirtualText {
buffer_id,
virtual_text_id,
position,
text,
color,
use_bg,
before,
} => {
self.handle_add_virtual_text(
buffer_id,
virtual_text_id,
position,
text,
color,
use_bg,
before,
);
}
PluginCommand::RemoveVirtualText {
buffer_id,
virtual_text_id,
} => {
self.handle_remove_virtual_text(buffer_id, virtual_text_id);
}
PluginCommand::RemoveVirtualTextsByPrefix { buffer_id, prefix } => {
self.handle_remove_virtual_texts_by_prefix(buffer_id, prefix);
}
PluginCommand::ClearVirtualTexts { buffer_id } => {
self.handle_clear_virtual_texts(buffer_id);
}
PluginCommand::AddVirtualLine {
buffer_id,
position,
text,
fg_color,
bg_color,
above,
namespace,
priority,
} => {
self.handle_add_virtual_line(
buffer_id, position, text, fg_color, bg_color, above, namespace, priority,
);
}
PluginCommand::ClearVirtualTextNamespace {
buffer_id,
namespace,
} => {
self.handle_clear_virtual_text_namespace(buffer_id, namespace);
}
// ==================== Conceal Commands ====================
PluginCommand::AddConceal {
buffer_id,
namespace,
start,
end,
replacement,
} => {
self.handle_add_conceal(buffer_id, namespace, start, end, replacement);
}
PluginCommand::ClearConcealNamespace {
buffer_id,
namespace,
} => {
self.handle_clear_conceal_namespace(buffer_id, namespace);
}
PluginCommand::ClearConcealsInRange {
buffer_id,
start,
end,
} => {
self.handle_clear_conceals_in_range(buffer_id, start, end);
}
PluginCommand::AddFold {
buffer_id,
start,
end,
placeholder,
} => {
self.handle_add_fold(buffer_id, start, end, placeholder);
}
PluginCommand::ClearFolds { buffer_id } => {
self.handle_clear_folds(buffer_id);
}
// ==================== Soft Break Commands ====================
PluginCommand::AddSoftBreak {
buffer_id,
namespace,
position,
indent,
} => {
self.handle_add_soft_break(buffer_id, namespace, position, indent);
}
PluginCommand::ClearSoftBreakNamespace {
buffer_id,
namespace,
} => {
self.handle_clear_soft_break_namespace(buffer_id, namespace);
}
PluginCommand::ClearSoftBreaksInRange {
buffer_id,
start,
end,
} => {
self.handle_clear_soft_breaks_in_range(buffer_id, start, end);
}
// ==================== Menu Commands ====================
PluginCommand::AddMenuItem {
menu_label,
item,
position,
} => {
self.handle_add_menu_item(menu_label, item, position);
}
PluginCommand::AddMenu { menu, position } => {
self.handle_add_menu(menu, position);
}
PluginCommand::RemoveMenuItem {
menu_label,
item_label,
} => {
self.handle_remove_menu_item(menu_label, item_label);
}
PluginCommand::RemoveMenu { menu_label } => {
self.handle_remove_menu(menu_label);
}
// ==================== Split Commands ====================
PluginCommand::FocusSplit { split_id } => {
self.handle_focus_split(split_id);
}
PluginCommand::SetSplitBuffer {
split_id,
buffer_id,
} => {
self.handle_set_split_buffer(split_id, buffer_id);
}
PluginCommand::SetSplitScroll { split_id, top_byte } => {
self.handle_set_split_scroll(split_id, top_byte);
}
PluginCommand::RequestHighlights {
buffer_id,
range,
request_id,
} => {
self.handle_request_highlights(buffer_id, range, request_id);
}
PluginCommand::CloseSplit { split_id } => {
self.handle_close_split(split_id);
}
PluginCommand::SetSplitRatio { split_id, ratio } => {
self.handle_set_split_ratio(split_id, ratio);
}
PluginCommand::SetSplitLabel { split_id, label } => {
self.split_manager.set_label(LeafId(split_id), label);
}
PluginCommand::ClearSplitLabel { split_id } => {
self.split_manager.clear_label(split_id);
}
PluginCommand::GetSplitByLabel { label, request_id } => {
let split_id = self.split_manager.find_split_by_label(&label);
let callback_id = fresh_core::api::JsCallbackId::from(request_id);
let json = serde_json::to_string(&split_id.map(|s| s.0 .0))
.unwrap_or_else(|_| "null".to_string());
self.plugin_manager.resolve_callback(callback_id, json);
}
PluginCommand::DistributeSplitsEvenly { split_ids: _ } => {
self.handle_distribute_splits_evenly();
}
PluginCommand::SetBufferCursor {
buffer_id,
position,
} => {
self.handle_set_buffer_cursor(buffer_id, position);
}
PluginCommand::SetBufferShowCursors { buffer_id, show } => {
if let Some(state) = self.buffers.get_mut(&buffer_id) {
state.show_cursors = show;
} else {
tracing::warn!("SetBufferShowCursors: buffer {:?} not found", buffer_id);
}
}
// ==================== View/Layout Commands ====================
PluginCommand::SetLayoutHints {
buffer_id,
split_id,
range: _,
hints,
} => {
self.handle_set_layout_hints(buffer_id, split_id, hints);
}
PluginCommand::SetLineNumbers { buffer_id, enabled } => {
self.handle_set_line_numbers(buffer_id, enabled);
}
PluginCommand::SetViewMode { buffer_id, mode } => {
self.handle_set_view_mode(buffer_id, &mode);
}
PluginCommand::SetLineWrap {
buffer_id,
split_id,
enabled,
} => {
self.handle_set_line_wrap(buffer_id, split_id, enabled);
}
PluginCommand::SubmitViewTransform {
buffer_id,
split_id,
payload,
} => {
self.handle_submit_view_transform(buffer_id, split_id, payload);
}
PluginCommand::ClearViewTransform {
buffer_id: _,
split_id,
} => {
self.handle_clear_view_transform(split_id);
}
PluginCommand::SetViewState {
buffer_id,
key,
value,
} => {
self.handle_set_view_state(buffer_id, key, value);
}
PluginCommand::SetGlobalState {
plugin_name,
key,
value,
} => {
self.handle_set_global_state(plugin_name, key, value);
}
PluginCommand::RefreshLines { buffer_id } => {
self.handle_refresh_lines(buffer_id);
}
PluginCommand::RefreshAllLines => {
self.handle_refresh_all_lines();
}
PluginCommand::HookCompleted { .. } => {
// Sentinel processed in render loop; no-op if encountered elsewhere.
}
PluginCommand::SetLineIndicator {
buffer_id,
line,
namespace,
symbol,
color,
priority,
} => {
self.handle_set_line_indicator(buffer_id, line, namespace, symbol, color, priority);
}
PluginCommand::SetLineIndicators {
buffer_id,
lines,
namespace,
symbol,
color,
priority,
} => {
self.handle_set_line_indicators(
buffer_id, lines, namespace, symbol, color, priority,
);
}
PluginCommand::ClearLineIndicators {
buffer_id,
namespace,
} => {
self.handle_clear_line_indicators(buffer_id, namespace);
}
PluginCommand::SetFileExplorerDecorations {
namespace,
decorations,
} => {
self.handle_set_file_explorer_decorations(namespace, decorations);
}
PluginCommand::ClearFileExplorerDecorations { namespace } => {
self.handle_clear_file_explorer_decorations(&namespace);
}
// ==================== Status/Prompt Commands ====================
PluginCommand::SetStatus { message } => {
self.handle_set_status(message);
}
PluginCommand::ApplyTheme { theme_name } => {
self.apply_theme(&theme_name);
}
PluginCommand::ReloadConfig => {
self.reload_config();
}
PluginCommand::ReloadThemes { apply_theme } => {
self.reload_themes();
if let Some(theme_name) = apply_theme {
self.apply_theme(&theme_name);
}
}
PluginCommand::RegisterGrammar {
language,
grammar_path,
extensions,
} => {
self.handle_register_grammar(language, grammar_path, extensions);
}
PluginCommand::RegisterLanguageConfig { language, config } => {
self.handle_register_language_config(language, config);
}
PluginCommand::RegisterLspServer { language, config } => {
self.handle_register_lsp_server(language, config);
}
PluginCommand::ReloadGrammars { callback_id } => {
self.handle_reload_grammars(callback_id);
}
PluginCommand::StartPrompt { label, prompt_type } => {
self.handle_start_prompt(label, prompt_type);
}
PluginCommand::StartPromptWithInitial {
label,
prompt_type,
initial_value,
} => {
self.handle_start_prompt_with_initial(label, prompt_type, initial_value);
}
PluginCommand::StartPromptAsync {
label,
initial_value,
callback_id,
} => {
self.handle_start_prompt_async(label, initial_value, callback_id);
}
PluginCommand::SetPromptSuggestions { suggestions } => {
self.handle_set_prompt_suggestions(suggestions);
}
PluginCommand::SetPromptInputSync { sync } => {
if let Some(prompt) = &mut self.prompt {
prompt.sync_input_on_navigate = sync;
}
}
// ==================== Command/Mode Registration ====================
PluginCommand::RegisterCommand { command } => {
self.handle_register_command(command);
}
PluginCommand::UnregisterCommand { name } => {
self.handle_unregister_command(name);
}
PluginCommand::DefineMode {
name,
bindings,
read_only,
allow_text_input,
inherit_normal_bindings,
plugin_name,
} => {
self.handle_define_mode(
name,
bindings,
read_only,
allow_text_input,
inherit_normal_bindings,
plugin_name,
);
}
// ==================== File/Navigation Commands ====================
PluginCommand::OpenFileInBackground { path } => {
self.handle_open_file_in_background(path);
}
PluginCommand::OpenFileAtLocation { path, line, column } => {
return self.handle_open_file_at_location(path, line, column);
}
PluginCommand::OpenFileInSplit {
split_id,
path,
line,
column,
} => {
return self.handle_open_file_in_split(split_id, path, line, column);
}
PluginCommand::ShowBuffer { buffer_id } => {
self.handle_show_buffer(buffer_id);
}
PluginCommand::CloseBuffer { buffer_id } => {
self.handle_close_buffer(buffer_id);
}
// ==================== LSP Commands ====================
PluginCommand::SendLspRequest {
language,
method,
params,
request_id,
} => {
self.handle_send_lsp_request(language, method, params, request_id);
}
// ==================== Clipboard Commands ====================
PluginCommand::SetClipboard { text } => {
self.handle_set_clipboard(text);
}
// ==================== Async Plugin Commands ====================
PluginCommand::SpawnProcess {
command,
args,
cwd,
callback_id,
} => {
// Spawn process asynchronously using the process spawner
// (supports both local and remote execution)
if let (Some(runtime), Some(bridge)) = (&self.tokio_runtime, &self.async_bridge) {
let effective_cwd = cwd.or_else(|| {
std::env::current_dir()
.map(|p| p.to_string_lossy().to_string())
.ok()
});
let sender = bridge.sender();
let spawner = self.process_spawner.clone();
runtime.spawn(async move {
// Receiver may be dropped if editor is shutting down
#[allow(clippy::let_underscore_must_use)]
match spawner.spawn(command, args, effective_cwd).await {
Ok(result) => {
let _ = sender.send(AsyncMessage::PluginProcessOutput {
process_id: callback_id.as_u64(),
stdout: result.stdout,
stderr: result.stderr,
exit_code: result.exit_code,
});
}
Err(e) => {
let _ = sender.send(AsyncMessage::PluginProcessOutput {
process_id: callback_id.as_u64(),
stdout: String::new(),
stderr: e.to_string(),
exit_code: -1,
});
}
}
});
} else {
// No async runtime - reject the callback
self.plugin_manager
.reject_callback(callback_id, "Async runtime not available".to_string());
}
}
PluginCommand::SpawnProcessWait {
process_id,
callback_id,
} => {
// TODO: Implement proper process wait tracking
// For now, just reject with an error since there's no process tracking yet
tracing::warn!(
"SpawnProcessWait not fully implemented - process_id={}",
process_id
);
self.plugin_manager.reject_callback(
callback_id,
format!(
"SpawnProcessWait not yet fully implemented for process_id={}",
process_id
),
);
}
PluginCommand::Delay {
callback_id,
duration_ms,
} => {
// Spawn async delay via tokio
if let (Some(runtime), Some(bridge)) = (&self.tokio_runtime, &self.async_bridge) {
let sender = bridge.sender();
let callback_id_u64 = callback_id.as_u64();
runtime.spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_millis(duration_ms)).await;
// Receiver may have been dropped during shutdown.
#[allow(clippy::let_underscore_must_use)]
let _ = sender.send(crate::services::async_bridge::AsyncMessage::Plugin(
fresh_core::api::PluginAsyncMessage::DelayComplete {
callback_id: callback_id_u64,
},
));
});
} else {
// Fallback to blocking if no runtime available
std::thread::sleep(std::time::Duration::from_millis(duration_ms));
self.plugin_manager
.resolve_callback(callback_id, "null".to_string());
}
}
PluginCommand::SpawnBackgroundProcess {
process_id,
command,
args,
cwd,
callback_id,
} => {
// Spawn background process with streaming output via tokio
if let (Some(runtime), Some(bridge)) = (&self.tokio_runtime, &self.async_bridge) {
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command as TokioCommand;
let effective_cwd = cwd.unwrap_or_else(|| {
std::env::current_dir()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| ".".to_string())
});
let sender = bridge.sender();
let sender_stdout = sender.clone();
let sender_stderr = sender.clone();
let callback_id_u64 = callback_id.as_u64();
// Receiver may be dropped if editor is shutting down
#[allow(clippy::let_underscore_must_use)]
let handle = runtime.spawn(async move {
let mut child = match TokioCommand::new(&command)
.args(&args)
.current_dir(&effective_cwd)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(e) => {
let _ = sender.send(
crate::services::async_bridge::AsyncMessage::Plugin(
fresh_core::api::PluginAsyncMessage::ProcessExit {
process_id,
callback_id: callback_id_u64,
exit_code: -1,
},
),
);
tracing::error!("Failed to spawn background process: {}", e);
return;
}
};
// Stream stdout
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let pid = process_id;
// Spawn stdout reader
if let Some(stdout) = stdout {
let sender = sender_stdout;
tokio::spawn(async move {
let reader = BufReader::new(stdout);
let mut lines = reader.lines();
while let Ok(Some(line)) = lines.next_line().await {
let _ = sender.send(
crate::services::async_bridge::AsyncMessage::Plugin(
fresh_core::api::PluginAsyncMessage::ProcessStdout {
process_id: pid,
data: line + "\n",
},
),
);
}
});
}
// Spawn stderr reader
if let Some(stderr) = stderr {
let sender = sender_stderr;
tokio::spawn(async move {
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
while let Ok(Some(line)) = lines.next_line().await {
let _ = sender.send(
crate::services::async_bridge::AsyncMessage::Plugin(
fresh_core::api::PluginAsyncMessage::ProcessStderr {
process_id: pid,
data: line + "\n",
},
),
);
}
});
}
// Wait for process to complete
let exit_code = match child.wait().await {
Ok(status) => status.code().unwrap_or(-1),
Err(_) => -1,
};
let _ = sender.send(crate::services::async_bridge::AsyncMessage::Plugin(
fresh_core::api::PluginAsyncMessage::ProcessExit {
process_id,
callback_id: callback_id_u64,
exit_code,
},
));
});
// Store abort handle for potential kill
self.background_process_handles
.insert(process_id, handle.abort_handle());
} else {
// No runtime - reject immediately
self.plugin_manager
.reject_callback(callback_id, "Async runtime not available".to_string());
}
}
PluginCommand::KillBackgroundProcess { process_id } => {
if let Some(handle) = self.background_process_handles.remove(&process_id) {
handle.abort();
tracing::debug!("Killed background process {}", process_id);
}
}
// ==================== Virtual Buffer Commands (complex, kept inline) ====================
PluginCommand::CreateVirtualBuffer {
name,
mode,
read_only,
} => {
let buffer_id = self.create_virtual_buffer(name.clone(), mode.clone(), read_only);
tracing::info!(
"Created virtual buffer '{}' with mode '{}' (id={:?})",
name,
mode,
buffer_id
);
// TODO: Return buffer_id to plugin via callback or hook
}
PluginCommand::CreateVirtualBufferWithContent {
name,
mode,
read_only,
entries,
show_line_numbers,
show_cursors,
editing_disabled,
hidden_from_tabs,
request_id,
} => {
let buffer_id = self.create_virtual_buffer(name.clone(), mode.clone(), read_only);
tracing::info!(
"Created virtual buffer '{}' with mode '{}' (id={:?})",
name,
mode,
buffer_id
);
// Apply view options to the buffer
// TODO: show_line_numbers is duplicated between EditorState.margins and
// BufferViewState. The renderer reads BufferViewState and overwrites
// margins each frame via configure_for_line_numbers(), making the margin
// setting here effectively write-only. Consider removing the margin call
// and only setting BufferViewState.show_line_numbers.
if let Some(state) = self.buffers.get_mut(&buffer_id) {
state.margins.configure_for_line_numbers(show_line_numbers);
state.show_cursors = show_cursors;
state.editing_disabled = editing_disabled;
tracing::debug!(
"Set buffer {:?} view options: show_line_numbers={}, show_cursors={}, editing_disabled={}",
buffer_id,
show_line_numbers,
show_cursors,
editing_disabled
);
}
let active_split = self.split_manager.active_split();
if let Some(view_state) = self.split_view_states.get_mut(&active_split) {
view_state.ensure_buffer_state(buffer_id).show_line_numbers = show_line_numbers;
}
// Apply hidden_from_tabs to buffer metadata
if hidden_from_tabs {
if let Some(meta) = self.buffer_metadata.get_mut(&buffer_id) {
meta.hidden_from_tabs = true;
}
}
// Now set the content
match self.set_virtual_buffer_content(buffer_id, entries) {
Ok(()) => {
tracing::debug!("Set virtual buffer content for {:?}", buffer_id);
// Switch to the new buffer to display it
self.set_active_buffer(buffer_id);
tracing::debug!("Switched to virtual buffer {:?}", buffer_id);
// Send response if request_id is present
if let Some(req_id) = request_id {
tracing::info!(
"CreateVirtualBufferWithContent: resolving callback for request_id={}, buffer_id={:?}",
req_id,
buffer_id
);
// createVirtualBuffer returns VirtualBufferResult: { bufferId, splitId }
let result = fresh_core::api::VirtualBufferResult {
buffer_id: buffer_id.0 as u64,
split_id: None,
};
self.plugin_manager.resolve_callback(
fresh_core::api::JsCallbackId::from(req_id),
serde_json::to_string(&result).unwrap_or_default(),
);
tracing::info!("CreateVirtualBufferWithContent: resolve_callback sent for request_id={}", req_id);
}
}
Err(e) => {
tracing::error!("Failed to set virtual buffer content: {}", e);
}
}
}
PluginCommand::CreateVirtualBufferInSplit {
name,
mode,
read_only,
entries,
ratio,
direction,
panel_id,
show_line_numbers,
show_cursors,
editing_disabled,
line_wrap,
before,
request_id,
} => {
// Check if this panel already exists (for idempotent operations)
if let Some(pid) = &panel_id {
if let Some(&existing_buffer_id) = self.panel_ids.get(pid) {
// Verify the buffer actually exists (defensive check for stale entries)
if self.buffers.contains_key(&existing_buffer_id) {
// Panel exists, just update its content
if let Err(e) =
self.set_virtual_buffer_content(existing_buffer_id, entries)
{
tracing::error!("Failed to update panel content: {}", e);
} else {
tracing::info!("Updated existing panel '{}' content", pid);
}
// Find and focus the split that contains this buffer
let splits = self.split_manager.splits_for_buffer(existing_buffer_id);
if let Some(&split_id) = splits.first() {
self.split_manager.set_active_split(split_id);
// NOTE: active_buffer is derived from split_manager,
// but we need to ensure the split shows the right buffer
self.split_manager.set_active_buffer_id(existing_buffer_id);
tracing::debug!(
"Focused split {:?} containing panel buffer",
split_id
);
}
// Send response with existing buffer ID and split ID via callback resolution
if let Some(req_id) = request_id {
let result = fresh_core::api::VirtualBufferResult {
buffer_id: existing_buffer_id.0 as u64,
split_id: splits.first().map(|s| s.0 .0 as u64),
};
self.plugin_manager.resolve_callback(
fresh_core::api::JsCallbackId::from(req_id),
serde_json::to_string(&result).unwrap_or_default(),
);
}
return Ok(());
} else {
// Buffer no longer exists, remove stale panel_id entry
tracing::warn!(
"Removing stale panel_id '{}' pointing to non-existent buffer {:?}",
pid,
existing_buffer_id
);
self.panel_ids.remove(pid);
// Fall through to create a new buffer
}
}
}
// Capture the source split before creating the buffer —
// `create_virtual_buffer` unconditionally adds the new buffer
// as a tab to the currently active split, which is the wrong
// thing for a panel that lives in its own dedicated split
// (it would show up as a tab in BOTH splits — see bug #3).
let source_split_before_create = self.split_manager.active_split();
// Create the virtual buffer first
let buffer_id = self.create_virtual_buffer(name.clone(), mode.clone(), read_only);
tracing::info!(
"Created virtual buffer '{}' with mode '{}' in split (id={:?})",
name,
mode,
buffer_id
);
// Apply view options to the buffer
if let Some(state) = self.buffers.get_mut(&buffer_id) {
state.margins.configure_for_line_numbers(show_line_numbers);
state.show_cursors = show_cursors;
state.editing_disabled = editing_disabled;
tracing::debug!(
"Set buffer {:?} view options: show_line_numbers={}, show_cursors={}, editing_disabled={}",
buffer_id,
show_line_numbers,
show_cursors,
editing_disabled
);
}
// Store the panel ID mapping if provided
if let Some(pid) = panel_id {
self.panel_ids.insert(pid, buffer_id);
}
// Set the content
if let Err(e) = self.set_virtual_buffer_content(buffer_id, entries) {
tracing::error!("Failed to set virtual buffer content: {}", e);
return Ok(());
}
// Determine split direction
let split_dir = match direction.as_deref() {
Some("vertical") => crate::model::event::SplitDirection::Vertical,
_ => crate::model::event::SplitDirection::Horizontal,
};
// Create a split with the new buffer
let created_split_id = match self
.split_manager
.split_active_positioned(split_dir, buffer_id, ratio, before)
{
Ok(new_split_id) => {
// The buffer now lives in its own split, so drop its
// tab from the source split (see bug #3). Only do
// this when the new split actually differs from the
// source split — otherwise we'd leave no split
// displaying the buffer.
if new_split_id != source_split_before_create {
if let Some(source_view_state) =
self.split_view_states.get_mut(&source_split_before_create)
{
source_view_state.remove_buffer(buffer_id);
}
}
// Create independent view state for the new split with the buffer in tabs
let mut view_state = SplitViewState::with_buffer(
self.terminal_width,
self.terminal_height,
buffer_id,
);
view_state.apply_config_defaults(
self.config.editor.line_numbers,
self.config.editor.highlight_current_line,
line_wrap
.unwrap_or_else(|| self.resolve_line_wrap_for_buffer(buffer_id)),
self.config.editor.wrap_indent,
self.resolve_wrap_column_for_buffer(buffer_id),
self.config.editor.rulers.clone(),
);
// Override with plugin-requested show_line_numbers
view_state.ensure_buffer_state(buffer_id).show_line_numbers =
show_line_numbers;
self.split_view_states.insert(new_split_id, view_state);
// Focus the new split (the diagnostics panel)
self.split_manager.set_active_split(new_split_id);
// NOTE: split tree was updated by split_active, active_buffer derives from it
tracing::info!(
"Created {:?} split with virtual buffer {:?}",
split_dir,
buffer_id
);
Some(new_split_id)
}
Err(e) => {
tracing::error!("Failed to create split: {}", e);
// Fall back to just switching to the buffer
self.set_active_buffer(buffer_id);
None
}
};
// Send response with buffer ID and split ID via callback resolution
// NOTE: Using VirtualBufferResult type for type-safe JSON serialization
if let Some(req_id) = request_id {
tracing::trace!("CreateVirtualBufferInSplit: resolving callback for request_id={}, buffer_id={:?}, split_id={:?}", req_id, buffer_id, created_split_id);
let result = fresh_core::api::VirtualBufferResult {
buffer_id: buffer_id.0 as u64,
split_id: created_split_id.map(|s| s.0 .0 as u64),
};
self.plugin_manager.resolve_callback(
fresh_core::api::JsCallbackId::from(req_id),
serde_json::to_string(&result).unwrap_or_default(),
);
}
}
PluginCommand::SetVirtualBufferContent { buffer_id, entries } => {
match self.set_virtual_buffer_content(buffer_id, entries) {
Ok(()) => {
tracing::debug!("Set virtual buffer content for {:?}", buffer_id);
}
Err(e) => {
tracing::error!("Failed to set virtual buffer content: {}", e);
}
}
}
PluginCommand::GetTextPropertiesAtCursor { buffer_id } => {
// Get text properties at cursor and fire a hook with the data
if let Some(state) = self.buffers.get(&buffer_id) {
let cursor_pos = self
.split_view_states
.values()
.find_map(|vs| vs.buffer_state(buffer_id))
.map(|bs| bs.cursors.primary().position)
.unwrap_or(0);
let properties = state.text_properties.get_at(cursor_pos);
tracing::debug!(
"Text properties at cursor in {:?}: {} properties found",
buffer_id,
properties.len()
);
// TODO: Fire hook with properties data for plugins to consume
}
}
PluginCommand::CreateVirtualBufferInExistingSplit {
name,
mode,
read_only,
entries,
split_id,
show_line_numbers,
show_cursors,
editing_disabled,
line_wrap,
request_id,
} => {
// Create the virtual buffer
let buffer_id = self.create_virtual_buffer(name.clone(), mode.clone(), read_only);
tracing::info!(
"Created virtual buffer '{}' with mode '{}' for existing split {:?} (id={:?})",
name,
mode,
split_id,
buffer_id
);
// Apply view options to the buffer
if let Some(state) = self.buffers.get_mut(&buffer_id) {
state.margins.configure_for_line_numbers(show_line_numbers);
state.show_cursors = show_cursors;
state.editing_disabled = editing_disabled;
}
// Set the content
if let Err(e) = self.set_virtual_buffer_content(buffer_id, entries) {
tracing::error!("Failed to set virtual buffer content: {}", e);
return Ok(());
}
// Show the buffer in the target split
let leaf_id = LeafId(split_id);
self.split_manager.set_split_buffer(leaf_id, buffer_id);
// Focus the target split and set its buffer
self.split_manager.set_active_split(leaf_id);
self.split_manager.set_active_buffer_id(buffer_id);
// Switch per-buffer view state in the target split
if let Some(view_state) = self.split_view_states.get_mut(&leaf_id) {
view_state.switch_buffer(buffer_id);
view_state.add_buffer(buffer_id);
view_state.ensure_buffer_state(buffer_id).show_line_numbers = show_line_numbers;
// Apply line_wrap setting if provided
if let Some(wrap) = line_wrap {
view_state.active_state_mut().viewport.line_wrap_enabled = wrap;
}
}
tracing::info!(
"Displayed virtual buffer {:?} in split {:?}",
buffer_id,
split_id
);
// Send response with buffer ID and split ID via callback resolution
if let Some(req_id) = request_id {
let result = fresh_core::api::VirtualBufferResult {
buffer_id: buffer_id.0 as u64,
split_id: Some(split_id.0 as u64),
};
self.plugin_manager.resolve_callback(
fresh_core::api::JsCallbackId::from(req_id),
serde_json::to_string(&result).unwrap_or_default(),
);
}
}
// ==================== Context Commands ====================
PluginCommand::SetContext { name, active } => {
if active {
self.active_custom_contexts.insert(name.clone());
tracing::debug!("Set custom context: {}", name);
} else {
self.active_custom_contexts.remove(&name);
tracing::debug!("Unset custom context: {}", name);
}
}
// ==================== Review Diff Commands ====================
PluginCommand::SetReviewDiffHunks { hunks } => {
self.review_hunks = hunks;
tracing::debug!("Set {} review hunks", self.review_hunks.len());
}
// ==================== Vi Mode Commands ====================
PluginCommand::ExecuteAction { action_name } => {
self.handle_execute_action(action_name);
}
PluginCommand::ExecuteActions { actions } => {
self.handle_execute_actions(actions);
}
PluginCommand::GetBufferText {
buffer_id,
start,
end,
request_id,
} => {
self.handle_get_buffer_text(buffer_id, start, end, request_id);
}
PluginCommand::GetLineStartPosition {
buffer_id,
line,
request_id,
} => {
self.handle_get_line_start_position(buffer_id, line, request_id);
}
PluginCommand::GetLineEndPosition {
buffer_id,
line,
request_id,
} => {
self.handle_get_line_end_position(buffer_id, line, request_id);
}
PluginCommand::GetBufferLineCount {
buffer_id,
request_id,
} => {
self.handle_get_buffer_line_count(buffer_id, request_id);
}
PluginCommand::ScrollToLineCenter {
split_id,
buffer_id,
line,
} => {
self.handle_scroll_to_line_center(split_id, buffer_id, line);
}
PluginCommand::ScrollBufferToLine { buffer_id, line } => {
self.handle_scroll_buffer_to_line(buffer_id, line);
}
PluginCommand::SetEditorMode { mode } => {
self.handle_set_editor_mode(mode);
}
// ==================== LSP Helper Commands ====================
PluginCommand::ShowActionPopup {
popup_id,
title,
message,
actions,
} => {
tracing::info!(
"Action popup requested: id={}, title={}, actions={}",
popup_id,
title,
actions.len()
);
// Build popup list items from actions
let items: Vec<crate::model::event::PopupListItemData> = actions
.iter()
.map(|action| crate::model::event::PopupListItemData {
text: action.label.clone(),
detail: None,
icon: None,
data: Some(action.id.clone()),
})
.collect();
// Store action info for when popup is confirmed/cancelled
let action_ids: Vec<(String, String)> =
actions.into_iter().map(|a| (a.id, a.label)).collect();
self.active_action_popup = Some((popup_id.clone(), action_ids));
// Create popup with message + action list
let popup = crate::model::event::PopupData {
kind: crate::model::event::PopupKindHint::List,
title: Some(title),
description: Some(message),
transient: false,
content: crate::model::event::PopupContentData::List { items, selected: 0 },
position: crate::model::event::PopupPositionData::BottomRight,
width: 60,
max_height: 15,
bordered: true,
};
self.show_popup(popup);
tracing::info!(
"Action popup shown: id={}, active_action_popup={:?}",
popup_id,
self.active_action_popup.as_ref().map(|(id, _)| id)
);
}
PluginCommand::DisableLspForLanguage { language } => {
tracing::info!("Disabling LSP for language: {}", language);
// 1. Stop the LSP server for this language if running
if let Some(ref mut lsp) = self.lsp {
lsp.shutdown_server(&language);
tracing::info!("Stopped LSP server for {}", language);
}
// 2. Update the config to disable the language
if let Some(lsp_configs) = self.config_mut().lsp.get_mut(&language) {
for c in lsp_configs.as_mut_slice() {
c.enabled = false;
c.auto_start = false;
}
tracing::info!("Disabled LSP config for {}", language);
}
// 3. Persist the config change
if let Err(e) = self.save_config() {
tracing::error!("Failed to save config: {}", e);
self.status_message = Some(format!(
"LSP disabled for {} (config save failed)",
language
));
} else {
self.status_message = Some(format!("LSP disabled for {}", language));
}
// 4. Clear any LSP-related warnings for this language
self.warning_domains.lsp.clear();
}
PluginCommand::RestartLspForLanguage { language } => {
tracing::info!("Plugin restarting LSP for language: {}", language);
let file_path = self
.buffer_metadata
.get(&self.active_buffer())
.and_then(|meta| meta.file_path().cloned());
let success = if let Some(ref mut lsp) = self.lsp {
let (ok, msg) = lsp.manual_restart(&language, file_path.as_deref());
self.status_message = Some(msg);
ok
} else {
self.status_message = Some("No LSP manager available".to_string());
false
};
if success {
self.reopen_buffers_for_language(&language);
}
}
PluginCommand::SetLspRootUri { language, uri } => {
tracing::info!("Plugin setting LSP root URI for {}: {}", language, uri);
// Parse the URI string into an lsp_types::Uri
match uri.parse::<lsp_types::Uri>() {
Ok(parsed_uri) => {
if let Some(ref mut lsp) = self.lsp {
let restarted = lsp.set_language_root_uri(&language, parsed_uri);
if restarted {
self.status_message = Some(format!(
"LSP root updated for {} (restarting server)",
language
));
} else {
self.status_message =
Some(format!("LSP root set for {}", language));
}
}
}
Err(e) => {
tracing::error!("Invalid LSP root URI '{}': {}", uri, e);
self.status_message = Some(format!("Invalid LSP root URI: {}", e));
}
}
}
// ==================== Scroll Sync Commands ====================
PluginCommand::CreateScrollSyncGroup {
group_id,
left_split,
right_split,
} => {
let success = self.scroll_sync_manager.create_group_with_id(
group_id,
left_split,
right_split,
);
if success {
tracing::debug!(
"Created scroll sync group {} for splits {:?} and {:?}",
group_id,
left_split,
right_split
);
} else {
tracing::warn!(
"Failed to create scroll sync group {} (ID already exists)",
group_id
);
}
}
PluginCommand::SetScrollSyncAnchors { group_id, anchors } => {
use crate::view::scroll_sync::SyncAnchor;
let anchor_count = anchors.len();
let sync_anchors: Vec<SyncAnchor> = anchors
.into_iter()
.map(|(left_line, right_line)| SyncAnchor {
left_line,
right_line,
})
.collect();
self.scroll_sync_manager.set_anchors(group_id, sync_anchors);
tracing::debug!(
"Set {} anchors for scroll sync group {}",
anchor_count,
group_id
);
}
PluginCommand::RemoveScrollSyncGroup { group_id } => {
if self.scroll_sync_manager.remove_group(group_id) {
tracing::debug!("Removed scroll sync group {}", group_id);
} else {
tracing::warn!("Scroll sync group {} not found", group_id);
}
}
// ==================== Composite Buffer Commands ====================
PluginCommand::CreateCompositeBuffer {
name,
mode,
layout,
sources,
hunks,
initial_focus_hunk,
request_id,
} => {
self.handle_create_composite_buffer(
name,
mode,
layout,
sources,
hunks,
initial_focus_hunk,
request_id,
);
}
PluginCommand::UpdateCompositeAlignment { buffer_id, hunks } => {
self.handle_update_composite_alignment(buffer_id, hunks);
}
PluginCommand::CloseCompositeBuffer { buffer_id } => {
self.close_composite_buffer(buffer_id);
}
PluginCommand::FlushLayout => {
self.flush_layout();
}
PluginCommand::CompositeNextHunk { buffer_id } => {
let split_id = self.split_manager.active_split();
self.composite_next_hunk(split_id, buffer_id);
}
PluginCommand::CompositePrevHunk { buffer_id } => {
let split_id = self.split_manager.active_split();
self.composite_prev_hunk(split_id, buffer_id);
}
// ==================== Buffer Groups ====================
PluginCommand::CreateBufferGroup {
name,
mode,
layout_json,
request_id,
} => match self.create_buffer_group(name, mode, layout_json) {
Ok(result) => {
if let Some(req_id) = request_id {
let json = serde_json::to_string(&result).unwrap_or_default();
self.plugin_manager
.resolve_callback(fresh_core::api::JsCallbackId::from(req_id), json);
}
}
Err(e) => {
tracing::error!("Failed to create buffer group: {}", e);
}
},
PluginCommand::SetPanelContent {
group_id,
panel_name,
entries,
} => {
self.set_panel_content(group_id, panel_name, entries);
}
PluginCommand::CloseBufferGroup { group_id } => {
self.close_buffer_group(group_id);
}
PluginCommand::FocusPanel {
group_id,
panel_name,
} => {
self.focus_panel(group_id, panel_name);
}
// ==================== File Operations ====================
PluginCommand::SaveBufferToPath { buffer_id, path } => {
self.handle_save_buffer_to_path(buffer_id, path);
}
// ==================== Plugin Management ====================
#[cfg(feature = "plugins")]
PluginCommand::LoadPlugin { path, callback_id } => {
self.handle_load_plugin(path, callback_id);
}
#[cfg(feature = "plugins")]
PluginCommand::UnloadPlugin { name, callback_id } => {
self.handle_unload_plugin(name, callback_id);
}
#[cfg(feature = "plugins")]
PluginCommand::ReloadPlugin { name, callback_id } => {
self.handle_reload_plugin(name, callback_id);
}
#[cfg(feature = "plugins")]
PluginCommand::ListPlugins { callback_id } => {
self.handle_list_plugins(callback_id);
}
// When plugins feature is disabled, these commands are no-ops
#[cfg(not(feature = "plugins"))]
PluginCommand::LoadPlugin { .. }
| PluginCommand::UnloadPlugin { .. }
| PluginCommand::ReloadPlugin { .. }
| PluginCommand::ListPlugins { .. } => {
tracing::warn!("Plugin management commands require the 'plugins' feature");
}
// ==================== Terminal Commands ====================
PluginCommand::CreateTerminal {
cwd,
direction,
ratio,
focus,
request_id,
} => {
let (cols, rows) = self.get_terminal_dimensions();
// Set up async bridge for terminal manager if not already done
if let Some(ref bridge) = self.async_bridge {
self.terminal_manager.set_async_bridge(bridge.clone());
}
// Determine working directory
let working_dir = cwd
.map(std::path::PathBuf::from)
.unwrap_or_else(|| self.working_dir.clone());
// Prepare persistent storage paths
let terminal_root = self.dir_context.terminal_dir_for(&working_dir);
if let Err(e) = self.filesystem.create_dir_all(&terminal_root) {
tracing::warn!("Failed to create terminal directory: {}", e);
}
let predicted_terminal_id = self.terminal_manager.next_terminal_id();
let log_path =
terminal_root.join(format!("fresh-terminal-{}.log", predicted_terminal_id.0));
let backing_path =
terminal_root.join(format!("fresh-terminal-{}.txt", predicted_terminal_id.0));
self.terminal_backing_files
.insert(predicted_terminal_id, backing_path);
let backing_path_for_spawn = self
.terminal_backing_files
.get(&predicted_terminal_id)
.cloned();
match self.terminal_manager.spawn(
cols,
rows,
Some(working_dir),
Some(log_path.clone()),
backing_path_for_spawn,
) {
Ok(terminal_id) => {
// Track log file path
self.terminal_log_files
.insert(terminal_id, log_path.clone());
// Fix up backing path if predicted ID differs
if terminal_id != predicted_terminal_id {
self.terminal_backing_files.remove(&predicted_terminal_id);
let backing_path =
terminal_root.join(format!("fresh-terminal-{}.txt", terminal_id.0));
self.terminal_backing_files
.insert(terminal_id, backing_path);
}
// Create buffer attached to the active split
let active_split = self.split_manager.active_split();
let buffer_id =
self.create_terminal_buffer_attached(terminal_id, active_split);
// If direction is specified, create a new split for the terminal.
// If direction is None, just place the terminal in the active split
// (no new split created — useful when the plugin manages layout).
let created_split_id = if let Some(dir_str) = direction.as_deref() {
let split_dir = match dir_str {
"horizontal" => crate::model::event::SplitDirection::Horizontal,
_ => crate::model::event::SplitDirection::Vertical,
};
let split_ratio = ratio.unwrap_or(0.5);
match self
.split_manager
.split_active(split_dir, buffer_id, split_ratio)
{
Ok(new_split_id) => {
let mut view_state = SplitViewState::with_buffer(
self.terminal_width,
self.terminal_height,
buffer_id,
);
view_state.apply_config_defaults(
self.config.editor.line_numbers,
self.config.editor.highlight_current_line,
false,
false,
None,
self.config.editor.rulers.clone(),
);
self.split_view_states.insert(new_split_id, view_state);
if focus.unwrap_or(true) {
self.split_manager.set_active_split(new_split_id);
}
tracing::info!(
"Created {:?} split for terminal {:?} with buffer {:?}",
split_dir,
terminal_id,
buffer_id
);
Some(new_split_id)
}
Err(e) => {
tracing::error!("Failed to create split for terminal: {}", e);
self.set_active_buffer(buffer_id);
None
}
}
} else {
// No split — just switch to the terminal buffer in the active split
self.set_active_buffer(buffer_id);
None
};
// Resize terminal to match actual split content area
self.resize_visible_terminals();
// Resolve the callback with TerminalResult
let result = fresh_core::api::TerminalResult {
buffer_id: buffer_id.0 as u64,
terminal_id: terminal_id.0 as u64,
split_id: created_split_id.map(|s| s.0 .0 as u64),
};
self.plugin_manager.resolve_callback(
fresh_core::api::JsCallbackId::from(request_id),
serde_json::to_string(&result).unwrap_or_default(),
);
tracing::info!(
"Plugin created terminal {:?} with buffer {:?}",
terminal_id,
buffer_id
);
}
Err(e) => {
tracing::error!("Failed to create terminal for plugin: {}", e);
self.plugin_manager.reject_callback(
fresh_core::api::JsCallbackId::from(request_id),
format!("Failed to create terminal: {}", e),
);
}
}
}
PluginCommand::SendTerminalInput { terminal_id, data } => {
if let Some(handle) = self.terminal_manager.get(terminal_id) {
handle.write(data.as_bytes());
tracing::trace!(
"Plugin sent {} bytes to terminal {:?}",
data.len(),
terminal_id
);
} else {
tracing::warn!(
"Plugin tried to send input to non-existent terminal {:?}",
terminal_id
);
}
}
PluginCommand::CloseTerminal { terminal_id } => {
// Find and close the buffer associated with this terminal
let buffer_to_close = self
.terminal_buffers
.iter()
.find(|(_, &tid)| tid == terminal_id)
.map(|(&bid, _)| bid);
if let Some(buffer_id) = buffer_to_close {
if let Err(e) = self.close_buffer(buffer_id) {
tracing::warn!("Failed to close terminal buffer: {}", e);
}
tracing::info!("Plugin closed terminal {:?}", terminal_id);
} else {
// Terminal exists but no buffer — just close the terminal directly
self.terminal_manager.close(terminal_id);
tracing::info!("Plugin closed terminal {:?} (no buffer found)", terminal_id);
}
}
PluginCommand::GrepProject {
pattern,
fixed_string,
case_sensitive,
max_results,
whole_words,
callback_id,
} => {
self.handle_grep_project(
pattern,
fixed_string,
case_sensitive,
max_results,
whole_words,
callback_id,
);
}
PluginCommand::GrepProjectStreaming {
pattern,
fixed_string,
case_sensitive,
max_results,
whole_words,
search_id,
callback_id,
} => {
self.handle_grep_project_streaming(
pattern,
fixed_string,
case_sensitive,
max_results,
whole_words,
search_id,
callback_id,
);
}
PluginCommand::ReplaceInBuffer {
file_path,
matches,
replacement,
callback_id,
} => {
self.handle_replace_in_buffer(file_path, matches, replacement, callback_id);
}
}
Ok(())
}
/// Save a buffer to a specific file path (for :w filename)
fn handle_save_buffer_to_path(&mut self, buffer_id: BufferId, path: std::path::PathBuf) {
if let Some(state) = self.buffers.get_mut(&buffer_id) {
// Save to the specified path
match state.buffer.save_to_file(&path) {
Ok(()) => {
// save_to_file already updates file_path internally via finalize_save
// Run on-save actions (formatting, etc.)
if let Err(e) = self.finalize_save(Some(path)) {
tracing::warn!("Failed to finalize save: {}", e);
}
tracing::debug!("Saved buffer {:?} to path", buffer_id);
}
Err(e) => {
self.handle_set_status(format!("Error saving: {}", e));
tracing::error!("Failed to save buffer to path: {}", e);
}
}
} else {
self.handle_set_status(format!("Buffer {:?} not found", buffer_id));
tracing::warn!("SaveBufferToPath: buffer {:?} not found", buffer_id);
}
}
/// Load a plugin from a file path
#[cfg(feature = "plugins")]
fn handle_load_plugin(&mut self, path: std::path::PathBuf, callback_id: JsCallbackId) {
match self.plugin_manager.load_plugin(&path) {
Ok(()) => {
tracing::info!("Loaded plugin from {:?}", path);
self.plugin_manager
.resolve_callback(callback_id, "true".to_string());
}
Err(e) => {
tracing::error!("Failed to load plugin from {:?}: {}", path, e);
self.plugin_manager
.reject_callback(callback_id, format!("{}", e));
}
}
}
/// Unload a plugin by name
#[cfg(feature = "plugins")]
fn handle_unload_plugin(&mut self, name: String, callback_id: JsCallbackId) {
match self.plugin_manager.unload_plugin(&name) {
Ok(()) => {
tracing::info!("Unloaded plugin: {}", name);
self.plugin_manager
.resolve_callback(callback_id, "true".to_string());
}
Err(e) => {
tracing::error!("Failed to unload plugin '{}': {}", name, e);
self.plugin_manager
.reject_callback(callback_id, format!("{}", e));
}
}
}
/// Reload a plugin by name
#[cfg(feature = "plugins")]
fn handle_reload_plugin(&mut self, name: String, callback_id: JsCallbackId) {
match self.plugin_manager.reload_plugin(&name) {
Ok(()) => {
tracing::info!("Reloaded plugin: {}", name);
self.plugin_manager
.resolve_callback(callback_id, "true".to_string());
}
Err(e) => {
tracing::error!("Failed to reload plugin '{}': {}", name, e);
self.plugin_manager
.reject_callback(callback_id, format!("{}", e));
}
}
}
/// List all loaded plugins
#[cfg(feature = "plugins")]
fn handle_list_plugins(&mut self, callback_id: JsCallbackId) {
let plugins = self.plugin_manager.list_plugins();
// Serialize to JSON array of { name, path, enabled }
let json_array: Vec<serde_json::Value> = plugins
.iter()
.map(|p| {
serde_json::json!({
"name": p.name,
"path": p.path.to_string_lossy(),
"enabled": p.enabled
})
})
.collect();
let json_str = serde_json::to_string(&json_array).unwrap_or_else(|_| "[]".to_string());
self.plugin_manager.resolve_callback(callback_id, json_str);
}
/// Execute an editor action by name (for vi mode plugin)
fn handle_execute_action(&mut self, action_name: String) {
use crate::input::keybindings::Action;
use std::collections::HashMap;
// Parse the action name into an Action enum
if let Some(action) = Action::from_str(&action_name, &HashMap::new()) {
// Execute the action
if let Err(e) = self.handle_action(action) {
tracing::warn!("Failed to execute action '{}': {}", action_name, e);
} else {
tracing::debug!("Executed action: {}", action_name);
}
} else {
tracing::warn!("Unknown action: {}", action_name);
}
}
/// Execute multiple actions in sequence, each with an optional repeat count
/// Used by vi mode for count prefix (e.g., "3dw" = delete 3 words)
fn handle_execute_actions(&mut self, actions: Vec<fresh_core::api::ActionSpec>) {
use crate::input::keybindings::Action;
use std::collections::HashMap;
for action_spec in actions {
if let Some(action) = Action::from_str(&action_spec.action, &HashMap::new()) {
// Execute the action `count` times
for _ in 0..action_spec.count {
if let Err(e) = self.handle_action(action.clone()) {
tracing::warn!("Failed to execute action '{}': {}", action_spec.action, e);
return; // Stop on first error
}
}
tracing::debug!(
"Executed action '{}' {} time(s)",
action_spec.action,
action_spec.count
);
} else {
tracing::warn!("Unknown action: {}", action_spec.action);
return; // Stop on unknown action
}
}
}
/// Get text from a buffer range (for vi mode yank operations)
fn handle_get_buffer_text(
&mut self,
buffer_id: BufferId,
start: usize,
end: usize,
request_id: u64,
) {
let result = if let Some(state) = self.buffers.get_mut(&buffer_id) {
// Get text from the buffer using the mutable get_text_range method
let len = state.buffer.len();
if start <= end && end <= len {
Ok(state.get_text_range(start, end))
} else {
Err(format!(
"Invalid range {}..{} for buffer of length {}",
start, end, len
))
}
} else {
Err(format!("Buffer {:?} not found", buffer_id))
};
// Resolve the JavaScript Promise callback directly
let callback_id = fresh_core::api::JsCallbackId::from(request_id);
match result {
Ok(text) => {
// Serialize text as JSON string
let json = serde_json::to_string(&text).unwrap_or_else(|_| "null".to_string());
self.plugin_manager.resolve_callback(callback_id, json);
}
Err(error) => {
self.plugin_manager.reject_callback(callback_id, error);
}
}
}
/// Set the global editor mode (for vi mode)
fn handle_set_editor_mode(&mut self, mode: Option<String>) {
self.editor_mode = mode.clone();
tracing::debug!("Set editor mode: {:?}", mode);
}
/// Get the byte offset of the start of a line in the active buffer
fn handle_get_line_start_position(&mut self, buffer_id: BufferId, line: u32, request_id: u64) {
// Use active buffer if buffer_id is 0
let actual_buffer_id = if buffer_id.0 == 0 {
self.active_buffer_id()
} else {
buffer_id
};
let result = if let Some(state) = self.buffers.get_mut(&actual_buffer_id) {
// Get line start position by iterating through the buffer content
let line_number = line as usize;
let buffer_len = state.buffer.len();
if line_number == 0 {
// First line always starts at 0
Some(0)
} else {
// Count newlines to find the start of the requested line
let mut current_line = 0;
let mut line_start = None;
// Read buffer content to find newlines using the BufferState's get_text_range
let content = state.get_text_range(0, buffer_len);
for (byte_idx, c) in content.char_indices() {
if c == '\n' {
current_line += 1;
if current_line == line_number {
// Found the start of the requested line (byte after newline)
line_start = Some(byte_idx + 1);
break;
}
}
}
line_start
}
} else {
None
};
// Resolve the JavaScript Promise callback directly
let callback_id = fresh_core::api::JsCallbackId::from(request_id);
// Serialize as JSON (null for None, number for Some)
let json = serde_json::to_string(&result).unwrap_or_else(|_| "null".to_string());
self.plugin_manager.resolve_callback(callback_id, json);
}
/// Get the byte offset of the end of a line in the active buffer
/// Returns the position after the last character of the line (before newline)
fn handle_get_line_end_position(&mut self, buffer_id: BufferId, line: u32, request_id: u64) {
// Use active buffer if buffer_id is 0
let actual_buffer_id = if buffer_id.0 == 0 {
self.active_buffer_id()
} else {
buffer_id
};
let result = if let Some(state) = self.buffers.get_mut(&actual_buffer_id) {
let line_number = line as usize;
let buffer_len = state.buffer.len();
// Read buffer content to find line boundaries
let content = state.get_text_range(0, buffer_len);
let mut current_line = 0;
let mut line_end = None;
for (byte_idx, c) in content.char_indices() {
if c == '\n' {
if current_line == line_number {
// Found the end of the requested line (position of newline)
line_end = Some(byte_idx);
break;
}
current_line += 1;
}
}
// Handle last line (no trailing newline)
if line_end.is_none() && current_line == line_number {
line_end = Some(buffer_len);
}
line_end
} else {
None
};
let callback_id = fresh_core::api::JsCallbackId::from(request_id);
let json = serde_json::to_string(&result).unwrap_or_else(|_| "null".to_string());
self.plugin_manager.resolve_callback(callback_id, json);
}
/// Get the total number of lines in a buffer
fn handle_get_buffer_line_count(&mut self, buffer_id: BufferId, request_id: u64) {
// Use active buffer if buffer_id is 0
let actual_buffer_id = if buffer_id.0 == 0 {
self.active_buffer_id()
} else {
buffer_id
};
let result = if let Some(state) = self.buffers.get_mut(&actual_buffer_id) {
let buffer_len = state.buffer.len();
let content = state.get_text_range(0, buffer_len);
// Count lines (number of newlines + 1, unless empty)
if content.is_empty() {
Some(1) // Empty buffer has 1 line
} else {
let newline_count = content.chars().filter(|&c| c == '\n').count();
// If file ends with newline, don't count extra line
let ends_with_newline = content.ends_with('\n');
if ends_with_newline {
Some(newline_count)
} else {
Some(newline_count + 1)
}
}
} else {
None
};
let callback_id = fresh_core::api::JsCallbackId::from(request_id);
let json = serde_json::to_string(&result).unwrap_or_else(|_| "null".to_string());
self.plugin_manager.resolve_callback(callback_id, json);
}
/// Scroll a split to center a specific line in the viewport
fn handle_scroll_to_line_center(
&mut self,
split_id: SplitId,
buffer_id: BufferId,
line: usize,
) {
// Use active split if split_id is 0
let actual_split_id = if split_id.0 == 0 {
self.split_manager.active_split()
} else {
LeafId(split_id)
};
// Use active buffer if buffer_id is 0
let actual_buffer_id = if buffer_id.0 == 0 {
self.active_buffer()
} else {
buffer_id
};
// Get viewport height
let viewport_height = if let Some(view_state) = self.split_view_states.get(&actual_split_id)
{
view_state.viewport.height as usize
} else {
return;
};
// Calculate the target line to scroll to (center the requested line)
let lines_above = viewport_height / 2;
let target_line = line.saturating_sub(lines_above);
// Get the buffer and scroll
if let Some(state) = self.buffers.get_mut(&actual_buffer_id) {
let buffer = &mut state.buffer;
if let Some(view_state) = self.split_view_states.get_mut(&actual_split_id) {
view_state.viewport.scroll_to(buffer, target_line);
// Mark to skip ensure_visible on next render so the scroll isn't undone
view_state.viewport.set_skip_ensure_visible();
}
}
}
/// Scroll every split whose active buffer is `buffer_id` so that
/// `line` is within the viewport. Used by plugin panels (buffer
/// groups) whose plugin-side "selected row" doesn't drive the
/// buffer cursor — after updating the selection, the plugin calls
/// this to bring the selected row into view.
///
/// Walks both the main split tree's leaves AND the inner leaves of
/// all Grouped subtrees stored in `grouped_subtrees`, because the
/// latter are not represented in `split_manager`'s tree.
fn handle_scroll_buffer_to_line(&mut self, buffer_id: BufferId, line: usize) {
if !self.buffers.contains_key(&buffer_id) {
return;
}
// Collect the leaf ids whose active buffer is `buffer_id`.
let mut target_leaves: Vec<LeafId> = Vec::new();
// Main tree: walk its leaves.
for leaf_id in self.split_manager.root().leaf_split_ids() {
if let Some(vs) = self.split_view_states.get(&leaf_id) {
if vs.active_buffer == buffer_id {
target_leaves.push(leaf_id);
}
}
}
// Grouped subtrees: walk each group's inner leaves.
for (_group_leaf_id, node) in self.grouped_subtrees.iter() {
if let crate::view::split::SplitNode::Grouped { layout, .. } = node {
for inner_leaf in layout.leaf_split_ids() {
if let Some(vs) = self.split_view_states.get(&inner_leaf) {
if vs.active_buffer == buffer_id && !target_leaves.contains(&inner_leaf) {
target_leaves.push(inner_leaf);
}
}
}
}
}
if target_leaves.is_empty() {
return;
}
let state = match self.buffers.get_mut(&buffer_id) {
Some(s) => s,
None => return,
};
for leaf_id in target_leaves {
let Some(view_state) = self.split_view_states.get_mut(&leaf_id) else {
continue;
};
let viewport_height = view_state.viewport.height as usize;
// Place `line` roughly a third of the viewport from the top so
// the next few navigation steps don't immediately scroll again.
let lines_above = viewport_height / 3;
let target = line.saturating_sub(lines_above);
view_state.viewport.scroll_to(&mut state.buffer, target);
view_state.viewport.set_skip_ensure_visible();
}
}
}