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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use ratatui::{
    buffer::Buffer as TuiBuf,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
};

use crate::config::Theme;
use crate::editor::EditorState;
use crate::markdown::cell_overlay::CellOverlay;
use crate::markdown::table_layout::char_cells;
use crate::ui::line_render;

use crate::document::row_map::{self, RawPos};
use crate::document::wrap::{Indent, PaintedRows};
use crate::markdown::{ColOrigin, ContentKind};

/// [`make_raw_line_with_selection`] with no selection.
#[cfg(test)]
pub(super) fn make_raw_line(raw_text: &str, theme: &Theme) -> Line<'static> {
    make_raw_line_with_selection(raw_text, None, theme)
}

/// A `Line` of `raw_text` (the raw-revealed cursor block) with `selection_cols` (a `[start, end)`
/// char range) painted in the selection background.
///
/// The cursor is NOT embedded: `line_render` paints it onto the resolved cell, so the wrap is
/// computed from the bare source and matches the wrap the scroll/navigation code uses.
pub(super) fn make_raw_line_with_selection(
    raw_text: &str,
    selection_cols: Option<(usize, usize)>,
    theme: &Theme,
) -> Line<'static> {
    make_raw_line_over(raw_text, selection_cols, theme, theme.normal)
}

/// [`make_raw_line_with_selection`] over a caller-supplied `base` style, so a revealed line
/// inside a block with its own surface (a blockquote wash) keeps that surface. `base` is also
/// the line-level style, so `line_render`'s trailing-cell fill carries it to the viewport edge.
pub(super) fn make_raw_line_over(
    raw_text: &str,
    selection_cols: Option<(usize, usize)>,
    theme: &Theme,
    base: Style,
) -> Line<'static> {
    let sel_style = theme.selection;
    let chars: Vec<char> = raw_text.chars().collect();
    let total = chars.len();

    // One span per char keeps per-char styling predictable when cursor and selection overlap.
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(total);
    for (i, ch) in chars.iter().enumerate() {
        let mut style = base;
        if matches!(selection_cols, Some((s, e)) if i >= s && i < e) {
            style = style.patch(sel_style);
        }
        spans.push(Span::styled(ch.to_string(), style));
    }
    Line::from(spans).style(base)
}

/// One body row of a mermaid block revealed as a code block, with `code_block_text` as the
/// line style so the trailing-cell fill extends the code background. Char positions stay 1:1
/// with `raw_text` (no leading pad) so click → raw col mapping needs no adjustment.
pub(super) fn make_code_styled_body_line(
    raw_text: &str,
    selection_cols: Option<(usize, usize)>,
    theme: &Theme,
) -> Line<'static> {
    let base = theme.code_block_text;
    let sel_style = theme.selection;
    let chars: Vec<char> = raw_text.chars().collect();
    let total = chars.len();

    let mut spans: Vec<Span<'static>> = Vec::with_capacity(total);
    for (i, ch) in chars.iter().enumerate() {
        let mut style = base;
        if matches!(selection_cols, Some((s, e)) if i >= s && i < e) {
            style = style.patch(sel_style);
        }
        spans.push(Span::styled(ch.to_string(), style));
    }
    Line::from(spans).style(base)
}

/// Which overlay [`paint_byte_range_overlay`] paints, which decides the two rows it can't map
/// exactly: a chrome row (a fence label, a rule, a big H1's glyph rows), which has no column
/// relation to the line it shows, and a content row no inline map renders exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Overlay {
    /// A selection or a yank: it covers the line a chrome row stands for, so the row washes
    /// whole; on an unmapped row it paints only what it covers to the row's ends, rather than
    /// a wrong span inside.
    Selection,
    /// A search match or a `:s` preview: it highlights only the text it matched, so a chrome
    /// row is left alone; on an unmapped row it shows at the one-for-one guess, as wide as the
    /// text it matched, since a match the user jumped to must show somewhere.
    Match,
}

/// Post-render pass: paint `style` over the rendered cells of one rendered line for the source
/// byte range `[sel_start_byte, sel_end_byte)`. Shared by the selection, search-match, `:s`
/// preview, and yank-flash overlays; `overlay` says which (see [`Overlay`]).
///
/// Intersects the range with the source lines *this rendered row* shows, then maps the covered
/// raw positions to rendered chars through the row's origin (`row_map`). Keep the per-row
/// clamp: multi-line ranges (a search match containing `\n`, a linewise selection) rely on it.
/// Lines come from the parse's line index (in `\n`s, as the origins count them; the rope also
/// breaks at `\r` and U+2028) and chars from the rope's, so a call costs the same in a block of
/// any size.
#[allow(clippy::too_many_arguments)]
pub(super) fn paint_byte_range_overlay(
    editor: &EditorState,
    buf: &mut TuiBuf,
    area: Rect,
    y_start: u16,
    rows_used: u16,
    skip_rows: usize,
    rendered_line_idx: usize,
    sel_start_byte: usize,
    sel_end_byte: usize,
    style: Style,
    overlay: Overlay,
) {
    let Some(block_byte) = editor
        .parsed
        .source_map
        .original_byte_for_rendered_line(rendered_line_idx)
    else {
        return;
    };
    let Some(block_range) = editor.parsed.source_map.original_range_for_byte(block_byte) else {
        return;
    };
    if block_range.end <= sel_start_byte || block_range.start >= sel_end_byte {
        return;
    }

    let rope = editor.buffer.rope();
    // With `parsed_dirty` set, an in-line edit may have shifted offsets so `block_range` runs past
    // the buffer or ends inside a multi-byte sequence: clamp, and let a slice off a char boundary
    // skip the frame.
    let block_end = block_range.end.min(rope.len_bytes());
    if block_range.start >= block_end {
        return;
    }
    let parsed = &editor.parsed;
    let first_line = parsed.byte_to_line(block_range.start);
    let Some(block_idx) = editor.parsed.source_map.block_for_byte(block_range.start) else {
        return;
    };
    // An image's reserved rows show no text to highlight.  A revealed diagram's rows show raw
    // source, but `RenderedView` paints their selection and yank flash itself, against that text.
    if editor.parsed.is_image_block(block_idx) {
        return;
    }
    let rendered_span = editor.parsed.source_map.rendered_lines_for_block(block_idx);
    let sub_idx_in_block = rendered_line_idx.saturating_sub(rendered_span.start);
    let Some(line) = editor.parsed.lines.get(rendered_line_idx) else {
        return;
    };
    let indent = editor.parsed.row_indent(rendered_line_idx);
    let actual_rendered: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();

    let line_start = |l: usize| match l {
        0 => block_range.start,
        _ => parsed.line_start_byte(first_line + l),
    };
    // A block line's end, its `\n` aside.
    let line_end = |l: usize| {
        (parsed.line_start_byte(first_line + l) + parsed.source_line(first_line + l).len())
            .min(block_end)
    };
    if let Some(hit) = row_map::table_row(parsed, block_idx, sub_idx_in_block) {
        // Borders and separators carry no raw-byte mapping.
        if !hit.cells {
            return;
        }
        let raw_line_start_abs = line_start(hit.line);
        let raw_line_end_abs = line_end(hit.line);
        let Some(raw_line) = rope
            .get_byte_slice(raw_line_start_abs.min(raw_line_end_abs)..raw_line_end_abs)
            .map(String::from)
        else {
            return;
        };
        let line_sel_start = sel_start_byte.max(raw_line_start_abs);
        let line_sel_end = sel_end_byte.min(raw_line_end_abs);
        if line_sel_start >= line_sel_end {
            return;
        }
        let col_at = |abs: usize| rope.byte_to_char(abs) - rope.byte_to_char(raw_line_start_abs);
        // A match's raw cols land in at most one wrap chunk per cell; mapping per `hit.sub`
        // keeps the highlight off sub-lines that don't show the matched text.
        for (rs, re) in crate::markdown::table_layout::table_raw_col_range_to_rendered_segments(
            &raw_line,
            hit.raw_col,
            line,
            col_at(line_sel_start),
            col_at(line_sel_end),
            hit.sub,
            parsed.ref_labels(),
        ) {
            paint_cols_on_line(
                line, indent, buf, area, y_start, rows_used, skip_rows, rs, re, style,
            );
        }
        return;
    }

    // The source lines the row shows, and the bytes they cover: from the first one's start (the
    // block's, on its first line) to the last one's end, its `\n` aside.
    let Some(lines) = row_map::lines_of_row(&editor.parsed, block_idx, sub_idx_in_block) else {
        return;
    };
    let (first, last) = (lines.start as usize, lines.end as usize - 1);
    let row_start = line_start(first);
    let row_end = line_end(last);
    let (sel_s, sel_e) = (sel_start_byte.max(row_start), sel_end_byte.min(row_end));
    if sel_s >= sel_e {
        return;
    }

    // A source byte of the block as `(line, col)`, columns on the first line counted from the
    // block's start.
    let pos_at = |abs: usize| {
        let line = parsed.byte_to_line(abs).saturating_sub(first_line);
        let from = line_start(line).min(abs);
        RawPos {
            line,
            col: rope.byte_to_char(abs) - rope.byte_to_char(from),
        }
    };
    let origin = &editor.parsed.row_origins()[rendered_line_idx];
    let ColOrigin::Content { kind, .. } = origin.cols else {
        // Chrome (a fence label, a rule) has no column relation: the whole row washes, or
        // nothing does.
        if overlay == Overlay::Match {
            return;
        }
        paint_cols_on_line(
            line,
            indent,
            buf,
            area,
            y_start,
            rows_used,
            skip_rows,
            0,
            actual_rendered,
            style,
        );
        return;
    };
    let rendered =
        |abs: usize| row_map::raw_to_rendered_col(parsed, block_idx, sub_idx_in_block, pos_at(abs));
    // A selection reaching the row's first char (VisualLine, a fully covered line) paints its
    // prefix too: the marker, the bar.  A code row's prefix is its pad cell, which it never
    // painted.  One covering the row's last char paints its whole content even where no map
    // places the end exactly, so a line selection never vanishes.
    let mut rend_start = if sel_start_byte <= row_start && kind != ContentKind::Verbatim {
        Some(0)
    } else {
        rendered(sel_s)
    };
    let mut rend_end = rendered(sel_e).or((sel_end_byte >= row_end).then_some(actual_rendered));
    if overlay == Overlay::Match && (rend_start.is_none() || rend_end.is_none()) {
        // A match the user jumped to must show somewhere: at the one-for-one guess, as wide as
        // the text it matched, kept inside the row.
        let width = rope.byte_to_char(sel_e) - rope.byte_to_char(sel_s);
        let guess =
            row_map::raw_to_rendered_col_near(parsed, block_idx, sub_idx_in_block, pos_at(sel_s));
        let end = (guess + width).min(actual_rendered);
        rend_start = Some(end.saturating_sub(width));
        rend_end = Some(end);
    }
    // A selection with no exact map: skip rather than paint off by N.
    let (Some(rend_start), Some(rend_end)) = (rend_start, rend_end) else {
        return;
    };
    if rend_start >= rend_end {
        return;
    }
    paint_cols_on_line(
        line, indent, buf, area, y_start, rows_used, skip_rows, rend_start, rend_end, style,
    );
}

/// Post-render pass: paint every visible search match; the focused one in `theme.selection`,
/// the rest in `selection_muted`. Called by `EditorView` for both Preview and Rendered, which
/// share the same wrap. Ranges are clamped against the live source so a stale match list
/// (one frame after an external content swap) skips rather than panics.
pub(crate) fn paint_search_overlays(
    editor: &EditorState,
    buf: &mut TuiBuf,
    area: Rect,
    theme: &Theme,
) {
    let Some(search) = editor.search.as_ref() else {
        return;
    };
    // A live `:s` preview rewrites the buffer, so search byte ranges are stale against it.
    if editor.substitute_preview.is_some() {
        return;
    }
    if search.matches.is_empty() || area.width == 0 || area.height == 0 {
        return;
    }
    let source_len = editor.buffer.rope().len_bytes();
    let width = area.width as usize;
    let (mut line_idx, mut first_sub_row) =
        editor.rendered_line_at_visual_row(editor.scroll, width.max(1));
    let mut vis_y: u16 = 0;
    while vis_y < area.height {
        if line_idx >= editor.parsed.lines.len() {
            break;
        }
        let rows = editor
            .parsed
            .visual_rows_for_line_at(line_idx, width)
            .max(1);
        let painted = rows
            .saturating_sub(first_sub_row)
            .min((area.height - vis_y) as usize);
        if painted == 0 {
            break;
        }
        let block_range = editor
            .parsed
            .source_map
            .original_byte_for_rendered_line(line_idx)
            .and_then(|b| editor.parsed.source_map.original_range_for_byte(b));
        if let Some(block_range) = block_range {
            // Matches are sorted: jump to the first that could touch this block.
            let start = search
                .matches
                .partition_point(|m| m.end <= block_range.start);
            for (i, m) in search.matches.iter().enumerate().skip(start) {
                if m.start >= block_range.end {
                    break;
                }
                if m.end > source_len {
                    continue;
                }
                let style = if i == search.focused_idx {
                    theme.selection
                } else {
                    theme.selection_muted
                };
                paint_byte_range_overlay(
                    editor,
                    buf,
                    area,
                    vis_y,
                    painted as u16,
                    first_sub_row,
                    line_idx,
                    m.start,
                    m.end,
                    style,
                    Overlay::Match,
                );
            }
        }
        vis_y += painted as u16;
        line_idx += 1;
        first_sub_row = 0;
    }
}

/// Post-render pass: paint the live `:s` preview's highlight ranges (matches while typing the
/// pattern, inserted replacement segments once one exists). Same walk as
/// [`paint_search_overlays`], single style — the preview has no focus concept.
pub(crate) fn paint_substitute_preview_overlays(
    editor: &EditorState,
    buf: &mut TuiBuf,
    area: Rect,
    theme: &Theme,
) {
    let Some(preview) = editor.substitute_preview.as_ref() else {
        return;
    };
    if preview.highlights.is_empty() || area.width == 0 || area.height == 0 {
        return;
    }
    let source_len = editor.buffer.rope().len_bytes();
    let width = area.width as usize;
    let (mut line_idx, mut first_sub_row) =
        editor.rendered_line_at_visual_row(editor.scroll, width.max(1));
    let mut vis_y: u16 = 0;
    while vis_y < area.height {
        if line_idx >= editor.parsed.lines.len() {
            break;
        }
        let rows = editor
            .parsed
            .visual_rows_for_line_at(line_idx, width)
            .max(1);
        let painted = rows
            .saturating_sub(first_sub_row)
            .min((area.height - vis_y) as usize);
        if painted == 0 {
            break;
        }
        let block_range = editor
            .parsed
            .source_map
            .original_byte_for_rendered_line(line_idx)
            .and_then(|b| editor.parsed.source_map.original_range_for_byte(b));
        if let Some(block_range) = block_range {
            let start = preview
                .highlights
                .partition_point(|r| r.end <= block_range.start);
            for r in preview.highlights.iter().skip(start) {
                if r.start >= block_range.end {
                    break;
                }
                if r.end > source_len {
                    continue;
                }
                paint_byte_range_overlay(
                    editor,
                    buf,
                    area,
                    vis_y,
                    painted as u16,
                    first_sub_row,
                    line_idx,
                    r.start,
                    r.end,
                    theme.selection,
                    Overlay::Match,
                );
            }
        }
        vis_y += painted as u16;
        line_idx += 1;
        first_sub_row = 0;
    }
}

/// Post-render pass: neovim-style yank highlight over [`EditorState::yank_flash`]'s range.
/// Same walk as [`paint_search_overlays`].  Preview only: Rendered mode paints the flash in
/// `RenderedView`'s loop, which knows what a revealed row shows.
pub(crate) fn paint_yank_flash(editor: &EditorState, buf: &mut TuiBuf, area: Rect, theme: &Theme) {
    let Some(flash) = editor.active_yank_flash() else {
        return;
    };
    if area.width == 0 || area.height == 0 {
        return;
    }
    let source_len = editor.buffer.rope().len_bytes();
    if flash.start >= flash.end || flash.end > source_len {
        return;
    }
    let width = area.width as usize;
    let (mut line_idx, mut first_sub_row) =
        editor.rendered_line_at_visual_row(editor.scroll, width.max(1));
    let mut vis_y: u16 = 0;
    while vis_y < area.height {
        if line_idx >= editor.parsed.lines.len() {
            break;
        }
        let rows = editor
            .parsed
            .visual_rows_for_line_at(line_idx, width)
            .max(1);
        let painted = rows
            .saturating_sub(first_sub_row)
            .min((area.height - vis_y) as usize);
        if painted == 0 {
            break;
        }
        let block_range = editor
            .parsed
            .source_map
            .original_byte_for_rendered_line(line_idx)
            .and_then(|b| editor.parsed.source_map.original_range_for_byte(b));
        if let Some(block_range) = block_range {
            if block_range.start < flash.end && block_range.end > flash.start {
                paint_byte_range_overlay(
                    editor,
                    buf,
                    area,
                    vis_y,
                    painted as u16,
                    first_sub_row,
                    line_idx,
                    flash.start,
                    flash.end,
                    theme.selection,
                    Overlay::Selection,
                );
            }
        }
        vis_y += painted as u16;
        line_idx += 1;
        first_sub_row = 0;
    }
}

/// Paint `sel_bg` onto the rendered cells for rendered char cols in `[start_col, end_col)`,
/// with `y_start` relative to `area` — [`line_render::patch_char_cols`] in this view's
/// coordinates.
#[allow(clippy::too_many_arguments)]
pub(super) fn paint_cols_on_line(
    line: &Line<'_>,
    indent: Indent,
    buf: &mut TuiBuf,
    area: Rect,
    y_start: u16,
    rows_used: u16,
    skip_rows: usize,
    start_col: usize,
    end_col: usize,
    sel_bg: Style,
) {
    line_render::patch_char_cols(
        line,
        indent,
        buf,
        area,
        area.y + y_start,
        rows_used,
        skip_rows,
        start_col..end_col,
        sel_bg,
    );
}

/// Where a rendered row was painted: `line` behind `indent`, from `visual_y`, its first
/// `skip_rows` wrap rows scrolled off and `rows_used` rows shown.
pub(super) struct PaintedRow<'l, 'a> {
    pub(super) line: &'l Line<'a>,
    pub(super) indent: Indent,
    pub(super) visual_y: u16,
    pub(super) skip_rows: usize,
    pub(super) rows_used: u16,
}

/// Paint `overlay.raw_text` into the cell's rendered column range of `row`, directly into the
/// buffer (the row must already be rendered). `selection_cols` is painted here because the
/// overlay clobbers whatever the generic selection pass already painted.
///
/// The overlay's columns count along the row unwrapped, so each cell lands where the row's wrap
/// put it ([`PaintedRows::unwrapped_cell_positions`]), the same geometry a click resolves
/// through: painted at the unwrapped column instead, a cell of a table wider than the viewport
/// showed on the wrong row, or past the edge (issue #69).
pub(super) fn overlay_raw_cell(
    buf: &mut TuiBuf,
    area: Rect,
    row: &PaintedRow<'_, '_>,
    overlay: &CellOverlay,
    selection_cols: Option<(usize, usize)>,
    theme: &Theme,
    // Block-cursor style when visible this frame; `None` when blinked off or not in this row.
    cursor: Option<Style>,
) {
    let PaintedRow {
        line,
        indent,
        visual_y,
        skip_rows,
        rows_used,
    } = *row;
    if visual_y >= area.height || area.width == 0 {
        return;
    }
    let positions =
        PaintedRows::new(line, indent, usize::from(area.width)).unwrapped_cell_positions();
    // The screen cell of unwrapped column `col`, when it's painted this frame.
    let screen_cell = |col: usize| {
        let (sub_row, x) = positions.get(col).copied().flatten()?;
        let row = u16::try_from(sub_row.checked_sub(skip_rows)?).ok()?;
        let y = visual_y
            .checked_add(row)
            .filter(|&y| row < rows_used && y < area.height)?;
        let x = u16::try_from(x).ok().filter(|&x| x < area.width)?;
        Some((area.x + x, area.y + y))
    };
    // Strip `theme.normal`'s bg so the table-row stripe under the cell survives.
    let base_style = Style {
        bg: None,
        ..theme.normal
    };

    // Walk chars (indices address `raw_text`, then one blank cell each past its end) while
    // advancing by cells, so a wide glyph takes two and the right border stays put.
    let mut chars = overlay.raw_text.chars();
    let mut col = overlay.rendered_start;
    let mut i = 0usize;
    // The cell of the last glyph painted, which a zero-width char joins.
    let mut glyph_cell = None;
    while col < overlay.rendered_end {
        let mut ch = chars.next().unwrap_or(' ');
        let mut w = char_cells(ch);
        if w == 0 {
            // Zero-width chars join the preceding glyph, as in `line_render::paint_row`.
            if let Some(at) = glyph_cell {
                line_render::append_zero_width(buf, at, ch);
            }
            i += 1;
            continue;
        }
        let at = screen_cell(col);
        // A wide glyph needs its two cells side by side: not past the border, and not split
        // across a wrap.
        let past_border = w > 1 && col + w > overlay.rendered_end;
        let split = w > 1
            && !past_border
            && at
                .zip(screen_cell(col + 1))
                .is_none_or(|((x, y), next)| next != (x + 1, y));
        let mut targets = [at, None];
        if past_border {
            // Blank the last cell before the border instead.
            (ch, w) = (' ', 1);
        } else if split {
            // Blank both cells, keeping the chars after it at the columns a click resolves.
            ch = ' ';
            targets[1] = screen_cell(col + 1);
        }
        // A blank standing in for a wide glyph is no glyph for its marks to join, nor is a cell
        // absorbed by a wrap or scrolled off.
        glyph_cell = at.filter(|_| !(past_border || split));
        let mut style = base_style;
        if matches!(selection_cols, Some((s, e)) if i >= s && i < e) {
            style = style.patch(theme.selection);
        }
        if let Some(cursor_style) = cursor.filter(|_| overlay.cursor_in_cell == Some(i)) {
            style = cursor_style;
        }
        for cell in targets.into_iter().flatten() {
            let Some(cell) = buf.cell_mut(cell) else {
                continue;
            };
            // `Cell::set_style` only adds/removes modifiers, so e.g. the BOLD of a rendered
            // `**x**` would bleed through the raw chars; zero them by hand.
            cell.modifier = Modifier::empty();
            cell.set_char(ch);
            cell.set_style(style);
        }
        col += w;
        i += 1;
    }
}

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

    use crate::config::Theme;

    fn overlay(start: usize, end: usize, raw: &str, cursor: Option<usize>) -> CellOverlay {
        CellOverlay {
            rendered_start: start,
            rendered_end: end,
            raw_text: raw.to_owned(),
            cursor_in_cell: cursor,
            raw_cell_byte_start: 0,
            left_pipe: start.saturating_sub(1),
            raw_content: 0..raw.chars().count(),
        }
    }

    fn painted(ov: &CellOverlay, cursor: Style) -> TuiBuf {
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = TuiBuf::empty(area);
        for x in 0..10 {
            buf[(x, 0)].set_char('x');
        }
        let line = Line::from("x".repeat(10));
        let row = PaintedRow {
            line: &line,
            indent: Indent::NONE,
            visual_y: 0,
            skip_rows: 0,
            rows_used: 1,
        };
        overlay_raw_cell(
            &mut buf,
            area,
            &row,
            ov,
            None,
            &Theme::default(),
            Some(cursor),
        );
        buf
    }

    /// `ov` over `│ a   │ b   │` painted 10 cells wide, which wraps it after `│ a   │ ` (issue
    /// #69), from the row's `skip_rows`th wrap row; unpainted cells keep their `x`.
    fn painted_wrapped(ov: &CellOverlay, cursor: Style, skip_rows: usize) -> TuiBuf {
        let area = Rect::new(0, 0, 10, 2);
        let mut buf = TuiBuf::empty(area);
        for y in 0..2 {
            for x in 0..10 {
                buf[(x, y)].set_char('x');
            }
        }
        let line = Line::from("│ a   │ b   │");
        let row = PaintedRow {
            line: &line,
            indent: Indent::NONE,
            visual_y: 0,
            skip_rows,
            rows_used: 2 - skip_rows as u16,
        };
        overlay_raw_cell(
            &mut buf,
            area,
            &row,
            ov,
            None,
            &Theme::default(),
            Some(cursor),
        );
        buf
    }

    /// The second cell of a row wrapped mid-cell paints where the wrap put each of its cells:
    /// its pad on the first row, its text and the cursor after it on the second, nothing past
    /// the first row's last char.  It used to paint all of it on the first row, at the
    /// unwrapped columns.
    #[test]
    fn overlay_raw_cell_follows_the_rows_wrap() {
        let cursor = Style::default().bg(ratatui::style::Color::Magenta);
        let buf = painted_wrapped(&overlay(7, 12, " b ", Some(2)), cursor, 0);
        assert_eq!(buf[(7, 0)].symbol(), " ");
        assert_eq!(buf[(8, 0)].symbol(), "x", "past the first row's text");
        assert_eq!(buf[(0, 1)].symbol(), "b");
        assert_eq!(buf[(1, 1)].bg, ratatui::style::Color::Magenta);
        assert_eq!(buf[(3, 1)].symbol(), " ");
        assert_eq!(
            buf[(4, 1)].symbol(),
            "x",
            "the border cell is not the overlay's"
        );

        // Scrolled one wrap row off the top, the second row paints at the top.
        let buf = painted_wrapped(&overlay(7, 12, " b ", Some(2)), cursor, 1);
        assert_eq!(buf[(0, 0)].symbol(), "b");
        assert_eq!(buf[(7, 0)].symbol(), "x", "the first row is scrolled off");
    }

    /// A wide raw glyph the wrap would split is blanked in both its cells, as at the border, and
    /// the char after it keeps its unwrapped column (9, the second row's second cell), where a
    /// click resolves to it.  Scrolled one wrap row off the top, the same holds on the top row.
    #[test]
    fn overlay_raw_cell_blanks_a_glyph_the_wrap_splits() {
        let ov = overlay(7, 12, "日x", None);
        let buf = painted_wrapped(&ov, Style::default(), 0);
        assert_eq!(buf[(7, 0)].symbol(), " ");
        assert_eq!(buf[(0, 1)].symbol(), " ");
        assert_eq!(buf[(1, 1)].symbol(), "x");
        let shown = (0..2).flat_map(|y| (0..10).map(move |x| (x, y)));
        assert!(shown.into_iter().all(|c| buf[c].symbol() != "日"));

        let buf = painted_wrapped(&ov, Style::default(), 1);
        assert_eq!(buf[(0, 0)].symbol(), " ");
        assert_eq!(buf[(1, 0)].symbol(), "x");
    }

    /// A wide raw glyph advances two cells, so the chars after it and the cursor land where
    /// the terminal draws them and the right border is untouched.
    #[test]
    fn overlay_raw_cell_advances_by_cells() {
        let cursor = Style::default().bg(ratatui::style::Color::Magenta);
        let buf = painted(&overlay(1, 6, "日a", Some(1)), cursor);
        assert_eq!(buf[(1, 0)].symbol(), "日");
        assert_eq!(buf[(3, 0)].symbol(), "a");
        assert_eq!(buf[(3, 0)].bg, ratatui::style::Color::Magenta);
        assert_eq!(buf[(4, 0)].symbol(), " ");
        assert_eq!(buf[(5, 0)].symbol(), " ");
        assert_eq!(
            buf[(6, 0)].symbol(),
            "x",
            "the border cell is not the overlay's"
        );
    }

    #[test]
    fn overlay_raw_cell_blanks_a_glyph_that_would_straddle_the_border() {
        let buf = painted(&overlay(1, 4, "ab日", None), Style::default());
        assert_eq!(buf[(3, 0)].symbol(), " ");
        assert_eq!(buf[(4, 0)].symbol(), "x");
    }

    /// A revealed cell's zero-width char joins the glyph before it, as on any other row.
    #[test]
    fn overlay_raw_cell_joins_zero_width_chars_to_the_preceding_glyph() {
        let buf = painted(&overlay(1, 6, "e\u{0301}a", None), Style::default());
        assert_eq!(buf[(1, 0)].symbol(), "e\u{0301}");
        assert_eq!(buf[(2, 0)].symbol(), "a");
    }

    /// A wide glyph blanked at the border takes its marks with it: they don't join the blank.
    #[test]
    fn overlay_raw_cell_drops_the_marks_of_a_glyph_blanked_at_the_border() {
        let buf = painted(&overlay(1, 3, "a\u{304B}\u{3099}", None), Style::default());
        assert_eq!(buf[(1, 0)].symbol(), "a");
        assert_eq!(buf[(2, 0)].symbol(), " ");
    }

    /// A chrome row (here a fence's ` rust ` label) has no column relation to its line: a
    /// selection over the line washes it whole, a match on its text leaves it alone.
    #[test]
    fn a_chrome_row_washes_for_a_selection_and_not_for_a_match() {
        let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
        let src = "```rust\nx\n```\n";
        let editor = EditorState::new(crate::document::Buffer::from_str(src), theme);
        let style = Style::default().bg(ratatui::style::Color::Rgb(9, 8, 7));
        let washed = |overlay: Overlay| {
            let area = Rect::new(0, 0, 20, 1);
            let mut buf = TuiBuf::empty(area);
            paint_byte_range_overlay(&editor, &mut buf, area, 0, 1, 0, 0, 3, 7, style, overlay);
            (0..area.width)
                .filter(|&x| buf[(x, 0)].bg == ratatui::style::Color::Rgb(9, 8, 7))
                .count()
        };
        assert_eq!(washed(Overlay::Selection), " rust ".len());
        assert_eq!(washed(Overlay::Match), 0);
    }

    /// On a row no inline map renders exactly, a match still shows (one for one), while a
    /// selection inside the row skips rather than paint a wrong span.
    #[test]
    fn an_unmapped_row_shows_a_match_and_not_a_partial_selection() {
        let theme: &'static Theme = Box::leak(Box::new(Theme::default()));
        // pulldown-cmark folds `ss` and `ß` to one label; the maps' lowercasing doesn't, so the
        // row (`x[ss] y`) has no exact map.
        let src = "x[^ss] y\n\n[^ß]: n\n";
        let editor = EditorState::new(crate::document::Buffer::from_str(src), theme);
        let style = Style::default().bg(ratatui::style::Color::Rgb(9, 8, 7));
        let y = src.find('y').unwrap();
        let painted = |overlay: Overlay| {
            let area = Rect::new(0, 0, 20, 1);
            let mut buf = TuiBuf::empty(area);
            paint_byte_range_overlay(
                &editor,
                &mut buf,
                area,
                0,
                1,
                0,
                0,
                y,
                y + 1,
                style,
                overlay,
            );
            (0..area.width)
                .filter(|&x| buf[(x, 0)].bg == ratatui::style::Color::Rgb(9, 8, 7))
                .count()
        };
        assert_eq!(painted(Overlay::Match), 1);
        assert_eq!(painted(Overlay::Selection), 0);
    }

    #[test]
    fn make_raw_line_keeps_source_text_verbatim() {
        // The cursor is painted onto the resolved cell, not baked into the line.
        let theme = Theme::default();
        let line = make_raw_line("hello", &theme);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, "hello");
    }

    #[test]
    fn make_raw_line_with_selection_paints_range() {
        let theme = Theme::default();
        let line = make_raw_line_with_selection("hello", Some((1, 3)), &theme);
        assert_eq!(line.spans[1].style.bg, theme.selection.bg);
        assert_eq!(line.spans[2].style.bg, theme.selection.bg);
        assert_ne!(line.spans[0].style.bg, theme.selection.bg);
    }
}