strop-engine 0.25.0

strop editor engine: documents, grammar dispatch, services, sessions — no terminal
Documentation
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
//! Editor-side LSP event handling and asynchronous navigation. Local
//! and remote documents share the request/server/incarnation/revision
//! ownership; a remote workspace adds the endpoint to every identity —
//! diagnostics, bindings and navigation never alias a remote path onto
//! the local disk (0036 RW8).

use super::{trace, Editor};
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;

use strop_lsp::protocol::ResolvedDiag;
use strop_lsp::registry;
use strop_lsp::{LspEvent, ServerId};
use strop_workspace::{Filesystem, ResourceLocation};

pub(crate) mod attach;
mod lifecycle;
pub(crate) mod remote;
pub(crate) mod state;
#[cfg(test)]
mod tests;

pub struct LspServer {
    pub id: ServerId,
    /// None for replayed servers: identity and replies come from the
    /// injected record/event stream — never a fake client.
    pub client: Option<strop_lsp::Client>,
    pub rx: Receiver<LspEvent>,
    pub ready: bool,
}

impl Editor {
    /// The current document's path identity: a local absolute path, or
    /// the canonical remote file's endpoint-scoped path. Remote
    /// windows must be complete for language services (0036 RW8) —
    /// partial/follow windows refuse, they never pretend.
    pub(super) fn lsp_current_doc_path(&self) -> Option<ResourceLocation> {
        if self.cur().remote_metadata().is_some() && !self.remote_window_complete() {
            return None;
        }
        self.lsp_doc_path(self.current())
    }

    fn lsp_doc_path(&self, document: strop_core::id::DocumentId) -> Option<ResourceLocation> {
        let document = self.docs.get(document)?;
        match &document.source {
            crate::editor::document::DocumentSource::Remote(file) => {
                Some(ResourceLocation::remote(
                    file.file.endpoint().clone(),
                    file.file.path().to_path_buf(),
                ))
            }
            crate::editor::document::DocumentSource::Container { container, path } => {
                Some(ResourceLocation {
                    filesystem: strop_workspace::Filesystem::Container(container.clone()),
                    path: path.clone(),
                })
            }
            _ => document
                .buf
                .path
                .as_ref()
                .map(|path| ResourceLocation::local(self.cwd.join(path))),
        }
    }

    /// A canonical remote file on `endpoint`, when any open document
    /// still owns one — the `with_path` seed for remote navigation.
    pub(super) fn remote_file_for(
        &self,
        endpoint: &strop_workspace::RemoteEndpoint,
    ) -> Option<strop_workspace::RemoteFile> {
        self.docs.iter().find_map(|(_, document)| {
            match &document.source {
                crate::editor::document::DocumentSource::Remote(source) => Some(&source.file),
                _ => None,
            }
            .filter(|file| file.endpoint() == endpoint)
            .cloned()
        })
    }

    pub(crate) fn handle_lsp_event(&mut self, event: LspEvent) {
        trace::services::lsp(&event);
        match event {
            LspEvent::Ready { server, name } => {
                if let Some(owner) = self.lsp_servers.iter_mut().find(|owner| owner.id == server) {
                    owner.ready = true;
                    // Success must not erase a configuration warning
                    // (0033 §2): readiness is reported alongside it.
                    self.message = match self.layer_warning() {
                        Some(warning) => format!("lsp: {name} ready — {warning}"),
                        None => format!("lsp: {name} ready"),
                    };
                }
            }
            LspEvent::Failed { server, name, hint } => {
                if self.lsp_servers.iter().any(|s| s.id == server) {
                    self.lsp_failed(server);
                    self.message = format!("lsp: {name} failed — {hint}");
                } else {
                    trace::services::rejected("lsp", "failure for an unowned server");
                }
            }
            LspEvent::ServerMessage { server, name, text } => {
                if self.lsp_servers.iter().any(|s| s.id == server) {
                    self.message = format!("lsp: {name}: {text}");
                } else {
                    trace::services::rejected("lsp", "message for an unowned server");
                }
            }
            LspEvent::Diagnostics {
                context,
                doc,
                diags,
            } => {
                let valid = self
                    .lsp_state
                    .bindings
                    .get(&context.document)
                    .is_some_and(|b| {
                        b.server == context.server
                            && b.path == doc.path
                            && b.target == doc.filesystem
                            && b.revision == context.revision
                    });
                let Some(doc_buffer) = self
                    .docs
                    .get(context.document)
                    .filter(|d| valid && d.buf.revision() == context.revision)
                else {
                    trace::services::rejected("lsp", "diagnostic owner/revision changed");
                    return;
                };
                let buffer = &doc_buffer.buf;
                let resolved: Vec<ResolvedDiag> = diags
                    .into_iter()
                    .map(|d| d.resolve(context.encoding, buffer))
                    .collect();
                self.diags.insert(
                    context.document,
                    super::diagnostics::DocumentDiagnostics {
                        revision: context.revision,
                        items: resolved,
                    },
                );
            }
            LspEvent::HoverText { context, text } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected(
                        "lsp",
                        "hover request/server/document/revision changed",
                    );
                    return;
                }
                self.hover_card = Some(text);
            }
            LspEvent::Note { context, text } => {
                self.continue_after_format();
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected(
                        "lsp",
                        "navigation request/server/document/revision changed",
                    );
                    return;
                }
                self.message = text;
            }
            LspEvent::Edits { context, edits } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected("lsp", "edit request owner/revision changed");
                    self.continue_after_format();
                    return;
                }
                if edits.is_empty() {
                    self.message = "already formatted".into();
                    self.continue_after_format();
                    return;
                }
                let Some(location) =
                    self.lsp_state
                        .bindings
                        .get(&context.stamp.document)
                        .map(|binding| ResourceLocation {
                            filesystem: binding.target.clone(),
                            path: binding.path.clone(),
                        })
                else {
                    trace::services::rejected("lsp", "edits for an unbound document");
                    self.continue_after_format();
                    return;
                };
                let plan = self.build_change_plan(
                    super::changes::ChangeProducer::Format,
                    vec![(location, edits)],
                    context.encoding,
                );
                self.apply_change_plan(plan);
                self.continue_after_format();
            }
            LspEvent::WorkspaceEdits { context, edits } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected("lsp", "workspace-edit owner/revision changed");
                    return;
                }
                if edits.is_empty() {
                    self.message = format!("lsp: {} made no edits", context.kind.label());
                    return;
                }
                let producer = match context.kind {
                    strop_lsp::RequestKind::Rename => super::changes::ChangeProducer::Rename,
                    _ => super::changes::ChangeProducer::CodeAction,
                };
                let plan = self.build_change_plan(producer, edits, context.encoding);
                self.present_change_plan(plan);
            }
            LspEvent::Symbols { context, symbols } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected("lsp", "symbol owner/revision changed");
                    return;
                }
                if symbols.is_empty() {
                    self.message = "no symbols in this document".into();
                    return;
                }
                use strop_picker::{Item, Payload};
                let items = symbols
                    .into_iter()
                    .filter_map(|symbol| {
                        let line = symbol.location.position.line.get() + 1;
                        let col = symbol.location.position.column.get() + 1;
                        let path = symbol.location.doc.path.clone();
                        let payload = match symbol.location.doc.filesystem {
                            strop_workspace::Filesystem::Local => Payload::Grep {
                                path,
                                line,
                                col,
                                match_len: 1,
                                line_text: String::new(),
                            },
                            strop_workspace::Filesystem::Remote(endpoint) => Payload::Remote {
                                endpoint,
                                path,
                                line,
                                col,
                            },
                            // No container LSP is wired (DC1a); drop with a
                            // trace rather than aliasing a local path.
                            strop_workspace::Filesystem::Container(_) => {
                                trace::services::rejected("lsp", "container symbol dropped");
                                return None;
                            }
                        };
                        let text = if symbol.container.is_empty() {
                            format!("{}  · {} · :{}", symbol.name, symbol.kind, line)
                        } else {
                            format!(
                                "{}  {} · {} · :{}",
                                symbol.name, symbol.container, symbol.kind, line
                            )
                        };
                        Some(Item { text, payload })
                    })
                    .collect();
                self.open_picker(strop_picker::Kind::Symbols);
                if let Some(glue) = self.picker.as_mut() {
                    glue.picker.append(items);
                }
                // Items landed after the initial (empty-catalog)
                // ranking: re-rank or the list renders empty.
                self.request_picker_ranking();
            }
            LspEvent::ActionList { context, actions } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected("lsp", "code-action owner/revision changed");
                    return;
                }
                if actions.is_empty() {
                    self.message = "no code actions here".into();
                    return;
                }
                let items = actions
                    .iter()
                    .enumerate()
                    .map(|(index, action)| strop_picker::Item {
                        text: action.title.clone(),
                        payload: strop_picker::Payload::CodeAction(index),
                    })
                    .collect();
                self.changes.pending_actions = actions;
                self.open_picker(strop_picker::Kind::CodeActions);
                self.changes.pending_encoding = context.encoding;
                if let Some(glue) = self.picker.as_mut() {
                    glue.picker.append(items);
                }
                // Same post-append re-rank as the symbols arm above:
                // the initial ranking ran over an empty catalog.
                self.request_picker_ranking();
            }
            LspEvent::GotoLocation { context, location } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected(
                        "lsp",
                        "navigation request/server/document/revision changed",
                    );
                    return;
                }
                self.jump_to_location(location, context);
            }
            LspEvent::Locations {
                context,
                kind,
                items,
            } => {
                if !self.finish_lsp_reply(&context) {
                    trace::services::rejected("lsp", "location-list owner changed");
                    return;
                }
                match items.len() {
                    0 => {
                        self.message = format!("no {}", kind.label());
                    }
                    1 => {
                        if let Some(location) = items.into_iter().next() {
                            self.jump_to_location(location, context);
                        }
                    }
                    count => {
                        use strop_picker::{Item, Kind, Payload};
                        let items = items
                            .into_iter()
                            .filter_map(|location| {
                                let line = location.position.line.get() + 1;
                                let col = location.position.column.get() + 1;
                                let text = format!("{}:{}:{}", location.doc.label(), line, col);
                                let payload = match location.doc.filesystem {
                                    Filesystem::Local => Payload::Grep {
                                        path: location.doc.path,
                                        line,
                                        col,
                                        match_len: 1,
                                        line_text: String::new(),
                                    },
                                    Filesystem::Remote(endpoint) => Payload::Remote {
                                        endpoint,
                                        path: location.doc.path,
                                        line,
                                        col,
                                    },
                                    // DC1a wires no container LSP, so a container
                                    // location cannot arrive; if one ever does, it
                                    // is dropped with a trace, never aliased to a
                                    // local path.
                                    Filesystem::Container(_) => {
                                        trace::services::rejected(
                                            "lsp",
                                            "location in a container namespace (unwired)",
                                        );
                                        return None;
                                    }
                                };
                                Some(Item { text, payload })
                            })
                            .collect();
                        let mut glue = super::PickerGlue::diagnostics(strop_picker::Picker::new(
                            Kind::Locations,
                            items,
                            false,
                        ));
                        glue.lsp_context = Some(context);
                        self.set_picker(glue);
                        self.message = format!("{count} {}", kind.label());
                    }
                }
            }
        }
    }

    pub(crate) fn jump_to_location(
        &mut self,
        location: strop_lsp::ServerLocation,
        context: strop_lsp::ReplyContext,
    ) {
        if !self.lsp_context_fresh(&context) {
            return;
        }
        let intent = super::io::OpenIntent::LspLocation {
            context,
            position: location.position,
        };
        match location.doc.filesystem {
            Filesystem::Local => self.request_open(location.doc.path, intent),
            Filesystem::Remote(endpoint) => {
                // The target is a file on the replying server's host:
                // resolve it through an open document's canonical seed
                // (`with_path` keeps endpoint + native bytes) — the
                // analogous local path is never opened or probed.
                match self.remote_file_for(&endpoint) {
                    Some(seed) => match seed.with_path(location.doc.path.clone()) {
                        Ok(file) => self
                            .request_target(crate::files::FileTarget::Remote(file.into()), intent),
                        Err(error) => {
                            trace::services::rejected("lsp", "remote navigation target invalid");
                            self.message = format!("lsp: remote target invalid: {error}");
                        }
                    },
                    None => {
                        trace::services::rejected("lsp", "remote navigation endpoint lost");
                        self.message =
                            "lsp: the remote workspace for this target was closed".into();
                    }
                }
            }
            Filesystem::Container(_) => {
                trace::services::rejected("lsp", "navigation into a container namespace (unwired)");
                self.message = "lsp: container locations are not navigable yet".into();
            }
        }
    }

    pub(crate) fn finish_lsp_jump(
        &mut self,
        target: strop_core::id::DocumentId,
        position: strop_lsp::ServerPosition,
        context: strop_lsp::ReplyContext,
    ) {
        if !self.lsp_context_fresh(&context) {
            trace::services::rejected("lsp", "navigation changed while target was loading");
            return;
        }
        let Some(target_doc) = self.docs.get(target) else {
            return;
        };
        let Some(binding) = self.lsp_state.bindings.get(&context.stamp.document) else {
            return;
        };
        let outside = match &target_doc.source {
            // A remote target is outside the workspace when its remote
            // path leaves the binding's remote root — never by
            // comparing against local paths.
            crate::editor::document::DocumentSource::Remote(file) => {
                !file.file.path().starts_with(&binding.root)
            }
            _ => target_doc
                .buf
                .path
                .as_ref()
                .is_some_and(|path| !self.cwd.join(path).starts_with(&binding.root)),
        };
        let line = position
            .line
            .get()
            .min(target_doc.buf.len_lines().saturating_sub(1));
        let text = target_doc
            .buf
            .text()
            .byte_slice(target_doc.buf.line_start(line)..target_doc.buf.line_end(line));
        let col = strop_lsp::to_byte_col_slice(text, position.column, context.encoding).get();
        let head = target_doc
            .buf
            .clamp_boundary(target_doc.buf.line_start(line).saturating_add(col));
        self.push_jump();
        self.lsp_state.navigation = None;
        self.switch_to(target);
        if outside && !self.buf().readonly {
            self.buf_mut().readonly = true;
            self.message = "readonly — outside workspace (:set noro to edit)".into();
        }
        self.set_head(head);
        self.clamp_cursor();
        // A server-originated jump carries its language-service context
        // (0049 §4.1): the replying server keeps answering inside the
        // target. A live binding another navigation established is never
        // switched (0049 §4.5), and namespaces never cross (0049 §4.7).
        let origin = self
            .lsp_state
            .bindings
            .get(&context.stamp.document)
            .map(|b| {
                (
                    b.server,
                    b.root.clone(),
                    b.target.clone(),
                    b.language.clone(),
                )
            });
        if let Some((server, root, origin_target, language)) = origin {
            let target_bound = self.lsp_state.bindings.contains_key(&target);
            let doc = self.lsp_doc_path(target);
            // C and C++ headers are interchangeable for the server that
            // serves both (0049 §4.4: an ambiguous `.h` inherits).
            let language_compatible = doc
                .as_ref()
                .and_then(|doc| lsp_language(&doc.path))
                .is_none_or(|known| {
                    known == language
                        || (matches!(known, "c" | "cpp")
                            && matches!(language.as_str(), "c" | "cpp"))
                });
            let context_free = !self.lsp_state.jump_contexts.contains_key(&target);
            if let (false, true, Some(doc), true) =
                (target_bound, context_free, doc, language_compatible)
            {
                if doc.filesystem == origin_target {
                    // A routing hint, not open state: didOpen follows in
                    // lsp_maybe_attach and becomes the real binding.
                    self.lsp_state.jump_contexts.insert(
                        target,
                        state::JumpContext {
                            server,
                            root,
                            language,
                            target: origin_target,
                        },
                    );
                }
            }
        }
        self.scroll_to_cursor(self.view_rows());
        self.lsp_maybe_attach();
    }

    /// A local picker hit with a live LSP request context: the server
    /// that produced the list owns the target's filesystem.
    pub(crate) fn lsp_jump_from_picker(
        &mut self,
        path: PathBuf,
        line: usize,
        col: usize,
        context: strop_lsp::ReplyContext,
    ) {
        self.jump_to_location(
            strop_lsp::ServerLocation {
                doc: ResourceLocation::local(path),
                position: strop_lsp::ServerPosition {
                    line: strop_core::id::LineIndex::new(line.saturating_sub(1)),
                    column: strop_lsp::ServerColumn::new(col.saturating_sub(1)),
                },
            },
            context,
        );
    }

    /// A remote picker hit (locations or diagnostics): re-parse the
    /// endpoint and route through the endpoint's file identity — with
    /// a live request context through the freshness-checked navigation
    /// path (server columns), without one as a direct remote open at a
    /// byte column. The analogous local path is never touched.
    pub(crate) fn lsp_open_remote_hit(
        &mut self,
        endpoint: &strop_workspace::RemoteEndpoint,
        path: &Path,
        line: usize,
        col: usize,
        context: Option<strop_lsp::ReplyContext>,
    ) {
        if let Some(context) = context {
            self.jump_to_location(
                strop_lsp::ServerLocation {
                    doc: ResourceLocation::remote(endpoint.clone(), path.to_owned()),
                    position: strop_lsp::ServerPosition {
                        line: strop_core::id::LineIndex::new(line.saturating_sub(1)),
                        column: strop_lsp::ServerColumn::new(col.saturating_sub(1)),
                    },
                },
                context,
            );
        } else if let Some(seed) = self.remote_file_for(endpoint) {
            // Context-free remote hits (symbol rows) record too —
            // ctrl-o after the jump returns (0047 §1).
            self.push_jump();
            match seed.with_path(path.to_owned()) {
                Ok(file) => self.request_target(
                    crate::files::FileTarget::Remote(file.into()),
                    super::io::OpenIntent::Grep {
                        line: strop_core::id::LineIndex::new(line.saturating_sub(1)),
                        column: strop_core::id::ByteColumn::new(col.saturating_sub(1)),
                    },
                ),
                Err(error) => self.message = format!("lsp remote location: {error}"),
            }
        } else {
            self.message = "lsp: the remote workspace for this hit was closed".into();
        }
    }
    pub(crate) fn lsp_locations(&mut self, kind: strop_lsp::LocKind) {
        self.lsp_request(strop_lsp::RequestKind::Locations(kind));
    }
    pub(crate) fn lsp_hover(&mut self) {
        self.lsp_request(strop_lsp::RequestKind::Hover);
    }
    pub(crate) fn lsp_goto_definition(&mut self) {
        self.lsp_request(strop_lsp::RequestKind::Goto);
    }
    pub(crate) fn lsp_switch_source_header(&mut self) {
        self.lsp_request(strop_lsp::RequestKind::SwitchHeader);
    }
    /// `:format` — server formatting through a change plan (0043).
    /// auto_format admission: a binding with a live, formatting-capable
    /// client. Anything less saves without formatting.
    pub(crate) fn lsp_format_available(&self) -> bool {
        let Some(binding) = self.lsp_state.bindings.get(&self.current()) else {
            return false;
        };
        self.lsp_live_client(binding.server)
            .is_some_and(|client| client.caps().formatting())
    }

    /// The format reply concluded: run the save that was waiting on it
    /// (config auto_format). Never fires twice — the slot is taken.
    pub(crate) fn continue_after_format(&mut self) {
        let Some(state::AfterFormat::Save { document, close }) = self.lsp_state.after_format.take()
        else {
            return;
        };
        self.request_save_document(document, None, false, close);
    }

    pub(crate) fn lsp_format(&mut self) {
        self.lsp_change_request(strop_lsp::RequestKind::Format, None);
    }
    /// `:rename <new>` — workspace rename through a change plan.
    pub(crate) fn lsp_rename(&mut self, new_name: &str) {
        self.lsp_change_request(strop_lsp::RequestKind::Rename, Some(new_name.to_string()));
    }
    /// `Space s` — the current document's symbols as a picker (0047 §1).
    pub(crate) fn lsp_document_symbols(&mut self) {
        self.lsp_request(strop_lsp::RequestKind::DocumentSymbols);
    }
    /// `Space a` — code actions at the cursor, offered as a picker.
    pub(crate) fn lsp_code_actions(&mut self) {
        self.lsp_change_request(strop_lsp::RequestKind::CodeAction, None);
    }

    pub(crate) fn jump_diagnostic(&mut self, forward: bool) {
        let Some(diags) = self
            .diags_for(self.current())
            .filter(|diags| !diags.is_empty())
        else {
            self.message = "no diagnostics".into();
            return;
        };
        let cur = self.buf().line_of(self.head());
        let col = self.buf().col_of(self.head());
        let target = if forward {
            diags
                .iter()
                .find(|d| d.line.get() > cur || (d.line.get() == cur && d.col.get() > col))
                .or(diags.first())
        } else {
            diags
                .iter()
                .rev()
                .find(|d| d.line.get() < cur || (d.line.get() == cur && d.col.get() < col))
                .or(diags.last())
        };
        let Some(d) = target else {
            return;
        };
        let (line, col, msg) = (d.line.get(), d.col.get(), d.message.clone());
        let start = self
            .buf()
            .line_start(line.min(self.buf().len_lines().saturating_sub(1)));
        self.set_head(self.buf().clamp_boundary(start + col));
        self.clamp_cursor();
        self.scroll_to_cursor(self.view_rows());
        self.message = msg;
    }

    pub(crate) fn open_diagnostics_picker(&mut self) {
        use strop_picker::{Item, Kind, Payload};
        // Deterministic row order across hash seeds (R11).
        let mut by_doc: Vec<_> = self
            .diags
            .keys()
            .filter_map(|&id| Some((self.lsp_doc_path(id)?, self.diags_for(id)?)))
            .collect();
        by_doc.sort_by(|a, b| {
            (a.0.filesystem.label(), &a.0.path).cmp(&(b.0.filesystem.label(), &b.0.path))
        });
        let mut items: Vec<Item> = Vec::new();
        for (doc, diags) in by_doc {
            for d in diags {
                let line = d.line.get() + 1;
                let col = d.col.get() + 1;
                match &doc.filesystem {
                    Filesystem::Local => items.push(Item {
                        text: format!(
                            "{}:{} {} {}",
                            doc.path.display(),
                            line,
                            d.severity_char(),
                            d.message
                        ),
                        payload: Payload::Grep {
                            path: doc.path.clone(),
                            line,
                            col,
                            match_len: 1,
                            line_text: d.message.clone(),
                        },
                    }),
                    // Remote diagnostics carry their endpoint: the
                    // preview stays local-clean and acceptance opens
                    // the remote target (0036).
                    Filesystem::Remote(endpoint) => items.push(Item {
                        text: format!(
                            "{}{}:{} {} {}",
                            endpoint,
                            doc.path.display(),
                            line,
                            d.severity_char(),
                            d.message
                        ),
                        payload: Payload::Remote {
                            endpoint: endpoint.clone(),
                            path: doc.path.clone(),
                            line,
                            col,
                        },
                    }),
                    // Unreachable in DC1a (no container bindings); if one
                    // ever arrives it is dropped with a trace, never
                    // aliased to a local path.
                    Filesystem::Container(_) => {
                        trace::services::rejected(
                            "lsp",
                            "diagnostic in a container namespace (unwired)",
                        );
                    }
                }
            }
        }
        if items.is_empty() {
            self.message = "no diagnostics".into();
            return;
        }
        self.set_picker(super::PickerGlue::diagnostics(strop_picker::Picker::new(
            Kind::Diagnostics,
            items,
            false,
        )));
    }

    pub(crate) fn lsp_goto_definition_pub(&mut self) {
        self.lsp_goto_definition();
    }
    pub(crate) fn lsp_switch_source_header_pub(&mut self) {
        self.lsp_switch_source_header();
    }
    pub(crate) fn lsp_hover_pub(&mut self) {
        self.lsp_hover();
    }
    pub fn lsp_code_actions_pub(&mut self) {
        self.lsp_code_actions();
    }
    pub fn lsp_document_symbols_pub(&mut self) {
        self.lsp_document_symbols();
    }
    pub fn lsp_locations_pub(&mut self, kind: strop_lsp::LocKind) {
        self.lsp_locations(kind);
    }
    pub fn jump_diagnostic_pub(&mut self, forward: bool) {
        self.jump_diagnostic(forward);
    }
}

/// The LSP language for a path, from the embedded extension table —
/// pure, in-memory, safe on every keystroke.
pub(crate) fn lsp_language(path: &Path) -> Option<&'static str> {
    let ext = path.extension()?.to_str()?;
    registry::language_for_extension_name(ext)
}

/// The didOpen languageId sent to servers.
pub(crate) fn lang_id(path: &Path) -> &'static str {
    match path.extension().and_then(|e| e.to_str()) {
        Some("rs") => "rust",
        Some("py") | Some("pyi") => "python",
        Some("go") => "go",
        Some("js") | Some("jsx") | Some("mjs") | Some("cjs") => "javascript",
        Some("ts") => "typescript",
        Some("tsx") => "typescriptreact",
        Some("json") => "json",
        Some("sh") | Some("bash") => "shellscript",
        Some("c") | Some("h") => "c",
        Some("cpp") | Some("cc") | Some("cxx") | Some("hpp") | Some("hh") => "cpp",
        _ => "plaintext",
    }
}