vorto 0.14.0

A Vim-flavored modal terminal editor with batteries included: tree-sitter, LSP, fuzzy pickers, vim-surround, multi-cursor, and optional Copilot.
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
//! LSP request side: methods that initiate an LSP round trip on
//! behalf of the user (jump, references, hover, code action, rename,
//! completion) plus the active completion popup's user-input flow
//! (filter / accept / cancel) and the periodic `didChange` sync.
//!
//! The matching response handlers — `apply_*_outcome` and
//! `handle_lsp_event` — live in [`super::lsp_apply`].

use anyhow::Result;

use crate::editor::Cursor;
use crate::lsp::{self, CodeAction, Diagnostic, Position, Range, TextEdit};

use super::completion::{identifier_prefix_start, prefix_slice};
use super::signature::SignatureTrigger;
use super::{App, Toast, root_cause};
use crate::vlog;

impl App {
    /// Send a request whose result is a list of `Location`s and whose
    /// expected handling is "jump to the first one". Covers
    /// `definition`, `declaration`, and `implementation` — all three
    /// answer with the same shape.
    pub(super) fn lsp_jump(&mut self, method: &str, label: &'static str) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        if let Err(e) = self.lsp.request_jump(method, label, self.editor.cursor) {
            self.push_toast(Toast::error(format!("lsp {}: {}", method, root_cause(&e))));
        }
    }

    pub(super) fn lsp_find_references(&mut self) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        if let Err(e) = self.lsp.request_references(self.editor.cursor) {
            self.push_toast(Toast::error(format!("lsp references: {}", root_cause(&e))));
        }
    }

    pub(super) fn open_rename_prompt(&mut self) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        self.prompt.open_rename();
    }

    /// Trigger a `textDocument/completion` request at the current
    /// cursor. The "prefix start" — where the identifier under the
    /// cursor begins — is snapshotted now so the response can be
    /// matched against the live cursor when it arrives.
    ///
    /// Completion fires from inside `handle_insert_key`, **before** the
    /// main loop's post-keypress `sync_buffer_if_dirty`. Without an
    /// up-front sync the server would resolve the cursor position
    /// against a stale buffer and either return nothing or the wrong
    /// items, so we flush pending edits here first.
    pub(super) fn lsp_completion(&mut self) {
        self.lsp_completion_inner(None);
    }

    /// Like `lsp_completion`, but tags the request with the trigger
    /// character that fired it. rust-analyzer (and others) special-case
    /// path completions when they see `triggerKind: TriggerCharacter` +
    /// `triggerCharacter: ":"`, so we need to forward the char that
    /// actually caused the auto-trigger.
    pub(super) fn lsp_completion_triggered(&mut self, trigger: char) {
        self.lsp_completion_inner(Some(trigger));
    }

    fn lsp_completion_inner(&mut self, trigger: Option<char>) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        self.sync_buffer_if_dirty();
        let cursor = self.editor.cursor;
        let line = &self.active_doc().lines[cursor.row];
        let start_col = identifier_prefix_start(line, cursor.col);
        let prefix_start = Cursor {
            row: cursor.row,
            col: start_col,
        };
        if let Err(e) = self.lsp.request_completion(cursor, prefix_start, trigger) {
            self.push_toast(Toast::error(format!("lsp completion: {}", root_cause(&e))));
        }
    }

    /// Re-filter the open completion popup against the live prefix.
    /// Called from `handle_insert_key` after every insert / backspace.
    /// Closes the popup when the cursor has left the row or backspaced
    /// past `prefix_start`.
    pub(super) fn update_completion_filter(&mut self) {
        let Some(state) = self.completion.as_mut() else {
            return;
        };
        let cursor = self.editor.cursor;
        if cursor.row != state.prefix_start.row || cursor.col < state.prefix_start.col {
            self.completion = None;
            return;
        }
        let doc = self
            .documents
            .get(&self.editor.doc)
            .expect("active doc present");
        let line = &doc.lines[cursor.row];
        let prefix = prefix_slice(line, state.prefix_start.col, cursor.col);
        // Close once the user has backspaced below the popup's
        // open-time threshold (2 for ident auto-trigger, 0 for
        // trigger-character popups). Without this an ident-triggered
        // popup keeps surfacing the whole identifier table at 0–1
        // chars, which is just noise.
        if prefix.chars().count() < state.min_prefix_len {
            self.completion = None;
            return;
        }
        state.refilter(&prefix);
        if state.is_empty() {
            self.completion = None;
        }
    }

    /// Apply the currently-selected completion. The primary replacement
    /// target is always `[prefix_start..cursor]` (in column terms on the
    /// prefix-start row), regardless of what range the server attached
    /// to its `textEdit` — the server's range was computed against the
    /// buffer state at request time, and the user may have kept typing
    /// since (auto-trigger fires the request as you type), so trusting
    /// the server's range would leave the post-request keystrokes
    /// stranded after the inserted completion. The text to insert is
    /// picked in spec order: `textEdit.newText` → `insertText` → `label`.
    ///
    /// `additionalTextEdits` (auto-import / `use` insertions) are
    /// applied in the same batch via `apply_text_edits`. The post-edit
    /// cursor position is adjusted for any line-count shift caused by
    /// additional edits that sit above the cursor row.
    ///
    /// When the item arrived without `additionalTextEdits` we follow up
    /// with `completionItem/resolve`. Servers that opt into the
    /// `resolveSupport` contract (rust-analyzer, JDT.LS, …) defer the
    /// import-line computation to that round trip so they don't have
    /// to do it for every candidate in the popup; the result is
    /// applied asynchronously by `apply_completion_resolved_outcome`.
    pub(super) fn accept_completion(&mut self) {
        let Some(state) = self.completion.take() else {
            return;
        };
        let Some(item) = state.current().cloned() else {
            return;
        };
        let needs_resolve = item.additional_text_edits.is_empty();
        let raw = item.raw.clone();
        let source = item.source.clone();
        let base = item
            .text_edit
            .as_ref()
            .map(|te| te.new_text.clone())
            .or_else(|| item.insert_text.clone())
            .unwrap_or_else(|| item.label.clone());

        // Auto-append `()` for callable kinds (Method=2, Function=3,
        // Constructor=4) when the server's replacement is a bare name —
        // single-line and without an existing paren. Snippet support is
        // disabled at handshake time, so callables come back as the raw
        // identifier; tacking on `()` saves the user a keystroke and
        // matches what other editors do. The cursor lands between the
        // parens so the user can start typing args immediately.
        let kind_is_callable = matches!(item.kind, 2..=4);
        let appended_call =
            kind_is_callable && !base.contains('(') && !base.contains('\n') && !base.is_empty();
        let replacement = if appended_call {
            format!("{}()", base)
        } else {
            base
        };

        ed_op!(self, snapshot());

        let prefix_start = state.prefix_start;
        let cursor = self.editor.cursor;
        // Honor the server's `textEdit` start column when it sits
        // before our notion of the prefix start — TypeScript and other
        // servers triggered on `.` return items whose range covers the
        // trigger char itself, with `newText` already including the
        // `.`. Replacing only `[prefix_start..cursor]` (which starts
        // *after* the dot) would leave the dot in place and prepend
        // another from `newText`, producing `..foo`. The end is always
        // the live cursor — the original concern about trusting the
        // server's range was about losing post-request keystrokes
        // typed after `range.end`, which only affects the END side.
        let replace_start_col = item
            .text_edit
            .as_ref()
            .filter(|te| te.range.start.line as usize == prefix_start.row)
            .map(|te| (te.range.start.character as usize).min(prefix_start.col))
            .unwrap_or(prefix_start.col);
        let primary = TextEdit {
            range: Range {
                start: Position {
                    line: prefix_start.row as u32,
                    character: replace_start_col as u32,
                },
                end: Position {
                    line: cursor.row as u32,
                    character: cursor.col as u32,
                },
            },
            new_text: replacement.clone(),
        };

        // Row shift contributed by auto-import edits that sit above the
        // cursor row — those move the primary edit's landing row down
        // (or up, on deletion). Same-row additional edits are vanishingly
        // rare for imports and would also require column tracking, so
        // we ignore them for the cursor-placement math.
        let row_shift: i64 = item
            .additional_text_edits
            .iter()
            .filter(|e| (e.range.start.line as usize) < prefix_start.row)
            .map(|e| {
                let added = e.new_text.matches('\n').count() as i64;
                let removed = (e.range.end.line - e.range.start.line) as i64;
                added - removed
            })
            .sum();

        let mut all_edits = item.additional_text_edits.clone();
        all_edits.push(primary);
        let doc = self.active_doc_mut();
        let mut lines = std::mem::take(&mut doc.lines);
        lsp::apply_text_edits(&mut lines, all_edits);
        doc.lines = lines;

        let replacement_newlines = replacement.matches('\n').count();
        let final_row =
            (prefix_start.row as i64 + row_shift + replacement_newlines as i64).max(0) as usize;
        let final_col = if replacement_newlines == 0 {
            let end = replace_start_col + replacement.chars().count();
            // When we auto-appended `()`, drop the cursor between the
            // parens so the user can start typing args.
            if appended_call { end - 1 } else { end }
        } else {
            // Multi-line replacement: cursor lands at the end of the
            // last inserted line.
            replacement
                .rsplit('\n')
                .next()
                .unwrap_or("")
                .chars()
                .count()
        };
        let last = self.active_doc().lines.len().saturating_sub(1);
        self.editor.cursor.row = final_row.min(last);
        self.editor.cursor.col = final_col;
        let doc = self.active_doc_mut();
        doc.bump_version();
        doc.dirty = true;

        // Best-effort follow-up. Servers that don't support resolve
        // either echo the item back unchanged or surface an error — the
        // coordinator drops both into an empty-edit outcome, so the user
        // sees the primary insertion regardless.
        if needs_resolve && self.lsp.has_lsp() {
            // `None` index: this resolve is for fetching auto-import
            // edits after the user already accepted the item; the popup
            // is already closed and there's no item slot to refresh.
            let _ = self.lsp.request_completion_resolve(raw, &source, None);
        }

        // When we auto-appended `()` for a callable, the cursor now
        // sits between the parens — the natural place to start typing
        // arguments. The `(` was inserted by us, not the user, so the
        // trigger-character path in insert mode won't fire; we have to
        // request signature help explicitly here.
        if appended_call {
            self.lsp_signature_help(SignatureTrigger::Invoked);
        }
    }

    pub(super) fn cancel_completion(&mut self) {
        self.completion = None;
    }

    /// Fire `textDocument/signatureHelp` at the current cursor.
    /// `trigger` distinguishes a fresh open (`TriggerCharacter` / first
    /// `Invoked`) from a per-keystroke refresh (`ContentChange`) so the
    /// server can branch its bookkeeping.
    ///
    /// We flush pending edits first — the cursor position the server
    /// resolves against has to match the live buffer, same reason
    /// `lsp_completion` does the up-front sync.
    pub(super) fn lsp_signature_help(&mut self, trigger: SignatureTrigger) {
        if !self.lsp.has_lsp() {
            return;
        }
        self.sync_buffer_if_dirty();
        let cursor = self.editor.cursor;
        let active = self.signature.as_ref().map(|s| &s.help);
        if let Err(e) = self.lsp.request_signature_help(cursor, trigger, active) {
            self.push_toast(Toast::error(format!(
                "lsp signatureHelp: {}",
                root_cause(&e)
            )));
        }
    }

    pub(super) fn cancel_signature_help(&mut self) {
        self.signature = None;
    }

    /// Issue `completionItem/resolve` for the currently-selected popup
    /// row when we haven't already resolved it. Lets us pull deferred
    /// `detail` / `documentation` into the popup while the user is
    /// still scrolling — without this, servers that defer those fields
    /// (typescript-language-server, pyright, rust-analyzer with
    /// `resolveSupport`) leave the right column blank until acceptance.
    /// No-op when the popup is closed, the item is already resolved,
    /// or no LSP client is attached.
    pub(super) fn resolve_current_completion_for_detail(&mut self) {
        let Some(state) = self.completion.as_ref() else {
            return;
        };
        // Preview-mode popups don't fire resolve — there's no row the
        // user has committed to, so spending a round-trip on `selected`
        // (which is the placeholder default, not a chosen item) would
        // be wasted both at the server and in the side detail popup
        // (which is hidden until selecting mode).
        if !state.selecting {
            return;
        }
        let Some(idx) = state.current_index() else {
            return;
        };
        if state.resolved.get(idx).copied().unwrap_or(true) {
            return;
        }
        let Some(item) = state.items.get(idx) else {
            return;
        };
        if !self.lsp.has_lsp() {
            return;
        }
        let raw = item.raw.clone();
        let source = item.source.clone();
        let _ = self.lsp.request_completion_resolve(raw, &source, Some(idx));
    }

    pub(super) fn lsp_hover(&mut self) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        if let Err(e) = self.lsp.request_hover(self.editor.cursor) {
            self.push_toast(Toast::error(format!("lsp hover: {}", root_cause(&e))));
        }
    }

    /// Build and open the `:lsp` status modal. `all=false` scopes the
    /// listing to the active buffer's language; `all=true` lists every
    /// language with an LSP configured. Each row marks the server
    /// running (with pid + open-file count) or stopped.
    pub(super) fn open_lsp_status(&mut self, all: bool) {
        use crate::app::lsp_coordinator::RunningLspInfo;
        use std::collections::HashMap;
        let running: HashMap<String, RunningLspInfo> = self
            .lsp
            .running_clients()
            .into_iter()
            .map(|info| (info.client_key.clone(), info))
            .collect();
        // Default scope: only the active buffer's language. Falls
        // through to the empty-list message below when the buffer has
        // no path / unknown extension / no LSP configured. `:lsp all`
        // bypasses the filter.
        let buffer_lang = self
            .active_doc()
            .path
            .as_deref()
            .and_then(|p| self.config.languages.by_path(p));
        let mut langs: Vec<&crate::config::Language> = if all {
            self.config
                .languages
                .iter()
                .filter(|l| !l.lsp.is_empty())
                .collect()
        } else {
            buffer_lang
                .filter(|l| !l.lsp.is_empty())
                .into_iter()
                .collect()
        };
        langs.sort_by(|a, b| a.name.cmp(&b.name));
        let mut content = String::new();
        if langs.is_empty() {
            if all {
                content.push_str("(no languages have an LSP configured)\n");
            } else {
                match buffer_lang {
                    None => {
                        content.push_str("(no language detected for this buffer — try :lsp all)\n")
                    }
                    Some(l) => content
                        .push_str(&format!("({}: no LSP configured — try :lsp all)\n", l.name)),
                }
            }
        }
        for lang in langs {
            content.push_str(&format!("\n{}\n", lang.name));
            for cfg in &lang.lsp {
                let key = format!("{}::{}", lang.name, cfg.name);
                if let Some(info) = running.get(&key) {
                    content.push_str(&format!(
                        "  ● {:<28} running  pid {}  {} file{}  ({})\n",
                        cfg.name,
                        info.pid,
                        info.open_count,
                        if info.open_count == 1 { "" } else { "s" },
                        info.language_id,
                    ));
                    content.push_str(&format!("      root: {}\n", info.root_uri));
                } else {
                    content.push_str(&format!(
                        "  ○ {:<28} stopped  ({})\n",
                        cfg.name, cfg.command,
                    ));
                }
            }
        }
        // Runtime clients whose key doesn't match any configured entry
        // (server name changed in config since spawn, etc). Only
        // surfaced in the `:lsp all` view — for the per-buffer view
        // they'd just be noise unrelated to the current language.
        let mut orphans: Vec<&RunningLspInfo> = running
            .values()
            .filter(|info| {
                let Some((lang, server)) = info.client_key.split_once("::") else {
                    return true;
                };
                !self
                    .config
                    .languages
                    .iter()
                    .filter(|l| l.name == lang)
                    .any(|l| l.lsp.iter().any(|c| c.name == server))
            })
            .collect();
        orphans.sort_by(|a, b| a.client_key.cmp(&b.client_key));
        if all && !orphans.is_empty() {
            content.push_str("\norphan (running, not in current config)\n");
            for info in orphans {
                content.push_str(&format!(
                    "  ● {:<28} pid {}  {} file{}  ({})\n",
                    info.client_key,
                    info.pid,
                    info.open_count,
                    if info.open_count == 1 { "" } else { "s" },
                    info.language_id,
                ));
                content.push_str(&format!("      root: {}\n", info.root_uri));
            }
        }

        // Copilot lives outside the per-language LSP table (it's a
        // global completion provider), so surface it as its own
        // section. Always shown — it's useful regardless of the
        // active buffer's language.
        content.push_str("\ncopilot\n");
        match &self.copilot {
            Some(client) => {
                let auth = match &self.copilot_auth {
                    crate::app::CopilotAuthState::Unknown => "checking…".to_string(),
                    crate::app::CopilotAuthState::SignedIn { user } => format!(
                        "signed in as {}",
                        user.as_deref().unwrap_or("(unknown user)")
                    ),
                    crate::app::CopilotAuthState::NotSignedIn => {
                        "not signed in (:copilot signin)".to_string()
                    }
                    crate::app::CopilotAuthState::NotAuthorized { reason } => format!(
                        "not authorized ({})",
                        reason.as_deref().unwrap_or("no entitlement")
                    ),
                };
                let open_count = client.open_count();
                content.push_str(&format!(
                    "  ● {:<28} running  pid {}  {} file{}  ({})\n",
                    "copilot-language-server",
                    client.pid(),
                    open_count,
                    if open_count == 1 { "" } else { "s" },
                    auth,
                ));
            }
            None => {
                content.push_str(&format!(
                    "  ○ {:<28} stopped  (copilot-language-server)\n",
                    "copilot-language-server",
                ));
            }
        }

        self.prompt.open_lsp_status(content);
    }

    pub(super) fn lsp_code_action(&mut self) {
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        let cursor = self.editor.cursor;
        // Diagnostics borrow ends before the mutable `request_code_action`
        // call, but the borrow checker can't prove that across `self`, so
        // collect into an owned Vec first.
        let diagnostics: Vec<Diagnostic> = self.lsp.current_diagnostics().unwrap_or_default();
        if let Err(e) = self.lsp.request_code_action(cursor, &diagnostics) {
            self.push_toast(Toast::error(format!("lsp codeAction: {}", root_cause(&e))));
        }
    }

    pub(super) fn submit_code_action(&mut self, action: CodeAction) {
        // Already-resolved actions go straight through. Otherwise round
        // trip via `codeAction/resolve` so servers (rust-analyzer in
        // particular) can fill in the heavy `edit` lazily.
        if action.edit.is_some() {
            self.apply_code_action(action);
            return;
        }
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        let source = action.source.clone();
        if let Err(e) = self.lsp.request_code_action_resolve(action.raw, &source) {
            self.push_toast(Toast::error(format!(
                "lsp codeAction/resolve: {}",
                root_cause(&e)
            )));
        }
    }

    pub(super) fn submit_rename(&mut self, new_name: String) {
        if new_name.is_empty() {
            self.push_toast(Toast::error("rename: empty name"));
            return;
        }
        if !self.lsp.has_lsp() {
            self.push_toast(Toast::error("no LSP for this buffer"));
            return;
        }
        if let Err(e) = self.lsp.request_rename(new_name, self.editor.cursor) {
            self.push_toast(Toast::error(format!("lsp rename: {}", root_cause(&e))));
        }
    }

    /// Sync the active buffer to every language server / Copilot that
    /// hasn't seen the latest content. Called from the main loop after
    /// every key handled; pays for the `lines.join` snapshot only when
    /// at least one consumer needs it.
    pub fn sync_buffer_if_dirty(&mut self) {
        let needs_lsp = self.active_doc().version != self.lsp.last_synced_version();
        let needs_copilot = self.copilot_needs_sync();
        if !needs_lsp && !needs_copilot {
            return;
        }
        let text = self.active_doc().lines.join("\n");
        if needs_lsp {
            self.lsp.set_last_synced_version(self.active_doc().version);
            if let Err(e) = self.lsp.did_change(&text) {
                // Background sync after every keystroke — toasting on
                // each failure would flood the screen. Log only; if the
                // client is wedged, subsequent user-initiated requests
                // will surface their own errors.
                vlog!("lsp didChange failed: {:#}", e);
            }
        }
        if needs_copilot {
            self.sync_buffer_to_copilot(&text);
        }
    }
}

impl App {
    /// Open `loc.uri` (switching buffers if needed) and place the cursor
    /// at `loc.range.start`. Used both by jump-style outcomes (incoming)
    /// and by user-driven location-picker selections — kept here as a
    /// `pub(super)` helper so both sides can reach it without
    /// duplicating the open-then-position dance.
    pub(super) fn jump_to_location(&mut self, loc: &crate::lsp::Location) -> Result<()> {
        let path = lsp::uri_to_path(&loc.uri)
            .ok_or_else(|| anyhow::anyhow!("unsupported uri scheme: {}", loc.uri))?;
        // Record where we're leaving from so `Ctrl-O` can return — covers
        // `gd`/`gr`/picker jumps. A no-op while navigating the jumplist.
        self.record_jump();
        let need_open = match &self.active_doc().path {
            Some(p) => p.canonicalize().ok() != path.canonicalize().ok(),
            None => true,
        };
        if need_open {
            self.open_path(&path)?;
        }
        let row = loc.range.start.line as usize;
        let col = loc.range.start.character as usize;
        let last = self.active_doc().lines.len().saturating_sub(1);
        self.editor.cursor.row = row.min(last);
        self.editor.cursor.col = col;
        ed_op_ref!(self, clamp_col(false));
        Ok(())
    }
}