plannotator-tui 0.13.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! The comment box: a small multi-line editor, shared by document and code reviews.
//!
//! Enter saves; Shift+Enter (where the terminal's keyboard protocol distinguishes it),
//! Alt+Enter and Ctrl+J insert a new line; Esc cancels. The usual readline keys edit by word
//! and by line, and Up and Down move between display rows. The buffer is a char vec with a
//! cursor, wrapped at word boundaries to the box width for display only — the saved body
//! keeps exactly the newlines the user typed.

use std::cell::Cell;
use std::ops::Range;

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr as _};

use crate::keys::{self, Action, Keymap};
use crate::theme::palette;

/// What a keystroke did to the compose box.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ComposeAction {
    Edited,
    Save,
    Cancel,
}

#[derive(Debug, Default)]
pub(crate) struct Compose {
    chars: Vec<char>,
    cursor: usize,
    /// The text the box opened with, to tell whether cancelling would lose anything.
    initial: String,
    /// Esc was pressed with changed text, and the box is asking whether to discard it.
    asking: bool,
    /// The first display row the box showed last frame. It moves only when the cursor leaves
    /// the rows shown, so a click or an arrow inside them does not shift the text.
    scroll: Cell<usize>,
}

/// The columns a tab takes in the box, and in a note's box in the diff.
pub(crate) const TAB_WIDTH: usize = 4;

/// The columns `c` takes in the box: a tab four, a control character (a code line's `\r`)
/// none.
fn width_of(c: char) -> usize {
    if c == '\t' { TAB_WIDTH } else { UnicodeWidthChar::width(c).unwrap_or(0) }
}

/// A display row as the terminal draws it: tabs as spaces, control characters as nothing.
/// The text itself keeps them.
fn shown(row: &str) -> String {
    row.chars()
        .flat_map(|c| match c {
            '\t' => vec![' '; TAB_WIDTH],
            c if c.is_control() => Vec::new(),
            c => vec![c],
        })
        .collect()
}

impl Compose {
    pub(crate) fn with_text(text: &str) -> Self {
        let chars: Vec<char> = text.chars().collect();
        let cursor = chars.len();
        Self { chars, cursor, initial: text.to_owned(), asking: false, scroll: Cell::new(0) }
    }

    pub(crate) fn value(&self) -> String {
        self.chars.iter().collect()
    }

    /// Whether saving would store something other than what the box opened with. Saving
    /// trims, so whitespace at the edges does not count.
    pub(crate) fn has_changes(&self) -> bool {
        self.value().trim() != self.initial.trim()
    }

    /// Apply one keystroke as a comment box: like [`Compose::handle_key`], except that Esc
    /// with changed text asks first. While it asks, only `yes` (which cancels) and `no` or
    /// `back` (which go back to editing) do anything; Enter is no answer, so a slip
    /// cannot lose the text.
    pub(crate) fn key(&mut self, keymap: &Keymap, key: KeyEvent, wrap_width: usize) -> ComposeAction {
        if self.asking {
            match keymap.action(&key, keys::CONFIRM_CLEAR) {
                Some(Action::Yes) => {
                    self.asking = false;
                    return ComposeAction::Cancel;
                }
                Some(Action::No | Action::Back) => self.asking = false,
                _ => {}
            }
            return ComposeAction::Edited;
        }
        match self.handle_key(key, wrap_width) {
            ComposeAction::Cancel if self.has_changes() => {
                self.asking = true;
                ComposeAction::Edited
            }
            action => action,
        }
    }

    /// The box's title: [`title`], or the discard question while it asks.
    pub(crate) fn heading(&self, verb: &str, shift_enter: bool, keymap: &Keymap) -> String {
        if !self.asking {
            return title(verb, shift_enter);
        }
        let answers = [(Action::Yes, "discard"), (Action::No, "keep editing")]
            .into_iter()
            .filter_map(|(action, label)| keymap.labelled(action, label))
            .collect::<Vec<_>>()
            .join(" \u{b7} ");
        format!(" discard {verb}? {answers} ")
    }

    /// Apply one keystroke. `wrap_width` is the width the box last wrapped to, which Up and
    /// Down move within.
    pub(crate) fn handle_key(&mut self, key: KeyEvent, wrap_width: usize) -> ComposeAction {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        match key.code {
            KeyCode::Esc => return ComposeAction::Cancel,
            KeyCode::Enter if key.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) => {
                self.insert('\n');
            }
            KeyCode::Enter => return ComposeAction::Save,
            KeyCode::Char('j' | 'J') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.insert('\n');
            }
            KeyCode::Char('a' | 'A') if ctrl => self.cursor = self.line_start(),
            KeyCode::Char('e' | 'E') if ctrl => self.cursor = self.line_end(),
            KeyCode::Char('u' | 'U') if ctrl => self.delete_to(self.line_start()),
            KeyCode::Char('k' | 'K') if ctrl => self.delete_to(self.line_end()),
            // Many terminals send Ctrl+H for Ctrl+Backspace.
            KeyCode::Char('w' | 'W' | 'h' | 'H') if ctrl => self.delete_to(self.previous_word_start()),
            KeyCode::Backspace if ctrl || alt => self.delete_to(self.previous_word_start()),
            KeyCode::Char('d' | 'D') if alt => self.delete_to(self.next_word_end()),
            KeyCode::Delete if ctrl => self.delete_to(self.next_word_end()),
            KeyCode::Char('b' | 'B') if alt => self.cursor = self.previous_word_start(),
            KeyCode::Char('f' | 'F') if alt => self.cursor = self.next_word_end(),
            KeyCode::Backspace => {
                if self.cursor > 0 {
                    self.cursor -= 1;
                    self.chars.remove(self.cursor);
                }
            }
            KeyCode::Delete => {
                if self.cursor < self.chars.len() {
                    self.chars.remove(self.cursor);
                }
            }
            KeyCode::Left if ctrl || alt => self.cursor = self.previous_word_start(),
            KeyCode::Right if ctrl || alt => self.cursor = self.next_word_end(),
            KeyCode::Left => self.cursor = self.cursor.saturating_sub(1),
            KeyCode::Right => self.cursor = (self.cursor + 1).min(self.chars.len()),
            KeyCode::Up => self.move_vertical(-1, wrap_width),
            KeyCode::Down => self.move_vertical(1, wrap_width),
            KeyCode::Home => self.cursor = self.line_start(),
            KeyCode::End => self.cursor = self.line_end(),
            KeyCode::Char(c) if !ctrl && !alt => self.insert(c),
            _ => {}
        }
        ComposeAction::Edited
    }

    /// Insert pasted text as typed characters, newlines included.
    pub(crate) fn insert_text(&mut self, text: &str) {
        // A paste during the discard question is an answer too: keep editing.
        self.asking = false;
        for c in text.replace("\r\n", "\n").replace('\r', "\n").chars() {
            self.insert(c);
        }
    }

    fn insert(&mut self, c: char) {
        self.chars.insert(self.cursor, c);
        self.cursor += 1;
    }

    /// Remove the text between the cursor and `index`, leaving the cursor at the gap.
    fn delete_to(&mut self, index: usize) {
        let range = self.cursor.min(index)..self.cursor.max(index);
        self.cursor = range.start;
        self.chars.drain(range);
    }

    /// Where the logical line under the cursor starts.
    fn line_start(&self) -> usize {
        let mut index = self.cursor;
        while index > 0 && self.chars.get(index - 1) != Some(&'\n') {
            index -= 1;
        }
        index
    }

    /// Where the logical line under the cursor ends, before its newline.
    fn line_end(&self) -> usize {
        let mut index = self.cursor;
        while index < self.chars.len() && self.chars.get(index) != Some(&'\n') {
            index += 1;
        }
        index
    }

    fn is_word_char_at(&self, index: usize) -> bool {
        self.chars.get(index).is_some_and(|c| c.is_alphanumeric() || *c == '_')
    }

    /// Where the word before the cursor starts, skipping any separators in between.
    fn previous_word_start(&self) -> usize {
        let mut index = self.cursor;
        while index > 0 && !self.is_word_char_at(index - 1) {
            index -= 1;
        }
        while index > 0 && self.is_word_char_at(index - 1) {
            index -= 1;
        }
        index
    }

    /// Where the word after the cursor ends, skipping any separators in between.
    fn next_word_end(&self) -> usize {
        let mut index = self.cursor;
        while index < self.chars.len() && !self.is_word_char_at(index) {
            index += 1;
        }
        while index < self.chars.len() && self.is_word_char_at(index) {
            index += 1;
        }
        index
    }

    /// Move to the display row above or below, landing on the nearest display column. The
    /// first and last rows have nowhere further to go, so the cursor stays put.
    fn move_vertical(&mut self, delta: isize, wrap_width: usize) {
        let rows = self.rows(wrap_width);
        let (row, col) = self.cursor_position(&rows);
        let Some(target_row) = row.checked_add_signed(delta) else { return };
        if let Some(cursor) = self.index_at(&rows, target_row, col) {
            self.cursor = cursor;
        }
    }

    /// A click on the text: the cursor goes to display row `row` (the last, below the text) at
    /// display column `col`, or the end of that row. While the box asks whether to discard,
    /// a click is no answer and changes nothing.
    #[cfg_attr(not(unix), allow(dead_code, reason = "only the code review reads it"))]
    pub(crate) fn click(&mut self, row: usize, col: usize, wrap_width: usize) {
        if self.asking {
            return;
        }
        let rows = self.rows(wrap_width);
        if let Some(cursor) = self.index_at(&rows, row.min(rows.len().saturating_sub(1)), col) {
            self.cursor = cursor;
        }
    }

    /// The index shown on display row `row` of `rows` nearest display column `col`.
    fn index_at(&self, rows: &[Range<usize>], row: usize, col: usize) -> Option<usize> {
        let target = rows.get(row)?;
        let mut cursor = target.start;
        let mut used = 0;
        for &c in self.chars.get(target.clone()).unwrap_or_default() {
            let w = width_of(c);
            if used + w > col {
                break;
            }
            used += w;
            cursor += 1;
        }
        // A wrapped row's end is the next row's start, which displays on that next row.
        let wraps = rows.get(row + 1).is_some_and(|next| next.start == target.end);
        Some(if wraps && cursor == target.end { cursor.saturating_sub(1) } else { cursor })
    }

    /// The range of `chars` each display row shows at `width`. Explicit newlines always
    /// break; a word that does not fit moves to the next row, and one wider than a whole row
    /// splits. Every char stays on a row so the cursor can reach it: spaces at a break hang
    /// past the edge rather than opening the next row.
    fn rows(&self, width: usize) -> Vec<Range<usize>> {
        let width = width.max(1);
        let mut rows = Vec::new();
        let (mut start, mut used) = (0, 0);
        let mut word_start = None;
        for (i, &c) in self.chars.iter().enumerate() {
            if c == '\n' {
                rows.push(start..i);
                start = i + 1;
                used = 0;
                word_start = None;
                continue;
            }
            let w = width_of(c);
            if c.is_whitespace() {
                word_start = Some(i + 1);
            } else if used + w > width {
                let at = word_start.take().unwrap_or(i);
                if at > start {
                    rows.push(start..at);
                    start = at;
                    used = self.chars.get(at..i).unwrap_or_default().iter().copied().map(width_of).sum();
                }
                // A wide char can overflow even a row holding only its own word.
                if used + w > width && i > start {
                    rows.push(start..i);
                    start = i;
                    used = 0;
                }
            }
            used += w;
        }
        rows.push(start..self.chars.len());
        rows
    }

    /// The cursor's (row, col) in `rows`. At a wrap the cursor shows on the later row, next
    /// to the character it sits before.
    fn cursor_position(&self, rows: &[Range<usize>]) -> (usize, usize) {
        let row = rows.iter().rposition(|range| range.start <= self.cursor).unwrap_or(0);
        let start = rows.get(row).map_or(0, |range| range.start);
        let before = self.chars.get(start..self.cursor).unwrap_or_default();
        (row, before.iter().copied().map(width_of).sum())
    }

    /// The buffer as display rows at `width`, with the cursor's (row, col) in them.
    pub(crate) fn wrapped(&self, width: usize) -> (Vec<String>, usize, usize) {
        let rows = self.rows(width);
        let (cursor_row, cursor_col) = self.cursor_position(&rows);
        let lines = rows
            .iter()
            .map(|range| self.chars.get(range.clone()).unwrap_or_default().iter().collect())
            .collect();
        (lines, cursor_row, cursor_col)
    }
}

/// Compose box columns not used for wrapping text: two borders, one of left padding, and one
/// so the cursor can sit past the last character of a full row.
pub(crate) const CHROME: u16 = 4;

/// The box's usual title: what it does and the keys it answers. The Shift+Enter hint
/// appears only when the terminal distinguishes it, so the hint is never a lie.
pub(crate) fn title(verb: &str, shift_enter: bool) -> String {
    let newline = if shift_enter { "shift+enter new line" } else { "alt+enter new line" };
    format!(" {verb} \u{b7} enter saves \u{b7} {newline} \u{b7} esc cancels ")
}

/// Split a ` · `-separated title into what fits `width` columns on the box's top border,
/// spaces included, and the rest for the bottom border, empty when it all fits.
fn split_title(title: &str, width: usize) -> (String, String) {
    const SEPARATOR: &str = " \u{b7} ";
    let mut first = String::new();
    let mut rest: Vec<&str> = Vec::new();
    for part in title.trim().split(SEPARATOR) {
        let joined = if first.is_empty() { part.to_owned() } else { format!("{first}{SEPARATOR}{part}") };
        if first.is_empty() || (rest.is_empty() && joined.width() + 2 <= width) {
            first = joined;
        } else {
            rest.push(part);
        }
    }
    (format!(" {first} "), rest.join(SEPARATOR))
}

/// Text rows the box shows for `compose` wrapped at `wrap_width`: one to eight.
fn content_rows(compose: &Compose, wrap_width: usize) -> usize {
    compose.wrapped(wrap_width).0.len().clamp(1, 8)
}

/// The box's height, borders included, for `compose` wrapped at `wrap_width`.
pub(crate) fn height(compose: &Compose, wrap_width: usize) -> u16 {
    content_rows(compose, wrap_width) as u16 + 2
}

/// Draw the box in `rect` with its text wrapped at `rect.width - CHROME`, and put the
/// terminal cursor at the insertion point. The box shows as many rows of text as `rect` has
/// inside its borders ([`height`] asks for them all, up to eight); taller text scrolls to keep
/// the cursor's row in view, and stays where it is while the cursor is in view. A title too
/// long for the top border continues on the bottom one. It is dim, and bold while the box
/// asks to discard its text. A `rect` too short for borders shows the text alone, and
/// nothing is ever drawn outside `rect`.
///
/// Returns where the text is drawn and the first of its display rows shown there, for a click.
pub(crate) fn draw(frame: &mut Frame, rect: Rect, compose: &Compose, title: &str) -> (Rect, usize) {
    let rect = rect.intersection(frame.area());
    frame.render_widget(Clear, rect);
    let bordered = rect.height >= 3 && rect.width > CHROME;
    let text = if bordered {
        let title_style = if compose.asking { Style::new().bold() } else { Style::new().dim() };
        let (title, title_rest) = split_title(title, usize::from(rect.width.saturating_sub(2)));
        let mut boxed = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(palette().comment))
            .title(Span::styled(title, title_style));
        if !title_rest.is_empty() {
            boxed = boxed.title_bottom(Span::styled(format!(" {title_rest} "), title_style));
        }
        let inner = boxed.inner(rect);
        frame.render_widget(boxed, rect);
        Rect { x: inner.x + 1, width: inner.width.saturating_sub(1), ..inner }
    } else {
        rect
    };
    if text.is_empty() {
        return (text, compose.scroll.get());
    }
    // One column stays free so the cursor can sit past a full row.
    let wrap_width = usize::from(text.width.saturating_sub(1)).max(1);
    let (lines, cursor_row, cursor_col) = compose.wrapped(wrap_width);
    let content_rows = usize::from(text.height);
    let last_start = lines.len().saturating_sub(content_rows);
    let scroll =
        compose.scroll.get().min(last_start).clamp(cursor_row.saturating_sub(content_rows - 1), cursor_row);
    compose.scroll.set(scroll);
    for (i, line) in lines.iter().skip(scroll).take(content_rows).enumerate() {
        let row = Rect { y: text.y + i as u16, height: 1, ..text };
        frame.render_widget(Paragraph::new(Line::from(shown(line))), row);
    }
    let cursor_x = text.x + cursor_col as u16;
    let cursor_y = text.y + (cursor_row - scroll) as u16;
    frame.set_cursor_position((cursor_x.min(text.right().saturating_sub(1)), cursor_y));
    (text, scroll)
}

#[cfg(test)]
mod tests {
    use super::*;

    const WRAP_WIDTH: usize = 45;

    fn press(compose: &mut Compose, code: KeyCode) {
        compose.handle_key(KeyEvent::new(code, KeyModifiers::CONTROL), WRAP_WIDTH);
    }

    #[test]
    fn a_word_that_does_not_fit_moves_whole_to_the_next_row() {
        let (lines, _, _) = Compose::with_text("the quick brown fox").wrapped(10);
        assert_eq!(lines, ["the quick ", "brown fox"]);
    }

    #[test]
    fn a_word_wider_than_a_row_splits() {
        let (lines, _, _) = Compose::with_text("hi aaaaaaaaaaaaaaa").wrapped(10);
        assert_eq!(lines, ["hi ", "aaaaaaaaaa", "aaaaa"]);
    }

    #[test]
    fn wrapping_keeps_every_character_of_the_buffer() {
        let text = "spaces   at   a   break and 日本語の長い行 keep their place";
        let (lines, _, _) = Compose::with_text(text).wrapped(7);
        assert_eq!(lines.concat(), text);
    }

    #[test]
    fn wide_characters_never_overflow_a_row() {
        let (lines, _, _) = Compose::with_text("a 日本語日本語").wrapped(5);
        assert_eq!(lines, ["a ", "日本", "語日", "本語"]);
    }

    #[test]
    fn spaces_past_the_edge_stay_on_the_row_they_follow() {
        let (lines, row, col) = Compose::with_text("0123456789  ").wrapped(10);
        assert_eq!(lines, ["0123456789  "]);
        assert_eq!((row, col), (0, 12));
    }

    #[test]
    fn the_cursor_follows_a_word_as_it_wraps() {
        let mut compose = Compose::with_text("0123456 ");
        compose.insert_text("abcdef");
        assert_eq!(compose.wrapped(10), (vec!["0123456 ".to_owned(), "abcdef".to_owned()], 1, 6));
    }

    #[test]
    fn up_and_down_cross_a_word_wrap_without_sticking() {
        let mut compose = Compose::with_text("the quick brown fox");
        compose.cursor = 0;
        compose.handle_key(KeyEvent::from(KeyCode::Down), 10);
        assert_eq!(compose.wrapped(10).1, 1);
        compose.handle_key(KeyEvent::from(KeyCode::End), 10);
        compose.handle_key(KeyEvent::from(KeyCode::Up), 10);
        assert_eq!(compose.wrapped(10).1, 0, "the end of the long row maps back onto the first");
    }

    #[test]
    fn ctrl_w_deletes_the_word_before_the_cursor_and_its_trailing_separators() {
        let mut compose = Compose::with_text("one two, ");
        press(&mut compose, KeyCode::Char('w'));
        assert_eq!(compose.value(), "one ");
        assert_eq!(compose.cursor, 4);
    }

    #[test]
    fn ctrl_w_keeps_the_text_after_the_cursor() {
        let mut compose = Compose::with_text("one two");
        compose.cursor = 5;
        press(&mut compose, KeyCode::Char('w'));
        assert_eq!(compose.value(), "one wo");
        assert_eq!(compose.cursor, 4);
    }

    #[test]
    fn ctrl_w_at_the_start_of_the_buffer_changes_nothing() {
        let mut compose = Compose::with_text("one");
        compose.cursor = 0;
        press(&mut compose, KeyCode::Char('w'));
        assert_eq!(compose.value(), "one");
        assert_eq!(compose.cursor, 0);
    }

    #[test]
    fn ctrl_left_lands_on_each_word_start_and_stops_at_the_buffer_start() {
        let mut compose = Compose::with_text("foo_1 bar-baz\nqux");
        let mut stops = Vec::new();
        for _ in 0..5 {
            press(&mut compose, KeyCode::Left);
            stops.push(compose.cursor);
        }
        assert_eq!(stops, [14, 10, 6, 0, 0]);
    }

    #[test]
    fn ctrl_right_lands_on_each_word_end_and_stops_at_the_buffer_end() {
        let mut compose = Compose::with_text("foo_1 bar-baz\nqux");
        compose.cursor = 0;
        let mut stops = Vec::new();
        for _ in 0..5 {
            press(&mut compose, KeyCode::Right);
            stops.push(compose.cursor);
        }
        assert_eq!(stops, [5, 9, 13, 17, 17]);
    }

    fn send(compose: &mut Compose, code: KeyCode, modifiers: KeyModifiers) {
        compose.handle_key(KeyEvent::new(code, modifiers), WRAP_WIDTH);
    }

    #[test]
    fn ctrl_a_and_ctrl_e_stay_on_the_logical_line() {
        let mut compose = Compose::with_text("one\ntwo three\nfour");
        compose.cursor = 6;
        press(&mut compose, KeyCode::Char('a'));
        assert_eq!(compose.cursor, 4);
        press(&mut compose, KeyCode::Char('e'));
        assert_eq!(compose.cursor, 13);
    }

    #[test]
    fn ctrl_u_and_ctrl_k_delete_to_the_line_edges_and_keep_other_lines() {
        let mut compose = Compose::with_text("one\ntwo three\nfour");
        compose.cursor = 7;
        press(&mut compose, KeyCode::Char('u'));
        assert_eq!(compose.value(), "one\n three\nfour");
        assert_eq!(compose.cursor, 4);
        press(&mut compose, KeyCode::Char('k'));
        assert_eq!(compose.value(), "one\n\nfour");
        assert_eq!(compose.cursor, 4);
    }

    #[test]
    fn every_previous_word_delete_key_deletes_the_word() {
        let keys = [
            (KeyCode::Char('w'), KeyModifiers::CONTROL),
            (KeyCode::Char('h'), KeyModifiers::CONTROL),
            (KeyCode::Backspace, KeyModifiers::ALT),
            (KeyCode::Backspace, KeyModifiers::CONTROL),
        ];
        for (code, modifiers) in keys {
            let mut compose = Compose::with_text("one two");
            send(&mut compose, code, modifiers);
            assert_eq!(compose.value(), "one ", "{code:?} {modifiers:?}");
        }
    }

    #[test]
    fn every_next_word_delete_key_deletes_the_word() {
        let keys = [(KeyCode::Char('d'), KeyModifiers::ALT), (KeyCode::Delete, KeyModifiers::CONTROL)];
        for (code, modifiers) in keys {
            let mut compose = Compose::with_text("one two three");
            compose.cursor = 3;
            send(&mut compose, code, modifiers);
            assert_eq!(compose.value(), "one three", "{code:?} {modifiers:?}");
            assert_eq!(compose.cursor, 3);
        }
    }

    #[test]
    fn plain_backspace_and_delete_still_remove_one_character() {
        let mut compose = Compose::with_text("one two");
        send(&mut compose, KeyCode::Backspace, KeyModifiers::NONE);
        assert_eq!(compose.value(), "one tw");
        compose.cursor = 0;
        send(&mut compose, KeyCode::Delete, KeyModifiers::NONE);
        assert_eq!(compose.value(), "ne tw");
    }

    #[test]
    fn alt_keys_jump_by_word_like_ctrl_arrows() {
        for (code, modifiers) in [(KeyCode::Left, KeyModifiers::ALT), (KeyCode::Char('b'), KeyModifiers::ALT)]
        {
            let mut compose = Compose::with_text("one two");
            send(&mut compose, code, modifiers);
            assert_eq!(compose.cursor, 4, "{code:?}");
        }
        for (code, modifiers) in
            [(KeyCode::Right, KeyModifiers::ALT), (KeyCode::Char('f'), KeyModifiers::ALT)]
        {
            let mut compose = Compose::with_text("one two");
            compose.cursor = 0;
            send(&mut compose, code, modifiers);
            assert_eq!(compose.cursor, 3, "{code:?}");
        }
    }

    #[test]
    fn up_and_down_move_between_wrapped_rows_of_one_line() {
        let text = "a".repeat(WRAP_WIDTH * 2 + 10);
        let mut compose = Compose::with_text(&text);
        compose.cursor = WRAP_WIDTH + 5;
        send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(compose.cursor, 5);
        send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
        assert_eq!(compose.cursor, WRAP_WIDTH + 5);
        send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
        assert_eq!(compose.cursor, WRAP_WIDTH * 2 + 5);
    }

    #[test]
    fn up_on_the_first_row_and_down_on_the_last_stay_put() {
        let mut compose = Compose::with_text("one\ntwo");
        compose.cursor = 1;
        send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(compose.cursor, 1);
        compose.cursor = 5;
        send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
        assert_eq!(compose.cursor, 5);
    }

    #[test]
    fn down_from_column_zero_lands_visibly_on_the_next_wrapped_row() {
        let text = "a".repeat(WRAP_WIDTH * 2);
        let mut compose = Compose::with_text(&text);
        compose.cursor = 0;
        send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
        let (_, row, col) = compose.wrapped(WRAP_WIDTH);
        assert_eq!((row, col), (1, 0));
    }

    #[test]
    fn up_from_past_a_full_row_stays_on_that_row() {
        let text = "a".repeat(WRAP_WIDTH * 2);
        let mut compose = Compose::with_text(&text);
        send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
        let (_, row, col) = compose.wrapped(WRAP_WIDTH);
        assert_eq!((row, col), (0, WRAP_WIDTH - 1));
    }

    #[test]
    fn vertical_moves_keep_the_display_column_across_wide_characters() {
        let mut compose = Compose::with_text("日本語\nabcdef");
        compose.cursor = 7;
        send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
        assert_eq!(compose.cursor, 1);
    }

    #[test]
    fn a_click_puts_the_cursor_at_the_clicked_cell_or_the_end_of_its_row() {
        let mut compose = Compose::with_text("the quick brown fox\njumps");
        compose.click(0, 4, 10);
        assert_eq!(compose.cursor, 4, "on the q");
        compose.click(1, 40, 10);
        assert_eq!(compose.cursor, 19, "past the end of the second display row: its end");
        compose.click(7, 1, 10);
        assert_eq!(compose.cursor, 21, "below the text: the last row");
    }

    /// `compose` drawn in `rect` of a `cols`×`rows` screen: the rows as text, and where the
    /// text went.
    fn drawn(compose: &Compose, cols: u16, rows: u16, rect: Rect) -> (Vec<String>, (Rect, usize)) {
        let mut terminal =
            ratatui::Terminal::new(ratatui::backend::TestBackend::new(cols, rows)).expect("terminal");
        let mut at = (Rect::default(), 0);
        terminal.draw(|frame| at = draw(frame, rect, compose, " comment ")).expect("draw");
        let buffer = terminal.backend().buffer();
        let text = (0..rows)
            .map(|y| (0..cols).filter_map(|x| buffer.cell((x, y)).map(|c| c.symbol().to_owned())).collect())
            .collect();
        (text, at)
    }

    #[test]
    fn tabs_draw_as_four_columns_and_stay_tabs_in_the_text() {
        let compose = Compose::with_text("\tindented\twith tabs\r");
        let (rows, _) = drawn(&compose, 40, 3, Rect::new(0, 0, 40, 3));
        assert!(rows.get(1).is_some_and(|r| r.contains("    indented    with tabs ")), "{rows:?}");
        assert_eq!(compose.value(), "\tindented\twith tabs\r");
    }

    #[test]
    fn a_box_too_short_for_its_borders_draws_its_text_inside_its_rectangle_alone() {
        for height in [0, 1, 2] {
            let mut compose = Compose::default();
            compose.insert_text("some draft text");
            let rect = Rect::new(2, 2, 30, height);
            let (rows, (text, _)) = drawn(&compose, 40, 6, rect);
            for (y, row) in rows.iter().enumerate() {
                let inside = (rect.top()..rect.bottom()).contains(&(y as u16));
                assert!(inside || row.trim().is_empty(), "height {height}: row {y} is {row:?}");
            }
            assert!(rect.union(text) == rect || text.is_empty(), "height {height}: {text:?}");
            if height > 0 {
                assert!(rows.get(2).is_some_and(|r| r.contains("some draft")), "height {height}: {rows:?}");
                assert!(!rows.concat().contains('\u{256d}'), "no borders");
            }
            assert_eq!(compose.value(), "some draft text", "the draft stays");
        }
    }

    #[test]
    fn the_text_stays_put_while_the_cursor_moves_inside_the_rows_shown() {
        let text: Vec<String> = (0..50).map(|n| format!("line {n}")).collect();
        let mut compose = Compose::with_text(&text.join("\n"));
        let rect = Rect::new(0, 0, 30, 10);
        let (rows, (_, first)) = drawn(&compose, 30, 10, rect);
        assert_eq!(first, 42, "the end shows: {rows:?}");
        compose.click(45, 0, 26);
        let (rows, (_, first)) = drawn(&compose, 30, 10, rect);
        assert_eq!(first, 42, "a click on a shown row moves nothing: {rows:?}");
        compose.click(first + 1, 0, 26);
        compose.insert_text("X");
        assert!(compose.value().contains("\nXline 43\n"), "the next click lands on the row clicked");
        compose.handle_key(KeyEvent::from(KeyCode::Up), 26);
        let (_, (_, first)) = drawn(&compose, 30, 10, rect);
        assert_eq!(first, 42, "Up inside the rows shown moves nothing either");
        compose.handle_key(KeyEvent::from(KeyCode::Up), 26);
        let (_, (_, first)) = drawn(&compose, 30, 10, rect);
        assert_eq!(first, 41, "Up past the first row shown scrolls one row");
    }

    #[test]
    fn only_a_real_change_counts_as_unsaved() {
        assert!(!Compose::default().has_changes());
        assert!(!Compose::with_text("body").has_changes());
        let mut blank = Compose::default();
        blank.insert_text("  \n ");
        assert!(!blank.has_changes(), "whitespace alone would never be saved");
        let mut edited = Compose::with_text("body");
        edited.insert_text("!");
        assert!(edited.has_changes());
        send(&mut edited, KeyCode::Backspace, KeyModifiers::NONE);
        assert!(!edited.has_changes(), "typing it back to the original loses nothing");
    }

    #[test]
    fn non_ascii_letters_count_as_word_characters() {
        let mut compose = Compose::with_text("über größe");
        press(&mut compose, KeyCode::Char('w'));
        assert_eq!(compose.value(), "über ");
    }
}