curd-editor 0.5.0

A small terminal code editor with language-server support, folding and snippets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
use std::cell::OnceCell;
use std::io::{stdout, BufWriter, Write};
use std::path::Path;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::Duration;

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    queue,
    style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor},
    terminal::{Clear, ClearType},
};
use serde_json::Value;

use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{Highlights, TokenKind};
use crate::lsp::{Client, Diagnostic, Encoding, Location, Reply, ServerSpec, Severity};
use crate::snippets::Language;
use crate::terminal::Terminal;

#[cfg(test)]
mod tests;

const TAB: &str = "    ";

/// How long typing must pause before edits are sent to the language server.
/// Sending them in batches keeps the server from re-checking on every key.
const LSP_DEBOUNCE: Duration = Duration::from_millis(100);

/// Everything the editor reacts to. Input and language-server messages come
/// from separate threads into one queue, so the editor sleeps until there is
/// something to do instead of polling.
pub enum AppEvent {
    Input(Event),
    /// A message from the language server, or `None` when it has exited.
    Lsp(Option<Value>),
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Style {
    Plain,
    Dim,
    Reverse,
    Error,
    Warning,
    /// Code with a colour or a decoration from the language server.
    Code(Decoration),
}

/// How one character of code is dressed up.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Decoration {
    /// Gives the colour: keyword, string and so on.
    kind: Option<TokenKind>,
    /// An error or warning covers this character.
    underlined: bool,
    /// Unused code.
    faded: bool,
    /// Deprecated code.
    struck: bool,
}

/// The colour for each kind of code. These are the terminal's own sixteen
/// colours, so they follow whatever theme the terminal uses.
fn color_of(kind: TokenKind) -> Color {
    match kind {
        TokenKind::Keyword => Color::Magenta,
        TokenKind::Function => Color::Blue,
        TokenKind::Type => Color::Cyan,
        TokenKind::String => Color::Green,
        TokenKind::Constant => Color::DarkYellow,
        TokenKind::Comment => Color::DarkGrey,
        TokenKind::Macro => Color::DarkCyan,
        TokenKind::Namespace => Color::DarkGreen,
    }
}

/// A piece of a screen row drawn in one style.
#[derive(Clone, Debug, PartialEq)]
struct Span {
    style: Style,
    text: String,
}

impl Span {
    fn new(style: Style, text: impl Into<String>) -> Self {
        Self {
            style,
            text: text.into(),
        }
    }
}

type Row = Vec<Span>;

pub struct Editor {
    document: Document,
    /// Decides snippets, folding style and language server. `None` for
    /// unknown file types.
    language: Option<Language>,
    folds: Folds,
    /// Where foldable blocks are. Worked out on first use after each edit.
    blocks: OnceCell<Blocks>,
    should_quit: bool,
    cursor_x: usize,
    cursor_y: usize,
    row_offset: usize,
    col_offset: usize,
    /// Shown in the status bar until the next key press.
    message: String,
    /// Lines shown in a panel over the text until the next key press
    /// (hover documentation).
    info: Vec<String>,
    /// True after Ctrl+Q was pressed once with unsaved changes.
    quit_pending: bool,
    lsp: Option<Client>,
    /// Problems reported by the language server, sorted by line.
    diagnostics: Vec<Diagnostic>,
    /// Colours from the language server.
    highlights: Highlights,
    /// True while a language server is attached: adds a column for
    /// error and warning markers.
    show_diagnostics: bool,
    /// What is on screen now, so only rows that changed are redrawn.
    last_frame: Vec<Row>,
    last_size: (usize, usize),
}

impl Editor {
    pub fn new(document: Document) -> Self {
        Self {
            language: document.path.as_deref().and_then(Language::from_path),
            document,
            folds: Folds::default(),
            blocks: OnceCell::new(),
            should_quit: false,
            cursor_x: 0,
            cursor_y: 0,
            row_offset: 0,
            col_offset: 0,
            message: String::new(),
            info: Vec::new(),
            quit_pending: false,
            lsp: None,
            diagnostics: Vec::new(),
            highlights: Highlights::default(),
            show_diagnostics: false,
            last_frame: Vec::new(),
            last_size: (0, 0),
        }
    }

    /// Starts the language server for the open file, if there is one for
    /// its type. Its messages arrive later through `events`.
    pub fn start_lsp(&mut self, events: Sender<AppEvent>) {
        let Some(path) = self.document.path.clone() else {
            return;
        };
        // CURD_LSP=off disables servers; any other value replaces the command.
        let custom = std::env::var("CURD_LSP").ok();
        let Some(spec) = ServerSpec::for_file(self.language, &path, custom.as_deref()) else {
            return;
        };
        let forward = move |message| {
            let _ = events.send(AppEvent::Lsp(message));
        };
        match Client::start(&spec, &path, forward) {
            Ok(client) => {
                self.message = format!("Starting {}...", client.name);
                self.lsp = Some(client);
                self.show_diagnostics = true;
            }
            Err(_) => self.message = format!("No language server: {} not found", spec.command),
        }
    }

    pub fn run(&mut self, events: &Receiver<AppEvent>) -> std::io::Result<()> {
        while !self.should_quit {
            let (width, height) = Terminal::size()?;
            self.scroll(
                width.saturating_sub(self.gutter_width()),
                height.saturating_sub(1),
            );
            self.draw(width, height)?;

            // Sleep until something happens. With edits waiting to go to the
            // language server, wake up after a short pause in typing instead.
            let waiting_to_sync = self.lsp.as_ref().is_some_and(Client::has_pending_changes);
            let event = if waiting_to_sync {
                match events.recv_timeout(LSP_DEBOUNCE) {
                    Ok(event) => Some(event),
                    Err(RecvTimeoutError::Timeout) => None,
                    Err(RecvTimeoutError::Disconnected) => break,
                }
            } else {
                match events.recv() {
                    Ok(event) => Some(event),
                    Err(_) => break,
                }
            };
            match event {
                Some(event) => {
                    self.handle_event(event);
                    // Handle everything already queued (a paste, held keys)
                    // before drawing once, rather than drawing per key.
                    while let Ok(event) = events.try_recv() {
                        self.handle_event(event);
                    }
                }
                None => self.sync_lsp(),
            }
        }
        Ok(())
    }

    fn handle_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::Input(Event::Key(key)) => self.handle_key(key),
            AppEvent::Input(Event::Paste(text)) => self.paste(&text),
            AppEvent::Input(_) => {}
            AppEvent::Lsp(Some(message)) => {
                if let Some(lsp) = &mut self.lsp {
                    let lines = &self.document.lines;
                    let reply = lsp.handle(&message, &|| lines.join("\n"));
                    self.apply_reply(reply);
                }
            }
            AppEvent::Lsp(None) => {
                if let Some(lsp) = self.lsp.take() {
                    self.message = format!("Language server {} stopped", lsp.name);
                    self.diagnostics.clear();
                    self.highlights = Highlights::default();
                    self.show_diagnostics = false;
                }
            }
        }
    }

    fn handle_key(&mut self, key: KeyEvent) {
        // Windows reports both key press and key release; only act on press.
        if key.kind == KeyEventKind::Release {
            return;
        }
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);

        // Messages, the hover panel and the quit confirmation only last
        // until the next key.
        let quit_was_pending = std::mem::take(&mut self.quit_pending);
        self.message.clear();
        self.info.clear();

        match key.code {
            KeyCode::Char('q') if ctrl => {
                if self.document.dirty && !quit_was_pending {
                    self.quit_pending = true;
                    self.message = "Unsaved changes! Ctrl+Q again to quit".into();
                } else {
                    self.should_quit = true;
                }
            }
            KeyCode::Char('s') if ctrl => self.save(),
            // Each command has an Alt or function-key form as well, because
            // some terminals (VS Code's, for one) keep Ctrl+K for themselves.
            KeyCode::Char('k') if ctrl || alt => self.toggle_fold(),
            KeyCode::Char('a') if alt => self.toggle_all_folds(),
            KeyCode::Char('h') if alt => self.ask_lsp(Client::hover),
            KeyCode::F(2) => self.ask_lsp(Client::hover),
            KeyCode::Char('g') if alt => self.ask_lsp(Client::definition),
            KeyCode::F(12) => self.ask_lsp(Client::definition),
            KeyCode::Char(c) if !ctrl && !alt => self.type_char(c),
            KeyCode::Tab => self.tab(),
            KeyCode::Enter => {
                let indent = self.indent_for_new_line();
                self.insert_newline();
                indent.chars().for_each(|c| self.insert_char(c));
            }
            KeyCode::Backspace => self.backspace(),
            KeyCode::Delete => self.delete(),
            KeyCode::Up => {
                if let Some(y) = self.folds.prev_visible(self.cursor_y) {
                    self.cursor_y = y;
                }
            }
            KeyCode::Down => {
                if let Some(y) = self.folds.next_visible(self.cursor_y, self.document.len()) {
                    self.cursor_y = y;
                }
            }
            KeyCode::Left => {
                if self.cursor_x > 0 {
                    self.cursor_x -= 1;
                }
            }
            KeyCode::Right => {
                if self.cursor_x < self.document.line_len(self.cursor_y) {
                    self.cursor_x += 1;
                }
            }
            KeyCode::Home => self.cursor_x = 0,
            KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
            _ => {}
        }

        self.clamp_cursor_x();
    }

    /// Moving to a shorter line: don't leave the cursor past its end.
    fn clamp_cursor_x(&mut self) {
        let len = self.document.line_len(self.cursor_y);
        if self.cursor_x > len {
            self.cursor_x = len;
        }
    }

    // ---- Editing -------------------------------------------------------
    //
    // Every change to the text goes through the four methods below, which
    // keep the cursor, the folds and the language server in step with the
    // document.

    /// Inserts `c` at the cursor.
    fn insert_char(&mut self, c: char) {
        // Editing a collapsed line opens it, so nothing changes out of sight.
        self.folds.unfold(self.cursor_y);
        let at = self.lsp_position(self.cursor_x, self.cursor_y);
        self.document.insert_char(self.cursor_x, self.cursor_y, c);
        self.highlights.inserted(self.cursor_x, self.cursor_y);
        self.text_changed(at, at, &c.to_string());
        self.cursor_x += 1;
    }

    /// Splits the line at the cursor and moves to the start of the new line.
    fn insert_newline(&mut self) {
        self.folds.unfold(self.cursor_y);
        let at = self.lsp_position(self.cursor_x, self.cursor_y);
        self.document.insert_newline(self.cursor_x, self.cursor_y);
        self.highlights.split(self.cursor_x, self.cursor_y);
        self.text_changed(at, at, "\n");
        self.lines_shifted(self.cursor_y, 1);
        self.cursor_y += 1;
        self.cursor_x = 0;
    }

    /// Deletes the character before the cursor, or joins this line onto the
    /// one above when the cursor is at the start of a line.
    fn backspace(&mut self) {
        self.folds.unfold(self.cursor_y);
        if self.cursor_x > 0 {
            self.cursor_x -= 1;
            self.delete_at_cursor();
        } else if self.cursor_y > 0 {
            // The line above may be hidden inside a fold: open it first.
            self.folds.reveal(self.cursor_y - 1);
            self.cursor_y -= 1;
            self.cursor_x = self.document.line_len(self.cursor_y);
            self.delete_at_cursor();
        }
    }

    /// Deletes the character under the cursor, or joins the next line onto
    /// this one when the cursor is at the end of a line.
    fn delete(&mut self) {
        self.folds.unfold(self.cursor_y);
        self.delete_at_cursor();
    }

    fn delete_at_cursor(&mut self) {
        let (x, y) = (self.cursor_x, self.cursor_y);
        let start = self.lsp_position(x, y);
        if x < self.document.line_len(y) {
            let end = self.lsp_position(x + 1, y);
            self.document.delete_char(x, y);
            self.highlights.deleted(x, y);
            self.text_changed(start, end, "");
        } else if y + 1 < self.document.len() {
            // Joining lines: the line break itself is what gets deleted.
            self.folds.unfold(y + 1);
            self.document.delete_char(x, y);
            self.highlights.joined(y, x);
            self.text_changed(start, (y + 1, 0), "");
            self.lines_shifted(y, -1);
        }
    }

    /// Where character `x` of line `y` is in the language server's terms.
    fn lsp_position(&self, x: usize, y: usize) -> (usize, usize) {
        let line = self.document.lines.get(y).map_or("", String::as_str);
        (y, self.encoding().to_units(line, x))
    }

    fn encoding(&self) -> Encoding {
        self.lsp.as_ref().map_or(Encoding::Utf32, Client::encoding)
    }

    /// Called after every edit with the range that was replaced.
    fn text_changed(&mut self, start: (usize, usize), end: (usize, usize), text: &str) {
        self.blocks = OnceCell::new();
        if let Some(lsp) = &mut self.lsp {
            lsp.change(start, end, text);
        }
    }

    /// Called when `delta` lines were added (or removed, when negative)
    /// just below line `y`, so line-based notes keep pointing at the same code.
    fn lines_shifted(&mut self, y: usize, delta: isize) {
        self.folds.shift_after(y, delta);
        for diagnostic in &mut self.diagnostics {
            for line in [&mut diagnostic.line, &mut diagnostic.end_line] {
                if *line > y {
                    *line = (*line as isize + delta) as usize;
                }
            }
        }
    }

    /// A character typed by the user. A `}` typed on an otherwise blank line
    /// steps back one indent level so it lines up with its opening line.
    fn type_char(&mut self, c: char) {
        if c == '}' && self.cursor_x > 0 && self.text_before_cursor().chars().all(|c| c == ' ') {
            for _ in 0..TAB.len().min(self.cursor_x) {
                self.backspace();
            }
        }
        self.insert_char(c);
    }

    /// Pasted text goes in exactly as it is: no auto-indent, no snippets.
    fn paste(&mut self, text: &str) {
        self.quit_pending = false;
        self.message.clear();
        self.info.clear();
        for c in text.chars() {
            match c {
                '\n' => self.insert_newline(),
                '\r' => {}
                '\t' => TAB.chars().for_each(|c| self.insert_char(c)),
                c => self.insert_char(c),
            }
        }
    }

    /// The part of the cursor line that is left of the cursor.
    fn text_before_cursor(&self) -> String {
        match self.document.lines.get(self.cursor_y) {
            Some(line) => line.chars().take(self.cursor_x).collect(),
            None => String::new(),
        }
    }

    /// The indentation a new line should start with: the same as the current
    /// line, plus one level after an opening bracket (or `:` in Python).
    fn indent_for_new_line(&self) -> String {
        let before = self.text_before_cursor();
        let mut indent: String = before.chars().take_while(|c| *c == ' ').collect();
        let opens_block = match before.trim_end().chars().last() {
            Some('{' | '(' | '[') => true,
            Some(':') => self.language == Some(Language::Python),
            _ => false,
        };
        if opens_block {
            indent.push_str(TAB);
        }
        indent
    }

    /// Tab expands the word before the cursor if it is a snippet trigger,
    /// and otherwise indents.
    fn tab(&mut self) {
        let before = self.text_before_cursor();
        let word_len = before
            .chars()
            .rev()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .count();
        let word: String = before.chars().skip(before.chars().count() - word_len).collect();

        match self.language.and_then(|language| language.snippet(&word)) {
            Some(body) => {
                self.expand_snippet(word_len, body);
                self.message = format!("Expanded snippet: {word}");
            }
            None => TAB.chars().for_each(|c| self.insert_char(c)),
        }
    }

    /// Replaces the `trigger_len` characters before the cursor with `body`.
    fn expand_snippet(&mut self, trigger_len: usize, body: &str) {
        for _ in 0..trigger_len {
            self.backspace();
        }
        let indent: String = self
            .text_before_cursor()
            .chars()
            .take_while(|c| *c == ' ')
            .collect();

        let mut cursor_target = None;
        let mut chars = body.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '$' if chars.peek() == Some(&'0') => {
                    chars.next();
                    cursor_target = Some((self.cursor_x, self.cursor_y));
                }
                '\n' => {
                    self.insert_newline();
                    indent.chars().for_each(|c| self.insert_char(c));
                }
                c => self.insert_char(c),
            }
        }
        if let Some((x, y)) = cursor_target {
            self.cursor_x = x;
            self.cursor_y = y;
        }
    }

    fn save(&mut self) {
        self.message = match self.document.save() {
            Ok(()) => {
                self.sync_lsp();
                if let Some(lsp) = &mut self.lsp {
                    lsp.did_save();
                }
                format!("Saved {} lines", self.document.len())
            }
            Err(error) => format!("Could not save: {error}"),
        };
    }

    // ---- Folding -------------------------------------------------------

    /// Where the foldable blocks are: by indentation in Python, by braces
    /// everywhere else. Worked out once per edit and then reused.
    fn blocks(&self) -> &Blocks {
        self.blocks.get_or_init(|| {
            if self.language == Some(Language::Python) {
                Blocks::by_indent(&self.document.lines)
            } else {
                Blocks::by_braces(&self.document.lines)
            }
        })
    }

    /// Expands the fold on the cursor line, or else collapses the block that
    /// starts on, or surrounds, the cursor line.
    fn toggle_fold(&mut self) {
        if self.folds.unfold(self.cursor_y) {
            self.message = "Unfolded".into();
            return;
        }
        let blocks = self.blocks();
        let block = blocks
            .end(self.cursor_y)
            .map(|end| (self.cursor_y, end))
            .or_else(|| blocks.enclosing(self.cursor_y));
        match block {
            Some((start, end)) => {
                self.folds.fold(start, end);
                self.cursor_y = start;
                self.message = format!("Folded {} lines", end - start);
            }
            None => self.message = "No block to fold here".into(),
        }
    }

    /// Expands everything if anything is folded; otherwise collapses every
    /// outermost block.
    fn toggle_all_folds(&mut self) {
        if !self.folds.is_empty() {
            self.folds.clear();
            self.message = "Unfolded all".into();
            return;
        }
        let blocks = self.blocks().top_level();
        for (start, end) in &blocks {
            self.folds.fold(*start, *end);
        }
        // The cursor may now be inside a collapsed block.
        self.cursor_y = self.folds.header_of(self.cursor_y);
        self.message = match blocks.len() {
            0 => "No blocks to fold".into(),
            count => format!("Folded {count} blocks"),
        };
    }

    // ---- Language server -----------------------------------------------

    /// Sends any edits the language server has not seen yet.
    fn sync_lsp(&mut self) {
        if let Some(lsp) = &mut self.lsp {
            let lines = &self.document.lines;
            lsp.flush(&|| lines.join("\n"));
        }
    }

    /// Sends a question about the cursor position (hover, definition).
    /// The answer arrives later through `apply_reply`.
    fn ask_lsp(&mut self, question: fn(&mut Client, usize, usize)) {
        let (line, units) = self.lsp_position(self.cursor_x, self.cursor_y);
        // The server must know about the latest edits before it answers.
        self.sync_lsp();
        match &mut self.lsp {
            Some(lsp) if lsp.is_ready() => question(lsp, line, units),
            Some(lsp) => self.message = format!("{} is still starting", lsp.name),
            None => self.message = "No language server for this file".into(),
        }
    }

    /// Acts on something the language server told us.
    fn apply_reply(&mut self, reply: Reply) {
        match reply {
            Reply::Ready => {
                if let Some(lsp) = &self.lsp {
                    self.message = format!("{} ready", lsp.name);
                }
            }
            Reply::Diagnostics(diagnostics) => self.diagnostics = diagnostics,
            Reply::Hover(lines) if lines.is_empty() => {
                self.message = "Nothing to show here".into();
            }
            Reply::Hover(lines) => self.info = lines,
            Reply::Definition(None) => self.message = "No definition found".into(),
            Reply::Definition(Some(location)) => self.go_to(location),
            Reply::Tokens(tokens) => {
                self.highlights = Highlights::new(&tokens, &self.document.lines, self.encoding());
            }
            Reply::Nothing => {}
        }
    }

    /// Jumps to a definition, if it is in the open file.
    fn go_to(&mut self, location: Location) {
        let in_this_file = match (&self.lsp, &self.document.path) {
            (Some(lsp), _) => lsp.path() == location.path,
            (None, Some(path)) => *path == location.path,
            (None, None) => false,
        };
        if !in_this_file || location.line >= self.document.len() {
            // Only one file can be open, so say where it is instead.
            let name = Path::new(&location.path)
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or(&location.path);
            self.message = format!("Defined in {name}, line {}", location.line + 1);
            return;
        }
        self.folds.reveal(location.line);
        self.cursor_y = location.line;
        self.cursor_x = self
            .encoding()
            .to_chars(&self.document.lines[location.line], location.units);
        self.message = format!("Jumped to line {}", location.line + 1);
    }

    /// The first problem reported on line `y`, if any. Errors come before
    /// warnings when a line has both.
    fn diagnostic_on(&self, y: usize) -> Option<&Diagnostic> {
        self.diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.line == y)
            .min_by_key(|diagnostic| match diagnostic.severity {
                Severity::Error => 0,
                Severity::Warning => 1,
                Severity::Info => 2,
            })
    }

    // ---- Drawing -------------------------------------------------------

    /// Width of the column left of the text: an error/warning marker (only
    /// with a language server), the line number, and a fold marker.
    /// An empty document shows the welcome screen with no gutter.
    fn gutter_width(&self) -> usize {
        if self.document.is_empty() {
            0
        } else {
            self.show_diagnostics as usize + self.document.len().to_string().len() + 1
        }
    }

    /// Moves the view so the cursor is inside a text area of `width` x `height`.
    fn scroll(&mut self, width: usize, height: usize) {
        // The top line may have been hidden by a fold or removed by an edit.
        self.row_offset = self.folds.header_of(self.row_offset.min(self.cursor_y));
        while height > 0 && self.folds.rows_between(self.row_offset, self.cursor_y) >= height {
            match self.folds.next_visible(self.row_offset, self.document.len()) {
                Some(next) => self.row_offset = next,
                None => break,
            }
        }
        if self.cursor_x < self.col_offset {
            self.col_offset = self.cursor_x;
        }
        if width > 0 && self.cursor_x >= self.col_offset + width {
            self.col_offset = self.cursor_x - width + 1;
        }
    }

    /// The text shown for line `y`. A collapsed block shows its first line
    /// followed by `...` (and its closing line, for brace blocks), like
    /// `fn main() { ... }`.
    fn display_line(&self, y: usize) -> String {
        let line = &self.document.lines[y];
        match self.folds.end_of(y) {
            Some(_) if self.language == Some(Language::Python) => format!("{line} ..."),
            Some(end) => format!("{line} ... {}", self.document.lines[end].trim()),
            None => line.clone(),
        }
    }

    /// The status bar text, exactly `width` characters wide: on the left a
    /// message, the problem on the cursor line, or the file name; on the
    /// right the cursor position.
    fn status_line(&self, width: usize) -> String {
        let left = if !self.message.is_empty() {
            self.message.clone()
        } else if let Some(diagnostic) = self.diagnostic_on(self.cursor_y) {
            let kind = match diagnostic.severity {
                Severity::Error => "error",
                Severity::Warning => "warning",
                Severity::Info => "info",
            };
            format!("{kind}: {}", diagnostic.message)
        } else {
            // Just the file name: a full path rarely fits.
            let name = self
                .document
                .path
                .as_deref()
                .and_then(|path| Path::new(path).file_name())
                .and_then(|name| name.to_str())
                .unwrap_or("[No Name]");
            let modified = if self.document.dirty { " [modified]" } else { "" };
            let count = |severity| {
                self.diagnostics
                    .iter()
                    .filter(|diagnostic| diagnostic.severity == severity)
                    .count()
            };
            let problems = match (count(Severity::Error), count(Severity::Warning)) {
                (0, 0) => String::new(),
                (errors, warnings) => format!("  E:{errors} W:{warnings}"),
            };
            format!("{name}{modified}{problems}")
        };
        let right = format!("Ln {}, Col {}", self.cursor_y + 1, self.cursor_x + 1);

        let left_len = left.chars().count();
        let line = if left_len + 1 + right.len() <= width {
            let gap = width - left_len - right.len();
            format!("{left}{}{right}", " ".repeat(gap))
        } else {
            // Not enough room for both: the left part matters more.
            left
        };
        fit(&line, width)
    }

    /// One row of text: problem marker, line number, fold marker, text.
    fn render_line(&self, y: usize, gutter: usize, text_width: usize) -> Row {
        let mut row = Row::new();
        let mut number_width = gutter - 1;
        if self.show_diagnostics {
            number_width -= 1;
            row.push(match self.diagnostic_on(y).map(|d| d.severity) {
                Some(Severity::Error) => Span::new(Style::Error, "E"),
                Some(Severity::Warning) => Span::new(Style::Warning, "W"),
                Some(Severity::Info) => Span::new(Style::Dim, "i"),
                None => Span::new(Style::Plain, " "),
            });
        }
        // `+` marks a collapsed block, `-` a line that can be collapsed.
        let marker = if self.folds.end_of(y).is_some() {
            '+'
        } else if self.blocks().end(y).is_some() {
            '-'
        } else {
            ' '
        };
        row.push(Span::new(
            Style::Dim,
            format!("{:>number_width$}{marker}", y + 1),
        ));
        // Cut the text into pieces that share one look.
        let decorations = self.decorations(y);
        let visible = self.display_line(y);
        let visible = visible.chars().enumerate().skip(self.col_offset).take(text_width);
        let mut current: Option<(Decoration, String)> = None;
        for (x, c) in visible {
            let decoration = decorations.get(x).copied().unwrap_or_default();
            match &mut current {
                Some((same, text)) if *same == decoration => text.push(c),
                _ => {
                    row.extend(current.take().map(code_span));
                    current = Some((decoration, c.to_string()));
                }
            }
        }
        row.extend(current.map(code_span));
        row
    }

    /// The colour and decoration of each character of line `y`: colours
    /// from the server's tokens, then underlines, fading and strike-through
    /// from the problems that cover the line.
    fn decorations(&self, y: usize) -> Vec<Decoration> {
        let line = &self.document.lines[y];
        let len = line.chars().count();
        let mut decorations = vec![Decoration::default(); len];
        for token in self.highlights.on(y) {
            for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
                decoration.kind = Some(token.kind);
            }
        }
        let encoding = self.encoding();
        for diagnostic in &self.diagnostics {
            if diagnostic.line > y {
                // They are sorted by line: none of the rest reach this one.
                break;
            }
            if diagnostic.end_line < y {
                continue;
            }
            // A problem spanning several lines covers the first from its
            // start column, the last up to its end column, and all between.
            let start = if diagnostic.line == y {
                encoding.to_chars(line, diagnostic.start)
            } else {
                0
            };
            let mut end = if diagnostic.end_line == y {
                encoding.to_chars(line, diagnostic.end)
            } else {
                len
            };
            if diagnostic.line == diagnostic.end_line {
                // Some problems point at a single spot: mark one character.
                end = end.max(start + 1).min(len);
            }
            let underlined = matches!(diagnostic.severity, Severity::Error | Severity::Warning);
            for decoration in decorations.iter_mut().take(end).skip(start) {
                decoration.underlined |= underlined;
                decoration.faded |= diagnostic.unnecessary;
                decoration.struck |= diagnostic.deprecated;
            }
        }
        decorations
    }

    /// Everything that should be on a `width` x `height` screen, row by row:
    /// the text, the hover panel if open, and the status bar on the last row.
    fn render(&self, width: usize, height: usize) -> Vec<Row> {
        let text_rows = height.saturating_sub(1);
        let gutter = self.gutter_width();
        let text_width = width.saturating_sub(gutter);
        let mut rows = Vec::with_capacity(height);

        // Collapsed lines are skipped, so walk the visible lines one by one.
        let mut next_line = Some(self.row_offset).filter(|y| *y < self.document.len());
        for row in 0..text_rows {
            if let Some(y) = next_line {
                rows.push(self.render_line(y, gutter, text_width));
                next_line = self.folds.next_visible(y, self.document.len());
            } else if self.document.is_empty() && row == text_rows / 3 {
                let msg = concat!("curd editor -- v", env!("CARGO_PKG_VERSION"));
                let padding = width.saturating_sub(msg.len()) / 2;
                let text = format!("~{}{}", " ".repeat(padding), msg);
                rows.push(vec![Span::new(Style::Plain, text)]);
            } else {
                rows.push(vec![Span::new(Style::Plain, "~")]);
            }
        }

        // The hover panel sits at the bottom, or at the top when it would
        // cover the cursor.
        let panel = self.info.len().min(text_rows / 2);
        if panel > 0 {
            let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
            let top = if cursor_row >= text_rows - panel { 0 } else { text_rows - panel };
            for (offset, line) in self.info.iter().take(panel).enumerate() {
                let text = fit(&format!(" {line}"), width);
                rows[top + offset] = vec![Span::new(Style::Reverse, text)];
            }
        }

        if height > 0 {
            rows.push(vec![Span::new(Style::Reverse, self.status_line(width))]);
        }
        rows
    }

    /// Updates the screen, rewriting only the rows that differ from what
    /// is already there.
    fn draw(&mut self, width: usize, height: usize) -> std::io::Result<()> {
        let frame = self.render(width, height);
        let mut out = BufWriter::new(stdout().lock());

        queue!(out, Hide)?;
        if self.last_size != (width, height) {
            // The window was resized: nothing on screen can be trusted.
            queue!(out, Clear(ClearType::All))?;
            self.last_frame.clear();
            self.last_size = (width, height);
        }
        for (y, row) in frame.iter().enumerate() {
            if self.last_frame.get(y) == Some(row) {
                continue;
            }
            queue!(out, MoveTo(0, y as u16), Clear(ClearType::UntilNewLine))?;
            for span in row {
                match span.style {
                    Style::Plain => {}
                    Style::Dim => queue!(out, SetAttribute(Attribute::Dim))?,
                    Style::Reverse => queue!(out, SetAttribute(Attribute::Reverse))?,
                    Style::Error => queue!(out, SetForegroundColor(Color::Red))?,
                    Style::Warning => queue!(out, SetForegroundColor(Color::Yellow))?,
                    Style::Code(decoration) => {
                        if let Some(kind) = decoration.kind {
                            queue!(out, SetForegroundColor(color_of(kind)))?;
                        }
                        if decoration.underlined {
                            queue!(out, SetAttribute(Attribute::Underlined))?;
                        }
                        if decoration.faded {
                            queue!(out, SetAttribute(Attribute::Dim))?;
                        }
                        if decoration.struck {
                            queue!(out, SetAttribute(Attribute::CrossedOut))?;
                        }
                    }
                }
                queue!(out, Print(&span.text))?;
                if span.style != Style::Plain {
                    queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
                }
            }
        }
        self.last_frame = frame;

        let screen_x = (self.gutter_width() + self.cursor_x - self.col_offset) as u16;
        let screen_y = self.folds.rows_between(self.row_offset, self.cursor_y) as u16;
        queue!(out, MoveTo(screen_x, screen_y), Show)?;
        out.flush()
    }
}

/// A piece of code as a span: plain when it has no colour or decoration.
fn code_span((decoration, text): (Decoration, String)) -> Span {
    if decoration == Decoration::default() {
        Span::new(Style::Plain, text)
    } else {
        Span::new(Style::Code(decoration), text)
    }
}

/// Cuts or pads `text` to exactly `width` characters.
fn fit(text: &str, width: usize) -> String {
    let mut fitted: String = text.chars().take(width).collect();
    let padding = width - fitted.chars().count();
    fitted.push_str(&" ".repeat(padding));
    fitted
}