calcli 0.2.0

Fast terminal calculator (TUI) with history, variables and engineering helpers
Documentation
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
//! Single-line text editing for the input field and inline history edits.
//!
//! A character caret with an optional selection anchor over a `String`, the key
//! handling that moves, selects and edits at it, plus block-cursor rendering
//! that scrolls to keep the caret visible. The value stays owned by the caller;
//! this module only mutates `(text, cursor)` and renders. Adapted (single-line
//! only) from the shared `text_edit` of the reference projects.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

use crate::tui::colors;
use crate::util::clipboard;

/// A character caret over an input value plus an optional selection anchor.
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct TextCursor {
    /// The moving caret as a character index in `0..=len`.
    pub pos: usize,
    /// Where the current selection began, or `None` when nothing is selected.
    pub anchor: Option<usize>,
}

impl TextCursor {
    /// A caret at `pos` with no selection.
    pub fn at(pos: usize) -> Self {
        TextCursor { pos, anchor: None }
    }

    /// Moves the caret to `pos`, dropping any selection.
    pub fn move_to(&mut self, pos: usize) {
        self.pos = pos;
        self.anchor = None;
    }

    /// Moves the caret to `pos`, seeding the anchor when no selection is active.
    pub fn extend_to(&mut self, pos: usize) {
        if self.anchor.is_none() {
            self.anchor = Some(self.pos);
        }
        self.pos = pos;
    }

    /// Selects the whole value of `len` characters.
    pub fn select_all(&mut self, len: usize) {
        self.anchor = Some(0);
        self.pos = len;
    }

    /// The selection as an ordered half-open `(start, end)`, or `None`.
    pub fn selection(&self) -> Option<(usize, usize)> {
        let anchor = self.anchor?;
        if anchor == self.pos {
            return None;
        }
        Some((anchor.min(self.pos), anchor.max(self.pos)))
    }

    /// Whether a non-empty selection is active.
    pub fn has_selection(&self) -> bool {
        self.selection().is_some()
    }
}

/// Where to paint the caret and selection within the rendered line.
#[derive(Clone, Copy, Default)]
pub struct LineCaret {
    /// The caret column, or `None` when the caret is off-screen.
    pub cursor: Option<usize>,
    /// The selected column range as a half-open `(start, end)`.
    pub selection: Option<(usize, usize)>,
}

/// Whether an input is a single logical line or soft-wrapped at a display width.
#[derive(Clone, Copy)]
pub enum EditMode {
    /// One logical line: `Home`/`End` jump to the value's start/end.
    SingleLine,
    /// Soft-wrapped at `width` columns: `Home`/`End` act on the display line and
    /// `Up`/`Down` move across wrapped lines. The value never contains `\n`.
    Multiline { width: usize },
}

/// Applies an editing key to `(text, cursor)`, returning `true` when the key was
/// an editing key. Steering keys the caller owns (`Esc`, a confirming `Enter`,
/// other chords) must be handled before delegating here.
pub fn apply_edit_key(
    text: &mut String,
    cursor: &mut TextCursor,
    key: KeyEvent,
    mode: EditMode,
) -> bool {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);
    if let Some(target) = motion_target(text, cursor.pos, key, mode) {
        if shift {
            cursor.extend_to(target);
        } else {
            cursor.move_to(target);
        }
        return true;
    }
    match key.code {
        KeyCode::Char('a') if ctrl => cursor.select_all(char_count(text)),
        KeyCode::Char('u') if ctrl => {
            cursor.anchor = Some(line_start(text, cursor.pos, mode));
            replace_selection(text, cursor, "");
        }
        KeyCode::Char('k') if ctrl => {
            cursor.anchor = Some(line_end(text, cursor.pos, mode));
            replace_selection(text, cursor, "");
        }
        KeyCode::Char(c) if !ctrl => {
            replace_selection(text, cursor, &c.to_string());
        }
        KeyCode::Backspace if cursor.has_selection() => {
            replace_selection(text, cursor, "");
        }
        KeyCode::Delete if cursor.has_selection() => {
            replace_selection(text, cursor, "");
        }
        KeyCode::Backspace => delete_before(text, cursor),
        KeyCode::Delete => delete_after(text, cursor),
        _ => return false,
    }
    true
}

/// Handles the clipboard chords: `Ctrl+C` copies the selection, `Ctrl+X` cuts
/// it, `Ctrl+V` pastes. Returns `true` when the key was one of them.
pub fn handle_clipboard(
    text: &mut String,
    cursor: &mut TextCursor,
    key: KeyEvent,
) -> bool {
    if !key.modifiers.contains(KeyModifiers::CONTROL) {
        return false;
    }
    match key.code {
        KeyCode::Char('c') => {
            if let Some(selected) = selected_text(text, cursor) {
                clipboard::copy(&selected);
            }
        }
        KeyCode::Char('x') => {
            if let Some(selected) = selected_text(text, cursor) {
                clipboard::copy(&selected);
                replace_selection(text, cursor, "");
            }
        }
        KeyCode::Char('v') => {
            if let Some(pasted) = clipboard::paste() {
                let one_line = pasted.replace(['\n', '\r'], " ");
                replace_selection(text, cursor, &one_line);
            }
        }
        _ => return false,
    }
    true
}

/// The motion target for a navigation key, or `None` when it is not one. A
/// vertical move that cannot go further returns the unchanged `pos`.
fn motion_target(
    text: &str,
    pos: usize,
    key: KeyEvent,
    mode: EditMode,
) -> Option<usize> {
    let multiline = matches!(mode, EditMode::Multiline { .. });
    let target = match key.code {
        KeyCode::Left => pos.saturating_sub(1),
        KeyCode::Right => (pos + 1).min(char_count(text)),
        KeyCode::Home => line_start(text, pos, mode),
        KeyCode::End => line_end(text, pos, mode),
        KeyCode::Up if multiline => display_line_target(text, pos, mode, -1),
        KeyCode::Down if multiline => display_line_target(text, pos, mode, 1),
        _ => return None,
    };
    Some(target)
}

/// The cursor index for `Home`: the value's start, or the display line's start.
fn line_start(text: &str, cursor: usize, mode: EditMode) -> usize {
    match mode {
        EditMode::SingleLine => 0,
        EditMode::Multiline { width } => {
            let lines = wrap_offsets(text, width);
            let (display_line, _) =
                cursor_to_display(&lines, char_count(text), cursor);
            display_to_cursor(&lines, display_line, 0)
        }
    }
}

/// The cursor index for `End`: the value's end, or the display line's end.
fn line_end(text: &str, cursor: usize, mode: EditMode) -> usize {
    match mode {
        EditMode::SingleLine => char_count(text),
        EditMode::Multiline { width } => {
            let lines = wrap_offsets(text, width);
            let (display_line, _) =
                cursor_to_display(&lines, char_count(text), cursor);
            let col = lines[display_line].0.chars().count();
            display_to_cursor(&lines, display_line, col)
        }
    }
}

/// The cursor index one display line up/down, keeping the column where possible;
/// returns `pos` unchanged when there is no line in that direction.
fn display_line_target(
    text: &str,
    pos: usize,
    mode: EditMode,
    delta: i32,
) -> usize {
    let EditMode::Multiline { width } = mode else {
        return pos;
    };
    let lines = wrap_offsets(text, width);
    let (display_line, col) = cursor_to_display(&lines, char_count(text), pos);
    let target = display_line as i32 + delta;
    if target < 0 || target >= lines.len() as i32 {
        return pos;
    }
    display_to_cursor(&lines, target as usize, col)
}

/// Replaces the active selection (or inserts at the caret) with `s`.
pub fn replace_selection(text: &mut String, cursor: &mut TextCursor, s: &str) {
    if let Some((start, end)) = cursor.selection() {
        let mut chars: Vec<char> = text.chars().collect();
        let end = end.min(chars.len());
        let start = start.min(end);
        chars.drain(start..end);
        *text = chars.into_iter().collect();
        cursor.pos = start;
    }
    cursor.anchor = None;
    insert_raw(text, cursor, s);
}

/// The selected substring, or `None` when nothing is selected.
pub fn selected_text(text: &str, cursor: &TextCursor) -> Option<String> {
    let (start, end) = cursor.selection()?;
    let chars: Vec<char> = text.chars().collect();
    let end = end.min(chars.len());
    let start = start.min(end);
    Some(chars[start..end].iter().collect())
}

/// The number of characters (not bytes) in `text`.
fn char_count(text: &str) -> usize {
    text.chars().count()
}

/// Inserts `s` at the caret, advancing it.
fn insert_raw(text: &mut String, cursor: &mut TextCursor, s: &str) {
    let mut chars: Vec<char> = text.chars().collect();
    let mut at = cursor.pos.min(chars.len());
    for c in s.chars() {
        chars.insert(at, c);
        at += 1;
    }
    cursor.pos = at;
    *text = chars.into_iter().collect();
}

/// Deletes the character before the caret (Backspace).
fn delete_before(text: &mut String, cursor: &mut TextCursor) {
    cursor.anchor = None;
    let mut chars: Vec<char> = text.chars().collect();
    let at = cursor.pos.min(chars.len());
    if at == 0 {
        return;
    }
    chars.remove(at - 1);
    cursor.pos = at - 1;
    *text = chars.into_iter().collect();
}

/// Deletes the character at the caret (forward Delete).
fn delete_after(text: &mut String, cursor: &mut TextCursor) {
    cursor.anchor = None;
    let mut chars: Vec<char> = text.chars().collect();
    let at = cursor.pos.min(chars.len());
    if at >= chars.len() {
        return;
    }
    chars.remove(at);
    *text = chars.into_iter().collect();
}

/// The overlap of `[s, e)` with `[lo, hi)`, or `None` when they don't meet.
fn intersect(
    s: usize,
    e: usize,
    lo: usize,
    hi: usize,
) -> Option<(usize, usize)> {
    let start = s.max(lo);
    let end = e.min(hi);
    (start < end).then_some((start, end))
}

/// Builds the spans for a single-line value of at most `width` columns with the
/// block cursor at `cursor.pos`, scrolling to keep the cursor visible and
/// marking clipped ends with a dim `…`.
pub fn single_line_spans(
    value: &str,
    cursor: TextCursor,
    width: usize,
    base: Style,
) -> Vec<Span<'static>> {
    let width = width.max(1);
    let chars: Vec<char> = value.chars().collect();
    let n = chars.len();
    let pos = cursor.pos.min(n);
    let end_cursor = pos >= n;
    if n + usize::from(end_cursor) <= width {
        let caret = LineCaret {
            cursor: Some(pos),
            selection: cursor.selection(),
        };
        return cursor_spans(value, caret, base);
    }
    let max_start = (n + usize::from(end_cursor)).saturating_sub(width - 1);
    let room = width.saturating_sub(2).max(1);
    let start = if pos < room {
        0
    } else {
        (pos + 1 - room).min(max_start)
    };
    let lead = usize::from(start > 0);
    let reach = (n - start) + usize::from(end_cursor) <= width - lead;
    let show = if reach { n - start } else { width - (lead + 1) };
    let visible_end = start + show;
    let visible: String = chars[start..visible_end.min(n)].iter().collect();
    let dim = Style::default().add_modifier(Modifier::DIM);
    let mut spans = Vec::new();
    if lead == 1 {
        spans.push(Span::styled("\u{2026}".to_string(), dim));
    }
    let col = (pos >= start && pos <= visible_end).then(|| pos - start);
    let selection = cursor
        .selection()
        .and_then(|(s, e)| intersect(s, e, start, visible_end))
        .map(|(s, e)| (s - start, e - start));
    let caret = LineCaret {
        cursor: col,
        selection,
    };
    spans.extend(cursor_spans(&visible, caret, base));
    if !reach {
        spans.push(Span::styled("\u{2026}".to_string(), dim));
    }
    spans
}

/// Splits `visible` into styled spans painting the selection and the block
/// cursor (a `â–ˆ` past the text, or the covered character on a tinted cell).
pub fn cursor_spans(
    visible: &str,
    caret: LineCaret,
    base: Style,
) -> Vec<Span<'static>> {
    let chars: Vec<char> = visible.chars().collect();
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut run = String::new();
    let mut run_style = base;
    for (i, c) in chars.iter().enumerate() {
        let style = cell_style(i, caret, base);
        if !run.is_empty() && style != run_style {
            spans.push(Span::styled(std::mem::take(&mut run), run_style));
        }
        if run.is_empty() {
            run_style = style;
        }
        run.push(*c);
    }
    if !run.is_empty() {
        spans.push(Span::styled(run, run_style));
    }
    if caret.cursor == Some(chars.len()) {
        spans.push(colors::cursor_block_span());
    }
    spans
}

/// The style of one rendered cell: the caret cell, a selected cell, or `base`.
fn cell_style(i: usize, caret: LineCaret, base: Style) -> Style {
    if caret.cursor == Some(i) {
        return base.bg(colors::INPUT_CURSOR);
    }
    if let Some((start, end)) = caret.selection
        && i >= start
        && i < end
    {
        return base.bg(colors::SELECTION_BG);
    }
    base
}

/// Like [`single_line_spans`], but the base style of each character `g` is
/// `styles[g]` (its highlight colour). `styles` is indexed by the value's
/// character position; missing entries fall back to the default style.
/// Adapted (single-line only) from numcli's `single_line_spans_styled`.
pub fn single_line_spans_styled(
    value: &str,
    cursor: TextCursor,
    width: usize,
    styles: &[Style],
) -> Vec<Span<'static>> {
    let width = width.max(1);
    let chars: Vec<char> = value.chars().collect();
    let n = chars.len();
    let pos = cursor.pos.min(n);
    let end_cursor = pos >= n;
    if n + usize::from(end_cursor) <= width {
        let caret = LineCaret {
            cursor: Some(pos),
            selection: cursor.selection(),
        };
        return cursor_spans_styled(value, caret, styles);
    }
    let max_start = (n + usize::from(end_cursor)).saturating_sub(width - 1);
    let room = width.saturating_sub(2).max(1);
    let start = if pos < room {
        0
    } else {
        (pos + 1 - room).min(max_start)
    };
    let lead = usize::from(start > 0);
    let reach = (n - start) + usize::from(end_cursor) <= width - lead;
    let show = if reach { n - start } else { width - (lead + 1) };
    let visible_end = start + show;
    let visible: String = chars[start..visible_end.min(n)].iter().collect();
    let visible_styles =
        &styles[start.min(styles.len())..visible_end.min(n).min(styles.len())];
    let dim = Style::default().add_modifier(Modifier::DIM);
    let mut spans = Vec::new();
    if lead == 1 {
        spans.push(Span::styled("\u{2026}".to_string(), dim));
    }
    let col = (pos >= start && pos <= visible_end).then(|| pos - start);
    let selection = cursor
        .selection()
        .and_then(|(s, e)| intersect(s, e, start, visible_end))
        .map(|(s, e)| (s - start, e - start));
    let caret = LineCaret {
        cursor: col,
        selection,
    };
    spans.extend(cursor_spans_styled(&visible, caret, visible_styles));
    if !reach {
        spans.push(Span::styled("\u{2026}".to_string(), dim));
    }
    spans
}

/// Like [`cursor_spans`], but each visible character `i` uses `styles[i]` as its
/// base style (missing entries fall back to the default).
pub fn cursor_spans_styled(
    visible: &str,
    caret: LineCaret,
    styles: &[Style],
) -> Vec<Span<'static>> {
    let chars: Vec<char> = visible.chars().collect();
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut run = String::new();
    let mut run_style = Style::default();
    for (i, c) in chars.iter().enumerate() {
        let base = styles.get(i).copied().unwrap_or_default();
        let style = cell_style(i, caret, base);
        if !run.is_empty() && style != run_style {
            spans.push(Span::styled(std::mem::take(&mut run), run_style));
        }
        if run.is_empty() {
            run_style = style;
        }
        run.push(*c);
    }
    if !run.is_empty() {
        spans.push(Span::styled(run, run_style));
    }
    if caret.cursor == Some(chars.len()) {
        spans.push(colors::cursor_block_span());
    }
    spans
}

/// Soft-wraps `value` to `width` columns and renders one [`Line`] per display
/// line (no cursor), applying the per-character `styles`. Used for the read-only
/// history rows.
pub fn wrapped_spans(
    value: &str,
    styles: &[Style],
    width: usize,
) -> Vec<Line<'static>> {
    let lines = wrap_offsets(value, width);
    lines
        .iter()
        .map(|(text, start)| {
            let len = text.chars().count();
            let line_styles = &styles
                [(*start).min(styles.len())..(*start + len).min(styles.len())];
            let caret = LineCaret {
                cursor: None,
                selection: None,
            };
            Line::from(cursor_spans_styled(text, caret, line_styles))
        })
        .collect()
}

/// Soft-wraps `value` to `width` columns and renders one [`Line`] per display
/// line, applying the per-character `styles` (highlighting) and painting the
/// block cursor / selection on the right line. Used by the growing input field.
pub fn multiline_spans_styled(
    value: &str,
    cursor: TextCursor,
    width: usize,
    styles: &[Style],
) -> Vec<Line<'static>> {
    let lines = wrap_offsets(value, width);
    let total = char_count(value);
    let (cursor_line, _) = cursor_to_display(&lines, total, cursor.pos);
    let selection = cursor.selection();

    let mut out: Vec<Line<'static>> = Vec::with_capacity(lines.len());
    for (index, (text, start)) in lines.iter().enumerate() {
        let len = text.chars().count();
        let line_styles = &styles
            [(*start).min(styles.len())..(*start + len).min(styles.len())];
        let column = (index == cursor_line)
            .then(|| cursor.pos.saturating_sub(*start).min(len));
        let line_selection = selection
            .and_then(|(s, e)| intersect(s, e, *start, *start + len))
            .map(|(s, e)| (s - *start, e - *start));
        let caret = LineCaret {
            cursor: column,
            selection: line_selection,
        };
        out.push(Line::from(cursor_spans_styled(text, caret, line_styles)));
    }
    out
}

/// The display line and column of cursor index `cursor` within `lines`.
pub fn cursor_to_display(
    lines: &[(String, usize)],
    total: usize,
    cursor: usize,
) -> (usize, usize) {
    let cursor = cursor.min(total);
    let mut display_line = 0;
    for (index, (_, start)) in lines.iter().enumerate() {
        if *start <= cursor {
            display_line = index;
        } else {
            break;
        }
    }
    let (text, start) = &lines[display_line];
    (display_line, (cursor - start).min(text.chars().count()))
}

/// Maps a `(display line, column)` back to a cursor char index.
fn display_to_cursor(
    lines: &[(String, usize)],
    line: usize,
    col: usize,
) -> usize {
    let (text, start) = &lines[line];
    start + col.min(text.chars().count())
}

/// Soft-wraps `text` to `width` columns, returning each display line with the
/// character offset (into `text`) at which it starts. An over-long word is
/// hard-split; the value carries no explicit newlines.
pub fn wrap_offsets(text: &str, width: usize) -> Vec<(String, usize)> {
    let width = width.max(1);
    let chars: Vec<char> = text.chars().collect();
    let mut out: Vec<(String, usize)> = Vec::new();
    wrap_logical(&chars, 0, width, &mut out);
    if out.is_empty() {
        out.push((String::new(), 0));
    }
    out
}

/// Greedily wraps `line` (starting at char offset `base`) into `out`.
fn wrap_logical(
    line: &[char],
    base: usize,
    width: usize,
    out: &mut Vec<(String, usize)>,
) {
    if line.is_empty() {
        out.push((String::new(), base));
        return;
    }
    let len = line.len();
    let mut start = 0usize;
    while start < len {
        let end = (start + width).min(len);
        if end == len {
            out.push((line[start..end].iter().collect(), base + start));
            break;
        }
        // Break at the last space in the window; else hard-split.
        let break_at = (start + 1..=end).rev().find(|&p| line[p - 1] == ' ');
        match break_at {
            Some(p) if p - 1 > start => {
                out.push((line[start..p - 1].iter().collect(), base + start));
                start = p; // consume the break space
            }
            _ => {
                out.push((line[start..end].iter().collect(), base + start));
                start = end;
            }
        }
    }
}

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

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::CONTROL)
    }

    fn apply(
        text: &str,
        cursor: TextCursor,
        key: KeyEvent,
    ) -> (String, TextCursor) {
        let mut text = text.to_string();
        let mut cursor = cursor;
        apply_edit_key(&mut text, &mut cursor, key, EditMode::SingleLine);
        (text, cursor)
    }

    fn apply_multiline(
        text: &str,
        cursor: TextCursor,
        key: KeyEvent,
        width: usize,
    ) -> (String, TextCursor) {
        let mut text = text.to_string();
        let mut cursor = cursor;
        let mode = EditMode::Multiline { width };
        apply_edit_key(&mut text, &mut cursor, key, mode);
        (text, cursor)
    }

    #[test]
    fn typing_inserts_at_the_caret() {
        let (text, cursor) =
            apply("ac", TextCursor::at(1), key(KeyCode::Char('b')));
        assert_eq!((text.as_str(), cursor.pos), ("abc", 2));
    }

    #[test]
    fn home_and_end_jump_to_the_edges() {
        assert_eq!(
            apply("abc", TextCursor::at(2), key(KeyCode::Home)).1.pos,
            0
        );
        assert_eq!(apply("abc", TextCursor::at(0), key(KeyCode::End)).1.pos, 3);
    }

    #[test]
    fn ctrl_u_and_ctrl_k_delete_to_the_edges() {
        let (text, _) =
            apply("hello", TextCursor::at(3), ctrl(KeyCode::Char('u')));
        assert_eq!(text, "lo");
        let (text, _) =
            apply("hello", TextCursor::at(3), ctrl(KeyCode::Char('k')));
        assert_eq!(text, "hel");
    }

    #[test]
    fn backspace_deletes_the_previous_character() {
        let (text, cursor) =
            apply("abc", TextCursor::at(2), key(KeyCode::Backspace));
        assert_eq!((text.as_str(), cursor.pos), ("ac", 1));
    }

    #[test]
    fn typing_replaces_an_active_selection() {
        let cursor = TextCursor {
            pos: 3,
            anchor: Some(1),
        };
        let (text, cursor) = apply("abcd", cursor, key(KeyCode::Char('X')));
        assert_eq!((text.as_str(), cursor.pos), ("aXd", 2));
    }

    #[test]
    fn wrap_offsets_breaks_on_words_and_long_words() {
        let lines = |t: &str, w| {
            wrap_offsets(t, w)
                .into_iter()
                .map(|(s, _)| s)
                .collect::<Vec<_>>()
        };
        assert_eq!(lines("alpha beta gamma", 11), vec!["alpha beta", "gamma"]);
        assert_eq!(lines("abcdef", 3), vec!["abc", "def"]);
        // A soft-wrapped value carries no newlines; offsets track char indices.
        let offsets = wrap_offsets("alpha beta gamma", 11);
        assert_eq!(offsets[1].1, 11);
        let total = "alpha beta gamma".chars().count();
        assert_eq!(cursor_to_display(&offsets, total, 13), (1, 2));
    }

    #[test]
    fn multiline_up_down_move_across_wrapped_lines() {
        let mode_width = 11;
        // "alpha beta gamma" wraps to ["alpha beta", "gamma"]; pos 13 is on
        // line 1, column 2. Up keeps the column on line 0.
        let (_, cursor) = apply_multiline(
            "alpha beta gamma",
            TextCursor::at(13),
            key(KeyCode::Up),
            mode_width,
        );
        assert_eq!(cursor.pos, 2);
        // Down from the top line returns to the lower line at the same column.
        let (_, cursor) = apply_multiline(
            "alpha beta gamma",
            TextCursor::at(2),
            key(KeyCode::Down),
            mode_width,
        );
        assert_eq!(cursor.pos, 13);
    }

    #[test]
    fn multiline_home_and_end_act_on_the_display_line() {
        let (_, cursor) = apply_multiline(
            "alpha beta gamma",
            TextCursor::at(13),
            key(KeyCode::Home),
            11,
        );
        assert_eq!(cursor.pos, 11);
        let (_, cursor) = apply_multiline(
            "alpha beta gamma",
            TextCursor::at(13),
            key(KeyCode::End),
            11,
        );
        assert_eq!(cursor.pos, 16);
    }
}