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
//! 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;

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::Finder;
use crate::git::{self, GitInfo};
use crate::lsp::{find_root, Client, Reply, ServerSpec};
use crate::screen::{fit, Row, Screen, Span, Style};
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;
/// Most matches shown by quick open.
const FINDER_ROWS: usize = 8;
const FINDER_PROMPT: &str = " Open file: ";

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

/// 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>,
    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,
            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! Ctrl+W again to close".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);
        }
    }

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

    // ---- 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)?;

            // 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.refresh_git();
            }
            AppEvent::Input(_) => {}
            AppEvent::Lsp(id, message) => self.handle_lsp(id, message),
            AppEvent::Git(git) => self.git = git,
            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.finder = Some(Finder::new(self.tree.root())),
            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);
        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 => {
                let chosen = finder.chosen().map(|path| self.tree.root().join(path));
                self.finder = None;
                if let Some(path) = chosen {
                    self.open(&path);
                }
            }
            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),
            _ => {}
        }
    }

    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();
        }
    }

    fn handle_mouse(&mut self, mouse: MouseEvent) {
        if self.finder.is_some() {
            return;
        }
        let layout = self.layout(self.size.0, self.size.1);
        let (x, y) = (mouse.column as usize, mouse.row as usize);
        let over_tree = x < layout.tree && y >= layout.tabs;
        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                if y < layout.tabs {
                    if let Some(tab) = self.tab_at(x) {
                        self.activate(tab);
                    }
                } 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);
                }
            }
            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, and a dot if it has unsaved
    /// changes.
    fn tab_labels(&self) -> Vec<String> {
        self.editors
            .iter()
            .map(|editor| {
                let dot = if editor.document.dirty { " ●" } else { "" };
                format!(" {}{dot} ", editor.name())
            })
            .collect()
    }

    /// The tab under screen column `x`, if any.
    fn tab_at(&self, x: usize) -> Option<usize> {
        let mut end = 0;
        self.tab_labels().iter().position(|label| {
            end += label.chars().count();
            x < 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!("{FINDER_PROMPT}{}", finder.query), pane_width),
            )];
            let matches = finder.visible(FINDER_ROWS.min(pane_height.saturating_sub(2)));
            if matches.is_empty() {
                lines.push(Span::new(Style::Dim, fit("   no matching files", 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 = FINDER_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)
    }
}