vorto 0.12.1

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
//! Minimal LSP client.
//!
//! One [`LspClient`] per language, spawned lazily the first time a buffer
//! of that language is opened. The client owns the server subprocess, a
//! reader thread that parses incoming JSON-RPC messages, and bookkeeping
//! for tracked documents.
//!
//! Threading model:
//! - The main thread writes requests/notifications to the server's stdin
//!   synchronously (it's a buffered pipe — writes are cheap).
//! - A per-client reader thread blocks on stdout, parses framed messages,
//!   and forwards interesting ones to the App via an mpsc channel.
//!
//! Implemented: `initialize` handshake, full-document sync
//! (`didOpen`/`didChange`/`didSave`/`didClose`), `publishDiagnostics`,
//! goto-definition / declaration / implementation, references, rename,
//! code actions (+ `codeAction/resolve`), hover, completion (+
//! `completionItem/resolve`), and signature help. Inlay hints remain
//! out of scope.
//!
//! Submodules:
//! - [`types`] — normalised wire-protocol structs/enums.
//! - [`codec`] — JSON-RPC framing + the per-client reader thread.
//! - [`parse`] — pure parsers from `serde_json::Value` into [`types`].
//! - [`uri`] — `file://` ↔ `Path` conversion.
//! - [`root`] — workspace-root discovery.
//! - [`edits`] — applying [`TextEdit`]s to an in-memory line buffer.

use std::collections::HashMap;
use std::io::BufReader;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};

use crate::config::LspConfig;
use crate::vlog;

pub(crate) mod codec;
mod edits;
mod parse;
mod root;
mod types;
mod uri;

pub use edits::apply_text_edits;
pub use parse::{
    parse_code_action, parse_code_actions, parse_completion, parse_completion_resolve, parse_hover,
    parse_locations, parse_signature_help, parse_workspace_edit,
};
pub use root::discover_root;
pub use types::{
    CodeAction, CompletionItem, Diagnostic, Hover, Location, LspEvent, ParameterLabel, Position,
    Range, Severity, SignatureHelp, SignatureInformation, TextEdit, WorkspaceEdit,
};
pub use uri::{path_to_uri, uri_to_path};

use codec::{notification, read_message, reader_loop, request, write_framed};

pub struct LspClient {
    /// The server subprocess. `std::process::Child` has no `Drop` of its
    /// own, so without our [`Drop`] impl below the server would outlive
    /// the editor (closing the pipes alone isn't a guaranteed signal).
    child: Child,
    /// Shared with the reader thread so it can reply to server-to-client
    /// requests (`client/registerCapability`, `workspace/configuration`,
    /// `window/workDoneProgress/create`, …) without round-tripping
    /// through the App.
    stdin: Arc<Mutex<ChildStdin>>,
    next_id: u64,
    /// Documents we've sent `didOpen` for — `uri → version`. The version
    /// is bumped on every `didChange` so we don't need to track it on
    /// the Buffer side.
    docs: HashMap<String, i32>,
    /// `languageId` to send in `didOpen`.
    language_id: String,
    /// Root URI passed to `initialize`. Stored so the `:lsp` status
    /// modal can show it; the protocol itself doesn't read it back.
    root_uri: String,
    /// `completionProvider.triggerCharacters` from the server's
    /// `initialize` response. Drives insert-mode auto-trigger so that
    /// e.g. rust-analyzer's `:` (`::` paths) and TypeScript's `<` fire
    /// the popup without us hardcoding language-specific punctuation.
    completion_trigger_characters: Vec<String>,
    /// `signatureHelpProvider.triggerCharacters` from the server's
    /// `initialize` response — punctuation that should fire a
    /// `textDocument/signatureHelp` request from a fresh state. `(` and
    /// `,` are the common case across most servers but it's the
    /// server's call. The matching retrigger set isn't tracked
    /// separately: once the popup is open we re-request on every
    /// keystroke regardless of character, so the distinction doesn't
    /// pay rent.
    signature_help_trigger_characters: Vec<String>,
    /// Side-channel for `request_blocking`. When a caller wants to block
    /// on a specific response (format-on-save is the only consumer for
    /// now), it registers `id → Sender` here and the reader thread
    /// forwards the matching response through it instead of emitting
    /// the usual async `LspEvent::Response`. Keeps blocking save flows
    /// from racing the event loop.
    blocking_pending: Arc<Mutex<HashMap<u64, mpsc::Sender<BlockingReply>>>>,
}

/// What the reader thread hands back to a `request_blocking` waiter.
pub(crate) enum BlockingReply {
    Ok(Value),
    Err(String),
}

/// Shared state between an [`LspClient`] and its reader thread for
/// blocking-response routing. Aliased so the type name doesn't bleed
/// across function signatures.
pub(crate) type BlockingPending = Arc<Mutex<HashMap<u64, mpsc::Sender<BlockingReply>>>>;

impl LspClient {
    /// Spawn the server, run the initialize handshake synchronously, then
    /// detach a reader thread that forwards future messages to `tx`.
    /// `client_key` is the per-server identifier the reader thread will
    /// stamp on every outbound [`LspEvent`] so the coordinator can route
    /// responses back to the right pending request when multiple
    /// servers share a buffer.
    pub fn spawn(
        client_key: &str,
        lang_name: &str,
        spec: &LspConfig,
        root_uri: &str,
        emit: Box<dyn Fn(LspEvent) + Send + 'static>,
    ) -> Result<Self> {
        let mut child = Command::new(&spec.command)
            .args(&spec.args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .with_context(|| format!("spawning LSP server `{}`", spec.command))?;

        let stdin_raw = child.stdin.take().ok_or_else(|| anyhow!("no stdin"))?;
        let stdout = child.stdout.take().ok_or_else(|| anyhow!("no stdout"))?;
        let mut reader = BufReader::new(stdout);
        let stdin = Arc::new(Mutex::new(stdin_raw));

        let workspace_name = root_uri
            .rsplit('/')
            .find(|s| !s.is_empty())
            .unwrap_or("workspace")
            .to_string();
        let init_id: u64 = 1;
        let init_params = json!({
            "processId": std::process::id(),
            "rootUri": root_uri,
            "workspaceFolders": [{ "uri": root_uri, "name": workspace_name }],
            "capabilities": {
                "workspace": {
                    "configuration": false,
                    "workspaceFolders": true,
                    "didChangeConfiguration": { "dynamicRegistration": false },
                    "didChangeWatchedFiles": { "dynamicRegistration": true }
                },
                "textDocument": {
                    "synchronization": {
                        "dynamicRegistration": false,
                        "didSave": true
                    },
                    "publishDiagnostics": { "relatedInformation": false },
                    // rust-analyzer (and others) gate refactor assists on
                    // `codeActionLiteralSupport`; without it the server only
                    // returns plain `Command`s, which we don't execute, so
                    // the picker would always look empty. `resolveSupport`
                    // tells the server it's allowed to defer the heavy
                    // `edit` until `codeAction/resolve`.
                    "codeAction": {
                        "dynamicRegistration": false,
                        "codeActionLiteralSupport": {
                            "codeActionKind": {
                                "valueSet": [
                                    "", "quickfix", "refactor",
                                    "refactor.extract", "refactor.inline",
                                    "refactor.rewrite", "source",
                                    "source.organizeImports"
                                ]
                            }
                        },
                        "resolveSupport": { "properties": ["edit"] },
                        "dataSupport": true
                    },
                    // We never request snippet expansion — the popup
                    // inserts `newText` verbatim, so `$0` / `${1:x}`
                    // tokens would land in the buffer as literal text.
                    // Declaring `snippetSupport: false` keeps servers
                    // honest (rust-analyzer emits a different `newText`
                    // shape when snippets are off).
                    // `resolveSupport.properties` opts the client into
                    // the deferred-fields contract: rust-analyzer
                    // (and a few others) will omit `additionalTextEdits`
                    // — the `use …;` lines that drive auto-import —
                    // from the initial completion response and only
                    // compute them when we send `completionItem/resolve`.
                    // Without declaring this, those servers ship the
                    // edits up front anyway, but at the cost of
                    // computing them for every candidate in the list;
                    // declaring it lets the server defer the work to
                    // just the one the user accepts.
                    "completion": {
                        "dynamicRegistration": false,
                        "completionItem": {
                            "snippetSupport": false,
                            "insertReplaceSupport": true,
                            "labelDetailsSupport": true,
                            "resolveSupport": {
                                "properties": [
                                    "additionalTextEdits",
                                    "detail",
                                    "documentation"
                                ]
                            }
                        }
                    },
                    // `labelOffsetSupport: true` tells the server we
                    // accept `parameters[].label` as `[start, end]`
                    // character offsets into the parent signature's
                    // `label`. Most servers (rust-analyzer, gopls,
                    // pyright) prefer the offset shape when this is on
                    // — saves us a substring search to find where to
                    // paint the active-parameter highlight.
                    "signatureHelp": {
                        "dynamicRegistration": false,
                        "signatureInformation": {
                            "parameterInformation": {
                                "labelOffsetSupport": true
                            },
                            "activeParameterSupport": true
                        }
                    }
                },
                "window": {
                    "workDoneProgress": true
                }
            },
            "clientInfo": { "name": "vorto" },
        });
        write_framed(&stdin, &request(init_id, "initialize", init_params))?;

        // Drain messages until we see the initialize response. The server
        // can interleave its own requests (workspace/configuration,
        // client/registerCapability, window/workDoneProgress/create)
        // before answering ours — we have to reply to those right here
        // or the handshake deadlocks.
        let (completion_trigger_characters, signature_help_trigger_characters): (
            Vec<String>,
            Vec<String>,
        ) = loop {
            let msg = read_message(&mut reader).with_context(|| "reading initialize response")?;
            let is_init_response = msg.get("id").and_then(|v| v.as_u64()) == Some(init_id)
                && msg.get("method").is_none();
            if is_init_response {
                if let Some(err) = msg.get("error") {
                    bail!("LSP initialize error: {}", err);
                }
                let str_array = |ptr: &str| {
                    msg.pointer(ptr)
                        .and_then(|v| v.as_array())
                        .map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_str().map(str::to_owned))
                                .collect()
                        })
                        .unwrap_or_default()
                };
                break (
                    str_array("/result/capabilities/completionProvider/triggerCharacters"),
                    str_array("/result/capabilities/signatureHelpProvider/triggerCharacters"),
                );
            }
            codec::handle_server_request(&stdin, &msg);
        };

        write_framed(&stdin, &notification("initialized", json!({})))?;

        let language_id = spec
            .language_id
            .clone()
            .unwrap_or_else(|| lang_name.to_string());

        let stdin_reader = Arc::clone(&stdin);
        let key_for_reader = client_key.to_string();
        let blocking_pending: BlockingPending = Arc::new(Mutex::new(HashMap::new()));
        let blocking_for_reader = Arc::clone(&blocking_pending);
        thread::spawn(move || {
            reader_loop(
                reader,
                emit,
                stdin_reader,
                key_for_reader,
                blocking_for_reader,
            )
        });

        Ok(Self {
            child,
            stdin,
            next_id: 2,
            docs: HashMap::new(),
            language_id,
            root_uri: root_uri.to_string(),
            completion_trigger_characters,
            signature_help_trigger_characters,
            blocking_pending,
        })
    }

    /// OS process id of the running language server. Used by the
    /// `:lsp` status modal.
    pub fn pid(&self) -> u32 {
        self.child.id()
    }

    /// Root URI passed to `initialize`. Used by the `:lsp` status
    /// modal.
    pub fn root_uri(&self) -> &str {
        &self.root_uri
    }

    /// `languageId` advertised in `didOpen` notifications. Distinct
    /// from our internal language name (e.g. `.tsx` → `tsx` internally
    /// but `typescriptreact` over the wire).
    pub fn language_id(&self) -> &str {
        &self.language_id
    }

    /// Trigger characters the server declared in its `initialize`
    /// response. Empty when the server didn't expose `completionProvider`
    /// or didn't list any characters.
    pub fn completion_trigger_characters(&self) -> &[String] {
        &self.completion_trigger_characters
    }

    /// Open-from-scratch trigger characters for signature help.
    pub fn signature_help_trigger_characters(&self) -> &[String] {
        &self.signature_help_trigger_characters
    }

    /// Send an arbitrary JSON-RPC request. Returns the assigned id so the
    /// caller can match it against the eventual [`LspEvent::Response`].
    pub fn request(&mut self, method: &str, params: Value) -> Result<u64> {
        let id = self.next_id;
        self.next_id += 1;
        write_framed(&self.stdin, &request(id, method, params))?;
        Ok(id)
    }

    pub fn did_open(&mut self, uri: &str, text: &str) -> Result<()> {
        if self.docs.contains_key(uri) {
            return Ok(());
        }
        self.docs.insert(uri.to_string(), 1);
        let params = json!({
            "textDocument": {
                "uri": uri,
                "languageId": self.language_id,
                "version": 1,
                "text": text,
            }
        });
        write_framed(&self.stdin, &notification("textDocument/didOpen", params))
    }

    /// Full-document sync — the simplest correct option for MVP. We bump
    /// the per-doc version and send the whole text every time.
    pub fn did_change(&mut self, uri: &str, text: &str) -> Result<()> {
        let v = match self.docs.get_mut(uri) {
            Some(v) => {
                *v += 1;
                *v
            }
            None => return Ok(()),
        };
        let params = json!({
            "textDocument": { "uri": uri, "version": v },
            "contentChanges": [ { "text": text } ],
        });
        write_framed(&self.stdin, &notification("textDocument/didChange", params))
    }

    pub fn did_save(&mut self, uri: &str, text: &str) -> Result<()> {
        if !self.docs.contains_key(uri) {
            return Ok(());
        }
        let params = json!({
            "textDocument": { "uri": uri },
            "text": text,
        });
        write_framed(&self.stdin, &notification("textDocument/didSave", params))
    }

    pub fn did_close(&mut self, uri: &str) -> Result<()> {
        if self.docs.remove(uri).is_none() {
            return Ok(());
        }
        let params = json!({ "textDocument": { "uri": uri } });
        write_framed(&self.stdin, &notification("textDocument/didClose", params))
    }

    /// Synchronously request `textDocument/formatting`. Registers a
    /// side-channel before sending so the reader thread routes the
    /// response straight to us instead of into the async `LspEvent`
    /// queue — necessary because save flows need the edits in hand
    /// before they can write the file. `timeout` caps how long we'll
    /// wait before giving up (e.g. on a slow rust-analyzer first-run).
    /// On error or timeout we clean the pending entry so a late reply
    /// can't leak.
    pub fn formatting(
        &mut self,
        uri: &str,
        options: Value,
        timeout: Duration,
    ) -> Result<Vec<TextEdit>> {
        let id = self.next_id;
        self.next_id += 1;
        let (tx, rx) = mpsc::channel();
        {
            let mut guard = self
                .blocking_pending
                .lock()
                .map_err(|_| anyhow!("lsp blocking pending poisoned"))?;
            guard.insert(id, tx);
        }
        let params = json!({
            "textDocument": { "uri": uri },
            "options": options,
        });
        if let Err(e) = write_framed(&self.stdin, &request(id, "textDocument/formatting", params)) {
            self.blocking_pending
                .lock()
                .ok()
                .and_then(|mut g| g.remove(&id));
            return Err(e);
        }
        let reply = rx.recv_timeout(timeout);
        // Always clean up — on timeout, otherwise the late response would
        // leak into the map forever.
        self.blocking_pending
            .lock()
            .ok()
            .and_then(|mut g| g.remove(&id));
        match reply {
            Ok(BlockingReply::Ok(v)) => Ok(parse::parse_text_edits(&v)),
            Ok(BlockingReply::Err(msg)) => bail!("textDocument/formatting: {}", msg),
            Err(mpsc::RecvTimeoutError::Timeout) => {
                bail!("textDocument/formatting timed out after {:?}", timeout)
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                bail!("textDocument/formatting: lsp reader gone")
            }
        }
    }
}

impl Drop for LspClient {
    /// Best-effort graceful shutdown per the LSP spec:
    ///   1. `shutdown` request — server stops accepting work, replies, then waits for `exit`.
    ///   2. `exit` notification — server terminates.
    ///   3. Poll the child briefly; SIGKILL if it overstays the budget.
    ///
    /// Without this the server would linger after the editor quits
    /// (`std::process::Child` has no `Drop`), and slow shutdowns of e.g.
    /// rust-analyzer would block the editor indefinitely.
    fn drop(&mut self) {
        let shutdown_wait = Duration::from_millis(500);
        let exit_wait = Duration::from_millis(300);
        vlog!(
            "lsp shutdown begin lang={} pid={}",
            self.language_id,
            self.child.id()
        );

        let shutdown_id = self.next_id;
        self.next_id += 1;
        let (tx, rx) = mpsc::channel();
        if let Ok(mut guard) = self.blocking_pending.lock() {
            guard.insert(shutdown_id, tx);
        }

        let shutdown_sent =
            write_framed(&self.stdin, &request(shutdown_id, "shutdown", Value::Null)).is_ok();

        if shutdown_sent {
            // We don't care about the reply contents, only that the
            // server has acknowledged before we send `exit`.
            let _ = rx.recv_timeout(shutdown_wait);
        }
        // Pop the pending entry whether or not the reader thread already
        // consumed it — leaves no dangling sender.
        if let Ok(mut guard) = self.blocking_pending.lock() {
            guard.remove(&shutdown_id);
        }

        if shutdown_sent {
            let _ = write_framed(&self.stdin, &notification("exit", Value::Null));
        }

        let deadline = std::time::Instant::now() + exit_wait;
        loop {
            match self.child.try_wait() {
                Ok(Some(status)) => {
                    vlog!(
                        "lsp shutdown clean lang={} status={status}",
                        self.language_id
                    );
                    return;
                }
                Ok(None) if std::time::Instant::now() >= deadline => break,
                Ok(None) => thread::sleep(Duration::from_millis(20)),
                Err(_) => break,
            }
        }
        vlog!("lsp shutdown kill lang={}", self.language_id);
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}