curd-editor 0.7.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, search, 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
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
use std::cell::{OnceCell, RefCell};
use std::path::Path;
use std::rc::Rc;

use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::style::Color;

use crate::diff::{self, Mark};
use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{self, Highlights, LineState};
use crate::history::{Change, History};
use crate::lsp::{Client, CompletionItem, Diagnostic, Encoding, Location, Reply, Severity};
use crate::screen::{fit, overlay, Decoration, Row, Span, Style};
use crate::search;
use crate::snippets::Language;

#[cfg(test)]
mod tests;

const TAB: &str = "    ";
/// Most suggestions shown at once, and the widest the list gets.
const MENU_ROWS: usize = 8;
const MENU_WIDTH: usize = 50;

/// A question asked in the status bar.
#[derive(Clone, Copy, Debug, PartialEq)]
enum PromptKind {
    Find,
    SaveAs,
}

impl PromptKind {
    fn label(self) -> &'static str {
        match self {
            Self::Find => "Find: ",
            Self::SaveAs => "Save as: ",
        }
    }
}

struct Prompt {
    kind: PromptKind,
    /// What has been typed in answer so far.
    text: String,
}

/// The list of suggestions from the language server, open under the cursor.
struct Completion {
    items: Vec<CompletionItem>,
    /// The items that match what has been typed, best first, as indexes
    /// into `items`. Never empty while the list is open.
    shown: Vec<usize>,
    /// Which of `shown` is picked.
    selected: usize,
    /// True once the arrows have been used to pick one.
    moved: bool,
    /// Where the word being completed starts: column and line.
    start: usize,
    y: usize,
}

fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// One open file: its text, cursor, view and everything known about it.
pub struct Editor {
    pub document: Document,
    /// The file's absolute path, which is how the language server and the
    /// rest of the workspace refer to it. `None` for a file with no name yet.
    pub abs_path: Option<String>,
    /// Decides snippets, folding style and language server. `None` for
    /// unknown file types.
    pub language: Option<Language>,
    folds: Folds,
    /// Where foldable blocks are. Worked out on first use after each edit.
    blocks: OnceCell<Blocks>,
    /// Whether each line starts inside a comment or string left open by an
    /// earlier line, for the built-in colouring. Empty for unknown file types.
    line_states: Vec<LineState>,
    cursor_x: usize,
    cursor_y: usize,
    row_offset: usize,
    col_offset: usize,
    /// Shown in the status bar until the next key press.
    pub message: String,
    /// Lines shown in a panel over the text until the next key press
    /// (hover documentation).
    info: Vec<String>,
    /// Set by a successful save, for the workspace to notice.
    pub just_saved: bool,
    /// Set when a file with no name was given one, for the workspace.
    pub renamed: bool,
    /// Rows of text on screen at the last draw: one page for PageUp/PageDown.
    page_rows: usize,
    history: History,
    /// The question in the status bar, while one is being asked.
    prompt: Option<Prompt>,
    /// Where the cursor was when the search started.
    find_from: (usize, usize),
    /// The last thing searched for, for "find next".
    last_query: String,
    completion: Option<Completion>,
    /// The word (start column, line) suggestions were last asked for, so
    /// each word is asked about once.
    completion_word: Option<(usize, usize)>,
    /// The number of the newest request for suggestions. Answers to older
    /// ones are out of date.
    completion_request: Option<u64>,
    /// The file's lines in the last git commit, if it is in one.
    git_base: Option<Vec<String>>,
    /// How each line compares with `git_base`. Worked out on first use
    /// after each edit.
    marks: OnceCell<Vec<Mark>>,
    /// The language server looking after this file. It is shared with the
    /// other open files of the same project and language.
    pub lsp: Option<Rc<RefCell<Client>>>,
    /// Problems reported by the language server, sorted by line.
    pub diagnostics: Vec<Diagnostic>,
    /// Colours from the language server.
    pub highlights: Highlights,
    /// True while a language server is attached: adds a column for
    /// error and warning markers.
    pub show_diagnostics: bool,
}

impl Editor {
    pub fn new(document: Document) -> Self {
        let language = document.path.as_deref().and_then(Language::from_path);
        let abs_path = document
            .path
            .as_deref()
            .and_then(|path| std::path::absolute(path).ok())
            .map(|path| path.to_string_lossy().into_owned());
        Self {
            language,
            abs_path,
            line_states: match language {
                Some(language) => highlight::line_states(&document.lines, language),
                None => Vec::new(),
            },
            document,
            folds: Folds::default(),
            blocks: OnceCell::new(),
            cursor_x: 0,
            cursor_y: 0,
            row_offset: 0,
            col_offset: 0,
            message: String::new(),
            info: Vec::new(),
            just_saved: false,
            renamed: false,
            page_rows: 0,
            history: History::default(),
            prompt: None,
            find_from: (0, 0),
            last_query: String::new(),
            completion: None,
            completion_word: None,
            completion_request: None,
            git_base: None,
            marks: OnceCell::new(),
            lsp: None,
            diagnostics: Vec::new(),
            highlights: Highlights::default(),
            show_diagnostics: false,
        }
    }

    /// Puts a language server in charge of this file.
    pub fn attach_lsp(&mut self, lsp: Rc<RefCell<Client>>) {
        self.lsp = Some(lsp);
        self.show_diagnostics = true;
    }

    /// Forgets the language server, and everything it said about the file.
    pub fn detach_lsp(&mut self) {
        self.lsp = None;
        self.diagnostics.clear();
        self.highlights = Highlights::default();
        self.show_diagnostics = false;
        self.completion = None;
        self.completion_request = None;
    }

    /// Sets what the file looked like in the last git commit (`None` if it
    /// is not in one), which the change markers compare against.
    pub fn set_git_base(&mut self, base: Option<Vec<String>>) {
        self.git_base = base;
        self.marks = OnceCell::new();
    }

    /// The file's name without its folders, for tabs and the status bar.
    pub fn name(&self) -> &str {
        self.document
            .path
            .as_deref()
            .and_then(|path| Path::new(path).file_name())
            .and_then(|name| name.to_str())
            .unwrap_or("[No Name]")
    }

    pub 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;
        }
        // Messages and the hover panel only last until the next key.
        self.message.clear();
        self.info.clear();

        if self.prompt.is_some() {
            self.prompt_key(key);
            return;
        }
        // Everything one key changes is undone together, and a run of
        // plain typing is too.
        let command = KeyModifiers::CONTROL | KeyModifiers::ALT;
        let typing = matches!(key.code, KeyCode::Char(c) if !key.modifiers.intersects(command) && c != ' ');
        self.history.begin((self.cursor_x, self.cursor_y), typing);
        self.edit_key(key);
        self.clamp_cursor_x();
        self.history.commit((self.cursor_x, self.cursor_y));
    }

    fn edit_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        let typed = matches!(key.code, KeyCode::Char(_) if !ctrl && !alt);

        // While the list of suggestions is open it takes a few keys itself.
        if let Some(completion) = &self.completion {
            match key.code {
                KeyCode::Up => return self.move_selection(-1),
                KeyCode::Down => return self.move_selection(1),
                KeyCode::Esc => return self.completion = None,
                // Tab on a snippet trigger still expands the snippet,
                // unless a suggestion was picked with the arrows.
                KeyCode::Tab if completion.moved || self.snippet_at_cursor().is_none() => {
                    return self.accept_completion();
                }
                KeyCode::Backspace => {}
                _ if typed => {}
                _ => self.completion = None,
            }
        }
        if !typed && key.code != KeyCode::Backspace {
            self.completion_word = None;
        }

        match key.code {
            KeyCode::Char('s') if ctrl => self.save_or_ask(),
            KeyCode::Char('z') if ctrl => self.undo(),
            KeyCode::Char('y') if ctrl => self.redo(),
            // Each command has an Alt or function-key form as well, because
            // some terminals (VS Code's, for one) keep Ctrl keys for themselves.
            KeyCode::Char('f') if ctrl || alt => self.open_prompt(PromptKind::Find),
            KeyCode::Char('n') if alt => self.find_again(),
            KeyCode::F(3) => self.find_again(),
            KeyCode::Char(' ') if ctrl => self.ask_completion(true),
            KeyCode::Char('/') if alt => self.ask_completion(true),
            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);
                self.after_typing(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();
                // Deleting the whole word closes the list of suggestions.
                if self.completion.as_ref().is_some_and(|completion| self.cursor_x <= completion.start) {
                    self.completion = None;
                }
                self.refilter();
            }
            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::PageUp => self.wheel(-(self.page_rows.max(1) as isize)),
            KeyCode::PageDown => self.wheel(self.page_rows.max(1) as isize),
            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 if ctrl => (self.cursor_x, self.cursor_y) = (0, 0),
            KeyCode::End if ctrl => {
                // The last line may be hidden inside a collapsed block.
                self.cursor_y = self.folds.header_of(self.document.len().saturating_sub(1));
                self.cursor_x = self.document.line_len(self.cursor_y);
            }
            KeyCode::Home => self.cursor_x = 0,
            KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
            _ => {}
        }
    }

    /// 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.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c });
        self.document.insert_char(self.cursor_x, self.cursor_y, c);
        self.highlights.inserted(self.cursor_x, self.cursor_y);
        self.rescan(self.cursor_y, 0);
        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.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c: '\n' });
        self.document.insert_newline(self.cursor_x, self.cursor_y);
        self.highlights.split(self.cursor_x, self.cursor_y);
        self.rescan(self.cursor_y, 1);
        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 let Some(c) = self.document.lines.get(y).and_then(|line| line.chars().nth(x)) {
            let end = self.lsp_position(x + 1, y);
            self.history.record(Change::Delete { x, y, c });
            self.document.delete_char(x, y);
            self.highlights.deleted(x, y);
            self.rescan(y, 0);
            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.history.record(Change::Delete { x, y, c: '\n' });
            self.document.delete_char(x, y);
            self.highlights.joined(y, x);
            self.rescan(y, -1);
            self.text_changed(start, (y + 1, 0), "");
            self.lines_shifted(y, -1);
        }
    }

    /// Updates the built-in colouring after an edit on line `y` that added
    /// `added` lines below it (-1 when the next line was joined onto it).
    fn rescan(&mut self, y: usize, added: isize) {
        let Some(language) = self.language else {
            return;
        };
        match added {
            1 => self.line_states.insert(y + 1, LineState::Code),
            -1 => drop(self.line_states.remove(y + 1)),
            _ => {}
        }
        // The first edit of an empty document creates its first line.
        self.line_states.resize(self.document.len(), LineState::Code);
        let last_changed = y + added.max(0) as usize;
        highlight::rescan(&mut self.line_states, &self.document.lines, language, y, last_changed);
    }

    /// 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, |lsp| lsp.borrow().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();
        self.marks = OnceCell::new();
        if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
            lsp.borrow_mut().change(path, 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.
    pub fn paste(&mut self, text: &str) {
        self.message.clear();
        self.info.clear();
        self.completion = None;
        if let Some(prompt) = &mut self.prompt {
            // Pasting into the status bar question: one line only.
            prompt.text.extend(text.chars().filter(|c| !c.is_control()));
            self.prompt_changed();
            return;
        }
        self.history.begin((self.cursor_x, self.cursor_y), false);
        self.insert_text(text);
        self.history.commit((self.cursor_x, self.cursor_y));
    }

    /// Puts `text` in at the cursor exactly as it is.
    fn insert_text(&mut self, text: &str) {
        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),
            }
        }
    }

    // ---- Undo and redo -------------------------------------------------

    /// Takes back the last step: a run of typing, a paste, a snippet.
    fn undo(&mut self) {
        let Some(step) = self.history.undo() else {
            self.message = "Nothing to undo".into();
            return;
        };
        for change in step.changes.iter().rev() {
            match *change {
                Change::Insert { x, y, .. } => self.remove_at(x, y),
                Change::Delete { x, y, c } => self.put_at(x, y, c),
            }
        }
        (self.cursor_x, self.cursor_y) = step.before;
        self.document.dirty = !self.history.is_saved();
    }

    /// Does again the step that was last undone.
    fn redo(&mut self) {
        let Some(step) = self.history.redo() else {
            self.message = "Nothing to redo".into();
            return;
        };
        for change in &step.changes {
            match *change {
                Change::Insert { x, y, c } => self.put_at(x, y, c),
                Change::Delete { x, y, .. } => self.remove_at(x, y),
            }
        }
        (self.cursor_x, self.cursor_y) = step.after;
        self.document.dirty = !self.history.is_saved();
    }

    /// Puts character `c` (or a line break) in at column `x` of line `y`.
    fn put_at(&mut self, x: usize, y: usize, c: char) {
        self.folds.reveal(y);
        (self.cursor_x, self.cursor_y) = (x, y);
        match c {
            '\n' => self.insert_newline(),
            c => self.insert_char(c),
        }
    }

    /// Takes out the character (or line break) at column `x` of line `y`.
    fn remove_at(&mut self, x: usize, y: usize) {
        self.folds.reveal(y);
        (self.cursor_x, self.cursor_y) = (x, y);
        self.delete_at_cursor();
    }

    /// 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
    }

    /// The word before the cursor.
    fn word_before_cursor(&self) -> String {
        let before = self.text_before_cursor();
        let start = self.word_start();
        before.chars().skip(start).collect()
    }

    /// The column where the word before the cursor starts (the cursor's
    /// own column, if there is no word there).
    fn word_start(&self) -> usize {
        let before = self.text_before_cursor();
        let word = before.chars().rev().take_while(|c| is_word_char(*c)).count();
        before.chars().count() - word
    }

    /// The snippet the word before the cursor stands for, if it is a
    /// trigger word.
    fn snippet_at_cursor(&self) -> Option<&'static str> {
        let word = self.word_before_cursor();
        self.language.and_then(|language| language.snippet(&word))
    }

    /// Tab expands the word before the cursor if it is a snippet trigger,
    /// and otherwise indents.
    fn tab(&mut self) {
        match self.snippet_at_cursor() {
            Some(body) => {
                let word = self.word_before_cursor();
                self.expand_snippet(word.chars().count(), 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;
        }
    }

    /// Ctrl+S: saves, first asking for a name if the file has none.
    fn save_or_ask(&mut self) {
        if self.document.path.is_none() {
            self.open_prompt(PromptKind::SaveAs);
        } else {
            self.save();
        }
    }

    /// Writes the file. Returns whether that worked.
    fn save(&mut self) -> bool {
        let result = self.document.save();
        self.message = match &result {
            Ok(()) => {
                self.just_saved = true;
                self.history.mark_saved();
                self.sync_lsp();
                if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
                    lsp.borrow_mut().did_save(path);
                }
                format!("Saved {} lines", self.document.len())
            }
            Err(error) => format!("Could not save: {error}"),
        };
        result.is_ok()
    }

    /// Gives a file that has no name the name `name` and saves it there.
    /// A file that already exists is never overwritten this way.
    fn save_as(&mut self, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.message = "Not saved: no file name given".into();
            return;
        }
        if Path::new(name).exists() {
            self.message = format!("Not saved: {name} already exists");
            return;
        }
        self.document.path = Some(name.to_string());
        if !self.save() {
            self.document.path = None;
            return;
        }
        // Now that it has a name it has a language too.
        self.abs_path = std::fs::canonicalize(name)
            .or_else(|_| std::path::absolute(name))
            .ok()
            .map(|path| path.to_string_lossy().into_owned());
        self.language = Language::from_path(name);
        self.line_states = match self.language {
            Some(language) => highlight::line_states(&self.document.lines, language),
            None => Vec::new(),
        };
        self.blocks = OnceCell::new();
        self.renamed = true;
    }

    // ---- Questions in the status bar -----------------------------------

    fn open_prompt(&mut self, kind: PromptKind) {
        self.completion = None;
        self.find_from = (self.cursor_x, self.cursor_y);
        self.prompt = Some(Prompt {
            kind,
            text: String::new(),
        });
    }

    /// A key pressed while a question is open in the status bar.
    fn prompt_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        let Some(prompt) = &mut self.prompt else {
            return;
        };
        let finding = prompt.kind == PromptKind::Find;
        match key.code {
            KeyCode::Esc => self.prompt = None,
            KeyCode::Char('f') if (ctrl || alt) && finding => self.find_step(true),
            KeyCode::Char(c) if !ctrl && !alt => {
                prompt.text.push(c);
                self.prompt_changed();
            }
            KeyCode::Backspace => {
                prompt.text.pop();
                self.prompt_changed();
            }
            KeyCode::Enter | KeyCode::Down if finding => self.find_step(true),
            KeyCode::Up if finding => self.find_step(false),
            KeyCode::Enter => {
                let name = std::mem::take(&mut prompt.text);
                self.prompt = None;
                self.save_as(&name);
            }
            _ => {}
        }
    }

    /// The search text changed: show the first match at or after the place
    /// the search started from.
    fn prompt_changed(&mut self) {
        let Some(Prompt { kind: PromptKind::Find, text }) = &self.prompt else {
            return;
        };
        let query = text.clone();
        (self.cursor_x, self.cursor_y) = self.find_from;
        self.jump_to_match(&query, true, true);
        self.last_query = query;
    }

    /// Enter or the arrows in a search: on to the next match, or back to
    /// the one before.
    fn find_step(&mut self, forward: bool) {
        let query = match &self.prompt {
            Some(prompt) if !prompt.text.is_empty() => prompt.text.clone(),
            _ => self.last_query.clone(),
        };
        self.jump_to_match(&query, forward, false);
    }

    /// Jumps to the next match of the last search, without asking again.
    fn find_again(&mut self) {
        if self.last_query.is_empty() {
            self.message = "Nothing searched for yet: Ctrl+F or Alt+F starts a search".into();
        } else {
            let query = self.last_query.clone();
            self.jump_to_match(&query, true, false);
        }
    }

    /// Moves the cursor to the nearest match of `query`, if there is one.
    fn jump_to_match(&mut self, query: &str, forward: bool, inclusive: bool) {
        if query.is_empty() {
            return;
        }
        let from = (self.cursor_x, self.cursor_y);
        match search::find(&self.document.lines, query, from, forward, inclusive) {
            Some((x, y)) => {
                self.folds.reveal(y);
                (self.cursor_x, self.cursor_y) = (x, y);
            }
            None => self.message = format!("No match for {query}"),
        }
    }

    // ---- Suggestions ---------------------------------------------------

    /// After a character was typed: narrows the open list of suggestions,
    /// or asks for one at the start of a word and after `.` or `::`.
    fn after_typing(&mut self, c: char) {
        if self.completion.is_some() && is_word_char(c) {
            self.refilter();
            return;
        }
        self.completion = None;
        if is_word_char(c) || c == '.' || self.text_before_cursor().ends_with("::") {
            self.ask_completion(false);
        }
    }

    /// Asks the language server what could be typed here. When not asked
    /// for by hand (`manual`), each word is only asked about once.
    fn ask_completion(&mut self, manual: bool) {
        let word = (self.word_start(), self.cursor_y);
        if !manual && self.completion_word == Some(word) {
            return;
        }
        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();
        let request = match (&self.lsp, &self.abs_path) {
            (Some(lsp), Some(path)) if lsp.borrow().is_ready() => {
                lsp.borrow_mut().completion(path, line, units)
            }
            _ => None,
        };
        match request {
            Some(_) => {
                self.completion_word = Some(word);
                self.completion_request = request;
            }
            None if manual => self.message = "No language server to suggest anything".into(),
            None => {}
        }
    }

    /// Keeps the suggestions that match what has been typed of the word:
    /// first those that start with it, then those that contain it. Closes
    /// the list when none are left or the cursor has left the word.
    fn refilter(&mut self) {
        let Some(mut completion) = self.completion.take() else {
            return;
        };
        if self.cursor_y != completion.y || self.cursor_x < completion.start {
            return;
        }
        let typed: String = self
            .text_before_cursor()
            .chars()
            .skip(completion.start)
            .collect::<String>()
            .to_lowercase();
        let names: Vec<String> = completion
            .items
            .iter()
            .map(|item| item.filter.to_lowercase())
            .collect();
        let starts_with = |index: &usize| names[*index].starts_with(&typed);
        let only_contains = |index: &usize| !starts_with(index) && names[*index].contains(&typed);
        completion.shown = (0..names.len())
            .filter(starts_with)
            .chain((0..names.len()).filter(only_contains))
            .collect();
        completion.selected = 0;
        completion.moved = false;
        if !completion.shown.is_empty() {
            self.completion = Some(completion);
        }
    }

    fn move_selection(&mut self, step: isize) {
        if let Some(completion) = &mut self.completion {
            let count = completion.shown.len() as isize;
            completion.selected = (completion.selected as isize + step).rem_euclid(count) as usize;
            completion.moved = true;
        }
    }

    /// Replaces the part of the word typed so far with the picked suggestion.
    fn accept_completion(&mut self) {
        let Some(completion) = self.completion.take() else {
            return;
        };
        let item = &completion.items[completion.shown[completion.selected]];
        while self.cursor_x > completion.start {
            self.backspace();
        }
        self.insert_text(&item.insert);
    }

    // ---- 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.
    pub fn sync_lsp(&mut self) {
        if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
            let lines = &self.document.lines;
            lsp.borrow_mut().flush(path, &|| 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, &str, 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 (&self.lsp, &self.abs_path) {
            (Some(lsp), Some(path)) => {
                let mut lsp = lsp.borrow_mut();
                if lsp.is_ready() {
                    question(&mut lsp, path, line, units);
                } else {
                    self.message = format!("{} is still starting", lsp.name);
                }
            }
            _ => self.message = "No language server for this file".into(),
        }
    }

    /// Acts on something the language server told us.
    pub fn apply_reply(&mut self, reply: Reply) {
        match reply {
            Reply::Ready => {
                if let Some(lsp) = &self.lsp {
                    self.message = format!("{} ready", lsp.borrow().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::Completion(id, items) => {
                // Only wanted if it answers the newest request and the
                // cursor is still in the word it was asked for.
                let word = (self.word_start(), self.cursor_y);
                if self.completion_request != Some(id)
                    || self.completion_word != Some(word)
                    || self.prompt.is_some()
                {
                    return;
                }
                match items {
                    Some(items) => {
                        self.completion = Some(Completion {
                            items,
                            shown: Vec::new(),
                            selected: 0,
                            moved: false,
                            start: word.0,
                            y: word.1,
                        });
                        self.refilter();
                    }
                    // The server gave up because more was typed meanwhile.
                    None => {
                        self.completion_word = None;
                        self.ask_completion(false);
                    }
                }
            }
            Reply::Nothing => {}
        }
    }

    /// Jumps to a definition, if it is in the open file.
    fn go_to(&mut self, location: Location) {
        let in_this_file = [&self.abs_path, &self.document.path]
            .iter()
            .any(|path| path.as_deref() == Some(location.path.as_str()));
        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, a fold marker, and a
    /// change marker (only for files in git).
    /// An empty document shows the welcome screen with no gutter.
    pub fn gutter_width(&self) -> usize {
        if self.document.is_empty() {
            0
        } else {
            self.show_diagnostics as usize
                + self.document.len().to_string().len()
                + 1
                + self.git_base.is_some() as usize
        }
    }

    /// Moves the view so the cursor is inside a text area of `width` x `height`.
    pub fn scroll(&mut self, width: usize, height: usize) {
        self.page_rows = height;
        // 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 let Some(prompt) = &self.prompt {
            let note = match self.message.as_str() {
                "" => String::new(),
                message => format!("   ({message})"),
            };
            format!("{}{}{note}", prompt.kind.label(), prompt.text)
        } else 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.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)
    }

    /// How line `y` compares with the last git commit.
    fn mark_on(&self, y: usize) -> Mark {
        let Some(base) = &self.git_base else {
            return Mark::Same;
        };
        let marks = self
            .marks
            .get_or_init(|| diff::marks(base, &self.document.lines));
        marks.get(y).copied().unwrap_or_default()
    }

    /// One row of text: problem marker, line number, fold marker, change
    /// 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 - self.git_base.is_some() as usize;
        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),
        ));
        if self.git_base.is_some() {
            // A bar beside lines that are new or changed since the last
            // commit, and a dash where lines were removed.
            row.push(match self.mark_on(y) {
                Mark::Added => Span::new(Style::Colored(Color::Green), "▎"),
                Mark::Modified => Span::new(Style::Colored(Color::Yellow), "▎"),
                Mark::RemovedBelow => Span::new(Style::Colored(Color::Red), "▁"),
                Mark::RemovedAbove => Span::new(Style::Colored(Color::Red), "▔"),
                Mark::Same => Span::new(Style::Plain, " "),
            });
        }
        // 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 built-in scanner, then the server's more exact ones over
    /// them, 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];
        let mut scanned = Vec::new();
        if let Some(language) = self.language {
            let state = self.line_states.get(y).copied().unwrap_or_default();
            highlight::lex_line(line, language, state, &mut scanned);
        }
        for token in scanned.iter().chain(self.highlights.on(y)) {
            for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
                decoration.kind = token.kind;
            }
        }
        // While a search is open, every match is shown.
        if let Some(Prompt { kind: PromptKind::Find, text }) = &self.prompt {
            let width = text.chars().count();
            for start in search::matches(line, text) {
                for decoration in &mut decorations[start..(start + width).min(len)] {
                    decoration.marked = true;
                }
            }
        }
        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.
    pub 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, "~")]);
            }
        }

        self.render_completion(&mut rows, width, text_rows);

        // 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
    }

    /// Lays the list of suggestions over the text: under the cursor, or
    /// above it when there is more room there.
    fn render_completion(&self, rows: &mut [Row], width: usize, text_rows: usize) {
        let Some(completion) = &self.completion else {
            return;
        };
        let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
        let below = text_rows.saturating_sub(cursor_row + 1);
        let wanted = completion.shown.len().min(MENU_ROWS);
        let (top, count) = if below >= wanted || below >= cursor_row {
            (cursor_row + 1, wanted.min(below))
        } else {
            let count = wanted.min(cursor_row);
            (cursor_row - count, count)
        };
        // Keep the picked one in view when the list is longer than fits.
        let first = (completion.selected + 1).saturating_sub(count);
        let lines: Vec<String> = completion.shown[first..first + count]
            .iter()
            .map(|index| {
                let item = &completion.items[*index];
                format!(" {}  {}", item.label, item.detail).trim_end().to_string() + " "
            })
            .collect();
        let widest = lines.iter().map(|line| line.chars().count()).max().unwrap_or(0);
        let menu_width = widest.min(MENU_WIDTH).min(width);
        // Line the labels up with the word being typed.
        let x = (self.gutter_width() + completion.start)
            .saturating_sub(self.col_offset + 1)
            .min(width - menu_width);
        for (offset, line) in lines.iter().enumerate() {
            let style = if first + offset == completion.selected {
                Style::Reverse
            } else {
                Style::Menu
            };
            overlay(&mut rows[top + offset], x, &Span::new(style, fit(line, menu_width)));
        }
    }

    /// Where the cursor is within the editor's part of the screen, as
    /// (column, row).
    pub fn cursor_on_screen(&self) -> (usize, usize) {
        if let Some(prompt) = &self.prompt {
            // In the status bar, after what has been typed.
            let typed = prompt.kind.label().len() + prompt.text.chars().count();
            return (typed, self.page_rows);
        }
        (
            self.gutter_width() + self.cursor_x - self.col_offset,
            self.folds.rows_between(self.row_offset, self.cursor_y),
        )
    }

    /// A mouse click at column `x`, row `y` of the editor's part of the
    /// screen: the cursor goes to the character under the pointer.
    pub fn click(&mut self, x: usize, y: usize) {
        self.message.clear();
        self.info.clear();
        self.completion = None;
        // Walk down the visible lines to the clicked row.
        let mut line = self.row_offset;
        for _ in 0..y {
            match self.folds.next_visible(line, self.document.len()) {
                Some(next) => line = next,
                // Below the last line: go to the last line.
                None => break,
            }
        }
        if line < self.document.len() {
            self.cursor_y = line;
            self.cursor_x = (x.saturating_sub(self.gutter_width()) + self.col_offset)
                .min(self.document.line_len(line));
        }
    }

    /// The mouse wheel: moves `lines` lines down (up, when negative).
    pub fn wheel(&mut self, lines: isize) {
        self.completion = None;
        for _ in 0..lines.unsigned_abs() {
            let next = if lines > 0 {
                self.folds.next_visible(self.cursor_y, self.document.len())
            } else {
                self.folds.prev_visible(self.cursor_y)
            };
            match next {
                Some(y) => self.cursor_y = y,
                None => break,
            }
        }
        self.clamp_cursor_x();
    }
}

/// 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)
    }
}