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
//! LSP (Language Server Protocol) request handling for the Editor.
//!
//! This module contains all methods related to LSP operations including:
//! - Completion requests and response handling
//! - Go-to-definition
//! - Hover documentation
//! - Find references
//! - Signature help
//! - Code actions
//! - Rename operations
//! - Inlay hints
use anyhow::Result as AnyhowResult;
use rust_i18n::t;
use std::io;
use std::time::{Duration, Instant};
use lsp_types::TextDocumentContentChangeEvent;
use crate::model::event::{BufferId, Event};
use crate::primitives::word_navigation::{find_word_end, find_word_start};
use crate::services::lsp::manager::detect_language;
use crate::view::prompt::{Prompt, PromptType};
use super::{uri_to_path, Editor, SemanticTokenRangeRequest};
const SEMANTIC_TOKENS_FULL_DEBOUNCE_MS: u64 = 500;
const SEMANTIC_TOKENS_RANGE_DEBOUNCE_MS: u64 = 50;
const SEMANTIC_TOKENS_RANGE_PADDING_LINES: usize = 10;
impl Editor {
/// Handle LSP completion response
pub(crate) fn handle_completion_response(
&mut self,
request_id: u64,
items: Vec<lsp_types::CompletionItem>,
) -> AnyhowResult<()> {
// Check if this is the pending completion request
if self.pending_completion_request != Some(request_id) {
tracing::debug!(
"Ignoring completion response for outdated request {}",
request_id
);
return Ok(());
}
self.pending_completion_request = None;
self.lsp_status.clear();
if items.is_empty() {
tracing::debug!("No completion items received");
return Ok(());
}
// Get the partial word at cursor to filter completions
use crate::primitives::word_navigation::find_completion_word_start;
let (word_start, cursor_pos) = {
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
let word_start = find_completion_word_start(&state.buffer, cursor_pos);
(word_start, cursor_pos)
};
let prefix = if word_start < cursor_pos {
self.active_state_mut()
.get_text_range(word_start, cursor_pos)
.to_lowercase()
} else {
String::new()
};
// Filter completions to match the typed prefix
let filtered_items: Vec<&lsp_types::CompletionItem> = if prefix.is_empty() {
// No prefix - show all completions
items.iter().collect()
} else {
// Filter to items that start with the prefix (case-insensitive)
items
.iter()
.filter(|item| {
item.label.to_lowercase().starts_with(&prefix)
|| item
.filter_text
.as_ref()
.map(|ft| ft.to_lowercase().starts_with(&prefix))
.unwrap_or(false)
})
.collect()
};
if filtered_items.is_empty() {
tracing::debug!("No completion items match prefix '{}'", prefix);
return Ok(());
}
// Convert CompletionItem to PopupListItem
use crate::view::popup::PopupListItem;
let popup_items: Vec<PopupListItem> = filtered_items
.iter()
.map(|item| {
let text = item.label.clone();
let detail = item.detail.clone();
let icon = match item.kind {
Some(lsp_types::CompletionItemKind::FUNCTION)
| Some(lsp_types::CompletionItemKind::METHOD) => Some("λ".to_string()),
Some(lsp_types::CompletionItemKind::VARIABLE) => Some("v".to_string()),
Some(lsp_types::CompletionItemKind::STRUCT)
| Some(lsp_types::CompletionItemKind::CLASS) => Some("S".to_string()),
Some(lsp_types::CompletionItemKind::CONSTANT) => Some("c".to_string()),
Some(lsp_types::CompletionItemKind::KEYWORD) => Some("k".to_string()),
_ => None,
};
let mut list_item = PopupListItem::new(text);
if let Some(detail) = detail {
list_item = list_item.with_detail(detail);
}
if let Some(icon) = icon {
list_item = list_item.with_icon(icon);
}
// Store the insert_text or label as data
let data = item
.insert_text
.clone()
.or_else(|| Some(item.label.clone()));
if let Some(data) = data {
list_item = list_item.with_data(data);
}
list_item
})
.collect();
// Show the popup
use crate::model::event::{
PopupContentData, PopupData, PopupListItemData, PopupPositionData,
};
let popup_data = PopupData {
title: Some(t!("lsp.popup_completion").to_string()),
description: None,
transient: false,
content: PopupContentData::List {
items: popup_items
.into_iter()
.map(|item| PopupListItemData {
text: item.text,
detail: item.detail,
icon: item.icon,
data: item.data,
})
.collect(),
selected: 0,
},
position: PopupPositionData::BelowCursor,
width: 50,
max_height: 15,
bordered: true,
};
// Store original items for type-to-filter
self.completion_items = Some(items);
self.active_state_mut()
.apply(&crate::model::event::Event::ShowPopup { popup: popup_data });
tracing::info!(
"Showing completion popup with {} items",
self.completion_items.as_ref().map_or(0, |i| i.len())
);
Ok(())
}
/// Handle LSP go-to-definition response
pub(crate) fn handle_goto_definition_response(
&mut self,
request_id: u64,
locations: Vec<lsp_types::Location>,
) -> AnyhowResult<()> {
// Check if this is the pending request
if self.pending_goto_definition_request != Some(request_id) {
tracing::debug!(
"Ignoring go-to-definition response for outdated request {}",
request_id
);
return Ok(());
}
self.pending_goto_definition_request = None;
if locations.is_empty() {
self.status_message = Some(t!("lsp.no_definition").to_string());
return Ok(());
}
// For now, just jump to the first location
let location = &locations[0];
// Convert URI to file path
if let Ok(path) = uri_to_path(&location.uri) {
// Open the file
let buffer_id = self.open_file(&path)?;
// Move cursor to the definition position
let line = location.range.start.line as usize;
let character = location.range.start.character as usize;
// Calculate byte position from line and character
if let Some(state) = self.buffers.get(&buffer_id) {
let position = state.buffer.line_col_to_position(line, character);
// Move cursor
let cursor_id = state.cursors.primary_id();
let old_position = state.cursors.primary().position;
let old_anchor = state.cursors.primary().anchor;
let old_sticky_column = state.cursors.primary().sticky_column;
let event = crate::model::event::Event::MoveCursor {
cursor_id,
old_position,
new_position: position,
old_anchor,
new_anchor: None,
old_sticky_column,
new_sticky_column: 0, // Reset sticky column for goto definition
};
if let Some(state) = self.buffers.get_mut(&buffer_id) {
state.apply(&event);
}
}
self.status_message = Some(
t!(
"lsp.jumped_to_definition",
path = path.display().to_string(),
line = line + 1
)
.to_string(),
);
} else {
self.status_message = Some(t!("lsp.cannot_open_definition").to_string());
}
Ok(())
}
/// Check if there are any pending LSP requests
pub fn has_pending_lsp_requests(&self) -> bool {
self.pending_completion_request.is_some() || self.pending_goto_definition_request.is_some()
}
/// Cancel any pending LSP requests
/// This should be called when the user performs an action that would make
/// the pending request's results stale (e.g., cursor movement, text editing)
pub(crate) fn cancel_pending_lsp_requests(&mut self) {
if let Some(request_id) = self.pending_completion_request.take() {
tracing::debug!("Canceling pending LSP completion request {}", request_id);
// Send cancellation to the LSP server
self.send_lsp_cancel_request(request_id);
self.lsp_status.clear();
}
if let Some(request_id) = self.pending_goto_definition_request.take() {
tracing::debug!(
"Canceling pending LSP goto-definition request {}",
request_id
);
// Send cancellation to the LSP server
self.send_lsp_cancel_request(request_id);
self.lsp_status.clear();
}
}
/// Send a cancel request to the LSP server for a specific request ID
fn send_lsp_cancel_request(&mut self, request_id: u64) {
// Get the current file path to determine language
let metadata = self.buffer_metadata.get(&self.active_buffer());
let file_path = metadata.and_then(|meta| meta.file_path());
if let Some(path) = file_path {
if let Some(language) = detect_language(path, &self.config.languages) {
if let Some(lsp) = self.lsp.as_mut() {
// Only send cancel if LSP is already running (no need to spawn just to cancel)
if let Some(handle) = lsp.get_handle_mut(&language) {
if let Err(e) = handle.cancel_request(request_id) {
tracing::warn!("Failed to send LSP cancel request: {}", e);
} else {
tracing::debug!("Sent $/cancelRequest for request_id={}", request_id);
}
}
}
}
}
}
/// Execute a closure with LSP handle, ensuring didOpen was sent first.
///
/// This helper centralizes the logic for:
/// 1. Getting buffer metadata, URI, and language
/// 2. Checking if LSP can be spawned (respects auto_start setting)
/// 3. Ensuring didOpen was sent to this server instance (lazy - only gets text if needed)
/// 4. Calling the provided closure with the handle
///
/// Returns None if any step fails (no file, no language, LSP disabled, auto_start=false, etc.)
/// Note: This respects the auto_start setting. If auto_start is false and the server
/// hasn't been manually started, this will return None without spawning the server.
pub(crate) fn with_lsp_for_buffer<F, R>(&mut self, buffer_id: BufferId, f: F) -> Option<R>
where
F: FnOnce(&crate::services::lsp::async_handler::LspHandle, &lsp_types::Uri, &str) -> R,
{
use crate::services::lsp::manager::LspSpawnResult;
// Get metadata (immutable borrow first to extract what we need)
let (uri, _path, language) = {
let metadata = self.buffer_metadata.get(&buffer_id)?;
if !metadata.lsp_enabled {
return None;
}
let uri = metadata.file_uri()?.clone();
let path = metadata.file_path()?.to_path_buf();
let language = detect_language(&path, &self.config.languages)?;
(uri, path, language)
};
// Try to spawn LSP (respects auto_start setting)
// This will only spawn if auto_start=true or the language was manually allowed
let lsp = self.lsp.as_mut()?;
if lsp.try_spawn(&language) != LspSpawnResult::Spawned {
return None;
}
// Get handle ID (handle exists since try_spawn succeeded)
let handle_id = lsp.get_handle_mut(&language)?.id();
// Check if didOpen is needed
let needs_open = {
let metadata = self.buffer_metadata.get(&buffer_id)?;
!metadata.lsp_opened_with.contains(&handle_id)
};
if needs_open {
// Only now get the text (can be expensive for large buffers)
let text = self.buffers.get(&buffer_id)?.buffer.to_string()?;
// Send didOpen
let lsp = self.lsp.as_mut()?;
let handle = lsp.get_handle_mut(&language)?;
if let Err(e) = handle.did_open(uri.clone(), text, language.clone()) {
tracing::warn!("Failed to send didOpen: {}", e);
return None;
}
// Mark as opened with this server instance
let metadata = self.buffer_metadata.get_mut(&buffer_id)?;
metadata.lsp_opened_with.insert(handle_id);
tracing::debug!(
"Sent didOpen for {} to LSP handle {} (language: {})",
uri.as_str(),
handle_id,
language
);
}
// Call the closure with the handle
let lsp = self.lsp.as_mut()?;
let handle = lsp.get_handle_mut(&language)?;
Some(f(handle, &uri, &language))
}
/// Request LSP completion at current cursor position
pub(crate) fn request_completion(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result =
handle.completion(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::info!(
"Requested completion at {}:{}:{}",
uri.as_str(),
line,
character
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_completion_request = Some(request_id);
self.lsp_status = "LSP: completion...".to_string();
}
Ok(())
}
/// Check if the inserted character should trigger completion
/// and if so, request completion automatically (possibly after a delay).
///
/// Triggers completion in two cases:
/// 1. Trigger characters (like `.`, `::`, etc.): immediate if suggest_on_trigger_characters is enabled
/// 2. Word characters: delayed by quick_suggestions_delay_ms if quick_suggestions is enabled
///
/// This provides VS Code-like behavior where suggestions appear while typing,
/// with debouncing to avoid spamming the LSP server.
pub(crate) fn maybe_trigger_completion(&mut self, c: char) {
// Get the active buffer's file path and detect its language
let path = match self.active_state().buffer.file_path() {
Some(p) => p,
None => return, // No path, no language detection
};
let language = match detect_language(path, &self.config.languages) {
Some(lang) => lang,
None => return, // Unknown language
};
// Check if this character is a trigger character for this language
let is_lsp_trigger = self
.lsp
.as_ref()
.map(|lsp| lsp.is_completion_trigger_char(c, &language))
.unwrap_or(false);
// Check if quick suggestions is enabled and this is a word character
let quick_suggestions_enabled = self.config.editor.quick_suggestions;
let suggest_on_trigger_chars = self.config.editor.suggest_on_trigger_characters;
let is_word_char = c.is_alphanumeric() || c == '_';
// Case 1: Trigger character - immediate trigger (bypasses delay)
if is_lsp_trigger && suggest_on_trigger_chars {
tracing::debug!(
"Trigger character '{}' immediately triggers completion for language {}",
c,
language
);
// Cancel any pending scheduled trigger
self.scheduled_completion_trigger = None;
let _ = self.request_completion();
return;
}
// Case 2: Word character with quick suggestions - schedule delayed trigger
if quick_suggestions_enabled && is_word_char {
let delay_ms = self.config.editor.quick_suggestions_delay_ms;
let trigger_time = Instant::now() + Duration::from_millis(delay_ms);
tracing::debug!(
"Scheduling completion trigger in {}ms for language {} (char '{}')",
delay_ms,
language,
c
);
// Schedule (or reschedule) the completion trigger
// This effectively debounces - each keystroke resets the timer
self.scheduled_completion_trigger = Some(trigger_time);
}
}
/// Request LSP go-to-definition at current cursor position
pub(crate) fn request_goto_definition(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result =
handle.goto_definition(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::info!(
"Requested go-to-definition at {}:{}:{}",
uri.as_str(),
line,
character
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_goto_definition_request = Some(request_id);
}
Ok(())
}
/// Request LSP hover documentation at current cursor position
pub(crate) fn request_hover(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
// Debug: Log the position conversion details
if let Some(pos) = state.buffer.offset_to_position(cursor_pos) {
tracing::debug!(
"Hover request: cursor_byte={}, line={}, byte_col={}, utf16_col={}",
cursor_pos,
pos.line,
pos.column,
character
);
}
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result = handle.hover(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::info!(
"Requested hover at {}:{}:{} (byte_pos={})",
uri.as_str(),
line,
character,
cursor_pos
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_hover_request = Some(request_id);
self.lsp_status = "LSP: hover...".to_string();
}
Ok(())
}
/// Request LSP hover documentation at a specific byte position
/// Used for mouse-triggered hover
pub(crate) fn request_hover_at_position(&mut self, byte_pos: usize) -> AnyhowResult<()> {
// Get the current buffer
let state = self.active_state();
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(byte_pos);
// Debug: Log the position conversion details
if let Some(pos) = state.buffer.offset_to_position(byte_pos) {
tracing::trace!(
"Mouse hover request: byte_pos={}, line={}, byte_col={}, utf16_col={}",
byte_pos,
pos.line,
pos.column,
character
);
}
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result = handle.hover(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::trace!(
"Mouse hover requested at {}:{}:{} (byte_pos={})",
uri.as_str(),
line,
character,
byte_pos
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_hover_request = Some(request_id);
self.lsp_status = "LSP: hover...".to_string();
}
Ok(())
}
/// Handle hover response from LSP
pub(crate) fn handle_hover_response(
&mut self,
request_id: u64,
contents: String,
is_markdown: bool,
range: Option<((u32, u32), (u32, u32))>,
) {
// Check if this response is for the current pending request
if self.pending_hover_request != Some(request_id) {
tracing::debug!("Ignoring stale hover response: {}", request_id);
return;
}
self.pending_hover_request = None;
self.lsp_status.clear();
if contents.is_empty() {
self.set_status_message(t!("lsp.no_hover").to_string());
self.hover_symbol_range = None;
return;
}
// Debug: log raw hover content to diagnose formatting issues
tracing::debug!(
"LSP hover content (markdown={}):\n{}",
is_markdown,
contents
);
// Convert LSP range to byte offsets for highlighting
if let Some(((start_line, start_char), (end_line, end_char))) = range {
let state = self.active_state();
let start_byte = state
.buffer
.lsp_position_to_byte(start_line as usize, start_char as usize);
let end_byte = state
.buffer
.lsp_position_to_byte(end_line as usize, end_char as usize);
self.hover_symbol_range = Some((start_byte, end_byte));
tracing::debug!(
"Hover symbol range: {}..{} (LSP {}:{}..{}:{})",
start_byte,
end_byte,
start_line,
start_char,
end_line,
end_char
);
// Remove previous hover overlay if any
if let Some(old_handle) = self.hover_symbol_overlay.take() {
let remove_event = crate::model::event::Event::RemoveOverlay { handle: old_handle };
self.apply_event_to_active_buffer(&remove_event);
}
// Add overlay to highlight the hovered symbol
let event = crate::model::event::Event::AddOverlay {
namespace: None,
range: start_byte..end_byte,
face: crate::model::event::OverlayFace::Background {
color: (80, 80, 120), // Subtle highlight for hovered symbol
},
priority: 90, // Below rename (100) but above syntax (lower)
message: None,
extend_to_line_end: false,
};
self.apply_event_to_active_buffer(&event);
// Store the handle for later removal
if let Some(state) = self.buffers.get(&self.active_buffer()) {
self.hover_symbol_overlay = state.overlays.all().last().map(|o| o.handle.clone());
}
} else {
// No range provided by LSP - compute word boundaries at hover position
// This prevents the popup from following the mouse within the same word
if let Some((hover_byte_pos, _, _, _)) = self.mouse_state.lsp_hover_state {
let state = self.active_state();
let start_byte = find_word_start(&state.buffer, hover_byte_pos);
let end_byte = find_word_end(&state.buffer, hover_byte_pos);
if start_byte < end_byte {
self.hover_symbol_range = Some((start_byte, end_byte));
tracing::debug!(
"Hover symbol range (computed from word boundaries): {}..{}",
start_byte,
end_byte
);
} else {
self.hover_symbol_range = None;
}
} else {
self.hover_symbol_range = None;
}
}
// Create a popup with the hover contents
use crate::view::popup::{Popup, PopupPosition};
use ratatui::style::Style;
// Use markdown rendering if the content is markdown
let mut popup = if is_markdown {
Popup::markdown(&contents, &self.theme, Some(&self.grammar_registry))
} else {
// Plain text - split by lines
let lines: Vec<String> = contents.lines().map(|s| s.to_string()).collect();
Popup::text(lines, &self.theme)
};
// Configure popup properties
popup.title = Some(t!("lsp.popup_hover").to_string());
popup.transient = true;
// Use mouse position if this was a mouse-triggered hover, otherwise use cursor position
popup.position = if let Some((x, y)) = self.mouse_hover_screen_position.take() {
// Position below the mouse, offset by 1 row
PopupPosition::Fixed { x, y: y + 1 }
} else {
PopupPosition::BelowCursor
};
popup.width = 80;
// Use dynamic max_height based on terminal size (60% of height, min 15, max 40)
// This allows hover popups to show more documentation on larger terminals
let dynamic_height = (self.terminal_height * 60 / 100).clamp(15, 40);
popup.max_height = dynamic_height;
popup.border_style = Style::default().fg(self.theme.popup_border_fg);
popup.background_style = Style::default().bg(self.theme.popup_bg);
// Show the popup
if let Some(state) = self.buffers.get_mut(&self.active_buffer()) {
state.popups.show(popup);
tracing::info!("Showing hover popup (markdown={})", is_markdown);
}
// Mark hover request as sent to prevent duplicate popups during race conditions
// (e.g., when mouse moves while a hover response is pending)
self.mouse_state.lsp_hover_request_sent = true;
}
/// Apply inlay hints to editor state as virtual text
pub(crate) fn apply_inlay_hints_to_state(
state: &mut crate::state::EditorState,
hints: &[lsp_types::InlayHint],
) {
use crate::view::virtual_text::VirtualTextPosition;
use ratatui::style::{Color, Style};
// Clear existing inlay hints
state.virtual_texts.clear(&mut state.marker_list);
if hints.is_empty() {
return;
}
// Style for inlay hints - dimmed to not distract from actual code
let hint_style = Style::default().fg(Color::Rgb(128, 128, 128));
for hint in hints {
// Convert LSP position to byte offset
let byte_offset = state.buffer.lsp_position_to_byte(
hint.position.line as usize,
hint.position.character as usize,
);
// Extract text from hint label
let text = match &hint.label {
lsp_types::InlayHintLabel::String(s) => s.clone(),
lsp_types::InlayHintLabel::LabelParts(parts) => {
parts.iter().map(|p| p.value.as_str()).collect::<String>()
}
};
// LSP inlay hint positions are insertion points between characters.
// For positions within the buffer, render hints before the character at the
// byte offset so they appear at the correct location (e.g., before punctuation
// or newline). Hints at or beyond EOF are anchored to the last character and
// rendered after it.
if state.buffer.is_empty() {
continue;
}
let (byte_offset, position) = if byte_offset >= state.buffer.len() {
// If hint is at EOF, anchor to last character and render after it.
(
state.buffer.len().saturating_sub(1),
VirtualTextPosition::AfterChar,
)
} else {
(byte_offset, VirtualTextPosition::BeforeChar)
};
// Use the hint text as-is - spacing is handled during rendering
let display_text = text;
state.virtual_texts.add(
&mut state.marker_list,
byte_offset,
display_text,
hint_style,
position,
0, // Default priority
);
}
tracing::debug!("Applied {} inlay hints as virtual text", hints.len());
}
/// Request LSP find references at current cursor position
pub(crate) fn request_references(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Extract the word under cursor for display
let symbol = {
let text = match state.buffer.to_string() {
Some(t) => t,
None => {
self.set_status_message(t!("error.buffer_not_loaded").to_string());
return Ok(());
}
};
let bytes = text.as_bytes();
let buf_len = bytes.len();
if cursor_pos <= buf_len {
// Find word boundaries
let is_word_char = |c: char| c.is_alphanumeric() || c == '_';
// Find start of word
let mut start = cursor_pos;
while start > 0 {
// Move to previous byte
start -= 1;
// Skip continuation bytes (UTF-8)
while start > 0 && (bytes[start] & 0xC0) == 0x80 {
start -= 1;
}
// Get the character at this position
if let Some(ch) = text[start..].chars().next() {
if !is_word_char(ch) {
start += ch.len_utf8();
break;
}
} else {
break;
}
}
// Find end of word
let mut end = cursor_pos;
while end < buf_len {
if let Some(ch) = text[end..].chars().next() {
if is_word_char(ch) {
end += ch.len_utf8();
} else {
break;
}
} else {
break;
}
}
if start < end {
text[start..end].to_string()
} else {
String::new()
}
} else {
String::new()
}
};
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result =
handle.references(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::info!(
"Requested find references at {}:{}:{} (byte_pos={})",
uri.as_str(),
line,
character,
cursor_pos
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_references_request = Some(request_id);
self.pending_references_symbol = symbol;
self.lsp_status = "LSP: finding references...".to_string();
}
Ok(())
}
/// Request LSP signature help at current cursor position
pub(crate) fn request_signature_help(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result =
handle.signature_help(request_id, uri.clone(), line as u32, character as u32);
if result.is_ok() {
tracing::info!(
"Requested signature help at {}:{}:{} (byte_pos={})",
uri.as_str(),
line,
character,
cursor_pos
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_signature_help_request = Some(request_id);
self.lsp_status = "LSP: signature help...".to_string();
}
Ok(())
}
/// Handle signature help response from LSP
pub(crate) fn handle_signature_help_response(
&mut self,
request_id: u64,
signature_help: Option<lsp_types::SignatureHelp>,
) {
// Check if this response is for the current pending request
if self.pending_signature_help_request != Some(request_id) {
tracing::debug!("Ignoring stale signature help response: {}", request_id);
return;
}
self.pending_signature_help_request = None;
self.lsp_status.clear();
let signature_help = match signature_help {
Some(help) if !help.signatures.is_empty() => help,
_ => {
tracing::debug!("No signature help available");
return;
}
};
// Get the active signature
let active_signature_idx = signature_help.active_signature.unwrap_or(0) as usize;
let signature = match signature_help.signatures.get(active_signature_idx) {
Some(sig) => sig,
None => return,
};
// Build the display content
let mut lines: Vec<String> = Vec::new();
// Add the signature label (function signature)
lines.push(signature.label.clone());
// Add parameter highlighting info
let active_param = signature_help
.active_parameter
.or(signature.active_parameter)
.unwrap_or(0) as usize;
// If there are parameters, highlight the active one
if let Some(params) = &signature.parameters {
if let Some(param) = params.get(active_param) {
// Get parameter label
let param_label = match ¶m.label {
lsp_types::ParameterLabel::Simple(s) => s.clone(),
lsp_types::ParameterLabel::LabelOffsets(offsets) => {
// Extract substring from signature label
let start = offsets[0] as usize;
let end = offsets[1] as usize;
if end <= signature.label.len() {
signature.label[start..end].to_string()
} else {
String::new()
}
}
};
if !param_label.is_empty() {
lines.push(format!("> {}", param_label));
}
// Add parameter documentation if available
if let Some(doc) = ¶m.documentation {
let doc_text = match doc {
lsp_types::Documentation::String(s) => s.clone(),
lsp_types::Documentation::MarkupContent(m) => m.value.clone(),
};
if !doc_text.is_empty() {
lines.push(String::new());
lines.push(doc_text);
}
}
}
}
// Add function documentation if available
if let Some(doc) = &signature.documentation {
let doc_text = match doc {
lsp_types::Documentation::String(s) => s.clone(),
lsp_types::Documentation::MarkupContent(m) => m.value.clone(),
};
if !doc_text.is_empty() {
if lines.len() > 1 {
lines.push(String::new());
lines.push("---".to_string());
}
lines.push(doc_text);
}
}
// Create a popup with the signature help
use crate::view::popup::{Popup, PopupPosition};
use ratatui::style::Style;
let mut popup = Popup::text(lines, &self.theme);
popup.title = Some(t!("lsp.popup_signature").to_string());
popup.transient = true;
popup.position = PopupPosition::BelowCursor;
popup.width = 60;
popup.max_height = 10;
popup.border_style = Style::default().fg(self.theme.popup_border_fg);
popup.background_style = Style::default().bg(self.theme.popup_bg);
// Show the popup
if let Some(state) = self.buffers.get_mut(&self.active_buffer()) {
state.popups.show(popup);
tracing::info!(
"Showing signature help popup for {} signatures",
signature_help.signatures.len()
);
}
}
/// Request LSP code actions at current cursor position
pub(crate) fn request_code_actions(&mut self) -> AnyhowResult<()> {
// Get the current buffer and cursor position
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Convert byte position to LSP position (line, UTF-16 code units)
let (line, character) = state.buffer.position_to_lsp_position(cursor_pos);
// Get selection range (if any) or use cursor position
let (start_line, start_char, end_line, end_char) =
if let Some(range) = state.cursors.primary().selection_range() {
let (s_line, s_char) = state.buffer.position_to_lsp_position(range.start);
let (e_line, e_char) = state.buffer.position_to_lsp_position(range.end);
(s_line as u32, s_char as u32, e_line as u32, e_char as u32)
} else {
(line as u32, character as u32, line as u32, character as u32)
};
// Get diagnostics at cursor position for context
// TODO: Implement diagnostic retrieval when needed
let diagnostics: Vec<lsp_types::Diagnostic> = Vec::new();
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result = handle.code_actions(
request_id,
uri.clone(),
start_line,
start_char,
end_line,
end_char,
diagnostics,
);
if result.is_ok() {
tracing::info!(
"Requested code actions at {}:{}:{}-{}:{} (byte_pos={})",
uri.as_str(),
start_line,
start_char,
end_line,
end_char,
cursor_pos
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_code_actions_request = Some(request_id);
self.lsp_status = "LSP: code actions...".to_string();
}
Ok(())
}
/// Handle code actions response from LSP
pub(crate) fn handle_code_actions_response(
&mut self,
request_id: u64,
actions: Vec<lsp_types::CodeActionOrCommand>,
) {
// Check if this response is for the current pending request
if self.pending_code_actions_request != Some(request_id) {
tracing::debug!("Ignoring stale code actions response: {}", request_id);
return;
}
self.pending_code_actions_request = None;
self.lsp_status.clear();
if actions.is_empty() {
self.set_status_message(t!("lsp.no_code_actions").to_string());
return;
}
// Build the display content
let mut lines: Vec<String> = Vec::new();
lines.push(format!("Code Actions ({}):", actions.len()));
lines.push(String::new());
for (i, action) in actions.iter().enumerate() {
let title = match action {
lsp_types::CodeActionOrCommand::Command(cmd) => &cmd.title,
lsp_types::CodeActionOrCommand::CodeAction(ca) => &ca.title,
};
lines.push(format!(" {}. {}", i + 1, title));
}
lines.push(String::new());
lines.push(t!("lsp.code_action_hint").to_string());
// Create a popup with the code actions
use crate::view::popup::{Popup, PopupPosition};
use ratatui::style::Style;
let mut popup = Popup::text(lines, &self.theme);
popup.title = Some(t!("lsp.popup_code_actions").to_string());
popup.position = PopupPosition::BelowCursor;
popup.width = 60;
popup.max_height = 15;
popup.border_style = Style::default().fg(self.theme.popup_border_fg);
popup.background_style = Style::default().bg(self.theme.popup_bg);
// Show the popup
if let Some(state) = self.buffers.get_mut(&self.active_buffer()) {
state.popups.show(popup);
tracing::info!("Showing code actions popup with {} actions", actions.len());
}
// Note: Executing code actions would require storing the actions and handling
// key presses to select and apply them. This is left for future enhancement.
self.set_status_message(
t!("lsp.code_actions_not_implemented", count = actions.len()).to_string(),
);
}
/// Handle find references response from LSP
pub(crate) fn handle_references_response(
&mut self,
request_id: u64,
locations: Vec<lsp_types::Location>,
) -> AnyhowResult<()> {
tracing::info!(
"handle_references_response: received {} locations for request_id={}",
locations.len(),
request_id
);
// Check if this response is for the current pending request
if self.pending_references_request != Some(request_id) {
tracing::debug!("Ignoring stale references response: {}", request_id);
return Ok(());
}
self.pending_references_request = None;
self.lsp_status.clear();
if locations.is_empty() {
self.set_status_message(t!("lsp.no_references").to_string());
return Ok(());
}
// Convert locations to hook args format
let lsp_locations: Vec<crate::services::plugins::hooks::LspLocation> = locations
.iter()
.map(|loc| {
// Convert URI to file path
let file = if loc.uri.scheme().map(|s| s.as_str()) == Some("file") {
// Extract path from file:// URI
loc.uri.path().as_str().to_string()
} else {
loc.uri.as_str().to_string()
};
crate::services::plugins::hooks::LspLocation {
file,
line: loc.range.start.line + 1, // LSP is 0-based, convert to 1-based
column: loc.range.start.character + 1, // LSP is 0-based
}
})
.collect();
let count = lsp_locations.len();
let symbol = std::mem::take(&mut self.pending_references_symbol);
self.set_status_message(
t!("lsp.found_references", count = count, symbol = &symbol).to_string(),
);
// Fire the lsp_references hook so plugins can display the results
self.plugin_manager.run_hook(
"lsp_references",
crate::services::plugins::hooks::HookArgs::LspReferences {
symbol: symbol.clone(),
locations: lsp_locations,
},
);
tracing::info!(
"Fired lsp_references hook with {} locations for symbol '{}'",
count,
symbol
);
Ok(())
}
/// Apply LSP text edits to a buffer and return the number of changes made.
/// Edits are sorted in reverse order and applied as a batch.
pub(crate) fn apply_lsp_text_edits(
&mut self,
buffer_id: BufferId,
mut edits: Vec<lsp_types::TextEdit>,
) -> AnyhowResult<usize> {
if edits.is_empty() {
return Ok(0);
}
// Sort edits by position (reverse order to avoid offset issues)
edits.sort_by(|a, b| {
b.range
.start
.line
.cmp(&a.range.start.line)
.then(b.range.start.character.cmp(&a.range.start.character))
});
// Collect all events for this buffer into a batch
let mut batch_events = Vec::new();
let mut changes = 0;
// Create events for all edits
for edit in edits {
let state = self
.buffers
.get_mut(&buffer_id)
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Buffer not found"))?;
// Convert LSP range to byte positions
let start_line = edit.range.start.line as usize;
let start_char = edit.range.start.character as usize;
let end_line = edit.range.end.line as usize;
let end_char = edit.range.end.character as usize;
let start_pos = state.buffer.lsp_position_to_byte(start_line, start_char);
let end_pos = state.buffer.lsp_position_to_byte(end_line, end_char);
let buffer_len = state.buffer.len();
// Log the conversion for debugging
let old_text = if start_pos < end_pos && end_pos <= buffer_len {
state.get_text_range(start_pos, end_pos)
} else {
format!(
"<invalid range: start={}, end={}, buffer_len={}>",
start_pos, end_pos, buffer_len
)
};
tracing::debug!(
" Converting LSP range line {}:{}-{}:{} to bytes {}..{} (replacing {:?} with {:?})",
start_line, start_char, end_line, end_char,
start_pos, end_pos, old_text, edit.new_text
);
// Delete old text
if start_pos < end_pos {
let deleted_text = state.get_text_range(start_pos, end_pos);
let cursor_id = state.cursors.primary_id();
let delete_event = Event::Delete {
range: start_pos..end_pos,
deleted_text,
cursor_id,
};
batch_events.push(delete_event);
}
// Insert new text
if !edit.new_text.is_empty() {
let state = self
.buffers
.get(&buffer_id)
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Buffer not found"))?;
let cursor_id = state.cursors.primary_id();
let insert_event = Event::Insert {
position: start_pos,
text: edit.new_text.clone(),
cursor_id,
};
batch_events.push(insert_event);
}
changes += 1;
}
// Apply all rename changes using bulk edit for O(n) performance
if !batch_events.is_empty() {
self.apply_events_to_buffer_as_bulk_edit(
buffer_id,
batch_events,
"LSP Rename".to_string(),
)?;
}
Ok(changes)
}
/// Handle rename response from LSP
pub fn handle_rename_response(
&mut self,
_request_id: u64,
result: Result<lsp_types::WorkspaceEdit, String>,
) -> AnyhowResult<()> {
self.lsp_status.clear();
match result {
Ok(workspace_edit) => {
// Log the full workspace edit for debugging
tracing::debug!(
"Received WorkspaceEdit: changes={:?}, document_changes={:?}",
workspace_edit.changes.as_ref().map(|c| c.len()),
workspace_edit.document_changes.as_ref().map(|dc| match dc {
lsp_types::DocumentChanges::Edits(e) => format!("{} edits", e.len()),
lsp_types::DocumentChanges::Operations(o) =>
format!("{} operations", o.len()),
})
);
// Apply the workspace edit
let mut total_changes = 0;
// Handle changes (map of URI -> Vec<TextEdit>)
if let Some(changes) = workspace_edit.changes {
for (uri, edits) in changes {
if let Ok(path) = uri_to_path(&uri) {
let buffer_id = self.open_file(&path)?;
total_changes += self.apply_lsp_text_edits(buffer_id, edits)?;
}
}
}
// Handle document_changes (TextDocumentEdit[])
// This is what rust-analyzer sends instead of changes
if let Some(document_changes) = workspace_edit.document_changes {
use lsp_types::DocumentChanges;
let text_edits = match document_changes {
DocumentChanges::Edits(edits) => edits,
DocumentChanges::Operations(ops) => {
// Extract TextDocumentEdit from operations
ops.into_iter()
.filter_map(|op| {
if let lsp_types::DocumentChangeOperation::Edit(edit) = op {
Some(edit)
} else {
None
}
})
.collect()
}
};
for text_doc_edit in text_edits {
let uri = text_doc_edit.text_document.uri;
if let Ok(path) = uri_to_path(&uri) {
let buffer_id = self.open_file(&path)?;
// Extract TextEdit from OneOf<TextEdit, AnnotatedTextEdit>
let edits: Vec<lsp_types::TextEdit> = text_doc_edit
.edits
.into_iter()
.map(|one_of| match one_of {
lsp_types::OneOf::Left(text_edit) => text_edit,
lsp_types::OneOf::Right(annotated) => annotated.text_edit,
})
.collect();
// Log the edits for debugging
tracing::info!(
"Applying {} edits from rust-analyzer for {:?}:",
edits.len(),
path
);
for (i, edit) in edits.iter().enumerate() {
tracing::info!(
" Edit {}: line {}:{}-{}:{} -> {:?}",
i,
edit.range.start.line,
edit.range.start.character,
edit.range.end.line,
edit.range.end.character,
edit.new_text
);
}
total_changes += self.apply_lsp_text_edits(buffer_id, edits)?;
}
}
}
self.status_message = Some(t!("lsp.renamed", count = total_changes).to_string());
}
Err(error) => {
// Per LSP spec: ContentModified errors (-32801) should NOT be shown to user
// These are expected when document changes during LSP operations
// Reference: https://github.com/neovim/neovim/issues/16900
if error.contains("content modified") || error.contains("-32801") {
tracing::debug!(
"LSP rename: ContentModified error (expected, ignoring): {}",
error
);
self.status_message = Some(t!("lsp.rename_cancelled").to_string());
} else {
// Show other errors to user
self.status_message = Some(t!("lsp.rename_failed", error = &error).to_string());
}
}
}
Ok(())
}
/// Apply events to a specific buffer using bulk edit optimization (O(n) vs O(n²))
///
/// This is similar to `apply_events_as_bulk_edit` but works on a specific buffer
/// (which may not be the active buffer) and handles LSP notifications correctly.
pub(crate) fn apply_events_to_buffer_as_bulk_edit(
&mut self,
buffer_id: BufferId,
events: Vec<Event>,
description: String,
) -> AnyhowResult<()> {
use crate::model::event::CursorId;
if events.is_empty() {
return Ok(());
}
// Create a temporary batch for collecting LSP changes (before applying)
let batch_for_lsp = Event::Batch {
events: events.clone(),
description: description.clone(),
};
// IMPORTANT: Calculate LSP changes BEFORE applying to buffer!
// The byte positions in the events are relative to the ORIGINAL buffer.
let original_active = self.active_buffer();
self.split_manager.set_active_buffer_id(buffer_id);
let lsp_changes = self.collect_lsp_changes(&batch_for_lsp);
self.split_manager.set_active_buffer_id(original_active);
let state = self
.buffers
.get_mut(&buffer_id)
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Buffer not found"))?;
// Capture old cursor states
let old_cursors: Vec<(CursorId, usize, Option<usize>)> = state
.cursors
.iter()
.map(|(id, c)| (id, c.position, c.anchor))
.collect();
// Snapshot the tree for undo (O(1) - Arc clone)
let old_tree = state.buffer.snapshot_piece_tree();
// Convert events to edit tuples: (position, delete_len, insert_text)
let mut edits: Vec<(usize, usize, String)> = Vec::new();
for event in &events {
match event {
Event::Insert { position, text, .. } => {
edits.push((*position, 0, text.clone()));
}
Event::Delete { range, .. } => {
edits.push((range.start, range.len(), String::new()));
}
_ => {}
}
}
// Sort edits by position descending (required by apply_bulk_edits)
edits.sort_by(|a, b| b.0.cmp(&a.0));
// Convert to references for apply_bulk_edits
let edit_refs: Vec<(usize, usize, &str)> = edits
.iter()
.map(|(pos, del, text)| (*pos, *del, text.as_str()))
.collect();
// Apply bulk edits - O(n) instead of O(n²)
let _delta = state.buffer.apply_bulk_edits(&edit_refs);
// Calculate new cursor positions based on edits
let mut position_deltas: Vec<(usize, isize)> = Vec::new();
for (pos, del_len, text) in &edits {
let delta = text.len() as isize - *del_len as isize;
position_deltas.push((*pos, delta));
}
position_deltas.sort_by_key(|(pos, _)| *pos);
let calc_shift = |original_pos: usize| -> isize {
let mut shift: isize = 0;
for (edit_pos, delta) in &position_deltas {
if *edit_pos < original_pos {
shift += delta;
}
}
shift
};
// Calculate new cursor positions
let buffer_len = state.buffer.len();
let new_cursors: Vec<(CursorId, usize, Option<usize>)> = old_cursors
.iter()
.map(|(id, pos, anchor)| {
let shift = calc_shift(*pos);
let new_pos = ((*pos as isize + shift).max(0) as usize).min(buffer_len);
let new_anchor = anchor.map(|a| {
let anchor_shift = calc_shift(a);
((a as isize + anchor_shift).max(0) as usize).min(buffer_len)
});
(*id, new_pos, new_anchor)
})
.collect();
// Apply new cursor positions
for (cursor_id, new_pos, new_anchor) in &new_cursors {
if let Some(cursor) = state.cursors.get_mut(*cursor_id) {
cursor.position = *new_pos;
cursor.anchor = *new_anchor;
}
}
// Snapshot the tree after edits (for redo) - O(1) Arc clone
let new_tree = state.buffer.snapshot_piece_tree();
// Invalidate syntax highlighting
state.highlighter.invalidate_all();
// Create BulkEdit event for undo log
let bulk_edit = Event::BulkEdit {
old_tree: Some(old_tree),
new_tree: Some(new_tree),
old_cursors,
new_cursors,
description,
};
// Add to event log
if let Some(event_log) = self.event_logs.get_mut(&buffer_id) {
event_log.append(bulk_edit);
}
// Notify LSP about the changes using pre-calculated positions
self.send_lsp_changes_for_buffer(buffer_id, lsp_changes);
Ok(())
}
/// Send pre-calculated LSP changes for a specific buffer
pub(crate) fn send_lsp_changes_for_buffer(
&mut self,
buffer_id: BufferId,
changes: Vec<TextDocumentContentChangeEvent>,
) {
if changes.is_empty() {
return;
}
// Check if LSP is enabled for this buffer
let metadata = match self.buffer_metadata.get(&buffer_id) {
Some(m) => m,
None => {
tracing::debug!(
"send_lsp_changes_for_buffer: no metadata for buffer {:?}",
buffer_id
);
return;
}
};
if !metadata.lsp_enabled {
tracing::debug!("send_lsp_changes_for_buffer: LSP disabled for this buffer");
return;
}
// Get the URI
let uri = match metadata.file_uri() {
Some(u) => u.clone(),
None => {
tracing::debug!(
"send_lsp_changes_for_buffer: no URI for buffer (not a file or URI creation failed)"
);
return;
}
};
// Get the file path for language detection
let path = match metadata.file_path() {
Some(p) => p,
None => {
tracing::debug!("send_lsp_changes_for_buffer: no file path for buffer");
return;
}
};
let language = match detect_language(path, &self.config.languages) {
Some(l) => l,
None => {
tracing::debug!(
"send_lsp_changes_for_buffer: no language detected for {:?}",
path
);
return;
}
};
tracing::trace!(
"send_lsp_changes_for_buffer: sending {} changes to {} in single didChange notification",
changes.len(),
uri.as_str()
);
// Check if we can use LSP (respects auto_start setting)
use crate::services::lsp::manager::LspSpawnResult;
let Some(lsp) = self.lsp.as_mut() else {
tracing::debug!("send_lsp_changes_for_buffer: no LSP manager available");
return;
};
if lsp.try_spawn(&language) != LspSpawnResult::Spawned {
tracing::debug!(
"send_lsp_changes_for_buffer: LSP not running for {} (auto_start disabled)",
language
);
return;
}
// Get handle ID (handle exists since try_spawn succeeded)
let Some(handle) = lsp.get_handle_mut(&language) else {
return;
};
let handle_id = handle.id();
// Check if didOpen needs to be sent first
let needs_open = {
let Some(metadata) = self.buffer_metadata.get(&buffer_id) else {
return;
};
!metadata.lsp_opened_with.contains(&handle_id)
};
if needs_open {
// Get text for didOpen
let text = match self
.buffers
.get(&buffer_id)
.and_then(|s| s.buffer.to_string())
{
Some(t) => t,
None => {
tracing::debug!(
"send_lsp_changes_for_buffer: buffer text not available for didOpen"
);
return;
}
};
// Send didOpen first
let Some(lsp) = self.lsp.as_mut() else { return };
let Some(handle) = lsp.get_handle_mut(&language) else {
return;
};
if let Err(e) = handle.did_open(uri.clone(), text, language.clone()) {
tracing::warn!("Failed to send didOpen before didChange: {}", e);
return;
}
tracing::debug!(
"Sent didOpen for {} to LSP handle {} before didChange",
uri.as_str(),
handle_id
);
// Mark as opened
if let Some(metadata) = self.buffer_metadata.get_mut(&buffer_id) {
metadata.lsp_opened_with.insert(handle_id);
}
}
// Now send didChange
let Some(lsp) = self.lsp.as_mut() else { return };
let Some(client) = lsp.get_handle_mut(&language) else {
return;
};
if let Err(e) = client.did_change(uri, changes) {
tracing::warn!("Failed to send didChange to LSP: {}", e);
} else {
tracing::trace!("Successfully sent batched didChange to LSP");
}
}
/// Start rename mode - select the symbol at cursor and allow inline editing
pub(crate) fn start_rename(&mut self) -> AnyhowResult<()> {
use crate::primitives::word_navigation::{find_word_end, find_word_start};
// Get the current buffer and cursor position
let (word_start, word_end) = {
let state = self.active_state();
let cursor_pos = state.cursors.primary().position;
// Find the word boundaries
let word_start = find_word_start(&state.buffer, cursor_pos);
let word_end = find_word_end(&state.buffer, cursor_pos);
// Check if we're on a word
if word_start >= word_end {
self.status_message = Some(t!("lsp.no_symbol_at_cursor").to_string());
return Ok(());
}
(word_start, word_end)
};
// Get the word text
let word_text = self.active_state_mut().get_text_range(word_start, word_end);
// Create an overlay to highlight the symbol being renamed
let overlay_handle = self.add_overlay(
None,
word_start..word_end,
crate::model::event::OverlayFace::Background {
color: (50, 100, 200), // Blue background for rename
},
100,
Some(t!("lsp.popup_renaming").to_string()),
);
// Enter rename mode using the Prompt system
// Store the rename metadata in the PromptType and pre-fill the input with the current name
let mut prompt = Prompt::new(
"Rename to: ".to_string(),
PromptType::LspRename {
original_text: word_text.clone(),
start_pos: word_start,
end_pos: word_end,
overlay_handle,
},
);
// Pre-fill the input with the current name and position cursor at the end
prompt.set_input(word_text);
self.prompt = Some(prompt);
Ok(())
}
/// Cancel rename mode - removes overlay if the prompt was for LSP rename
pub(crate) fn cancel_rename_overlay(&mut self, handle: &crate::view::overlay::OverlayHandle) {
self.remove_overlay(handle.clone());
}
/// Perform the actual LSP rename request
pub(crate) fn perform_lsp_rename(
&mut self,
new_name: String,
original_text: String,
start_pos: usize,
overlay_handle: crate::view::overlay::OverlayHandle,
) {
// Remove the overlay first
self.cancel_rename_overlay(&overlay_handle);
// Check if the name actually changed
if new_name == original_text {
self.status_message = Some(t!("lsp.name_unchanged").to_string());
return;
}
// Use the position from when we entered rename mode, NOT the current cursor position
// This ensures we send the rename request for the correct symbol even if cursor moved
let rename_pos = start_pos;
// Convert byte position to LSP position (line, UTF-16 code units)
// LSP uses UTF-16 code units for character offsets, not byte offsets
let state = self.active_state();
let (line, character) = state.buffer.position_to_lsp_position(rename_pos);
let buffer_id = self.active_buffer();
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result = handle.rename(
request_id,
uri.clone(),
line as u32,
character as u32,
new_name.clone(),
);
if result.is_ok() {
tracing::info!(
"Requested rename at {}:{}:{} to '{}'",
uri.as_str(),
line,
character,
new_name
);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.lsp_status = "LSP: rename...".to_string();
} else if self
.buffer_metadata
.get(&buffer_id)
.and_then(|m| m.file_path())
.is_none()
{
self.status_message = Some(t!("lsp.cannot_rename_unsaved").to_string());
}
}
/// Request inlay hints for the active buffer (if enabled and LSP available)
pub(crate) fn request_inlay_hints_for_active_buffer(&mut self) {
if !self.config.editor.enable_inlay_hints {
return;
}
let buffer_id = self.active_buffer();
// Get line count from buffer state
let line_count = if let Some(state) = self.buffers.get(&buffer_id) {
state.buffer.line_count().unwrap_or(1000)
} else {
return;
};
let last_line = line_count.saturating_sub(1) as u32;
let request_id = self.next_lsp_request_id;
// Use helper to ensure didOpen is sent before the request
let sent = self
.with_lsp_for_buffer(buffer_id, |handle, uri, _language| {
let result = handle.inlay_hints(request_id, uri.clone(), 0, 0, last_line, 10000);
if result.is_ok() {
tracing::info!(
"Requested inlay hints for {} (request_id={})",
uri.as_str(),
request_id
);
} else if let Err(e) = &result {
tracing::debug!("Failed to request inlay hints: {}", e);
}
result.is_ok()
})
.unwrap_or(false);
if sent {
self.next_lsp_request_id += 1;
self.pending_inlay_hints_request = Some(request_id);
}
}
/// Request semantic tokens for a specific buffer if supported and needed.
pub(crate) fn maybe_request_semantic_tokens(&mut self, buffer_id: BufferId) {
if !self.config.editor.enable_semantic_tokens_full {
return;
}
// Avoid duplicate in-flight requests per buffer
if self.semantic_tokens_in_flight.contains_key(&buffer_id) {
return;
}
let Some(metadata) = self.buffer_metadata.get(&buffer_id) else {
return;
};
if !metadata.lsp_enabled {
return;
}
let Some(uri) = metadata.file_uri().cloned() else {
return;
};
let Some(path) = metadata.file_path() else {
return;
};
let Some(language) = detect_language(path, &self.config.languages) else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
if !lsp.semantic_tokens_full_supported(&language) {
return;
}
if lsp.semantic_tokens_legend(&language).is_none() {
return;
}
// Ensure there is a running server
use crate::services::lsp::manager::LspSpawnResult;
if lsp.try_spawn(&language) != LspSpawnResult::Spawned {
return;
}
let Some(state) = self.buffers.get(&buffer_id) else {
return;
};
let buffer_version = state.buffer.version();
if let Some(store) = state.semantic_tokens.as_ref() {
if store.version == buffer_version {
return; // Already up to date
}
}
let previous_result_id = state
.semantic_tokens
.as_ref()
.and_then(|store| store.result_id.clone());
let supports_delta = lsp.semantic_tokens_full_delta_supported(&language);
let use_delta = previous_result_id.is_some() && supports_delta;
let Some(handle) = lsp.get_handle_mut(&language) else {
return;
};
let request_id = self.next_lsp_request_id;
self.next_lsp_request_id += 1;
let request_kind = if use_delta {
super::SemanticTokensFullRequestKind::FullDelta
} else {
super::SemanticTokensFullRequestKind::Full
};
let request_result = if use_delta {
handle.semantic_tokens_full_delta(request_id, uri, previous_result_id.unwrap())
} else {
handle.semantic_tokens_full(request_id, uri)
};
match request_result {
Ok(_) => {
self.pending_semantic_token_requests.insert(
request_id,
super::SemanticTokenFullRequest {
buffer_id,
version: buffer_version,
kind: request_kind,
},
);
self.semantic_tokens_in_flight
.insert(buffer_id, (request_id, buffer_version, request_kind));
}
Err(e) => {
tracing::debug!("Failed to request semantic tokens: {}", e);
}
}
}
/// Schedule a full semantic token refresh for a buffer (debounced).
pub(crate) fn schedule_semantic_tokens_full_refresh(&mut self, buffer_id: BufferId) {
if !self.config.editor.enable_semantic_tokens_full {
return;
}
let next_time = Instant::now() + Duration::from_millis(SEMANTIC_TOKENS_FULL_DEBOUNCE_MS);
self.semantic_tokens_full_debounce
.insert(buffer_id, next_time);
}
/// Issue a debounced full semantic token request if the timer has elapsed.
pub(crate) fn maybe_request_semantic_tokens_full_debounced(&mut self, buffer_id: BufferId) {
if !self.config.editor.enable_semantic_tokens_full {
self.semantic_tokens_full_debounce.remove(&buffer_id);
return;
}
let Some(ready_at) = self.semantic_tokens_full_debounce.get(&buffer_id).copied() else {
return;
};
if Instant::now() < ready_at {
return;
}
self.semantic_tokens_full_debounce.remove(&buffer_id);
self.maybe_request_semantic_tokens(buffer_id);
}
/// Request semantic tokens for a viewport range (with padding).
pub(crate) fn maybe_request_semantic_tokens_range(
&mut self,
buffer_id: BufferId,
start_line: usize,
end_line: usize,
) {
let Some(metadata) = self.buffer_metadata.get(&buffer_id) else {
return;
};
if !metadata.lsp_enabled {
return;
}
let Some(uri) = metadata.file_uri().cloned() else {
return;
};
let Some(path) = metadata.file_path() else {
return;
};
let Some(language) = detect_language(path, &self.config.languages) else {
return;
};
let Some(lsp) = self.lsp.as_mut() else {
return;
};
if !lsp.semantic_tokens_range_supported(&language) {
// Fall back to full document tokens if range not supported.
self.maybe_request_semantic_tokens(buffer_id);
return;
}
if lsp.semantic_tokens_legend(&language).is_none() {
return;
}
// Ensure there is a running server
use crate::services::lsp::manager::LspSpawnResult;
if lsp.try_spawn(&language) != LspSpawnResult::Spawned {
return;
}
let Some(handle) = lsp.get_handle_mut(&language) else {
return;
};
let Some(state) = self.buffers.get(&buffer_id) else {
return;
};
let buffer_version = state.buffer.version();
let mut padded_start = start_line.saturating_sub(SEMANTIC_TOKENS_RANGE_PADDING_LINES);
let mut padded_end = end_line.saturating_add(SEMANTIC_TOKENS_RANGE_PADDING_LINES);
if let Some(line_count) = state.buffer.line_count() {
if line_count == 0 {
return;
}
let max_line = line_count.saturating_sub(1);
padded_start = padded_start.min(max_line);
padded_end = padded_end.min(max_line);
}
let start_byte = state.buffer.line_start_offset(padded_start).unwrap_or(0);
let end_char = state
.buffer
.get_line(padded_end)
.map(|line| String::from_utf8_lossy(&line).encode_utf16().count())
.unwrap_or(0);
let end_byte = if state.buffer.line_start_offset(padded_end).is_some() {
state.buffer.lsp_position_to_byte(padded_end, end_char)
} else {
state.buffer.len()
};
if start_byte >= end_byte {
return;
}
let range = start_byte..end_byte;
if let Some((in_flight_id, in_flight_start, in_flight_end, in_flight_version)) =
self.semantic_tokens_range_in_flight.get(&buffer_id)
{
if *in_flight_start == padded_start
&& *in_flight_end == padded_end
&& *in_flight_version == buffer_version
{
return;
}
if let Err(e) = handle.cancel_request(*in_flight_id) {
tracing::debug!("Failed to cancel semantic token range request: {}", e);
}
self.pending_semantic_token_range_requests
.remove(in_flight_id);
self.semantic_tokens_range_in_flight.remove(&buffer_id);
}
if let Some((applied_start, applied_end, applied_version)) =
self.semantic_tokens_range_applied.get(&buffer_id)
{
if *applied_start == padded_start
&& *applied_end == padded_end
&& *applied_version == buffer_version
{
return;
}
}
let now = Instant::now();
if let Some((last_start, last_end, last_version, last_time)) =
self.semantic_tokens_range_last_request.get(&buffer_id)
{
if *last_start == padded_start
&& *last_end == padded_end
&& *last_version == buffer_version
&& now.duration_since(*last_time)
< Duration::from_millis(SEMANTIC_TOKENS_RANGE_DEBOUNCE_MS)
{
return;
}
}
let lsp_range = lsp_types::Range {
start: lsp_types::Position {
line: padded_start as u32,
character: 0,
},
end: lsp_types::Position {
line: padded_end as u32,
character: end_char as u32,
},
};
let request_id = self.next_lsp_request_id;
self.next_lsp_request_id += 1;
match handle.semantic_tokens_range(request_id, uri, lsp_range) {
Ok(_) => {
self.pending_semantic_token_range_requests.insert(
request_id,
SemanticTokenRangeRequest {
buffer_id,
version: buffer_version,
range: range.clone(),
start_line: padded_start,
end_line: padded_end,
},
);
self.semantic_tokens_range_in_flight.insert(
buffer_id,
(request_id, padded_start, padded_end, buffer_version),
);
self.semantic_tokens_range_last_request
.insert(buffer_id, (padded_start, padded_end, buffer_version, now));
}
Err(e) => {
tracing::debug!("Failed to request semantic token range: {}", e);
}
}
}
}
#[cfg(test)]
mod tests {
use crate::model::filesystem::StdFileSystem;
use std::sync::Arc;
fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
Arc::new(StdFileSystem)
}
use super::Editor;
use crate::model::buffer::Buffer;
use crate::state::EditorState;
use crate::view::virtual_text::VirtualTextPosition;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Position};
fn make_hint(line: u32, character: u32, label: &str, kind: Option<InlayHintKind>) -> InlayHint {
InlayHint {
position: Position { line, character },
label: InlayHintLabel::String(label.to_string()),
kind,
text_edits: None,
tooltip: None,
padding_left: None,
padding_right: None,
data: None,
}
}
#[test]
fn test_inlay_hint_inserts_before_character() {
let mut state = EditorState::new(
80,
24,
crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
test_fs(),
);
state.buffer = Buffer::from_str_test("ab");
if !state.buffer.is_empty() {
state.marker_list.adjust_for_insert(0, state.buffer.len());
}
let hints = vec![make_hint(0, 1, ": i32", Some(InlayHintKind::TYPE))];
Editor::apply_inlay_hints_to_state(&mut state, &hints);
let lookup = state
.virtual_texts
.build_lookup(&state.marker_list, 0, state.buffer.len());
let vtexts = lookup.get(&1).expect("expected hint at byte offset 1");
assert_eq!(vtexts.len(), 1);
assert_eq!(vtexts[0].text, ": i32");
assert_eq!(vtexts[0].position, VirtualTextPosition::BeforeChar);
}
#[test]
fn test_inlay_hint_at_eof_renders_after_last_char() {
let mut state = EditorState::new(
80,
24,
crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
test_fs(),
);
state.buffer = Buffer::from_str_test("ab");
if !state.buffer.is_empty() {
state.marker_list.adjust_for_insert(0, state.buffer.len());
}
let hints = vec![make_hint(0, 2, ": i32", Some(InlayHintKind::TYPE))];
Editor::apply_inlay_hints_to_state(&mut state, &hints);
let lookup = state
.virtual_texts
.build_lookup(&state.marker_list, 0, state.buffer.len());
let vtexts = lookup.get(&1).expect("expected hint anchored to last byte");
assert_eq!(vtexts.len(), 1);
assert_eq!(vtexts[0].text, ": i32");
assert_eq!(vtexts[0].position, VirtualTextPosition::AfterChar);
}
#[test]
fn test_inlay_hint_empty_buffer_is_ignored() {
let mut state = EditorState::new(
80,
24,
crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
test_fs(),
);
state.buffer = Buffer::from_str_test("");
let hints = vec![make_hint(0, 0, ": i32", Some(InlayHintKind::TYPE))];
Editor::apply_inlay_hints_to_state(&mut state, &hints);
assert!(state.virtual_texts.is_empty());
}
}