curd-editor 0.10.0

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

use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};

use crossterm::event::{
    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use serde_json::Value;

use crate::document::Document;
use crate::editor::Editor;
use crate::finder::{self, Finder};
use crate::git::{self, GitInfo};
use crate::lsp::{find_root, Client, Reply, ServerSpec};
use crate::screen::{fit, Row, Screen, Span, Style};
use crate::search::{self, Hit};
use crate::terminal::Terminal;
use crate::tree::Tree;

#[cfg(test)]
mod tests;

/// 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(30);
/// Width of the file tree, on screens wide enough for it.
const TREE_WIDTH: usize = 30;
/// Lines moved by one notch of the mouse wheel.
const WHEEL_LINES: isize = 3;
/// Two clicks on the same spot within this long are a double click.
const DOUBLE_CLICK: Duration = Duration::from_millis(400);
/// The mark on each tab that closes it when clicked.
const CLOSE_ICON: char = '×';
/// Most matches shown by quick open.
const FINDER_ROWS: usize = 8;

/// What the list over the text is being used for.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Picker {
    /// Quick open.
    Files,
    /// Asking what to search the project for.
    Search,
    /// The lines a project search found.
    Results,
    /// The git commands.
    Git,
    Branches,
    /// Asking for a commit message.
    Commit,
    /// Asking for the name of a new branch.
    NewBranch,
}

impl Picker {
    fn prompt(self) -> &'static str {
        match self {
            Self::Files => " Open file: ",
            Self::Search => " Search project: ",
            Self::Results => " Matches: ",
            Self::Git => " Git: ",
            Self::Branches => " Switch to branch: ",
            Self::Commit => " Commit message: ",
            Self::NewBranch => " New branch: ",
        }
    }

    /// True for the ones that ask for text instead of offering a list.
    fn is_question(self) -> bool {
        matches!(self, Self::Search | Self::Commit | Self::NewBranch)
    }
}

/// The git commands, in the order the menu lists them.
const GIT_MENU: [&str; 9] = [
    "Stage this file",
    "Unstage this file",
    "Stage all changes",
    "Unstage everything",
    "Commit...",
    "Switch branch...",
    "New branch...",
    "Pull",
    "Push",
];

/// Everything the workspace reacts to. Input, language-server messages and
/// git results 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 with this number, or `None` when
    /// it has exited.
    Lsp(usize, Option<Value>),
    /// Fresh git state for the project (`None` if it is not in git).
    Git(Option<GitInfo>),
    /// The lines of the file at this path as they were in the last commit
    /// (`None` if it is not in one).
    Committed(String, Option<Vec<String>>),
    /// A git command from the menu finished: what to say about it.
    GitDone(String),
}

/// Which part of the window the keys go to.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Focus {
    Editor,
    Tree,
}

/// A running language server and what it was started for.
struct Server {
    id: usize,
    /// Command and project folder: files with the same key share a server.
    key: String,
    client: Rc<RefCell<Client>>,
}

/// Where the parts of the window are.
struct Layout {
    /// Rows taken by the tab bar: 1 when several files are open, else 0.
    tabs: usize,
    /// Columns taken by the file tree and the line beside it; 0 if hidden.
    tree: usize,
    pane_width: usize,
    pane_height: usize,
}

pub struct Workspace {
    /// The open files, in tab order.
    editors: Vec<Editor>,
    /// The one in front.
    active: usize,
    tree: Tree,
    show_tree: bool,
    focus: Focus,
    git: Option<GitInfo>,
    /// Quick open, while it is on screen.
    finder: Option<Finder>,
    /// What that list is for.
    picker: Picker,
    /// The lines the last project search found, in the order listed.
    hits: Vec<Hit>,
    /// The text last copied or cut, which Ctrl+V pastes.
    clipboard: String,
    /// When and where the text was last clicked, to tell a double click.
    last_click: Option<(Instant, usize, usize)>,
    /// Copied text still to be handed to the terminal's clipboard.
    clipboard_out: Option<String>,
    servers: Vec<Server>,
    next_server: usize,
    /// Where background threads send their results. `None` in tests, which
    /// start no language servers and no git.
    events: Option<Sender<AppEvent>>,
    /// The CURD_LSP setting: "off", or a command to use instead.
    lsp_setting: Option<String>,
    /// Shown in the status bar when no file is open.
    message: String,
    /// True after Ctrl+Q was pressed once with unsaved changes.
    quit_pending: bool,
    /// The same for Ctrl+W.
    close_pending: bool,
    should_quit: bool,
    size: (usize, usize),
    screen: Screen,
}

impl Workspace {
    /// A workspace for the project in `root`, with no file open yet.
    pub fn new(
        root: PathBuf,
        events: Option<Sender<AppEvent>>,
        lsp_setting: Option<String>,
    ) -> Self {
        Self {
            editors: Vec::new(),
            active: 0,
            tree: Tree::new(root),
            show_tree: false,
            focus: Focus::Editor,
            git: None,
            finder: None,
            picker: Picker::Files,
            hits: Vec::new(),
            clipboard: String::new(),
            last_click: None,
            clipboard_out: None,
            servers: Vec::new(),
            next_server: 0,
            events,
            lsp_setting,
            message: String::new(),
            quit_pending: false,
            close_pending: false,
            should_quit: false,
            size: (0, 0),
            screen: Screen::default(),
        }
    }

    /// Starts with an empty file that has no name, as `curd` with no
    /// arguments does.
    pub fn open_empty(&mut self) {
        self.editors.push(Editor::new(Document::default()));
        self.active = self.editors.len() - 1;
        self.focus = Focus::Editor;
    }

    /// Shows the file tree and puts the keys there.
    pub fn show_folder(&mut self) {
        self.show_tree = true;
        self.focus = Focus::Tree;
    }

    pub fn has_files(&self) -> bool {
        !self.editors.is_empty()
    }

    // ---- Opening, closing and switching files -------------------------

    /// Shows `text` in the status bar until the next key.
    fn say(&mut self, text: String) {
        match self.editors.get_mut(self.active) {
            Some(editor) => editor.message = text,
            None => self.message = text,
        }
    }

    /// Opens the file at `path`, or brings it to the front if it is open
    /// already. A path with nothing there yet starts a new file. Returns
    /// false if it could not be opened.
    pub fn open(&mut self, path: &Path) -> bool {
        // One spelling per file, so the same file is never opened twice.
        let path = std::fs::canonicalize(path)
            .or_else(|_| std::path::absolute(path))
            .unwrap_or_else(|_| path.to_path_buf());
        let text = path.to_string_lossy().into_owned();
        let name = path.file_name().map_or_else(
            || text.clone(),
            |name| name.to_string_lossy().into_owned(),
        );

        if let Some(index) = self
            .editors
            .iter()
            .position(|editor| editor.abs_path.as_deref() == Some(text.as_str()))
        {
            self.active = index;
        } else if path.is_dir() {
            self.say(format!("{name} is a folder"));
            return false;
        } else {
            let document = match Document::open(&text) {
                Ok(document) => document,
                Err(error) => {
                    self.say(format!("Could not open {name}: {error}"));
                    return false;
                }
            };
            let mut editor = Editor::new(document);
            self.attach_lsp(&mut editor);
            // An untouched empty file made way for the first real one.
            let placeholder = self.editors.len() == 1
                && self.editors[0].document.path.is_none()
                && !self.editors[0].document.dirty;
            if placeholder {
                self.editors.clear();
            }
            self.editors.push(editor);
            self.active = self.editors.len() - 1;
            // Find out what the new file looked like in the last commit.
            self.refresh_git();
        }
        self.focus = Focus::Editor;
        self.tree.reveal(&path);
        true
    }

    /// Brings tab `index` to the front.
    fn activate(&mut self, index: usize) {
        if index < self.editors.len() {
            self.active = index;
            self.focus = Focus::Editor;
            if let Some(path) = self.editors[index].abs_path.clone() {
                self.tree.reveal(Path::new(&path));
            }
        }
    }

    /// Moves `step` tabs to the right (left, when negative), wrapping round.
    fn next_tab(&mut self, step: isize) {
        let count = self.editors.len() as isize;
        if count > 0 {
            self.activate((self.active as isize + step).rem_euclid(count) as usize);
        }
    }

    /// Closes the file in front. With unsaved changes it takes a second
    /// press.
    fn close_active(&mut self, was_pending: bool) {
        let Some(editor) = self.editors.get_mut(self.active) else {
            return;
        };
        if editor.document.dirty && !was_pending {
            self.close_pending = true;
            editor.message = "Unsaved changes! Close again to discard".into();
            return;
        }
        let editor = self.editors.remove(self.active);
        if let (Some(lsp), Some(path)) = (&editor.lsp, &editor.abs_path) {
            lsp.borrow_mut().close(path);
        }
        drop(editor);
        // A server with no files left to look after is shut down.
        self.servers.retain(|server| !server.client.borrow().is_unused());

        self.active = self.active.min(self.editors.len().saturating_sub(1));
        if self.editors.is_empty() {
            self.show_folder();
        } else {
            self.activate(self.active);
        }
    }

    /// Closes tab `index`, as a click on its close mark does. A file with
    /// unsaved changes takes a second click.
    fn close_tab(&mut self, index: usize) {
        let pending = std::mem::take(&mut self.close_pending) && index == self.active;
        if index < self.editors.len() {
            self.activate(index);
            self.close_active(pending);
        }
    }

    /// Quits, unless files have unsaved changes: then it takes a second
    /// press.
    fn quit(&mut self, was_pending: bool) {
        let unsaved = self.editors.iter().filter(|editor| editor.document.dirty).count();
        if unsaved == 0 || was_pending {
            self.should_quit = true;
            return;
        }
        self.quit_pending = true;
        // Show one of the files in question.
        if !self.editors[self.active].document.dirty {
            let first = self.editors.iter().position(|editor| editor.document.dirty);
            self.activate(first.unwrap_or(self.active));
        }
        self.say(match unsaved {
            1 => "Unsaved changes! Ctrl+Q again to quit".into(),
            _ => format!("Unsaved changes in {unsaved} files! Ctrl+Q again to quit"),
        });
    }

    // ---- Language servers ---------------------------------------------

    /// Puts a language server in charge of `editor`'s file, starting one
    /// unless a server for the same language and project is running.
    fn attach_lsp(&mut self, editor: &mut Editor) {
        let (Some(events), Some(path)) = (&self.events, editor.abs_path.clone()) else {
            return;
        };
        let setting = self.lsp_setting.as_deref();
        let Some(spec) = ServerSpec::for_file(editor.language, &path, setting) else {
            return;
        };
        let folder = Path::new(&path).parent().unwrap_or(Path::new("/"));
        let root = find_root(folder, spec.root_markers);
        let key = format!("{} {:?} {}", spec.command, spec.args, root.display());

        let client = match self.servers.iter().find(|server| server.key == key) {
            Some(server) => server.client.clone(),
            None => {
                let id = self.next_server;
                self.next_server += 1;
                let events = events.clone();
                let forward = move |message| {
                    let _ = events.send(AppEvent::Lsp(id, message));
                };
                match Client::start(&spec, &root, forward) {
                    Ok(client) => {
                        editor.message = format!("Starting {}...", client.name);
                        let client = Rc::new(RefCell::new(client));
                        self.servers.push(Server {
                            id,
                            key,
                            client: client.clone(),
                        });
                        client
                    }
                    Err(_) => {
                        editor.message =
                            format!("No language server: {} not found", spec.command);
                        return;
                    }
                }
            }
        };
        let lines = &editor.document.lines;
        client
            .borrow_mut()
            .open(&path, spec.language_id, &|| lines.join("\n"));
        editor.attach_lsp(client);
    }

    /// Handles a message from language server `id`, or its exit.
    fn handle_lsp(&mut self, id: usize, message: Option<Value>) {
        let Some(position) = self.servers.iter().position(|server| server.id == id) else {
            return;
        };
        let client = self.servers[position].client.clone();
        let uses_it = |editor: &Editor| editor.lsp.as_ref().is_some_and(|lsp| Rc::ptr_eq(lsp, &client));

        let Some(message) = message else {
            // The server exited: carry on as a plain editor.
            let name = client.borrow().name.clone();
            self.servers.remove(position);
            for (index, editor) in self.editors.iter_mut().enumerate() {
                if uses_it(editor) {
                    editor.detach_lsp();
                    if index == self.active {
                        editor.message = format!("Language server {name} stopped");
                    }
                }
            }
            return;
        };

        let editors = &self.editors;
        let text_of = |path: &str| {
            editors
                .iter()
                .find(|editor| editor.abs_path.as_deref() == Some(path))
                .map(|editor| editor.document.lines.join("\n"))
                .unwrap_or_default()
        };
        let (path, reply) = client.borrow_mut().handle(&message, &text_of);
        let in_front = self.editors.get(self.active).and_then(|editor| editor.abs_path.clone());

        match reply {
            Reply::Nothing => {}
            Reply::Ready => {
                if let Some(editor) = self.editors.get_mut(self.active).filter(|editor| uses_it(editor))
                {
                    editor.apply_reply(Reply::Ready);
                }
            }
            // Answers to a question only matter while the file that asked
            // is still in front.
            Reply::Hover(_) | Reply::Definition(_) if path != in_front => {}
            Reply::Definition(Some(mut location)) => {
                // A definition in another file: open that file, then jump.
                if Some(&location.path) != in_front.as_ref()
                    && Path::new(&location.path).is_file()
                    && self.open(Path::new(&location.path))
                    && let Some(opened) = self.editors[self.active].abs_path.clone()
                {
                    location.path = opened;
                }
                self.editors[self.active].apply_reply(Reply::Definition(Some(location)));
            }
            reply => {
                if let Some(editor) = self
                    .editors
                    .iter_mut()
                    .find(|editor| editor.abs_path.is_some() && editor.abs_path == path)
                {
                    editor.apply_reply(reply);
                }
            }
        }
    }

    /// Asks git, on a background thread, what state the project is in and
    /// what each open file looked like in the last commit. The answers
    /// arrive later as `AppEvent::Git` and `AppEvent::Committed`.
    fn refresh_git(&self) {
        if let Some(events) = &self.events {
            let events = events.clone();
            let root = self.tree.root().to_path_buf();
            let open: Vec<String> = self
                .editors
                .iter()
                .filter_map(|editor| editor.abs_path.clone())
                .collect();
            std::thread::spawn(move || {
                let _ = events.send(AppEvent::Git(git::load(&root)));
                for path in open {
                    let lines = git::committed_lines(Path::new(&path));
                    let _ = events.send(AppEvent::Committed(path, lines));
                }
            });
        }
    }

    // ---- Project search and git commands ------------------------------

    /// Opens the list over the text for `picker`, offering `items`.
    fn pick(&mut self, picker: Picker, items: Vec<String>) {
        self.picker = picker;
        self.finder = Some(match picker {
            Picker::Files => Finder::with_files(items),
            _ => Finder::list(items),
        });
    }

    /// Searches every file of the project for `query` and lists the lines
    /// that hold it.
    fn search_project(&mut self, query: &str) {
        let files = finder::project_files(self.tree.root());
        self.hits = search::in_files(self.tree.root(), &files, query);
        if self.hits.is_empty() {
            self.say(format!("No match for {query} in the project"));
            return;
        }
        let lines = self
            .hits
            .iter()
            .map(|hit| format!("{}:{}: {}", hit.file, hit.y + 1, hit.text))
            .collect();
        self.pick(Picker::Results, lines);
    }

    /// Opens the file line `index` of the search results is in, there.
    fn open_hit(&mut self, index: usize) {
        let Some(hit) = self.hits.get(index) else {
            return;
        };
        let (path, x, y) = (self.tree.root().join(&hit.file), hit.x, hit.y);
        if self.open(&path) {
            self.editors[self.active].jump_to(x, y);
        }
    }

    fn open_git_menu(&mut self) {
        if self.git.is_some() {
            self.pick(Picker::Git, GIT_MENU.iter().map(|item| item.to_string()).collect());
        } else {
            self.say("This folder is not in git".into());
        }
    }

    /// The file a git command is about: the one selected in the tree while
    /// the keys are there, or else the one in front.
    fn git_target(&self) -> Option<PathBuf> {
        match (self.focus, self.tree.selected()) {
            (Focus::Tree, Some(entry)) => Some(entry.path.clone()),
            _ => self.editors.get(self.active)?.abs_path.as_ref().map(PathBuf::from),
        }
    }

    /// Runs line `index` of the git menu.
    fn git_command(&mut self, index: usize) {
        let unsaved = self.editors.iter().any(|editor| editor.document.dirty);
        match GIT_MENU[index] {
            "Stage this file" | "Unstage this file" => {
                let Some(path) = self.git_target() else {
                    return self.say("No file to stage: open or select one first".into());
                };
                let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
                let path = path.to_string_lossy().into_owned();
                if GIT_MENU[index] == "Stage this file" {
                    self.run_git(format!("Staged {name}"), move |root| {
                        git::action(root, &["add", "--", &path])
                    });
                } else {
                    self.run_git(format!("Unstaged {name}"), move |root| {
                        git::action(root, &["restore", "--staged", "--", &path])
                    });
                }
            }
            "Stage all changes" => {
                self.run_git("Staged all changes".into(), |root| git::action(root, &["add", "--all"]));
            }
            "Unstage everything" => {
                self.run_git("Unstaged everything".into(), |root| git::action(root, &["reset", "--quiet"]));
            }
            "Commit..." => self.pick(Picker::Commit, Vec::new()),
            "New branch..." => self.pick(Picker::NewBranch, Vec::new()),
            // These two change files on disk, which unsaved text would
            // then silently disagree with.
            "Switch branch..." | "Pull" if unsaved => {
                self.say("Save your changes first: this changes the files on disk".into());
            }
            "Switch branch..." => {
                let branches = git::branches(self.tree.root());
                self.pick(Picker::Branches, branches);
            }
            "Pull" => {
                self.run_git("Pulled".into(), |root| git::action(root, &["pull", "--no-edit"]));
            }
            _ => self.run_git("Pushed".into(), git::push),
        }
    }

    /// Runs `job` (a git command) in the project folder, away from the
    /// keys so a slow one does not freeze the editor, and says `done`
    /// afterwards, or what went wrong.
    fn run_git(
        &mut self,
        done: String,
        job: impl FnOnce(&Path) -> Result<(), String> + Send + 'static,
    ) {
        let root = self.tree.root().to_path_buf();
        let report = move || match job(&root) {
            Ok(()) => done,
            Err(error) => format!("git: {error}"),
        };
        match &self.events {
            Some(events) => {
                let events = events.clone();
                std::thread::spawn(move || {
                    let _ = events.send(AppEvent::GitDone(report()));
                });
                self.say("Running git...".into());
            }
            // Tests have no queue to answer on: do it on the spot.
            None => {
                let message = report();
                self.git_done(message);
            }
        }
    }

    /// A git command finished: files, branch and states may all be new.
    fn git_done(&mut self, message: String) {
        self.tree.refresh();
        self.reload_changed();
        self.refresh_git();
        self.say(message);
    }

    /// Reads again every open file that was changed on disk by something
    /// else (a branch switch, a pull, another program). Files with unsaved
    /// changes are left alone.
    fn reload_changed(&mut self) {
        for editor in &mut self.editors {
            let Some(path) = editor.abs_path.clone().filter(|path| Path::new(path).is_file()) else {
                continue;
            };
            if editor.document.dirty {
                continue;
            }
            if let Ok(on_disk) = Document::open(&path)
                && on_disk.lines.join("\n") != editor.document.lines.join("\n")
            {
                editor.reload(&on_disk.lines);
            }
        }
    }

    // ---- Events --------------------------------------------------------

    pub fn run(&mut self, events: &Receiver<AppEvent>) -> std::io::Result<()> {
        self.refresh_git();
        while !self.should_quit {
            self.size = Terminal::size()?;
            let (frame, cursor) = self.render(self.size.0, self.size.1);
            self.screen.draw(frame, self.size, cursor)?;
            if let Some(text) = self.clipboard_out.take() {
                Terminal::copy(&text)?;
            }

            // Sleep until something happens. With edits waiting to go to a
            // language server, wake up after a short pause in typing instead.
            let waiting_to_sync = self
                .servers
                .iter()
                .any(|server| server.client.borrow().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.editors.iter_mut().for_each(Editor::sync_lsp),
            }
        }
        Ok(())
    }

    fn handle_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::Input(Event::Key(key)) => self.handle_key(key),
            AppEvent::Input(Event::Mouse(mouse)) => self.handle_mouse(mouse),
            AppEvent::Input(Event::Paste(text)) => self.paste(&text),
            AppEvent::Input(Event::FocusGained) => {
                // Coming back from another window: files and git state may
                // have changed there.
                self.tree.refresh();
                self.reload_changed();
                self.refresh_git();
            }
            AppEvent::Input(_) => {}
            AppEvent::Lsp(id, message) => self.handle_lsp(id, message),
            AppEvent::Git(git) => self.git = git,
            AppEvent::GitDone(message) => self.git_done(message),
            AppEvent::Committed(path, lines) => {
                if let Some(editor) = self
                    .editors
                    .iter_mut()
                    .find(|editor| editor.abs_path.as_deref() == Some(path.as_str()))
                {
                    editor.set_git_base(lines);
                }
            }
        }
    }

    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;
        }
        if self.finder.is_some() {
            self.finder_key(key);
            return;
        }
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);

        // Messages and confirmations only last until the next key.
        let quit_was_pending = std::mem::take(&mut self.quit_pending);
        let close_was_pending = std::mem::take(&mut self.close_pending);
        self.message.clear();
        if let Some(editor) = self.editors.get_mut(self.active) {
            editor.message.clear();
        }

        // Commands for the whole window come first. Each has an Alt form
        // as well, because some terminals keep Ctrl keys for themselves.
        match key.code {
            KeyCode::Char('q') if ctrl => self.quit(quit_was_pending),
            KeyCode::Char('p') if ctrl || alt => {
                self.picker = Picker::Files;
                self.finder = Some(Finder::new(self.tree.root()));
            }
            KeyCode::Char('s') if alt => self.pick(Picker::Search, Vec::new()),
            KeyCode::Char('g') if ctrl => self.open_git_menu(),
            KeyCode::Char('v') if alt => self.open_git_menu(),
            KeyCode::Char('v') if ctrl => {
                let text = self.clipboard.clone();
                self.paste(&text);
            }
            KeyCode::Char('b') if ctrl || alt => self.toggle_tree(),
            KeyCode::Char('e') if alt => self.switch_focus(),
            KeyCode::Char('w') if ctrl || alt => self.close_active(close_was_pending),
            KeyCode::Char('.') if alt => self.next_tab(1),
            KeyCode::Char(',') if alt => self.next_tab(-1),
            KeyCode::PageDown if ctrl => self.next_tab(1),
            KeyCode::PageUp if ctrl => self.next_tab(-1),
            KeyCode::Char(digit @ '1'..='9') if alt => self.activate(digit as usize - '1' as usize),
            _ if self.focus == Focus::Tree => self.tree_key(key),
            _ => self.editor_key(key),
        }
    }

    /// A key for the file in front.
    fn editor_key(&mut self, key: KeyEvent) {
        let Some(editor) = self.editors.get_mut(self.active) else {
            return;
        };
        editor.handle_key(key);
        if let Some(text) = editor.copied.take() {
            self.clipboard = text.clone();
            self.clipboard_out = Some(text);
        }
        let saved = std::mem::take(&mut editor.just_saved);
        let renamed = std::mem::take(&mut editor.renamed);
        if renamed {
            // The file has a name now, so it can have a language server
            // and a place in the tree.
            let mut editor = self.editors.remove(self.active);
            self.attach_lsp(&mut editor);
            self.editors.insert(self.active, editor);
        }
        if saved {
            // A save can create a file and always changes its git state.
            self.tree.refresh();
            self.refresh_git();
        }
        if renamed && let Some(path) = self.editors[self.active].abs_path.clone() {
            self.tree.reveal(Path::new(&path));
        }
    }

    fn tree_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Up => self.tree.move_by(-1),
            KeyCode::Down => self.tree.move_by(1),
            KeyCode::PageUp => self.tree.move_by(-10),
            KeyCode::PageDown => self.tree.move_by(10),
            KeyCode::Home => self.tree.move_by(isize::MIN / 2),
            KeyCode::End => self.tree.move_by(isize::MAX / 2),
            KeyCode::Left => self.tree.left(),
            KeyCode::Right => self.tree.right(),
            KeyCode::Enter => {
                if let Some(path) = self.tree.activate() {
                    self.open(&path);
                }
            }
            KeyCode::Esc if self.has_files() => self.focus = Focus::Editor,
            _ => {}
        }
    }

    fn finder_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Some(finder) = &mut self.finder else {
            return;
        };
        match key.code {
            KeyCode::Esc => self.finder = None,
            KeyCode::Char('p' | 'q' | 'c') if ctrl => self.finder = None,
            KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::ALT) => self.finder = None,
            KeyCode::Enter => self.accept_picked(),
            KeyCode::Up => finder.move_by(-1),
            KeyCode::Down => finder.move_by(1),
            KeyCode::Backspace => finder.backspace(),
            KeyCode::Char(c) if !ctrl => finder.type_char(c),
            _ => {}
        }
    }

    /// Enter in the list over the text (or a click on one of its lines):
    /// acts on what is selected or was typed.
    fn accept_picked(&mut self) {
        let Some(finder) = &self.finder else {
            return;
        };
        let typed = finder.query.trim().to_string();
        let index = finder.chosen_index();
        let chosen = finder.chosen().map(String::from);
        self.finder = None;
        match (self.picker, index, chosen) {
            (picker, ..) if picker.is_question() && typed.is_empty() => {}
            (Picker::Search, ..) => self.search_project(&typed),
            (Picker::Commit, ..) => {
                let message = typed.clone();
                self.run_git(format!("Committed: {typed}"), move |root| {
                    git::action(root, &["commit", "--message", &message])
                });
            }
            (Picker::NewBranch, ..) => {
                let name = typed.clone();
                self.run_git(format!("On new branch {typed}"), move |root| {
                    git::action(root, &["switch", "--create", &name])
                });
            }
            (Picker::Files, _, Some(file)) => {
                let path = self.tree.root().join(file);
                self.open(&path);
            }
            (Picker::Results, Some(index), _) => self.open_hit(index),
            (Picker::Git, Some(index), _) => self.git_command(index),
            (Picker::Branches, _, Some(branch)) => {
                let name = branch.clone();
                self.run_git(format!("Switched to {branch}"), move |root| {
                    git::action(root, &["switch", &name])
                });
            }
            _ => {}
        }
    }

    fn paste(&mut self, text: &str) {
        if let Some(finder) = &mut self.finder {
            text.chars()
                .filter(|c| !c.is_control())
                .for_each(|c| finder.type_char(c));
        } else if self.focus == Focus::Editor
            && let Some(editor) = self.editors.get_mut(self.active)
        {
            editor.paste(text);
        }
    }

    /// Shows or hides the file tree. Showing it puts the keys there.
    fn toggle_tree(&mut self) {
        if self.show_tree && self.has_files() {
            self.show_tree = false;
            self.focus = Focus::Editor;
        } else {
            self.show_folder();
            self.tree.refresh();
            self.refresh_git();
        }
    }

    /// Moves the keys between the file tree and the file in front.
    fn switch_focus(&mut self) {
        if self.focus == Focus::Tree && self.has_files() {
            self.focus = Focus::Editor;
        } else {
            self.show_folder();
        }
    }

    /// The mouse while the list over the text is open: a click on a line
    /// picks it, the wheel moves the selection, a click elsewhere closes it.
    fn picker_mouse(&mut self, mouse: MouseEvent, layout: &Layout) {
        let Some(finder) = &mut self.finder else {
            return;
        };
        let (x, y) = (mouse.column as usize, mouse.row as usize);
        let count = FINDER_ROWS.min(layout.pane_height.saturating_sub(2));
        match mouse.kind {
            MouseEventKind::ScrollDown => finder.move_by(1),
            MouseEventKind::ScrollUp => finder.move_by(-1),
            MouseEventKind::Down(MouseButton::Left) => {
                // The list starts on the row under the question.
                let row = y.checked_sub(layout.tabs + 1).filter(|_| x >= layout.tree);
                if row.is_some_and(|row| finder.select_row(row, count)) {
                    self.accept_picked();
                } else if y != layout.tabs {
                    self.finder = None;
                }
            }
            _ => {}
        }
    }

    fn handle_mouse(&mut self, mouse: MouseEvent) {
        let layout = self.layout(self.size.0, self.size.1);
        if self.finder.is_some() {
            return self.picker_mouse(mouse, &layout);
        }
        let (x, y) = (mouse.column as usize, mouse.row as usize);
        let over_tree = x < layout.tree && y >= layout.tabs;
        let over_tabs = y < layout.tabs;
        match mouse.kind {
            // The middle button on a tab closes it.
            MouseEventKind::Down(MouseButton::Middle) if over_tabs => {
                if let Some((tab, _)) = self.tab_at(x) {
                    self.close_tab(tab);
                }
            }
            // The wheel over the tab bar goes through the tabs.
            MouseEventKind::ScrollDown if over_tabs => self.next_tab(1),
            MouseEventKind::ScrollUp if over_tabs => self.next_tab(-1),
            MouseEventKind::Down(MouseButton::Left) => {
                if over_tabs {
                    match self.tab_at(x) {
                        Some((tab, true)) => self.close_tab(tab),
                        Some((tab, false)) => self.activate(tab),
                        None => {}
                    }
                } else if over_tree {
                    self.focus = Focus::Tree;
                    // The first row of the tree is its title.
                    if let Some(row) = (y - layout.tabs).checked_sub(1)
                        && let Some(path) = self.tree.click(row)
                    {
                        self.open(&path);
                    }
                } else if let Some(editor) = self.editors.get_mut(self.active) {
                    self.focus = Focus::Editor;
                    editor.click(x - layout.tree, y - layout.tabs);
                    // A second click on the same spot selects the word.
                    let now = Instant::now();
                    let double = self.last_click.is_some_and(|(at, last_x, last_y)| {
                        (last_x, last_y) == (x, y) && now.duration_since(at) < DOUBLE_CLICK
                    });
                    if double {
                        editor.select_word();
                    }
                    self.last_click = (!double).then_some((now, x, y));
                }
            }
            // Dragging over the text selects it.
            MouseEventKind::Drag(MouseButton::Left)
                if self.focus == Focus::Editor && y >= layout.tabs && x >= layout.tree =>
            {
                if let Some(editor) = self.editors.get_mut(self.active) {
                    editor.drag(x - layout.tree, y - layout.tabs);
                }
            }
            MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
                let lines = match mouse.kind {
                    MouseEventKind::ScrollDown => WHEEL_LINES,
                    _ => -WHEEL_LINES,
                };
                if over_tree {
                    self.tree.move_by(lines);
                } else if let Some(editor) = self.editors.get_mut(self.active) {
                    editor.wheel(lines);
                }
            }
            _ => {}
        }
    }

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

    fn layout(&self, width: usize, height: usize) -> Layout {
        let tabs = (self.editors.len() > 1) as usize;
        let tree = if self.show_tree {
            // The tree and the line that separates it from the text.
            TREE_WIDTH.min(width / 2) + 1
        } else {
            0
        };
        Layout {
            tabs,
            tree,
            pane_width: width.saturating_sub(tree),
            pane_height: height.saturating_sub(tabs),
        }
    }

    /// The text of each tab: the file's name, a dot if it has unsaved
    /// changes, and the mark that closes it.
    fn tab_labels(&self) -> Vec<String> {
        self.editors
            .iter()
            .map(|editor| {
                let dot = if editor.document.dirty { " ●" } else { "" };
                format!(" {}{dot} {CLOSE_ICON} ", editor.name())
            })
            .collect()
    }

    /// The tab under screen column `x`, if any, and whether `x` is on its
    /// close mark.
    fn tab_at(&self, x: usize) -> Option<(usize, bool)> {
        let mut end = 0;
        let tab = self.tab_labels().iter().position(|label| {
            end += label.chars().count();
            x < end
        })?;
        // The mark and the space after it.
        Some((tab, x + 2 >= end))
    }

    fn tab_row(&self, width: usize) -> Row {
        let mut row = Row::new();
        let mut used = 0;
        for (index, label) in self.tab_labels().iter().enumerate() {
            let label = fit(label, label.chars().count().min(width - used));
            used += label.chars().count();
            let style = if index == self.active { Style::Reverse } else { Style::Dim };
            row.push(Span::new(style, label));
        }
        row
    }

    /// What fills the text area when no file is open.
    fn empty_pane(&self, width: usize, height: usize) -> Vec<Row> {
        let mut rows = Vec::with_capacity(height);
        for y in 0..height.saturating_sub(1) {
            let text = match y.checked_sub(height / 3) {
                Some(0) => concat!("curd editor -- v", env!("CARGO_PKG_VERSION")),
                Some(2) => "Enter   open the selected file",
                Some(3) => "Ctrl+P  find a file by name",
                Some(4) => "Ctrl+Q  quit",
                _ => "",
            };
            let padding = width.saturating_sub(30) / 2;
            let line: String = format!("{}{text}", " ".repeat(padding))
                .chars()
                .take(width)
                .collect();
            rows.push(vec![Span::new(Style::Dim, line)]);
        }
        if height > 0 {
            let status = if self.message.is_empty() { "No file open" } else { &self.message };
            rows.push(vec![Span::new(Style::Reverse, fit(status, width))]);
        }
        rows
    }

    /// Everything that should be on a `width` x `height` screen, and where
    /// the cursor goes (nowhere, while the keys are in the file tree).
    fn render(&mut self, width: usize, height: usize) -> (Vec<Row>, Option<(usize, usize)>) {
        let layout = self.layout(width, height);
        let (pane_width, pane_height) = (layout.pane_width, layout.pane_height);

        let mut pane = match self.editors.get_mut(self.active) {
            Some(editor) => {
                editor.scroll(
                    pane_width.saturating_sub(editor.gutter_width()),
                    pane_height.saturating_sub(1),
                );
                editor.render(pane_width, pane_height)
            }
            None => self.empty_pane(pane_width, pane_height),
        };
        let mut cursor = match (self.focus, self.editors.get(self.active)) {
            (Focus::Editor, Some(editor)) => Some(editor.cursor_on_screen()),
            _ => None,
        };

        // Quick open sits over the top of the text.
        if let Some(finder) = &self.finder {
            let mut lines = vec![Span::new(
                Style::Reverse,
                fit(&format!("{}{}", self.picker.prompt(), finder.query), pane_width),
            )];
            let matches = finder.visible(FINDER_ROWS.min(pane_height.saturating_sub(2)));
            if matches.is_empty() && !self.picker.is_question() {
                let nothing = match self.picker {
                    Picker::Files => "   no matching files",
                    _ => "   nothing matches",
                };
                lines.push(Span::new(Style::Dim, fit(nothing, pane_width)));
            }
            for (path, selected) in matches {
                lines.push(if selected {
                    Span::new(Style::Bold, fit(&format!(" > {path}"), pane_width))
                } else {
                    Span::new(Style::Dim, fit(&format!("   {path}"), pane_width))
                });
            }
            for (row, line) in pane.iter_mut().zip(lines) {
                *row = vec![line];
            }
            let typed = self.picker.prompt().len() + finder.query.chars().count();
            cursor = Some((typed.min(pane_width.saturating_sub(1)), 0));
        }

        let mut sidebar = (layout.tree > 0).then(|| {
            let focused = self.focus == Focus::Tree && self.finder.is_none();
            self.tree
                .render(layout.tree - 1, pane_height, focused, self.git.as_ref())
        });

        let mut rows = Vec::with_capacity(height);
        if layout.tabs > 0 && height > 0 {
            rows.push(self.tab_row(width));
        }
        for (y, pane_row) in pane.into_iter().enumerate() {
            let mut row = Row::new();
            if let Some(sidebar) = &mut sidebar {
                row.append(&mut sidebar[y]);
                row.push(Span::new(Style::Dim, "│"));
            }
            row.extend(pane_row);
            rows.push(row);
        }
        let cursor = cursor.map(|(x, y)| (x + layout.tree, y + layout.tabs));
        (rows, cursor)
    }
}