mnml-rs 0.2.14

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! LSP client subsystem. One [`client::LspClient`] per `(project-root, language)`,
//! each a subprocess speaking JSON-RPC over stdio on its own reader thread; the
//! thread forwards `publishDiagnostics` notifications (and request responses we
//! care about) over an mpsc channel that [`crate::app::App::tick`] drains.
//!
//! Servers come from `[lsp.<name>]` config tables (`cmd`, `args`, `extensions`,
//! `root_markers`); a small built-in default set covers common languages so it
//! works out of the box. Everything degrades gracefully — a server that's not
//! installed / not configured / dies just means no LSP for that language.
//!
//! Known simplifications (first cut): full-text document sync (no incremental);
//! columns are treated as char offsets (LSP uses UTF-16 code units — fine for
//! ASCII, off for astral-plane chars on a line); `initialize` is followed
//! immediately by `initialized` + `didOpen` without waiting for the response
//! (works with rust-analyzer/gopls/pyright/clangd/tsserver in practice).

pub mod client;
pub mod diagnostics_pane;
pub mod outline_pane;

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc;

use crate::config::Config;

/// 0-based position, LSP semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pos {
    pub line: u32,
    pub character: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Range {
    pub start: Pos,
    pub end: Pos,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
    Info,
    Hint,
}

impl Severity {
    fn from_lsp(n: u64) -> Severity {
        match n {
            1 => Severity::Error,
            2 => Severity::Warning,
            3 => Severity::Info,
            _ => Severity::Hint,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub range: Range,
    pub severity: Severity,
    pub message: String,
    /// e.g. `"rustc"`, `"clippy"`, `"eslint"` — the diagnostic's source, if given.
    pub source: Option<String>,
}

/// One candidate as parsed from a `textDocument/completion` reply:
/// `(label, insert_text, detail, documentation, raw_json, is_snippet)`.
/// `raw_json` is the original server item — kept so the App can round-trip
/// it on a `completionItem/resolve` request. `is_snippet` is `true` when
/// the server marked the item with `insertTextFormat == 2` (the `insert`
/// then holds LSP snippet syntax — `$1` / `${1:default}` / `$0`).
// 7th element is the LSP `CompletionItemKind` (1..=25, 0 = unknown).
pub type CompletionItemTuple = (
    String,
    String,
    Option<String>,
    Option<String>,
    serde_json::Value,
    bool,
    u8,
);

/// What the reader thread sends to the event loop.
#[derive(Debug)]
pub enum LspEvent {
    /// New diagnostics for a file (replaces any previous set for that path).
    Diagnostics {
        path: PathBuf,
        diags: Vec<Diagnostic>,
    },
    /// Result of a `textDocument/definition` request — jump here.
    GotoDefinition {
        path: PathBuf,
        line: u32,
        character: u32,
    },
    /// Result of a `textDocument/hover` request — show this (markdown-ish) text.
    Hover { text: String },
    /// Result of a `textDocument/references` request — `(path, line, character)` per hit.
    References(Vec<(PathBuf, u32, u32)>),
    /// Result of a `textDocument/rename` request — a `WorkspaceEdit` flattened to
    /// `(path, [(range, new_text)])` per affected file.
    Rename(Vec<(PathBuf, Vec<(Range, String)>)>),
    /// Server-initiated `workspace/applyEdit` — same shape as `Rename`, with
    /// an optional label the server provides for the user-facing toast.
    ApplyEdit {
        label: Option<String>,
        edits: Vec<(PathBuf, Vec<(Range, String)>)>,
    },
    /// Result of a `textDocument/completion` request — see
    /// [`CompletionItemTuple`] for the field layout.
    Completion(Vec<CompletionItemTuple>),
    /// Result of a `completionItem/resolve` request — the resolved item's
    /// `(label, documentation, detail)`. `label` is the lookup key on the
    /// popup side; documentation may still be empty if the server didn't
    /// have anything to add.
    CompletionResolve {
        label: String,
        detail: Option<String>,
        documentation: Option<String>,
    },
    /// Result of a `textDocument/formatting` request — the `TextEdit[]` for `path`.
    Formatting {
        path: PathBuf,
        edits: Vec<(Range, String)>,
    },
    /// Result of a `textDocument/willSaveWaitUntil` request — the
    /// `TextEdit[]` the server wants applied *before* the file hits disk.
    /// Same shape as `Formatting` but a separate variant so the save
    /// state machine knows to chain into format-on-save (if enabled)
    /// after applying these edits.
    WillSaveWaitUntil {
        path: PathBuf,
        edits: Vec<(Range, String)>,
    },
    /// Result of a `textDocument/codeAction` request — the available actions at
    /// the requested range, in server order.
    CodeAction(Vec<CodeAction>),
    /// Result of a `codeAction/resolve` request — the resolved (edit, command)
    /// pair. The App matches it back to a pending action via the
    /// `pending_code_action_resolve` slot it set when firing the request.
    CodeActionResolve {
        edit: Option<WorkspaceEdit>,
        command: Option<CodeCommand>,
    },
    /// Result of a `textDocument/documentSymbol` request — `(name, kind,
    /// line, character, depth)` per symbol, depth-first (parents before
    /// children; depth = nesting level). Both the hierarchical `DocumentSymbol[]`
    /// reply shape and the legacy flat `SymbolInformation[]` shape feed in here.
    DocumentSymbols(Vec<DocumentSymbol>),
    /// Result of a `workspace/symbol` request — `(name, kind, path, line,
    /// character)` per hit across the whole project. Multiple servers may
    /// each contribute; events are emitted per server reply (the app merges).
    WorkspaceSymbols(Vec<WorkspaceSymbol>),
    /// Result of a `textDocument/signatureHelp` request — parameter info for
    /// the function call the cursor sits inside. `None` reply ⇒ no event
    /// emitted (so the open popup stays put).
    SignatureHelp(SignatureHelp),
    /// Result of a `textDocument/inlayHint` request — virtual text the
    /// server suggests inserting at specific positions. Rendered as dim
    /// chips by the editor view.
    InlayHints {
        path: PathBuf,
        hints: Vec<InlayHint>,
    },
    /// Result of a `textDocument/semanticTokens/full` request — server-aware
    /// syntax highlight spans, decoded from the protocol's flat delta-
    /// encoded `data[]` array. Layered on top of tree-sitter highlights by
    /// the editor renderer.
    SemanticTokens {
        path: PathBuf,
        tokens: Vec<SemanticToken>,
    },
    /// Result of a `textDocument/codeLens` request — actionable annotations
    /// (like "5 references" or "Run | Debug") attached to specific lines.
    /// Rendered as dim chips at end-of-line by the editor view.
    CodeLens {
        path: PathBuf,
        lenses: Vec<CodeLens>,
    },
    /// Result of a `codeLens/resolve` request — the server fills in the
    /// command for a previously-stub lens. App merges the command back
    /// onto the right lens (matched by `lens_index`) and re-runs the
    /// click that triggered the resolve.
    CodeLensResolve {
        path: PathBuf,
        lens_index: usize,
        lens: CodeLens,
    },
    /// Result of a `textDocument/documentLink` request — clickable links
    /// (URLs / file paths) the server identified in the buffer.
    DocumentLinks {
        path: PathBuf,
        links: Vec<DocumentLink>,
    },
    /// Result of a `textDocument/foldingRange` request — line-based fold
    /// ranges the server suggests (`(start_line, end_line)`, inclusive,
    /// 0-based file lines).
    FoldingRanges {
        path: PathBuf,
        ranges: Vec<(u32, u32)>,
    },
    /// Result of a `textDocument/selectionRange` request — semantic
    /// ranges around the cursor, ordered smallest → largest. Each entry
    /// is `(start_line, start_char, end_line, end_char)`.
    SelectionRanges {
        path: PathBuf,
        ranges: Vec<(u32, u32, u32, u32)>,
    },
    /// Result of a `textDocument/documentColor` request — color literals
    /// the server recognized in the buffer.
    DocumentColor {
        path: PathBuf,
        colors: Vec<ColorDecoration>,
    },
    /// Result of a `textDocument/documentHighlight` request — usages of
    /// the symbol at the requested position, scope-aware. Each entry is
    /// `(start_line, start_char, end_line, end_char)`.
    DocumentHighlights {
        path: PathBuf,
        ranges: Vec<(u32, u32, u32, u32)>,
    },
    /// Result of a `textDocument/prepareCallHierarchy` request — items
    /// the server thinks the cursor is on (typically one). The App
    /// re-fires `callHierarchy/incomingCalls` or `outgoingCalls` using
    /// the first item; multi-item disambiguation is a follow-up.
    CallHierarchyPrepared {
        direction: CallHierarchyDirection,
        items: Vec<CallHierarchyItem>,
    },
    /// Result of `callHierarchy/{incoming,outgoing}Calls` — each entry is
    /// a `(name, path, line, character)` for the call site (incoming) or
    /// the callee (outgoing).
    CallHierarchyCalls {
        direction: CallHierarchyDirection,
        origin_name: String,
        hits: Vec<CallHit>,
    },
    /// Result of a `textDocument/prepareTypeHierarchy` request — same
    /// shape as call hierarchy's prepare. Direction tells the App which
    /// follow-up to fire (`supertypes` vs `subtypes`).
    TypeHierarchyPrepared {
        direction: TypeHierarchyDirection,
        items: Vec<CallHierarchyItem>,
    },
    /// Result of `typeHierarchy/{super,sub}types` — same `(name, path,
    /// line, character)` shape as call hits, reusing [`CallHit`].
    TypeHierarchyTypes {
        direction: TypeHierarchyDirection,
        origin_name: String,
        hits: Vec<CallHit>,
    },
    /// `$/progress` with `kind: begin` — a long-running server task started.
    /// `token` is the server-assigned id; `title` is the user-facing label.
    /// Used by the statusline busy chip.
    ProgressBegin { token: String, title: String },
    /// `$/progress` with `kind: report` — same task, possibly updated
    /// label / percentage. `title` is the latest message.
    ProgressReport { token: String, title: String },
    /// `$/progress` with `kind: end` — task done. Drop the token.
    ProgressEnd { token: String },
    /// A server-side message worth surfacing as a toast.
    Message(String),
}

/// Direction of a call-hierarchy walk. Incoming = "callers of this fn";
/// outgoing = "callees from this fn".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallHierarchyDirection {
    Incoming,
    Outgoing,
}

/// Direction of a type-hierarchy walk. Super = "parent classes / traits";
/// sub = "subclasses / impls".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeHierarchyDirection {
    Supertypes,
    Subtypes,
}

/// A `CallHierarchyItem` from `textDocument/prepareCallHierarchy`. We
/// keep the original JSON in `raw` so the follow-up
/// `callHierarchy/{incoming,outgoing}Calls` request can hand it back to
/// the server without re-parsing.
#[derive(Debug, Clone)]
pub struct CallHierarchyItem {
    pub name: String,
    pub kind: u32,
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
    pub raw: serde_json::Value,
}

/// One call site / callee returned by `callHierarchy/{incoming,outgoing}Calls`.
/// For incoming: `name` is the caller, `path/line/character` is the call's
/// source position in the caller. For outgoing: `name` is the callee.
#[derive(Debug, Clone)]
pub struct CallHit {
    pub name: String,
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
}

/// One semantic-token span returned by `textDocument/semanticTokens/full`.
/// The LSP wire form is a flat `data: number[]` with delta encoding (every
/// 5 numbers = deltaLine, deltaStart, length, tokenTypeIdx, modifiers); the
/// reader decodes that into absolute positions + resolves the token type
/// index to a name via the per-server legend before sending up.
///
/// `type_name` is the legend string (`"function"` / `"variable"` /
/// `"string"` / …) which the editor renderer maps to a theme color.
/// `modifiers` is the resolved set of modifier names (`"deprecated"` /
/// `"defaultLibrary"` / `"readonly"` / `"static"` / etc.) the renderer
/// maps to a `ratatui::style::Modifier` (CROSSED_OUT / DIM / ITALIC /
/// BOLD). Modifiers with no visual mapping are kept on the token but
/// have no rendering effect.
#[derive(Debug, Clone)]
pub struct SemanticToken {
    pub line: u32,
    pub start_char: u32,
    pub length: u32,
    pub type_name: String,
    pub modifiers: Vec<String>,
}

/// One color literal the server recognized. We keep just enough to paint
/// a swatch glyph at the literal's position. RGB is `0xRRGGBB` packed
/// (alpha dropped — the renderer uses a fixed-glyph chip).
#[derive(Debug, Clone)]
pub struct ColorDecoration {
    pub line: u32,
    pub start_char: u32,
    pub end_char: u32,
    /// Packed 0xRRGGBB.
    pub rgb: u32,
}

/// One link the server says is clickable — `range` is where it sits in the
/// source, `target` is the URL / path to open.
#[derive(Debug, Clone)]
pub struct DocumentLink {
    pub line: u32,
    pub start_char: u32,
    pub end_char: u32,
    pub target: String,
}

/// A single inlay hint — virtual text the server wants displayed at a
/// specific position. We keep just `(line, character, label)` since the
/// MVP renderer paints them as dim end-of-line chips.
#[derive(Debug, Clone)]
pub struct InlayHint {
    pub line: u32,
    pub character: u32,
    pub label: String,
}

/// A single code lens — an actionable annotation on a line. The renderer
/// paints `title` as an end-of-line chip; clicking the chip fires
/// `command` (if any) via `workspace/executeCommand`. Stubs (title-only
/// lenses where the server held the command for a `codeLens/resolve`
/// round-trip) keep the original JSON in `raw` so resolve can hand it
/// back to the server verbatim.
#[derive(Debug, Clone)]
pub struct CodeLens {
    pub line: u32,
    pub title: String,
    pub command: Option<CodeCommand>,
    /// The original lens JSON from the server. Servers that defer the
    /// command to a `codeLens/resolve` round-trip expect us to hand the
    /// whole object (`data` field included) back verbatim. `None` when
    /// we don't need / can't do a resolve.
    pub raw: Option<serde_json::Value>,
}

/// A single entry in a `textDocument/documentSymbol` reply. We keep just
/// what the picker / jump needs — name, a short kind label, the position to
/// land the cursor at, and the nesting depth (so the picker can indent
/// children under their parent).
#[derive(Debug, Clone)]
pub struct DocumentSymbol {
    pub name: String,
    /// "fn" / "struct" / "class" / "method" / "h1" / etc.
    pub kind: &'static str,
    pub line: u32,
    pub character: u32,
    pub depth: u32,
}

/// Parsed `textDocument/signatureHelp` reply — what to render in the popup.
#[derive(Debug, Clone)]
pub struct SignatureHelp {
    pub signatures: Vec<SignatureInfo>,
    /// Which signature in `signatures` is "active" (the one to show first).
    pub active_signature: usize,
}

/// One signature in a [`SignatureHelp`] reply — its label (full prototype
/// text the server returns), the parameter ranges within that label, and
/// which parameter is currently active.
#[derive(Debug, Clone)]
pub struct SignatureInfo {
    pub label: String,
    /// `(start_char, end_char)` ranges into `label`, one per parameter.
    /// May be empty if the server didn't expose them (we fall back to just
    /// showing the label without a highlight).
    pub parameters: Vec<(usize, usize)>,
    /// Index into `parameters` for the active param — `None` when unknown
    /// or out of range.
    pub active_parameter: Option<usize>,
}

/// A single entry in a `workspace/symbol` reply — like [`DocumentSymbol`] but
/// project-wide (and so includes the file path). `container` is the owning
/// scope (`"impl Foo"`, `"mod inner"`, …) when the server supplies one — used
/// as a dim detail in the picker.
#[derive(Debug, Clone)]
pub struct WorkspaceSymbol {
    pub name: String,
    pub kind: &'static str,
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
    pub container: Option<String>,
}

/// Flattened `WorkspaceEdit` — `(path, [(range, new_text), …])` per affected
/// file. Same shape `textDocument/rename` produces.
pub type WorkspaceEdit = Vec<(PathBuf, Vec<(Range, String)>)>;

/// One offered code action. The server may give us a fully-resolved action
/// (with `edit` and/or `command` populated) or — for some servers / capabilities
/// — a stub that needs a follow-up `codeAction/resolve`. We don't advertise
/// resolveSupport in `initialize`, so in practice we get the eager shape.
#[derive(Debug, Clone)]
pub struct CodeAction {
    pub title: String,
    /// LSP `CodeActionKind` (`"quickfix"`, `"refactor.extract"`, …) when given.
    pub kind: Option<String>,
    /// Flattened `WorkspaceEdit` — `Some` ⇒ applying the action means applying
    /// these edits.
    pub edit: Option<WorkspaceEdit>,
    /// LSP `Command` — `Some` ⇒ also (or instead) send `workspace/executeCommand`
    /// when the action is accepted.
    pub command: Option<CodeCommand>,
    /// Original server JSON. Kept so we can round-trip the item back to the
    /// server on `codeAction/resolve` when `edit` is empty. `None` for
    /// internally-synthesized actions.
    pub raw: Option<serde_json::Value>,
}

/// LSP `Command` — `workspace/executeCommand` payload.
#[derive(Debug, Clone)]
pub struct CodeCommand {
    pub command: String,
    pub arguments: Vec<serde_json::Value>,
}

/// One configured language server.
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// Display name (the `[lsp.<name>]` key).
    pub name: String,
    /// Executable (looked up on PATH).
    pub cmd: String,
    pub args: Vec<String>,
    /// File extensions this server handles (without the dot).
    pub extensions: Vec<String>,
    /// Files whose presence marks a project root (walk up from the file).
    pub root_markers: Vec<String>,
    /// The LSP `languageId` to tag documents with (e.g. `"rust"`, `"typescript"`).
    pub language_id: String,
}

/// Derive the LSP `languageId` to send on textDocument/didOpen from
/// the file's extension. Most servers accept the registered server's
/// language_id directly, but a few cases need per-extension mapping
/// (TypeScript: tsx→typescriptreact / jsx→javascriptreact / js→
/// javascript; C++: cpp→cpp / c→c; etc.). multilang 2026-06-28 SEV-2.
fn derive_lsp_language_id(path: &Path, fallback: &str) -> String {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    match ext.as_str() {
        "tsx" => "typescriptreact".to_string(),
        "jsx" => "javascriptreact".to_string(),
        "js" | "mjs" | "cjs" => "javascript".to_string(),
        "ts" | "mts" | "cts" => "typescript".to_string(),
        "c" | "h" => "c".to_string(),
        "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh" => "cpp".to_string(),
        _ => fallback.to_string(),
    }
}

/// Built-in defaults (used unless `[lsp.<name>]` overrides the same name).
fn builtin_servers() -> Vec<ServerConfig> {
    let s = |name: &str, cmd: &str, args: &[&str], exts: &[&str], roots: &[&str], lang: &str| {
        ServerConfig {
            name: name.to_string(),
            cmd: cmd.to_string(),
            args: args.iter().map(|a| a.to_string()).collect(),
            extensions: exts.iter().map(|e| e.to_string()).collect(),
            root_markers: roots.iter().map(|r| r.to_string()).collect(),
            language_id: lang.to_string(),
        }
    };
    vec![
        s(
            "rust",
            "rust-analyzer",
            &[],
            &["rs"],
            &["Cargo.toml"],
            "rust",
        ),
        s(
            "python",
            "pyright-langserver",
            &["--stdio"],
            &["py"],
            &["pyproject.toml", "setup.py", "requirements.txt"],
            "python",
        ),
        s(
            "typescript",
            "typescript-language-server",
            &["--stdio"],
            &["ts", "tsx", "js", "jsx"],
            &["tsconfig.json", "jsconfig.json", "package.json"],
            "typescript",
        ),
        s("go", "gopls", &[], &["go"], &["go.mod"], "go"),
        s(
            "c",
            "clangd",
            &[],
            &["c", "h", "cpp", "hpp", "cc"],
            &["compile_commands.json", ".clangd"],
            "cpp",
        ),
        // C# / .NET — OmniSharp over stdio (needs the `-lsp` flag; the
        // default HTTP mode won't talk LSP). Root markers cover both
        // solution-scoped (`*.sln`) and single-project layouts
        // (`*.csproj`) plus modern SDK-style workspaces (`global.json`).
        // Install: `brew install omnisharp` (macOS) or download from
        // https://github.com/OmniSharp/omnisharp-roslyn/releases.
        s(
            "csharp",
            "omnisharp",
            &["-lsp"],
            &["cs", "csx", "cake"],
            &["*.sln", "*.csproj", "global.json"],
            "csharp",
        ),
    ]
}

/// Parse `[lsp.<name>]` tables, layered over the built-in defaults (a config
/// table replaces the built-in of the same name; partial tables fall back
/// field-by-field).
fn server_configs(cfg: &Config) -> Vec<ServerConfig> {
    let mut by_name: HashMap<String, ServerConfig> = builtin_servers()
        .into_iter()
        .map(|s| (s.name.clone(), s))
        .collect();
    for (name, val) in &cfg.lsp {
        let t = match val.as_table() {
            Some(t) => t,
            None => continue,
        };
        let str_of = |k: &str| t.get(k).and_then(|v| v.as_str()).map(str::to_string);
        let strs_of = |k: &str| {
            t.get(k).and_then(|v| v.as_array()).map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect::<Vec<_>>()
            })
        };
        let base = by_name.get(name).cloned();
        let merged = ServerConfig {
            name: name.clone(),
            cmd: str_of("cmd")
                .or_else(|| base.as_ref().map(|b| b.cmd.clone()))
                .unwrap_or_else(|| name.clone()),
            args: strs_of("args")
                .or_else(|| base.as_ref().map(|b| b.args.clone()))
                .unwrap_or_default(),
            extensions: strs_of("extensions")
                .or_else(|| base.as_ref().map(|b| b.extensions.clone()))
                .unwrap_or_default(),
            root_markers: strs_of("root_markers")
                .or_else(|| base.as_ref().map(|b| b.root_markers.clone()))
                .unwrap_or_default(),
            language_id: str_of("language_id")
                .or_else(|| base.as_ref().map(|b| b.language_id.clone()))
                .unwrap_or_else(|| name.clone()),
        };
        by_name.insert(name.clone(), merged);
    }
    by_name.into_values().collect()
}

/// Walk up from `file`'s directory looking for any of `markers`; fall back to
/// the file's directory (or `fallback`) if none found.
///
/// A marker is either a literal filename (`Cargo.toml`, `go.mod`) or a
/// simple glob with `*` at the start (`*.sln`, `*.csproj` — needed for
/// C# / .NET projects, which have variable-named solution / project
/// files). Full glob syntax isn't parsed — only leading `*` prefix +
/// extension suffix, which is what every real root-marker use case
/// actually needs.
fn find_root(file: &Path, markers: &[String], fallback: &Path) -> PathBuf {
    let start = file.parent().unwrap_or(fallback);
    let mut cur = Some(start);
    while let Some(dir) = cur {
        if markers.iter().any(|m| marker_matches(dir, m)) {
            return dir.to_path_buf();
        }
        cur = dir.parent();
    }
    start.to_path_buf()
}

/// Does `dir` contain a file matching `marker`? Literal name = plain
/// `.exists()` check; leading `*` = scan the dir for any entry whose
/// name ends with the rest.
fn marker_matches(dir: &Path, marker: &str) -> bool {
    if let Some(suffix) = marker.strip_prefix('*') {
        // Glob path — scan the directory once and match any entry
        // whose file_name ends with the suffix (e.g. `*.sln` matches
        // `Foo.sln`). Short-circuits on the first hit; misses (dir
        // unreadable) return false, matching the literal path's
        // "doesn't count" semantic.
        std::fs::read_dir(dir)
            .map(|entries| {
                entries.flatten().any(|entry| {
                    entry
                        .file_name()
                        .to_str()
                        .is_some_and(|name| name.ends_with(suffix))
                })
            })
            .unwrap_or(false)
    } else {
        dir.join(marker).exists()
    }
}

pub struct LspManager {
    workspace: PathBuf,
    servers: Vec<ServerConfig>,
    /// Keyed `(root, server-name)`.
    clients: HashMap<(PathBuf, String), client::LspClient>,
    /// Server names we've already tried + failed to spawn (don't retry / re-toast).
    dead: std::collections::HashSet<String>,
    tx: mpsc::Sender<LspEvent>,
    rx: mpsc::Receiver<LspEvent>,
}

impl LspManager {
    pub fn new(workspace: &Path, cfg: &Config) -> LspManager {
        let (tx, rx) = mpsc::channel();
        LspManager {
            workspace: workspace.to_path_buf(),
            servers: server_configs(cfg),
            clients: HashMap::new(),
            dead: std::collections::HashSet::new(),
            tx,
            rx,
        }
    }

    /// True when no language server is currently running. Used as a guard
    /// before workspace-wide requests (`workspace/symbol`).
    pub fn is_empty(&self) -> bool {
        self.clients.is_empty()
    }

    /// Count of running servers (each `(root, server-name)` pair counts once).
    pub fn server_count(&self) -> usize {
        self.clients.len()
    }

    /// Drop every running server (each `LspClient` kills its child on Drop).
    /// `dead` is cleared too so a new `did_open` can respawn them. Used by
    /// `:LspRestart` — a "the LSP got stuck" recovery gesture.
    pub fn restart_all(&mut self) {
        self.clients.clear();
        self.dead.clear();
    }

    /// `(server-name, root)` for each running server. Used by the statusline
    /// chip + `:LspStatus` ex command.
    pub fn servers_running(&self) -> Vec<(String, PathBuf)> {
        let mut v: Vec<_> = self
            .clients
            .keys()
            .map(|(root, name)| (name.clone(), root.clone()))
            .collect();
        v.sort();
        v
    }

    fn server_for_ext(&self, ext: &str) -> Option<ServerConfig> {
        self.servers
            .iter()
            .find(|s| s.extensions.iter().any(|e| e == ext))
            .cloned()
    }

    /// Ensure a client exists for `path`'s language; returns the `(root, name)`
    /// key + the language id, or `None` if there's no server for this extension /
    /// it couldn't be started.
    fn ensure_client(&mut self, path: &Path) -> Option<((PathBuf, String), String)> {
        let ext = path.extension()?.to_str()?.to_string();
        let sc = self.server_for_ext(&ext)?;
        if self.dead.contains(&sc.name) {
            return None;
        }
        let root = find_root(path, &sc.root_markers, &self.workspace);
        let key = (root.clone(), sc.name.clone());
        if !self.clients.contains_key(&key) {
            match client::LspClient::spawn(&sc, &root, self.tx.clone()) {
                Ok(c) => {
                    self.clients.insert(key.clone(), c);
                }
                Err(e) => {
                    self.dead.insert(sc.name.clone());
                    // 2026-06-21 multilang feature: when the LSP
                    // binary isn't on PATH, include the exact
                    // install command for the recognized servers.
                    // Recognized via the cmd's basename. Falls
                    // back to a generic "install it on PATH" when
                    // we don't have a hint for the binary.
                    let short = if e.to_lowercase().contains("not found")
                        || e.to_lowercase().contains("no such file")
                    {
                        match install_hint_for(&sc.cmd) {
                            Some(install) => {
                                format!("LSP: {} not installed — `{install}`", sc.cmd)
                            }
                            None => format!("LSP: {} not installed — install it on PATH", sc.cmd),
                        }
                    } else {
                        format!("LSP: {} unavailable", sc.cmd)
                    };
                    let _ = self.tx.send(LspEvent::Message(short));
                    return None;
                }
            }
        }
        // multilang 2026-06-28 SEV-2: typescript-language-server's
        // builtin entry maps ts/tsx/js/jsx to a single "typescript"
        // language_id, but the LSP protocol expects per-extension
        // ids: ts→typescript, tsx→typescriptreact, js→javascript,
        // jsx→javascriptreact. Wrong id silently breaks JSX parsing
        // (every React component shows red underlines, no hover).
        // Derive the right id from the actual file extension.
        let language_id = derive_lsp_language_id(path, &sc.language_id);
        Some((key, language_id))
    }

    pub fn did_open(&mut self, path: &Path, text: &str) {
        if let Some((key, lang)) = self.ensure_client(path)
            && let Some(c) = self.clients.get_mut(&key)
        {
            c.did_open(path, &lang, text);
        }
    }
    pub fn did_change(&mut self, path: &Path, text: &str) {
        for c in self.clients.values_mut() {
            c.did_change(path, text);
        }
    }
    pub fn did_save(&mut self, path: &Path, text: &str) {
        for c in self.clients.values_mut() {
            c.did_save(path, text);
        }
    }
    pub fn did_close(&mut self, path: &Path) {
        for c in self.clients.values_mut() {
            c.did_close(path);
        }
    }
    /// Send a `textDocument/definition` request for the cursor position.
    pub fn goto_definition(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/definition", path, line, character)
    }
    /// Send a `textDocument/declaration` request — reply routes through
    /// [`LspEvent::GotoDefinition`] (same shape).
    pub fn goto_declaration(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/declaration", path, line, character)
    }
    /// Send a `textDocument/typeDefinition` request — reply routes through
    /// [`LspEvent::GotoDefinition`] (same shape).
    pub fn goto_type_definition(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/typeDefinition", path, line, character)
    }
    /// Send a `textDocument/implementation` request — reply routes through
    /// [`LspEvent::GotoDefinition`] (same shape).
    pub fn goto_implementation(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/implementation", path, line, character)
    }
    /// Send a `textDocument/hover` request for the cursor position.
    pub fn hover(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/hover", path, line, character)
    }
    /// Send a `textDocument/references` request for the cursor position.
    pub fn references(&mut self, path: &Path, line: u32, character: u32) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.references(path, line, character);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/rename` request — the reply arrives as [`LspEvent::Rename`].
    pub fn rename(&mut self, path: &Path, line: u32, character: u32, new_name: &str) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.rename(path, line, character, new_name);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/completion` request — the reply arrives as [`LspEvent::Completion`].
    pub fn completion(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/completion", path, line, character)
    }
    /// Send a `completionItem/resolve` for `item` against whichever server
    /// has `path` open. Reply arrives as [`LspEvent::CompletionResolve`] tagged
    /// with `label` so the popup can find the row.
    pub fn completion_resolve(
        &mut self,
        path: &Path,
        label: &str,
        item: serde_json::Value,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.completion_resolve(item.clone(), label);
                sent = true;
            }
        }
        sent
    }
    /// Send a `codeAction/resolve` for `action` against whichever server has
    /// `path` open. Reply arrives as [`LspEvent::CodeActionResolve`].
    pub fn code_action_resolve(&mut self, path: &Path, action: serde_json::Value) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.code_action_resolve(action.clone());
                sent = true;
            }
        }
        sent
    }
    /// Send a `codeLens/resolve` for `lens` (the original JSON the server
    /// returned) against whichever server has `path` open. Reply arrives as
    /// [`LspEvent::CodeLensResolve`] keyed by `lens_index`.
    pub fn code_lens_resolve(
        &mut self,
        path: &Path,
        lens: serde_json::Value,
        lens_index: usize,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.code_lens_resolve(lens.clone(), lens_index);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/formatting` request — the reply arrives as [`LspEvent::Formatting`].
    pub fn formatting(&mut self, path: &Path, tab_size: u32, insert_spaces: bool) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.formatting(path, tab_size, insert_spaces);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/willSaveWaitUntil` request — fired before
    /// save, reply arrives as [`LspEvent::WillSaveWaitUntil`] and the
    /// edits are spliced into the buffer *before* the disk write.
    pub fn will_save_wait_until(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.will_save_wait_until(path);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/documentSymbol` request — reply arrives as
    /// [`LspEvent::DocumentSymbols`].
    pub fn document_symbol(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.document_symbol(path);
                sent = true;
            }
        }
        sent
    }
    /// Send `workspace/symbol` to **every** running server (each may host its
    /// own project; merging on the app side). Reply arrives per server as
    /// [`LspEvent::WorkspaceSymbols`].
    pub fn workspace_symbol(&mut self, query: &str) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            c.workspace_symbol(query);
            sent = true;
        }
        sent
    }
    /// Send `textDocument/signatureHelp` at `(line, character)` — reply
    /// arrives as [`LspEvent::SignatureHelp`].
    pub fn signature_help(&mut self, path: &Path, line: u32, character: u32) -> bool {
        self.request_at("textDocument/signatureHelp", path, line, character)
    }
    /// Send `textDocument/inlayHint` for the whole file — reply arrives as
    /// [`LspEvent::InlayHints`]. Caller passes `line_count` so the request
    /// range covers the whole buffer.
    pub fn inlay_hint(&mut self, path: &Path, line_count: u32) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.inlay_hint(path, line_count);
                sent = true;
            }
        }
        sent
    }
    /// Request semantic tokens — the client picks the best request shape
    /// per advertised capability: viewport-only `range` (when `viewport`
    /// is `Some` AND the server supports range), `full/delta` (delta +
    /// cached resultId), `full` (the typical path), or whole-file
    /// `range` (the server doesn't advertise full). Reply arrives as
    /// [`LspEvent::SemanticTokens`]. `line_count` is used only for the
    /// whole-file range fallback.
    pub fn semantic_tokens(
        &mut self,
        path: &Path,
        line_count: u32,
        viewport: Option<(u32, u32)>,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.semantic_tokens(path, line_count, viewport);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/documentLink` — reply arrives as
    /// [`LspEvent::DocumentLinks`].
    pub fn document_link(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.document_link(path);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/foldingRange` — reply arrives as
    /// [`LspEvent::FoldingRanges`].
    pub fn folding_range(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.folding_range(path);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/selectionRange` at `(line, character)` — reply
    /// arrives as [`LspEvent::SelectionRanges`].
    pub fn selection_range(&mut self, path: &Path, line: u32, character: u32) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.selection_range(path, line, character);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/documentColor` — reply arrives as
    /// [`LspEvent::DocumentColor`].
    pub fn document_color(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.document_color(path);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/documentHighlight` at `(line, character)` —
    /// reply arrives as [`LspEvent::DocumentHighlights`].
    pub fn document_highlight(&mut self, path: &Path, line: u32, character: u32) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.document_highlight(path, line, character);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/prepareCallHierarchy` at `(line, character)`. The
    /// `direction` is stashed so the reply (carried as
    /// [`LspEvent::CallHierarchyPrepared`]) tells the App which follow-up
    /// to fire (`incomingCalls` vs `outgoingCalls`).
    pub fn prepare_call_hierarchy(
        &mut self,
        path: &Path,
        line: u32,
        character: u32,
        direction: CallHierarchyDirection,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.prepare_call_hierarchy(path, line, character, direction);
                sent = true;
            }
        }
        sent
    }
    /// Send `textDocument/onTypeFormatting` at `(line, char)` with a
    /// trigger char. Reply is delivered as [`LspEvent::Formatting`]
    /// (shape is identical to `textDocument/formatting`).
    pub fn on_type_formatting(
        &mut self,
        path: &Path,
        line: u32,
        character: u32,
        trigger: char,
        tab_size: u32,
        insert_spaces: bool,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.on_type_formatting(path, line, character, trigger, tab_size, insert_spaces);
                sent = true;
            }
        }
        sent
    }

    /// Send `callHierarchy/incomingCalls` for a previously-prepared item.
    /// `origin_name` is the prepared item's name — round-tripped back in
    /// [`LspEvent::CallHierarchyCalls`] so the picker title reads
    /// `"Incoming calls — fn foo"` without an extra lookup.
    pub fn call_hierarchy_incoming(&mut self, item: &CallHierarchyItem) {
        for c in self.clients.values_mut() {
            if c.is_open(&item.path) {
                c.call_hierarchy_calls(item, CallHierarchyDirection::Incoming);
                return;
            }
        }
    }
    /// Send `callHierarchy/outgoingCalls` for a previously-prepared item.
    pub fn call_hierarchy_outgoing(&mut self, item: &CallHierarchyItem) {
        for c in self.clients.values_mut() {
            if c.is_open(&item.path) {
                c.call_hierarchy_calls(item, CallHierarchyDirection::Outgoing);
                return;
            }
        }
    }

    /// Send `textDocument/prepareTypeHierarchy` at `(line, character)`.
    pub fn prepare_type_hierarchy(
        &mut self,
        path: &Path,
        line: u32,
        character: u32,
        direction: TypeHierarchyDirection,
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.prepare_type_hierarchy(path, line, character, direction);
                sent = true;
            }
        }
        sent
    }
    /// Send `typeHierarchy/supertypes` for a previously-prepared item.
    pub fn type_hierarchy_supertypes(&mut self, item: &CallHierarchyItem) {
        for c in self.clients.values_mut() {
            if c.is_open(&item.path) {
                c.type_hierarchy_types(item, TypeHierarchyDirection::Supertypes);
                return;
            }
        }
    }
    /// Send `typeHierarchy/subtypes` for a previously-prepared item.
    pub fn type_hierarchy_subtypes(&mut self, item: &CallHierarchyItem) {
        for c in self.clients.values_mut() {
            if c.is_open(&item.path) {
                c.type_hierarchy_types(item, TypeHierarchyDirection::Subtypes);
                return;
            }
        }
    }
    /// Send `textDocument/codeLens` — reply arrives as [`LspEvent::CodeLens`].
    pub fn code_lens(&mut self, path: &Path) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.code_lens(path);
                sent = true;
            }
        }
        sent
    }
    /// Send a `textDocument/codeAction` request — the reply arrives as
    /// [`LspEvent::CodeAction`]. `diagnostics` are the ones overlapping the
    /// requested range (the server uses them to decide which quickfixes apply).
    pub fn code_action(&mut self, path: &Path, range: Range, diagnostics: &[Diagnostic]) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.code_action(path, range, diagnostics);
                sent = true;
            }
        }
        sent
    }
    /// Same as [`Self::code_action`] but with a `context.only` filter so
    /// the server returns only actions of those kinds (e.g.
    /// `["source.organizeImports"]`). Reply still arrives as
    /// [`LspEvent::CodeAction`].
    pub fn code_action_with_only(
        &mut self,
        path: &Path,
        range: Range,
        diagnostics: &[Diagnostic],
        only: &[String],
    ) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.code_action_with_only(path, range, diagnostics, only);
                sent = true;
            }
        }
        sent
    }
    /// Send a `workspace/executeCommand` request (no reply handling — fire and
    /// forget; the server's effects come back as `applyEdit` / diagnostics).
    pub fn execute_command(&mut self, path: &Path, cmd: &CodeCommand) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.execute_command(cmd);
                sent = true;
            }
        }
        sent
    }
    fn request_at(&mut self, method: &str, path: &Path, line: u32, character: u32) -> bool {
        let mut sent = false;
        for c in self.clients.values_mut() {
            if c.is_open(path) {
                c.request_text_position(method, path, line, character);
                sent = true;
            }
        }
        sent
    }

    /// Drain everything the reader threads have produced since last call.
    pub fn poll(&mut self) -> Vec<LspEvent> {
        self.rx.try_iter().collect()
    }
}

// ── shared JSON helpers used by client.rs ──────────────────────────

/// `file:///abs/path` for `path` (already absolute). Minimal percent-encoding.
pub(crate) fn path_to_uri(path: &Path) -> String {
    let s = path.to_string_lossy();
    let mut out = String::from("file://");
    for b in s.bytes() {
        match b {
            b'/' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => out.push(b as char),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// Inverse of [`path_to_uri`] (best-effort): `file:///x` → `/x`, percent-decoded.
pub(crate) fn uri_to_path(uri: &str) -> Option<PathBuf> {
    let rest = uri.strip_prefix("file://")?;
    let mut bytes = Vec::with_capacity(rest.len());
    let mut it = rest.bytes();
    while let Some(b) = it.next() {
        if b == b'%' {
            let h = it.next()?;
            let l = it.next()?;
            let hv = (h as char).to_digit(16)?;
            let lv = (l as char).to_digit(16)?;
            bytes.push((hv * 16 + lv) as u8);
        } else {
            bytes.push(b);
        }
    }
    Some(PathBuf::from(String::from_utf8_lossy(&bytes).into_owned()))
}

/// Parse a diagnostic JSON object into our [`Diagnostic`].
pub(crate) fn parse_diagnostic(v: &serde_json::Value) -> Option<Diagnostic> {
    let r = v.get("range")?;
    let pos = |k: &str| -> Option<Pos> {
        let p = r.get(k)?;
        Some(Pos {
            line: p.get("line")?.as_u64()? as u32,
            character: p.get("character")?.as_u64()? as u32,
        })
    };
    Some(Diagnostic {
        range: Range {
            start: pos("start")?,
            end: pos("end")?,
        },
        severity: v
            .get("severity")
            .and_then(|s| s.as_u64())
            .map(Severity::from_lsp)
            .unwrap_or(Severity::Error),
        message: v
            .get("message")
            .and_then(|m| m.as_str())
            .unwrap_or("")
            .to_string(),
        source: v.get("source").and_then(|s| s.as_str()).map(str::to_string),
    })
}

/// Byte offset in `text` of the `character`-th char on the 0-based `line`
/// (LSP positions are line + UTF-16 units; we treat `character` as a *char*
/// index — fine for ASCII / BMP). `character` past the end of the line maps to
/// the line's end (before the `\n`). `None` if `line` is out of range.
pub(crate) fn byte_at(text: &str, line: u32, character: u32) -> Option<usize> {
    let mut start = 0usize;
    for _ in 0..line {
        let nl = text[start..].find('\n')?;
        start += nl + 1;
    }
    let line_text = match text[start..].find('\n') {
        Some(nl) => &text[start..start + nl],
        None => &text[start..],
    };
    match line_text.char_indices().nth(character as usize) {
        Some((off, _)) => Some(start + off),
        None => Some(start + line_text.len()),
    }
}

/// 2026-06-21 — return an install-command hint for a recognized
/// LSP binary, or None when we don't know it. Matched on basename
/// so it works whether the user configured `rust-analyzer` or an
/// absolute path. The `attach()` toast interpolates this into the
/// "not installed" message so a new user gets a concrete next step
/// instead of a generic "install it on PATH."
fn install_hint_for(cmd: &str) -> Option<&'static str> {
    let base = std::path::Path::new(cmd)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(cmd);
    match base {
        "rust-analyzer" => Some("rustup component add rust-analyzer"),
        "typescript-language-server" => Some("npm i -g typescript typescript-language-server"),
        "tsserver" => Some("npm i -g typescript"),
        "pylsp" => Some("pip install python-lsp-server"),
        "pyright" | "pyright-langserver" => Some("npm i -g pyright"),
        "gopls" => Some("go install golang.org/x/tools/gopls@latest"),
        "clangd" => Some("brew install llvm  /  apt install clangd"),
        "omnisharp" | "OmniSharp" => Some(
            "brew install omnisharp  /  see https://github.com/OmniSharp/omnisharp-roslyn/releases",
        ),
        "csharp-ls" => Some("dotnet tool install -g csharp-ls"),
        "lua-language-server" => Some("brew install lua-language-server"),
        "ruby-lsp" => Some("gem install ruby-lsp"),
        "solargraph" => Some("gem install solargraph"),
        "bash-language-server" => Some("npm i -g bash-language-server"),
        "vscode-html-language-server"
        | "vscode-css-language-server"
        | "vscode-json-language-server"
        | "vscode-eslint-language-server" => Some("npm i -g vscode-langservers-extracted"),
        "yaml-language-server" => Some("npm i -g yaml-language-server"),
        "vue-language-server" => Some("npm i -g @vue/language-server"),
        "tailwindcss-language-server" => Some("npm i -g @tailwindcss/language-server"),
        "marksman" => Some("brew install marksman"),
        "taplo" => Some("cargo install taplo-cli --features lsp"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn byte_at_resolves_positions() {
        let t = "ab\ncde\nf";
        assert_eq!(byte_at(t, 0, 0), Some(0));
        assert_eq!(byte_at(t, 0, 2), Some(2)); // end of line 0 (the '\n')
        assert_eq!(byte_at(t, 1, 0), Some(3));
        assert_eq!(byte_at(t, 1, 1), Some(4));
        assert_eq!(byte_at(t, 1, 9), Some(6)); // past end → line end
        assert_eq!(byte_at(t, 2, 0), Some(7));
        assert_eq!(byte_at(t, 3, 0), None); // out of range
    }

    #[test]
    fn uri_round_trips() {
        let p = Path::new("/tmp/a b/x.rs");
        let u = path_to_uri(p);
        assert!(u.starts_with("file:///tmp/a%20b/x.rs"));
        assert_eq!(uri_to_path(&u).unwrap(), p);
    }

    #[test]
    fn ext_lookup_hits_builtins() {
        let cfg = Config::default();
        let m = LspManager::new(Path::new("/tmp"), &cfg);
        assert!(m.server_for_ext("rs").is_some());
        assert_eq!(m.server_for_ext("rs").unwrap().cmd, "rust-analyzer");
        assert!(m.server_for_ext("zzz").is_none());
    }

    #[test]
    fn config_overrides_builtin() {
        let mut cfg = Config::default();
        let mut t = toml::value::Table::new();
        t.insert("cmd".into(), toml::Value::String("my-ra".into()));
        cfg.lsp.insert("rust".into(), toml::Value::Table(t));
        let m = LspManager::new(Path::new("/tmp"), &cfg);
        assert_eq!(m.server_for_ext("rs").unwrap().cmd, "my-ra");
        // unspecified fields keep the builtin
        assert_eq!(m.server_for_ext("rs").unwrap().language_id, "rust");
    }

    #[test]
    fn parse_diagnostic_basic() {
        let v = serde_json::json!({
            "range": {"start": {"line": 3, "character": 1}, "end": {"line": 3, "character": 5}},
            "severity": 2, "message": "unused", "source": "rustc"
        });
        let d = parse_diagnostic(&v).unwrap();
        assert_eq!(d.severity, Severity::Warning);
        assert_eq!(d.range.start.line, 3);
        assert_eq!(d.source.as_deref(), Some("rustc"));
    }

    #[test]
    fn derive_lsp_language_id_maps_typescript_and_c_variants() {
        // multilang-dev-user 2026-06-28 SEV-2 coverage gap.
        // A one-line accidental revert of `"tsx" => "typescriptreact"`
        // would silently break JSX parsing — no test failure since
        // LSP wire messages aren't observable in headless mode.
        // Lock the mapping.
        let p = |s: &str| std::path::PathBuf::from(s);
        assert_eq!(derive_lsp_language_id(&p("a.ts"), "fallback"), "typescript");
        assert_eq!(
            derive_lsp_language_id(&p("a.tsx"), "fallback"),
            "typescriptreact"
        );
        assert_eq!(derive_lsp_language_id(&p("a.js"), "fallback"), "javascript");
        assert_eq!(
            derive_lsp_language_id(&p("a.jsx"), "fallback"),
            "javascriptreact"
        );
        assert_eq!(
            derive_lsp_language_id(&p("a.mts"), "fallback"),
            "typescript"
        );
        assert_eq!(
            derive_lsp_language_id(&p("a.cjs"), "fallback"),
            "javascript"
        );
        assert_eq!(derive_lsp_language_id(&p("a.c"), "fallback"), "c");
        assert_eq!(derive_lsp_language_id(&p("a.h"), "fallback"), "c");
        assert_eq!(derive_lsp_language_id(&p("a.cpp"), "fallback"), "cpp");
        assert_eq!(derive_lsp_language_id(&p("a.hxx"), "fallback"), "cpp");
        // Fallback path: unknown extension → fallback string.
        assert_eq!(derive_lsp_language_id(&p("a.rs"), "rust"), "rust");
        // No extension → fallback.
        assert_eq!(derive_lsp_language_id(&p("Makefile"), "make"), "make");
    }

    #[test]
    fn marker_matches_literal_and_glob() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("global.json"), "{}").unwrap();
        std::fs::write(dir.path().join("Acme.sln"), "").unwrap();
        std::fs::write(dir.path().join("Nested.csproj"), "").unwrap();
        // Literal name — existing behavior.
        assert!(marker_matches(dir.path(), "global.json"));
        assert!(!marker_matches(dir.path(), "Cargo.toml"));
        // Glob — the new C# markers.
        assert!(marker_matches(dir.path(), "*.sln"));
        assert!(marker_matches(dir.path(), "*.csproj"));
        assert!(!marker_matches(dir.path(), "*.xyz"));
    }

    #[test]
    fn find_root_climbs_to_csproj() {
        // Nested layout: <root>/Acme.csproj + <root>/src/Foo.cs.
        // find_root should climb from src/ up to root when asked for
        // `*.csproj` — the ".sln"/".csproj" case that motivated the
        // glob-marker support.
        let root = tempfile::tempdir().unwrap();
        let src = root.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(root.path().join("Acme.csproj"), "").unwrap();
        let file = src.join("Foo.cs");
        std::fs::write(&file, "").unwrap();
        let found = find_root(
            &file,
            &["*.sln".into(), "*.csproj".into(), "global.json".into()],
            root.path(),
        );
        // Compare canonicalized paths — on macOS tempdir may resolve
        // through /private/…
        assert_eq!(
            std::fs::canonicalize(&found).unwrap(),
            std::fs::canonicalize(root.path()).unwrap(),
        );
    }
}