curd-editor 0.10.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
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
//! A small Language Server Protocol (LSP) client.
//!
//! The editor knows nothing about any programming language. Instead it
//! starts that language's server (for example `rust-analyzer`) as a child
//! process and exchanges JSON messages with it over stdin and stdout: the
//! same protocol VS Code, Neovim and Helix use.
//!
//! A background thread reads the server's messages and forwards them to the
//! editor, so the editor never blocks waiting for the server.

use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};

use serde_json::{json, Value};

use crate::highlight::TokenKind;
use crate::snippets::Language;

#[cfg(test)]
mod tests;

/// The error a server answers with when the text changed under a request.
const CONTENT_MODIFIED: i64 = -32801;
/// Longest hover text shown, in lines.
const MAX_HOVER_LINES: usize = 12;

// ---- Which server to run ------------------------------------------------

/// How to start the language server for a file.
#[derive(Debug, PartialEq)]
pub struct ServerSpec {
    pub command: String,
    pub args: Vec<String>,
    /// The name LSP uses for the file's language, such as "rust".
    pub language_id: &'static str,
    /// Files that mark the top folder of a project.
    pub root_markers: &'static [&'static str],
}

impl ServerSpec {
    /// The server for `path`.
    ///
    /// `override_command` is the value of the `CURD_LSP` environment
    /// variable: "off" disables language servers, and anything else is used
    /// as the command line instead of the built-in default.
    pub fn for_file(
        language: Option<Language>,
        path: &str,
        override_command: Option<&str>,
    ) -> Option<Self> {
        let extension = Path::new(path)
            .extension()
            .and_then(|extension| extension.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        let (command, language_id, root_markers): (&str, &str, &[&str]) = match language {
            Some(Language::Rust) => ("rust-analyzer", "rust", &["Cargo.toml"]),
            Some(Language::Python) => (
                "pyright-langserver --stdio",
                "python",
                &["pyproject.toml", "setup.py", "requirements.txt"],
            ),
            Some(Language::JavaScript) => (
                "typescript-language-server --stdio",
                match extension.as_str() {
                    "ts" => "typescript",
                    "tsx" => "typescriptreact",
                    "jsx" => "javascriptreact",
                    _ => "javascript",
                },
                &["tsconfig.json", "package.json"],
            ),
            Some(Language::C) => (
                "clangd",
                if extension == "c" { "c" } else { "cpp" },
                &["compile_commands.json", "CMakeLists.txt", "Makefile"],
            ),
            Some(Language::Go) => ("gopls", "go", &["go.mod"]),
            Some(Language::Yaml) => ("yaml-language-server --stdio", "yaml", &[]),
            None => ("", "plaintext", &[]),
        };

        let command_line = match override_command.map(str::trim) {
            Some("off") => return None,
            Some(custom) if !custom.is_empty() => custom,
            _ => command,
        };
        let mut words = command_line.split_whitespace().map(String::from);
        Some(Self {
            command: words.next()?,
            args: words.collect(),
            language_id,
            root_markers,
        })
    }
}

/// The project folder for a file: the nearest folder at or above `dir` that
/// holds one of `markers` (or a `.git` folder), or else `dir` itself.
pub fn find_root(dir: &Path, markers: &[&str]) -> PathBuf {
    dir.ancestors()
        .find(|folder| {
            markers
                .iter()
                .chain(&[".git"])
                .any(|marker| folder.join(marker).exists())
        })
        .unwrap_or(dir)
        .to_path_buf()
}

// ---- Positions ----------------------------------------------------------

/// How the server counts columns. The editor counts characters, so every
/// column is converted on the way in and out.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Encoding {
    Utf8,
    Utf16,
    Utf32,
}

impl Encoding {
    /// LSP's default is UTF-16 unless the server agrees to something else.
    fn from_name(name: Option<&str>) -> Self {
        match name {
            Some("utf-8") => Self::Utf8,
            Some("utf-32") => Self::Utf32,
            _ => Self::Utf16,
        }
    }

    fn units_of(self, c: char) -> usize {
        match self {
            Self::Utf8 => c.len_utf8(),
            Self::Utf16 => c.len_utf16(),
            Self::Utf32 => 1,
        }
    }

    /// Converts character column `x` of `line` to the server's units.
    pub fn to_units(self, line: &str, x: usize) -> usize {
        line.chars().take(x).map(|c| self.units_of(c)).sum()
    }

    /// Converts a column in the server's units to a character column.
    pub fn to_chars(self, line: &str, units: usize) -> usize {
        let mut used = 0;
        for (x, c) in line.chars().enumerate() {
            if used >= units {
                return x;
            }
            used += self.units_of(c);
        }
        line.chars().count()
    }
}

// ---- Wire format --------------------------------------------------------

/// Wraps a JSON message in the `Content-Length` header LSP requires.
pub fn encode(message: &Value) -> Vec<u8> {
    let body = message.to_string();
    format!("Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes()
}

/// Reads one message. Returns `None` when the stream has ended.
pub fn read_message(reader: &mut impl BufRead) -> io::Result<Option<Value>> {
    let mut length = None;
    loop {
        let mut header = String::new();
        if reader.read_line(&mut header)? == 0 {
            return Ok(None);
        }
        let header = header.trim_end();
        if header.is_empty() {
            break;
        }
        if let Some((name, value)) = header.split_once(':')
            && name.eq_ignore_ascii_case("content-length")
        {
            length = value.trim().parse::<usize>().ok();
        }
    }
    let invalid = |reason: String| io::Error::new(io::ErrorKind::InvalidData, reason);
    let length = length.ok_or_else(|| invalid("message without Content-Length".into()))?;
    let mut body = vec![0; length];
    reader.read_exact(&mut body)?;
    serde_json::from_slice(&body)
        .map(Some)
        .map_err(|error| invalid(error.to_string()))
}

/// Turns a file path into a `file://` URI.
pub fn path_to_uri(path: &Path) -> String {
    let mut text = path.to_string_lossy().replace('\\', "/");
    if !text.starts_with('/') {
        // Windows paths like C:/dir need a leading slash in a URI.
        text.insert(0, '/');
    }
    let mut uri = String::from("file://");
    for byte in text.bytes() {
        match byte {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'/' | b'-' | b'.' | b'_' | b'~' => {
                uri.push(byte as char)
            }
            _ => uri.push_str(&format!("%{byte:02X}")),
        }
    }
    uri
}

/// Turns a `file://` URI back into a path, undoing percent-encoding.
pub fn uri_to_path(uri: &str) -> Option<String> {
    let encoded = uri.strip_prefix("file://")?;
    let mut bytes = Vec::with_capacity(encoded.len());
    let mut rest = encoded.bytes();
    while let Some(byte) = rest.next() {
        if byte == b'%' {
            let hex = [rest.next()?, rest.next()?];
            let hex = std::str::from_utf8(&hex).ok()?;
            bytes.push(u8::from_str_radix(hex, 16).ok()?);
        } else {
            bytes.push(byte);
        }
    }
    String::from_utf8(bytes).ok()
}

// ---- What the server tells us -------------------------------------------

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

/// A problem the server found in the file. It covers the text from
/// (`line`, `start`) to (`end_line`, `end`), columns in the server's units.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Diagnostic {
    pub line: usize,
    pub start: usize,
    pub end_line: usize,
    pub end: usize,
    pub severity: Severity,
    pub message: String,
    /// The code is never used: editors show it faded.
    pub unnecessary: bool,
    /// The code is deprecated: editors show it struck through.
    pub deprecated: bool,
}

/// One coloured piece of code, with the column and length still in the
/// server's units.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SemanticToken {
    pub line: usize,
    pub start: usize,
    pub length: usize,
    /// `None` for things that get no colour, such as plain variables.
    pub kind: Option<TokenKind>,
}

/// A place in a file, with the column still in the server's units.
#[derive(Debug, PartialEq)]
pub struct Location {
    pub path: String,
    pub line: usize,
    pub units: usize,
}

/// One suggestion for what to type next.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CompletionItem {
    /// What the list shows.
    pub label: String,
    /// What goes into the file when it is chosen.
    pub insert: String,
    /// What typed letters are matched against.
    pub filter: String,
    /// A short note shown beside the label, such as a type.
    pub detail: String,
}

/// What a message from the server means for the editor.
#[derive(Debug, PartialEq)]
pub enum Reply {
    /// The server finished starting up.
    Ready,
    Diagnostics(Vec<Diagnostic>),
    /// Lines of documentation for the symbol under the cursor (may be empty).
    Hover(Vec<String>),
    Definition(Option<Location>),
    /// Colours for the whole file.
    Tokens(Vec<SemanticToken>),
    /// Suggestions for what to type at the cursor, in answer to the request
    /// with this number. `None` when the server gave up because the text
    /// changed while it was working: worth asking again.
    Completion(u64, Option<Vec<CompletionItem>>),
    /// Nothing the editor needs to act on.
    Nothing,
}

fn parse_diagnostics(params: &Value) -> Vec<Diagnostic> {
    let Some(items) = params["diagnostics"].as_array() else {
        return Vec::new();
    };
    let mut diagnostics: Vec<Diagnostic> = items
        .iter()
        .map(|item| {
            let number = |value: &Value| value.as_u64().unwrap_or(0) as usize;
            let (start, end) = (&item["range"]["start"], &item["range"]["end"]);
            let has_tag = |tag: u64| {
                item["tags"]
                    .as_array()
                    .is_some_and(|tags| tags.iter().any(|value| value.as_u64() == Some(tag)))
            };
            Diagnostic {
            line: number(&start["line"]),
            start: number(&start["character"]),
            // A range that ends before it starts is treated as one point.
            end_line: number(&end["line"]).max(number(&start["line"])),
            end: number(&end["character"]),
            unnecessary: has_tag(1),
            deprecated: has_tag(2),
            severity: match item["severity"].as_u64() {
                Some(1) | None => Severity::Error,
                Some(2) => Severity::Warning,
                _ => Severity::Info,
            },
            // Only the first line fits in the status bar.
            message: item["message"]
                .as_str()
                .unwrap_or("")
                .lines()
                .next()
                .unwrap_or("")
                .to_string(),
            }
        })
        .collect();
    diagnostics.sort_by_key(|diagnostic| diagnostic.line);
    diagnostics
}

/// Hover text comes in several shapes: a string, `{ value }`, or a list of
/// either. Markdown code fences are dropped since the terminal shows plain text.
fn parse_hover(result: &Value) -> Vec<String> {
    fn text_of(value: &Value) -> String {
        match value {
            Value::String(text) => text.clone(),
            Value::Array(items) => items.iter().map(text_of).collect::<Vec<_>>().join("\n"),
            other => other["value"].as_str().unwrap_or("").to_string(),
        }
    }
    let text = text_of(&result["contents"]);
    let mut lines: Vec<String> = Vec::new();
    for line in text.lines().map(str::trim_end) {
        let is_fence = line.trim_start().starts_with("```");
        let repeats_blank = line.is_empty() && lines.last().is_none_or(|last| last.is_empty());
        if !is_fence && !repeats_blank {
            lines.push(line.to_string());
        }
    }
    while lines.last().is_some_and(|line| line.is_empty()) {
        lines.pop();
    }
    if lines.len() > MAX_HOVER_LINES {
        lines.truncate(MAX_HOVER_LINES - 1);
        lines.push("...".into());
    }
    lines
}

/// A definition comes back as one location, a list of them, or "links".
fn parse_location(result: &Value) -> Option<Location> {
    let first = match result {
        Value::Array(items) => items.first()?,
        Value::Null => return None,
        single => single,
    };
    let uri = first["uri"].as_str().or(first["targetUri"].as_str())?;
    let start = if first["targetSelectionRange"].is_object() {
        &first["targetSelectionRange"]["start"]
    } else {
        &first["range"]["start"]
    };
    Some(Location {
        path: uri_to_path(uri)?,
        line: start["line"].as_u64()? as usize,
        units: start["character"].as_u64()? as usize,
    })
}

/// Completions come back as a list, or as `{ items }`. They are put in the
/// order the server ranks them (its `sortText`).
fn parse_completion(result: &Value) -> Vec<CompletionItem> {
    let Some(items) = result.as_array().or(result["items"].as_array()) else {
        return Vec::new();
    };
    let mut ranked: Vec<(&str, CompletionItem)> = items
        .iter()
        .filter_map(|item| {
            let label = item["label"].as_str()?;
            let insert = item["textEdit"]["newText"]
                .as_str()
                .or(item["insertText"].as_str())
                .unwrap_or(label);
            let detail = item["detail"].as_str().unwrap_or("");
            Some((
                item["sortText"].as_str().unwrap_or(label),
                CompletionItem {
                    label: label.to_string(),
                    insert: insert.to_string(),
                    filter: item["filterText"].as_str().unwrap_or(label).to_string(),
                    detail: detail.lines().next().unwrap_or("").to_string(),
                },
            ))
        })
        .collect();
    ranked.sort_by(|a, b| a.0.cmp(b.0));
    ranked.into_iter().map(|(_, item)| item).collect()
}

/// Semantic tokens arrive as one flat list of numbers, five per token:
/// lines down from the previous token, columns right of it (or of the line
/// start, on a new line), length, type, and modifiers. `legend` says which
/// kind each type number stands for. Returns `None` if the server sent no
/// token list at all (an error, or a cancelled request).
fn parse_tokens(result: &Value, legend: &[Option<TokenKind>]) -> Option<Vec<SemanticToken>> {
    let data: Vec<usize> = result["data"]
        .as_array()?
        .iter()
        .map(|number| number.as_u64().unwrap_or(0) as usize)
        .collect();
    let mut tokens = Vec::new();
    let (mut line, mut start) = (0, 0);
    for token in data.as_chunks::<5>().0 {
        if token[0] > 0 {
            line += token[0];
            start = 0;
        }
        start += token[1];
        tokens.push(SemanticToken {
            line,
            start,
            length: token[2],
            kind: legend.get(token[3]).copied().flatten(),
        });
    }
    Some(tokens)
}

// ---- The client ---------------------------------------------------------

/// Requests we are still waiting on an answer for.
enum Pending {
    Initialize,
    Hover,
    Definition,
    Completion,
    /// Asked when the file was at this version.
    Tokens(i64),
}

/// One file the server has been told about.
struct OpenFile {
    uri: String,
    language_id: &'static str,
    version: i64,
    /// Edits made since the last `didChange`, waiting to be sent together.
    changes: Vec<Value>,
}

/// A running language server. One server looks after every open file of
/// its language in a project, the way it does in VS Code.
pub struct Client {
    child: Child,
    stdin: ChildStdin,
    /// The server's command name, for status messages.
    pub name: String,
    next_id: u64,
    /// What each unanswered request was, and which file it was about.
    pending: HashMap<u64, (Pending, String)>,
    encoding: Encoding,
    /// True when the server accepts just the changed ranges instead of the
    /// whole file on every edit.
    incremental: bool,
    ready: bool,
    /// The kind each of the server's token type numbers stands for. Empty
    /// when the server cannot colour code.
    legend: Vec<Option<TokenKind>>,
    /// The open files, by absolute path.
    files: HashMap<String, OpenFile>,
}

impl Client {
    /// Starts the server for the project in `root` and begins the handshake.
    ///
    /// `forward` is called from a background thread with every message the
    /// server sends, and with `None` once the server has exited.
    pub fn start(
        spec: &ServerSpec,
        root: &Path,
        forward: impl Fn(Option<Value>) + Send + 'static,
    ) -> io::Result<Self> {
        let mut child = Command::new(&spec.command)
            .args(&spec.args)
            .current_dir(root)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()?;
        let stdin = child.stdin.take().expect("stdin was piped");
        let stdout = child.stdout.take().expect("stdout was piped");

        std::thread::spawn(move || {
            let mut reader = BufReader::new(stdout);
            while let Ok(Some(message)) = read_message(&mut reader) {
                forward(Some(message));
            }
            forward(None);
        });

        let mut client = Self {
            child,
            stdin,
            name: spec.command.clone(),
            next_id: 1,
            pending: HashMap::new(),
            encoding: Encoding::Utf16,
            incremental: false,
            ready: false,
            legend: Vec::new(),
            files: HashMap::new(),
        };
        client.request(
            Pending::Initialize,
            "",
            "initialize",
            json!({
                "processId": std::process::id(),
                "clientInfo": { "name": "curd", "version": env!("CARGO_PKG_VERSION") },
                "rootUri": path_to_uri(root),
                "capabilities": {
                    // Prefer counting columns the way the editor does.
                    "general": { "positionEncodings": ["utf-32", "utf-16"] },
                    // Let the server say when its colours are out of date
                    // (rust-analyzer does once it has loaded the project).
                    "workspace": { "semanticTokens": { "refreshSupport": true } },
                    "textDocument": {
                        "synchronization": { "didSave": true },
                        // Tags mark unused (1) and deprecated (2) code.
                        "publishDiagnostics": { "tagSupport": { "valueSet": [1, 2] } },
                        "hover": { "contentFormat": ["plaintext", "markdown"] },
                        "definition": { "linkSupport": true },
                        // Plain text only: no snippet placeholders to fill in.
                        "completion": { "completionItem": { "snippetSupport": false } },
                        "semanticTokens": {
                            "requests": { "full": true },
                            "formats": ["relative"],
                            "tokenTypes": [
                                "namespace", "type", "class", "enum", "interface", "struct",
                                "typeParameter", "parameter", "variable", "property",
                                "enumMember", "event", "function", "method", "macro",
                                "keyword", "modifier", "comment", "string", "number",
                                "regexp", "operator", "decorator",
                            ],
                            "tokenModifiers": [],
                            "multilineTokenSupport": false,
                            "overlappingTokenSupport": false,
                            // The server's colours go over our own, so ask
                            // for keywords, strings and comments too.
                            "augmentsSyntaxTokens": false,
                        },
                    },
                },
            }),
        );
        Ok(client)
    }

    fn send(&mut self, message: Value) {
        // If the server has died the reader thread reports it; nothing to do here.
        let _ = self.stdin.write_all(&encode(&message));
        let _ = self.stdin.flush();
    }

    fn notify(&mut self, method: &str, params: Value) {
        self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
    }

    /// Sends a request about the file at `path` ("" for none), and returns
    /// the number the answer will carry.
    fn request(&mut self, kind: Pending, path: &str, method: &str, params: Value) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        self.pending.insert(id, (kind, path.to_string()));
        self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
        id
    }

    /// True once the handshake is done and the server knows the open files.
    pub fn is_ready(&self) -> bool {
        self.ready
    }

    pub fn encoding(&self) -> Encoding {
        self.encoding
    }

    /// Tells the server about a file the user opened. `path` must be
    /// absolute. Before the handshake is done the file is only noted, and
    /// sent once the server is ready.
    pub fn open(&mut self, path: &str, language_id: &'static str, text: &dyn Fn() -> String) {
        self.files.insert(
            path.to_string(),
            OpenFile {
                uri: path_to_uri(Path::new(path)),
                language_id,
                version: 0,
                changes: Vec::new(),
            },
        );
        if self.ready {
            self.did_open(path, text());
        }
    }

    fn did_open(&mut self, path: &str, text: String) {
        let Some(file) = self.files.get(path) else {
            return;
        };
        let params = json!({ "textDocument": {
            "uri": file.uri,
            "languageId": file.language_id,
            "version": file.version,
            "text": text,
        }});
        self.notify("textDocument/didOpen", params);
        self.request_tokens(path);
    }

    /// Tells the server the user closed a file.
    pub fn close(&mut self, path: &str) {
        if let Some(file) = self.files.remove(path)
            && self.ready
        {
            self.notify(
                "textDocument/didClose",
                json!({ "textDocument": { "uri": file.uri } }),
            );
        }
    }

    /// True when no file is using this server any more.
    pub fn is_unused(&self) -> bool {
        self.files.is_empty()
    }

    /// Handles one message from the server. `text` gives the current
    /// contents of an open file, and is only called when the server needs
    /// all of it. Returns what the message means and which file it is about.
    pub fn handle(
        &mut self,
        message: &Value,
        text: &dyn Fn(&str) -> String,
    ) -> (Option<String>, Reply) {
        if let Some(method) = message["method"].as_str() {
            if !message["id"].is_null() {
                // The server is asking us something. We support none of the
                // optional features, but it still needs an answer.
                let result = match message["params"]["items"].as_array() {
                    Some(items) if method == "workspace/configuration" => {
                        json!(vec![Value::Null; items.len()])
                    }
                    _ => Value::Null,
                };
                self.send(json!({ "jsonrpc": "2.0", "id": message["id"], "result": result }));
                if method == "workspace/semanticTokens/refresh" {
                    let paths: Vec<String> = self.files.keys().cloned().collect();
                    for path in paths {
                        self.request_tokens(&path);
                    }
                }
                return (None, Reply::Nothing);
            }
            let params = &message["params"];
            if method == "textDocument/publishDiagnostics"
                && let Some(path) = params["uri"].as_str().and_then(uri_to_path)
                && self.files.contains_key(&path)
            {
                return (Some(path), Reply::Diagnostics(parse_diagnostics(params)));
            }
            return (None, Reply::Nothing);
        }

        let id = message["id"].as_u64().unwrap_or(0);
        let Some((kind, path)) = self.pending.remove(&id) else {
            return (None, Reply::Nothing);
        };
        let result = &message["result"];
        let reply = match kind {
            Pending::Initialize => {
                let capabilities = &result["capabilities"];
                self.encoding = Encoding::from_name(capabilities["positionEncoding"].as_str());
                let sync = &capabilities["textDocumentSync"];
                self.incremental = sync.as_u64().or(sync["change"].as_u64()) == Some(2);
                let provider = &capabilities["semanticTokensProvider"];
                if provider["full"].as_bool() != Some(false) && !provider["full"].is_null() {
                    self.legend = provider["legend"]["tokenTypes"]
                        .as_array()
                        .map(|names| {
                            names
                                .iter()
                                .map(|name| name.as_str().and_then(TokenKind::from_name))
                                .collect()
                        })
                        .unwrap_or_default();
                }
                self.notify("initialized", json!({}));
                self.ready = true;
                // Files opened while the server was starting are sent now.
                let paths: Vec<String> = self.files.keys().cloned().collect();
                for path in paths {
                    let contents = text(&path);
                    self.did_open(&path, contents);
                }
                return (None, Reply::Ready);
            }
            Pending::Hover => Reply::Hover(parse_hover(result)),
            Pending::Definition => Reply::Definition(parse_location(result)),
            Pending::Completion => {
                let gave_up = message["error"]["code"].as_i64() == Some(CONTENT_MODIFIED);
                Reply::Completion(id, (!gave_up).then(|| parse_completion(result)))
            }
            Pending::Tokens(version) => {
                // An answer about an older version of the file would put the
                // colours in the wrong places; a newer one is already on its way.
                let current = self
                    .files
                    .get(&path)
                    .is_some_and(|file| file.version == version && file.changes.is_empty());
                match parse_tokens(result, &self.legend) {
                    Some(tokens) if current => Reply::Tokens(tokens),
                    _ => Reply::Nothing,
                }
            }
        };
        (Some(path), reply)
    }

    /// Records an edit to the file at `path`: the text between `start` and
    /// `end` (line, column in the server's units) was replaced by `text`.
    /// Edits are batched and sent by `flush`.
    pub fn change(&mut self, path: &str, start: (usize, usize), end: (usize, usize), text: &str) {
        // Before the handshake is done there is nothing to keep in sync:
        // the file is sent whole once the server is ready.
        if self.ready
            && let Some(file) = self.files.get_mut(path)
        {
            file.changes.push(json!({
                "range": {
                    "start": { "line": start.0, "character": start.1 },
                    "end": { "line": end.0, "character": end.1 },
                },
                "text": text,
            }));
        }
    }

    /// True if any open file has edits the server has not been sent yet.
    pub fn has_pending_changes(&self) -> bool {
        self.files.values().any(|file| !file.changes.is_empty())
    }

    /// Sends the edits to `path` recorded since the last flush as one
    /// notification.
    pub fn flush(&mut self, path: &str, text: &dyn Fn() -> String) {
        let incremental = self.incremental;
        let Some(file) = self.files.get_mut(path) else {
            return;
        };
        if file.changes.is_empty() {
            return;
        }
        let changes = std::mem::take(&mut file.changes);
        file.version += 1;
        let content_changes = if incremental {
            json!(changes)
        } else {
            json!([{ "text": text() }])
        };
        let params = json!({
            "textDocument": { "uri": file.uri, "version": file.version },
            "contentChanges": content_changes,
        });
        self.notify("textDocument/didChange", params);
        self.request_tokens(path);
    }

    /// Asks for the colours of a whole file, if the server can give them.
    /// The answer arrives later as `Reply::Tokens`.
    fn request_tokens(&mut self, path: &str) {
        if self.ready
            && !self.legend.is_empty()
            && let Some(file) = self.files.get(path)
        {
            let params = json!({ "textDocument": { "uri": file.uri } });
            let version = file.version;
            self.request(
                Pending::Tokens(version),
                path,
                "textDocument/semanticTokens/full",
                params,
            );
        }
    }

    fn ask(
        &mut self,
        kind: Pending,
        method: &str,
        path: &str,
        line: usize,
        units: usize,
    ) -> Option<u64> {
        let file = self.files.get(path)?;
        let params = json!({
            "textDocument": { "uri": file.uri },
            "position": { "line": line, "character": units },
        });
        Some(self.request(kind, path, method, params))
    }

    /// Asks what the symbol at this position is. The answer arrives later
    /// as `Reply::Hover`.
    pub fn hover(&mut self, path: &str, line: usize, units: usize) {
        self.ask(Pending::Hover, "textDocument/hover", path, line, units);
    }

    /// Asks where the symbol at this position is defined. The answer arrives
    /// later as `Reply::Definition`.
    pub fn definition(&mut self, path: &str, line: usize, units: usize) {
        self.ask(Pending::Definition, "textDocument/definition", path, line, units);
    }

    /// Asks what could be typed at this position. The answer arrives later
    /// as `Reply::Completion`, carrying the number returned here.
    pub fn completion(&mut self, path: &str, line: usize, units: usize) -> Option<u64> {
        self.ask(Pending::Completion, "textDocument/completion", path, line, units)
    }

    /// Tells the server a file was saved. Many servers run their slower
    /// checks (such as `cargo check`) at this point.
    pub fn did_save(&mut self, path: &str) {
        if self.ready
            && let Some(file) = self.files.get(path)
        {
            let params = json!({ "textDocument": { "uri": file.uri } });
            self.notify("textDocument/didSave", params);
        }
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        // Ask politely, then make sure no server is left running.
        self.send(json!({ "jsonrpc": "2.0", "id": 0, "method": "shutdown" }));
        self.notify("exit", Value::Null);
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}