edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
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
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
use ratatui::{buffer::Buffer as TuiBuf, layout::Rect, style::Style, text::Line};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::document::wrap::{char_cells, visual_rows_of_chars, Indent, PaintedRows};

/// Write a styled `Line` to the TUI buffer, wrapping at `area.width` (in *cells*) when
/// `wrap` is true.  Returns the visual rows consumed (≥ 1).
///
/// Trailing cells are filled with the line's base style so styled blocks extend the full
/// width.  Wrapping is word-aware, and the rows start behind `indent`: its `lead` before the
/// first, its `hang` before every continuation row.  The caller states it — a rendered row's
/// from `ParsedDoc::row_indent`, a revealed line's from `row_map::revealed_indent` — so the
/// painter and every reader of the same row agree.
///
/// `cursor_col_override` is `Some((char index, style))` — not a cell column — and recolors
/// that cell while leaving the character visible.  It applies only to a wide char's first
/// cell; terminals can't style the right half independently.
///
/// Used by tests here; production code calls [`render_line_from_visual`] for sub-row
/// scrolling.
#[allow(dead_code)]
pub fn render_line(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
) -> u16 {
    render_line_with_cursor_from_visual(line, indent, area, buf, visual_y, wrap, None, 0)
}

pub fn render_line_from_visual(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    skip_rows: usize,
) -> u16 {
    render_line_with_cursor_from_visual(line, indent, area, buf, visual_y, wrap, None, skip_rows)
}

/// Used by tests in this module.
#[allow(dead_code)]
pub fn render_line_with_cursor(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
) -> u16 {
    render_line_with_cursor_from_visual(
        line,
        indent,
        area,
        buf,
        visual_y,
        wrap,
        cursor_col_override,
        0,
    )
}

#[allow(clippy::too_many_arguments)]
pub fn render_line_with_cursor_from_visual(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
    skip_rows: usize,
) -> u16 {
    render_line_reporting_cursor(
        line,
        indent,
        area,
        buf,
        visual_y,
        wrap,
        cursor_col_override,
        skip_rows,
    )
    .0
}

/// [`render_line_with_cursor_from_visual`] plus the absolute `(x, y)` cell the cursor
/// override was painted at.  `RenderedView` uses it to re-stamp the cursor over post-pass
/// overlays (search highlights, selection washes) that would otherwise bury it.
#[allow(clippy::too_many_arguments)]
pub fn render_line_reporting_cursor(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
    skip_rows: usize,
) -> (u16, Option<(u16, u16)>) {
    render_line_core(
        line,
        indent,
        area,
        buf,
        visual_y,
        wrap,
        cursor_col_override,
        skip_rows,
    )
}

/// Raw-mode variant of [`render_line_with_cursor_from_visual`]: a **flat** wrap, never a
/// hanging indent.
///
/// Raw mode shows the file, so indenting continuation rows would draw whitespace that
/// isn't in the document — and `visual_rows_of_str`, which backs both the scroll cache and
/// the click mapping, wraps at indent 0, so an indent here would give the painter a
/// different row count from the scroll math and offset every continuation-row click.
/// Indent 0 also suppresses the blockquote-bar repaint, correctly: the `> ` on the first
/// row is real source text and continuation rows have none.
pub fn render_raw_line_with_cursor(
    line: &Line<'static>,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    cursor_col_override: Option<(usize, Style)>,
    skip_rows: usize,
) -> u16 {
    render_line_core(
        line,
        Indent::NONE,
        area,
        buf,
        visual_y,
        true,
        cursor_col_override,
        skip_rows,
    )
    .0
}

/// Shared implementation behind [`render_line_reporting_cursor`] and
/// [`render_raw_line_with_cursor`], which passes [`Indent::NONE`] for Raw mode's flat wrap.
#[allow(clippy::too_many_arguments)]
fn render_line_core(
    line: &Line<'static>,
    indent: Indent,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
    skip_rows: usize,
) -> (u16, Option<(u16, u16)>) {
    if visual_y >= area.height {
        return (0, None);
    }
    let width = area.width as usize;
    if width == 0 {
        return (1, None);
    }
    let abs_y = area.y + visual_y;

    let line_style = line.style;
    let mut chars: Vec<(char, Style)> = Vec::new();
    for span in &line.spans {
        let style = line_style.patch(span.style);
        for ch in span.content.chars() {
            chars.push((ch, style));
        }
    }

    if !wrap {
        if skip_rows > 0 {
            return (0, None);
        }
        let cursor_cell = paint_row(
            &chars,
            0,
            chars.len(),
            0,
            0,
            &[],
            area,
            buf,
            abs_y,
            line_style,
            cursor_col_override,
        );
        return (1, cursor_cell);
    }

    // Single source of truth for row breaks, keeping the renderer in lockstep with the
    // navigation/selection helpers below.
    let rows = visual_rows_of_chars(&chars, width, indent);
    let indent = indent.at(width);
    // Repainted on each continuation row so the quote gutter doesn't vanish mid-quote.
    let cont_prefix = leading_bar_prefix(&chars);

    let mut cursor_cell = None;
    let mut cur_visual = visual_y;
    for (row_idx, &(start, row_end, _next_start)) in rows.iter().enumerate().skip(skip_rows) {
        if cur_visual >= area.height {
            break;
        }
        let cur_abs_y = area.y + cur_visual;
        let row_indent = indent.row(row_idx);
        let row_prefix: &[(char, Style)] = if row_idx == 0 { &[] } else { &cont_prefix };
        // A space absorbed by the previous row's break owns no cell, so show a cursor
        // resting on it at this row's first char — where `sub_line_of_col` reports it.
        let row_override = match (
            row_idx.checked_sub(1).and_then(|p| rows.get(p)),
            cursor_col_override,
        ) {
            (Some(&(_, prev_end, prev_next)), Some((col, style)))
                if col >= prev_end && col < prev_next =>
            {
                Some((start, style))
            }
            _ => cursor_col_override,
        };
        if let Some(cell) = paint_row(
            &chars,
            start,
            row_end,
            start,
            row_indent,
            row_prefix,
            area,
            buf,
            cur_abs_y,
            line_style,
            row_override,
        ) {
            cursor_cell = Some(cell);
        }
        cur_visual += 1;
    }

    (cur_visual - visual_y, cursor_cell)
}

/// Join zero-width `ch` (a combining mark, a Hangul vowel or final jamo) to the glyph already
/// painted at `at`, which the terminal composes into one grapheme in the same cells.  Painting
/// it in a cell of its own would shift the row; skipping it drops it (`cafe\u{301}` showed as
/// `cafe`).
///
/// Only a char that extends the cell's grapheme cluster joins it.  Any other zero-width char
/// stays dropped: a tab or other control char (`char_cells` gives them 0 as well), which would
/// move the terminal's cursor, and a zero-width space, which joins nothing.  So does a char
/// that changes the cluster's width as ratatui measures it (`❤` + U+FE0F = 2, `⌚` + U+FE0E =
/// 1): ratatui's diff skips the cells after a glyph by that width, so it must agree with the
/// per-char sum the layout gives the cell, or the rest of the row shifts off the cells the
/// cursor and clicks map to.  A zero-width joiner stays dropped too, though it changes no
/// width: the terminal may fuse it with the next cell's glyph (a ZWJ family drawn in 2 cells
/// rather than 6).
pub(crate) fn append_zero_width(buf: &mut TuiBuf, at: (u16, u16), ch: char) {
    if ch == '\u{200D}' {
        return;
    }
    if let Some(cell) = buf.cell_mut(at) {
        let mut symbol = cell.symbol().to_owned();
        let width = symbol.width();
        symbol.push(ch);
        if symbol.graphemes(true).nth(1).is_none() && symbol.width() == width {
            cell.set_symbol(&symbol);
        }
    }
}

/// Paint one visual row: `chars[start..end]` after `row_indent` cells of padding.
/// `abs_col_base` is added to each relative index when matching
/// `cursor_col_override` — the row's `start` when wrapped, 0 on the no-wrap path.
///
/// `cont_prefix` is the styled run repainted into the indent zone (the blockquote bar, see
/// [`leading_bar_prefix`]); remaining indent cells are blank-filled in `line_style`.
///
/// Returns the absolute cell the cursor override was drawn at, `None` when it isn't on
/// this row.
#[allow(clippy::too_many_arguments)]
fn paint_row(
    chars: &[(char, Style)],
    start: usize,
    end: usize,
    abs_col_base: usize,
    row_indent: usize,
    cont_prefix: &[(char, Style)],
    area: Rect,
    buf: &mut TuiBuf,
    abs_y: u16,
    line_style: Style,
    cursor_col_override: Option<(usize, Style)>,
) -> Option<(u16, u16)> {
    let mut cursor_cell = None;
    let mut x = area.x;
    let area_end = area.x + area.width;
    // Repaint the leading bars and indent (`leading_bar_prefix`), then blank-fill the rest of
    // the indent with the surrounding background.
    let mut prefix_iter = cont_prefix.iter();
    for _ in 0..row_indent {
        if x >= area_end {
            break;
        }
        if let Some(cell) = buf.cell_mut((x, abs_y)) {
            match prefix_iter.next() {
                Some((ch, style)) => {
                    cell.set_char(*ch);
                    cell.set_style(*style);
                }
                None => {
                    cell.set_char(' ');
                    cell.set_style(line_style);
                }
            }
        }
        x += 1;
    }
    // The last char's cell, while every char of the row has one (for the full-row EOL cursor).
    let mut last_cell = None;
    // The cell of the last glyph painted on this row, which a zero-width char joins.
    let mut glyph_cell = None;
    // The column of a glyph clipped at the area's edge, which the fill below stands in for.
    let mut clipped = None;
    for (rel_idx, (ch, style)) in chars[start..end].iter().enumerate() {
        let cells = char_cells(*ch) as u16;
        if cells == 0 {
            // Zero-width chars join the preceding glyph's cell without advancing `x`, so
            // each char keeps the width `str_cells` measures.
            if let Some(at) = glyph_cell {
                append_zero_width(buf, at, *ch);
            }
            continue;
        }
        // A glyph that doesn't fit whole stays off the row rather than straddle the edge: its
        // right half would land in the next widget's cell (unwrapped, or wrapped into a
        // one-cell row).
        if x + cells > area_end {
            last_cell = None;
            clipped = Some(abs_col_base + rel_idx);
            break;
        }
        last_cell = Some(x);
        glyph_cell = Some((x, abs_y));
        let abs_col = abs_col_base + rel_idx;
        let cursor_style = cursor_col_override
            .filter(|(col, _)| *col == abs_col)
            .map(|(_, s)| s);
        if let Some(cell) = buf.cell_mut((x, abs_y)) {
            cell.set_char(*ch);
            cell.set_style(cursor_style.unwrap_or(*style));
        }
        if cursor_style.is_some() {
            cursor_cell = Some((x, abs_y));
        }
        x += cells;
    }
    // End-of-line cursor: its column is one past the last char, so the loop above never
    // reaches it — draw it on the first trailing blank cell instead.  Guarded on
    // `col == chars.len()` so a word-wrap gap never matches.  Likewise a cursor on a glyph
    // clipped at the edge takes the blank cell in its place, and the fill's columns resume from
    // that glyph rather than the row's end.
    let eol_cursor = cursor_col_override.filter(|&(col, _)| col == chars.len());
    let fill_cursor =
        cursor_col_override.filter(|&(col, _)| col == chars.len() || Some(col) == clipped);
    let mut fill_col = clipped.unwrap_or(abs_col_base + (end - start));
    while x < area_end {
        if let Some(cell) = buf.cell_mut((x, abs_y)) {
            if let Some((_, s)) = fill_cursor.filter(|&(col, _)| col == fill_col) {
                cell.set_char(' ');
                cell.set_style(s);
                cursor_cell = Some((x, abs_y));
            } else {
                cell.set_style(line_style);
            }
        }
        x += 1;
        fill_col += 1;
    }
    // A row ending the line that fills every cell leaves the EOL cursor no blank to sit on:
    // draw it over the last char instead, rather than nowhere.
    if let (None, Some(lx), Some((_, s))) = (cursor_cell, last_cell, eol_cursor) {
        if end == chars.len() {
            if let Some(cell) = buf.cell_mut((lx, abs_y)) {
                cell.set_style(s);
                cursor_cell = Some((lx, abs_y));
            }
        }
    }
    cursor_cell
}

/// Patch `style` onto the screen cells of `line`'s chars in `cols` (char columns), walking the
/// line's wrapped rows as [`render_line`] lays them out at `area.width`.  `y_first` is the
/// absolute row of the first painted sub-row, `skip_rows` the sub-rows scrolled off above it,
/// and `rows_used` how many the line painted.  A wide glyph gets both its cells; trailing
/// padding is never touched.  The one highlight painter behind Preview selection and Rendered
/// search / selection.
#[allow(clippy::too_many_arguments)]
pub fn patch_char_cols(
    line: &Line<'_>,
    indent: Indent,
    buf: &mut TuiBuf,
    area: Rect,
    y_first: u16,
    rows_used: u16,
    skip_rows: usize,
    cols: std::ops::Range<usize>,
    style: Style,
) {
    let width = area.width as usize;
    if width == 0 || cols.is_empty() {
        return;
    }
    let painted = PaintedRows::new(line, indent, width);
    for (painted_off, (row_off, &(row_start, row_end, _))) in
        painted.rows.iter().enumerate().skip(skip_rows).enumerate()
    {
        if painted_off as u16 >= rows_used {
            break;
        }
        let y = y_first + painted_off as u16;
        if y >= area.y + area.height {
            break;
        }
        let sel_start = cols.start.max(row_start);
        let sel_end = cols.end.min(row_end);
        if sel_start >= sel_end {
            continue;
        }
        // Columns are chars; the screen advances by cells, two for a wide glyph.
        let mut x_off = painted.cell_of(row_off, sel_start);
        for &(ch, _) in &painted.chars[sel_start..sel_end] {
            let w = char_cells(ch);
            for dx in 0..w {
                let x = area.x + (x_off + dx) as u16;
                if x >= area.x + area.width {
                    break;
                }
                if let Some(cell) = buf.cell_mut((x, y)) {
                    cell.set_style(cell.style().patch(style));
                }
            }
            x_off += w;
        }
    }
}

/// The leading run of rendered `▎ ` bar units and spaces, repainted into each continuation
/// row's indent zone in their own styles: the quote gutter survives the wrap, and an indent
/// ahead of a surface (a list item's, before a quote or a code block) keeps the background
/// around the item rather than taking the line's.  Only the rendered glyph is captured: a
/// raw-revealed `> ` is literal source and gets plain blank padding.
fn leading_bar_prefix(chars: &[(char, Style)]) -> Vec<(char, Style)> {
    let mut i = 0;
    while i < chars.len() {
        match chars[i].0 {
            ' ' => i += 1,
            '▎' if chars.get(i + 1).is_some_and(|c| c.0 == ' ') => i += 2,
            _ => break,
        }
    }
    chars[..i].to_vec()
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::style::Color;
    use ratatui::text::Span;

    /// Highlight columns are chars; the painter places them in cells, so `a` after two wide
    /// glyphs sits at cell 4, and a highlighted wide glyph covers both its cells.
    #[test]
    fn patch_char_cols_places_char_columns_in_cells() {
        let sel = Style::default().bg(Color::Magenta);
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = TuiBuf::empty(area);
        patch_char_cols(
            &Line::from("日本ab"),
            Indent::NONE,
            &mut buf,
            area,
            0,
            1,
            0,
            1..3,
            sel,
        );
        let bg = |x: u16| buf[(x, 0)].bg;
        assert_ne!(bg(1), Color::Magenta);
        assert_eq!(bg(2), Color::Magenta);
        assert_eq!(bg(3), Color::Magenta);
        assert_eq!(bg(4), Color::Magenta, "`a` is at cell 4");
        assert_ne!(bg(5), Color::Magenta);
    }

    /// At a width the hanging indent leaves no room in, continuation rows start at the left edge,
    /// and the highlight follows the painter there.  It once padded them by the unclamped indent.
    #[test]
    fn patch_char_cols_drops_an_indent_that_leaves_no_room() {
        let sel = Style::default().bg(Color::Magenta);
        let area = Rect::new(0, 0, 3, 3);
        let line = Line::from("• abcdef");
        let indent = Indent::hanging(2);
        let mut painted = TuiBuf::empty(area);
        render_line(&line, indent, area, &mut painted, 0, true);
        assert_eq!(painted[(0, 1)].symbol(), "a", "rows: `• ` / `abc` / `def`");
        let mut buf = TuiBuf::empty(area);
        patch_char_cols(&line, indent, &mut buf, area, 0, 3, 0, 2..3, sel);
        assert_eq!(
            buf[(0, 1)].bg,
            Color::Magenta,
            "`a` is at the row's first cell"
        );
        assert_ne!(buf[(2, 1)].bg, Color::Magenta);
    }

    #[test]
    fn leading_bar_prefix_captures_rendered_bars_only() {
        let rendered: Vec<(char, Style)> = "▎ ▎ quoted"
            .chars()
            .map(|c| (c, Style::default()))
            .collect();
        assert_eq!(leading_bar_prefix(&rendered).len(), 4);
        // Raw `> ` is literal source, never repainted on continuation rows.
        let raw: Vec<(char, Style)> = "> quoted".chars().map(|c| (c, Style::default())).collect();
        assert!(leading_bar_prefix(&raw).is_empty());
        // A list item's indent ahead of a bar, or of a code block's pad cell, is kept too.
        let nested: Vec<(char, Style)> = "  ▎ q".chars().map(|c| (c, Style::default())).collect();
        assert_eq!(leading_bar_prefix(&nested).len(), 4);
    }

    /// A quote in a list item sits behind the item's indent; its continuation rows repaint
    /// the indent and the bar both.
    #[test]
    fn wrapped_quote_in_a_list_item_repaints_indent_and_bar() {
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = TuiBuf::empty(area);
        let line = Line::from(vec![Span::raw("  ▎ "), Span::raw("alpha beta gamma")]);
        let rows = render_line(&line, Indent::hanging(4), area, &mut buf, 0, true);
        assert!(rows >= 2, "expected the quote to wrap, got {rows} row(s)");
        let row1: String = (0..4).map(|x| buf[(x, 1)].symbol().to_string()).collect();
        assert_eq!(row1, "  ▎ ");
    }

    #[test]
    fn wrapped_blockquote_repaints_bar_on_continuation_rows() {
        // "▎ alpha beta gamma" wrapped at width 10: row 0 holds "▎ alpha "
        // and the continuation row must begin with the "▎ " gutter, not blanks.
        let area = Rect::new(0, 0, 10, 3);
        let mut buf = TuiBuf::empty(area);
        let line = Line::from(vec![Span::raw("▎ "), Span::raw("alpha beta gamma")]);
        let rows = render_line(&line, Indent::hanging(2), area, &mut buf, 0, true);
        assert!(rows >= 2, "expected the quote to wrap, got {rows} row(s)");
        // Row 0 starts with the bar.
        assert_eq!(
            buf.cell((0, 0)).map(|c| c.symbol().to_string()),
            Some("▎".into())
        );
        assert_eq!(
            buf.cell((0, 1)).map(|c| c.symbol().to_string()),
            Some("▎".into())
        );
        assert_eq!(
            buf.cell((1, 1)).map(|c| c.symbol().to_string()),
            Some(" ".into())
        );
        assert_ne!(
            buf.cell((2, 1)).map(|c| c.symbol().to_string()),
            Some(" ".into())
        );
    }

    /// A line whose last row fills every cell has no trailing blank for an end-of-line cursor,
    /// so the cursor is drawn over the last char, unwrapped or on a wrapped last row.  A line
    /// cut off unwrapped never shows its end, so its cursor stays hidden.
    #[test]
    fn eol_cursor_on_a_full_row_paints_over_the_last_char() {
        let style = Style::default().fg(ratatui::style::Color::Red);
        let area = Rect::new(0, 0, 10, 3);
        // The cell and the symbol left under the cursor: the last char, or the trailing blank
        // a line one cell shorter keeps.
        for (text, wrap, want) in [
            ("abcdefghij", true, Some(((9, 0), "j"))),
            ("abcdefghij", false, Some(((9, 0), "j"))),
            ("abcdefghij abcdefghij", true, Some(((9, 1), "j"))),
            ("abcdefghi", true, Some(((9, 0), " "))),
            ("abcdefghijk", false, None),
        ] {
            let mut buf = TuiBuf::empty(area);
            let col = text.chars().count();
            let (_, cursor) = render_line_reporting_cursor(
                &Line::from(text),
                Indent::NONE,
                area,
                &mut buf,
                0,
                wrap,
                Some((col, style)),
                0,
            );
            assert_eq!(cursor, want.map(|(cell, _)| cell), "{text:?}, wrap {wrap}");
            if let Some((cell, symbol)) = want {
                assert_eq!(buf[cell].fg, ratatui::style::Color::Red, "{text:?}");
                assert_eq!(buf[cell].symbol(), symbol, "{text:?}");
            }
        }
    }

    #[test]
    fn cursor_on_an_absorbed_space_paints_on_the_next_row() {
        let line = Line::from("abcdefghij klm");
        let area = Rect::new(0, 0, 10, 3);
        let mut buf = TuiBuf::empty(area);
        let style = Style::default().fg(ratatui::style::Color::Red);
        let (_, cursor) = render_line_reporting_cursor(
            &line,
            Indent::NONE,
            area,
            &mut buf,
            0,
            true,
            Some((10, style)),
            0,
        );
        assert_eq!(cursor, Some((0, 1)));
    }

    /// A `lead` pads the first row and narrows it; the cursor and the continuation rows follow.
    #[test]
    fn a_lead_pads_the_first_row_and_the_cursor_with_it() {
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = TuiBuf::empty(area);
        let style = Style::default().fg(ratatui::style::Color::Red);
        let indent = Indent { lead: 1, hang: 4 };
        let (rows, cursor) = render_line_reporting_cursor(
            &Line::from("6. alpha bravo"),
            indent,
            area,
            &mut buf,
            0,
            true,
            Some((3, style)),
            0,
        );
        let row = |y: u16| (0..12u16).map(|x| buf[(x, y)].symbol()).collect::<String>();
        assert_eq!(rows, 2);
        assert_eq!(row(0), " 6. alpha   ");
        assert_eq!(row(1), "    bravo   ");
        assert_eq!(cursor, Some((4, 0)), "on the `a`, past the pad");
    }

    /// A wide glyph that doesn't fit whole stays off the row instead of painting its right half
    /// into the next widget's cell: unwrapped at the edge, or wrapped into a one-cell row.
    #[test]
    fn a_wide_glyph_never_straddles_the_area_edge() {
        for (text, width, wrap) in [("abc日", 4, false), ("日", 1, true)] {
            let mut buf = TuiBuf::empty(Rect::new(0, 0, 6, 2));
            for x in 0..6 {
                buf[(x, 0)].set_char('x');
            }
            let area = Rect::new(0, 0, width, 2);
            render_line(&Line::from(text), Indent::NONE, area, &mut buf, 0, wrap);
            assert_ne!(
                buf[(width - 1, 0)].symbol(),
                "日",
                "{text:?}: the last cell"
            );
            assert_eq!(buf[(width, 0)].symbol(), "x", "{text:?}: past the area");
        }
    }

    /// The blank cell left by a clipped glyph stands in for that glyph: a cursor on it shows
    /// there, and an end-of-line cursor doesn't, which would read as the line ending before it.
    #[test]
    fn a_clipped_glyph_s_blank_cell_carries_its_cursor_not_the_eol_one() {
        let style = Style::default().fg(ratatui::style::Color::Red);
        for (col, expected) in [(3, Some((3, 0))), (4, None)] {
            let area = Rect::new(0, 0, 4, 1);
            let mut buf = TuiBuf::empty(area);
            let (_, cursor) = render_line_reporting_cursor(
                &Line::from("abc日"),
                Indent::NONE,
                area,
                &mut buf,
                0,
                false,
                Some((col, style)),
                0,
            );
            assert_eq!(cursor, expected, "cursor at column {col}");
        }
    }

    #[test]
    fn render_line_paints_wide_char_using_two_cells() {
        // The right-half cell of the wide char is left unwritten — terminals own it — so
        // the next char lands at column 3.
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = TuiBuf::empty(area);
        let line = Line::from(vec![Span::raw("A🥇B")]);
        render_line(&line, Indent::NONE, area, &mut buf, 0, false);
        assert_eq!(
            buf.cell((0, 0)).map(|c| c.symbol().to_string()),
            Some("A".into())
        );
        assert_eq!(
            buf.cell((1, 0)).map(|c| c.symbol().to_string()),
            Some("🥇".into())
        );
        assert_eq!(
            buf.cell((3, 0)).map(|c| c.symbol().to_string()),
            Some("B".into())
        );
    }

    #[test]
    fn zero_width_combining_mark_does_not_advance_cell_cursor() {
        // The combining mark has zero display width and must not consume a cell, so
        // column 1 holds '!' rather than a blank.
        let area = Rect::new(0, 0, 4, 1);
        let mut buf = TuiBuf::empty(area);
        let line = Line::from(vec![Span::raw("e\u{0301}!")]);
        render_line(&line, Indent::NONE, area, &mut buf, 0, false);
        assert_eq!(
            buf.cell((0, 0)).map(|c| c.symbol().to_string()),
            Some("e\u{0301}".into())
        );
        assert_eq!(
            buf.cell((1, 0)).map(|c| c.symbol().to_string()),
            Some("!".into())
        );
    }

    /// A zero-width char joins the glyph before it instead of vanishing: a combining accent,
    /// and the vowel and final jamo of decomposed (NFD) Hangul, which macOS writes.  A wide
    /// glyph's marks go to its first cell, and every later char keeps its cell.
    #[test]
    fn zero_width_chars_join_the_preceding_glyph() {
        let area = Rect::new(0, 0, 12, 1);
        let mut buf = TuiBuf::empty(area);
        // `한국` decomposed, then `é` decomposed.
        let text = "\u{1112}\u{1161}\u{11AB}\u{1100}\u{116E}\u{11A8}e\u{0301}!";
        render_line(&Line::from(text), Indent::NONE, area, &mut buf, 0, false);
        let cells: Vec<&str> = (0..6).map(|x| buf[(x, 0)].symbol()).collect();
        assert_eq!(
            cells,
            [
                "\u{1112}\u{1161}\u{11AB}",
                " ",
                "\u{1100}\u{116E}\u{11A8}",
                " ",
                "e\u{0301}",
                "!",
            ]
        );
    }

    /// A zero-width joiner stays dropped, as do U+FE0F and U+FE0E, which change the cluster's
    /// width from the per-char cells the layout gives it.  So do a tab, which would move the terminal's
    /// cursor, and a zero-width space, which extends no cluster.  A mark opening a row has no
    /// glyph to join.
    #[test]
    fn zero_width_chars_that_join_no_cluster_or_widen_it_are_dropped() {
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = TuiBuf::empty(area);
        render_line(
            &Line::from(
                "\u{0301}\u{2764}\u{FE0F}\u{1F468}\u{200D}\u{1F469}a\tb\u{200B}c\u{231A}\u{FE0E}",
            ),
            Indent::NONE,
            area,
            &mut buf,
            0,
            false,
        );
        let cells: Vec<&str> = (0..7).map(|x| buf[(x, 0)].symbol()).collect();
        assert_eq!(
            cells,
            ["\u{2764}", "\u{1F468}", " ", "\u{1F469}", " ", "a", "b"]
        );
        assert_eq!(buf[(7, 0)].symbol(), "c");
        assert_eq!(buf[(8, 0)].symbol(), "\u{231A}");
    }
}