edamame 0.1.1

A fast TUI Markdown editor and viewer
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
use ratatui::{buffer::Buffer as TuiBuf, layout::Rect, style::Style, text::Line};
use unicode_width::UnicodeWidthChar;

/// Display width of `ch` in terminal cells.  Wide chars (CJK, most emoji)
/// return 2; ASCII / BMP narrow chars return 1; control chars return 0.
/// Used by both the renderer and the wrap-row calculator so on-screen
/// geometry agrees with cursor and selection coordinates.
pub fn char_cells(ch: char) -> usize {
    UnicodeWidthChar::width(ch).unwrap_or(0)
}

/// Char index in `text` (0-based) corresponding to screen cell column
/// `target_cell`, assuming the row's first content cell sits at column
/// `indent` (>0 for hanging-indent continuation rows).  Implements the
/// landing rules used by vertical navigation and mouse clicks alike:
///
/// - **Forbidden indent zone:** when `target_cell <= indent` the cursor
///   lands at char index 0 — the first content char.  The hanging-indent
///   padding on a wrapped list-item continuation row is virtual, not
///   text, so the cursor never sits there.
/// - **Wide-char snap-past:** when `target_cell` falls *inside* a
///   multi-cell glyph (CJK, emoji), the cursor lands *after* that glyph.
///   It never visually sits in the right half of a wide char.
/// - **Past content:** when `target_cell` exceeds the row's total cell
///   width, returns the total char count of `text` (one past the last
///   char) — callers clamp to row end as appropriate.
pub fn char_idx_at_cell_col<I>(iter: I, target_cell: usize, indent: usize) -> usize
where
    I: IntoIterator<Item = char>,
{
    if target_cell <= indent {
        return 0;
    }
    let mut acc = indent;
    let mut count = 0;
    for ch in iter {
        let w = char_cells(ch);
        if acc + w > target_cell {
            return if acc == target_cell { count } else { count + 1 };
        }
        acc += w;
        count += 1;
    }
    count
}

/// Inverse of `char_idx_at_cell_col`: cumulative cell width of the first
/// `char_idx` chars of `iter`, plus `indent`.  Use this to seed
/// `preferred_col` after a horizontal cursor move so subsequent vertical
/// navigation lands at the same screen cell.
pub fn cell_col_at_char_idx<I>(iter: I, char_idx: usize, indent: usize) -> usize
where
    I: IntoIterator<Item = char>,
{
    let mut acc = indent;
    for (i, ch) in iter.into_iter().enumerate() {
        if i >= char_idx {
            break;
        }
        acc += char_cells(ch);
    }
    acc
}

/// Largest `n` such that the cumulative cell width of
/// `chars[start..start + n]` fits within `cell_budget`.  When the very
/// first char is itself wider than `cell_budget` we still return `1` so
/// the wrap loop makes progress at very narrow viewports — the renderer
/// will clip the overflowing right half on draw.
fn chars_within_cell_budget(chars: &[(char, Style)], start: usize, cell_budget: usize) -> usize {
    let mut total = 0usize;
    let mut count = 0usize;
    for (ch, _) in &chars[start..] {
        let w = char_cells(*ch);
        if count > 0 && total + w > cell_budget {
            break;
        }
        total += w;
        count += 1;
        if total >= cell_budget {
            break;
        }
    }
    count
}

/// Write a styled `Line` to the TUI buffer, wrapping at `area.width` when
/// `wrap` is true. Returns the number of visual rows consumed (≥ 1).
///
/// Trailing cells in every visual row are filled with the line's base style so
/// styled blocks (e.g. code blocks) extend to the full width of `area`.  The
/// wrap algorithm is word-aware: breaks prefer the last non-alphanumeric
/// character within the row, falling back to a hard break when a single word
/// exceeds the row width.  `area.width` is interpreted as terminal *cells*,
/// so wide chars (emoji, CJK) consume two columns of budget per char.
///
/// Hanging-indent: when the line begins with a recognized list marker (or
/// leading whitespace from a list-item continuation paragraph), wrapped
/// continuation rows are left-padded so their text aligns with the column
/// where the first row's text begins — the marker hangs off on the left.
/// Detection lives in `compute_hanging_indent`; an indent of 0 (the default
/// for non-list lines) preserves the legacy zero-padding wrap.
///
/// `cursor_col_override`: when `Some((col, style))`, the character at char
/// index `col` (NOT cell column) on the first output row is rendered as the
/// block cursor — the cell is recolored with `style` while the character stays
/// visible (used to show a cursor indicator during the jitter-suppression
/// delay in hybrid rendered mode).  The override applies only to the first
/// cell of a wide char — terminals can't independently style the right half.
/// Used by tests in this module; production code uses `render_line_from_visual`
/// to support sub-row scrolling.
#[allow(dead_code)]
pub fn render_line(
    line: &Line<'static>,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
) -> u16 {
    render_line_with_cursor_from_visual(line, area, buf, visual_y, wrap, None, 0)
}

pub fn render_line_from_visual(
    line: &Line<'static>,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    skip_rows: usize,
) -> u16 {
    render_line_with_cursor_from_visual(line, 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>,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
) -> u16 {
    render_line_with_cursor_from_visual(line, area, buf, visual_y, wrap, cursor_col_override, 0)
}

pub fn render_line_with_cursor_from_visual(
    line: &Line<'static>,
    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,
        area,
        buf,
        visual_y,
        wrap,
        cursor_col_override,
        skip_rows,
    )
    .0
}

/// Like [`render_line_with_cursor_from_visual`], but also returns the
/// absolute `(x, y)` cell where the cursor override was painted (`None`
/// when no override, or the override fell outside the drawn rows).  The
/// hybrid `RenderedView` uses the reported cell to re-stamp the cursor on
/// top of post-pass overlays (search-match highlights, selection washes)
/// that run after this widget and would otherwise bury it.
pub fn render_line_reporting_cursor(
    line: &Line<'static>,
    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,
        area,
        buf,
        visual_y,
        wrap,
        cursor_col_override,
        skip_rows,
        None,
    )
}

/// Raw-mode variant of [`render_line_with_cursor_from_visual`]: wraps with a
/// **flat** layout, never a hanging indent.
///
/// Raw mode shows the file, so the only liberty it takes with the source is
/// word-wrapping a line too long for the viewport; indenting the continuation
/// rows would draw leading whitespace that isn't in the document.  It is also
/// what the rest of Raw mode already assumes: `visual_rows_of_str` — which
/// backs the scroll cache (`EditorState::raw_line_at_visual_row`,
/// `raw_total_visual_rows`) and the click mapping
/// (`mouse_ops::coord::raw_click_to_offset`) — wraps at indent 0, so a
/// hanging indent here would put the painter in a different layout from the
/// scroll math (a differing *row count* at narrow widths, not just a column
/// shift) and offset every click on a continuation row by the marker width.
///
/// Passing indent 0 also suppresses the blockquote-bar repaint, which is
/// correct here for the same reason: in Raw mode the `> ` on the first row is
/// real source text, and the 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,
        area,
        buf,
        visual_y,
        true,
        cursor_col_override,
        skip_rows,
        Some(0),
    )
    .0
}

/// Shared implementation behind [`render_line_reporting_cursor`] and
/// [`render_raw_line_with_cursor`].  `hanging_indent` of `None` detects the
/// indent from the line's leading marker (`compute_hanging_indent`); `Some(n)`
/// forces it, which is how Raw mode asks for a flat wrap.
#[allow(clippy::too_many_arguments)]
fn render_line_core(
    line: &Line<'static>,
    area: Rect,
    buf: &mut TuiBuf,
    visual_y: u16,
    wrap: bool,
    cursor_col_override: Option<(usize, Style)>,
    skip_rows: usize,
    hanging_indent: Option<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;

    // Collect all (char, style) pairs from the spans, resolving line-level style.
    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 — keeps the renderer in lockstep
    // with the navigation/selection helpers below.
    let indent = hanging_indent.unwrap_or_else(|| compute_hanging_indent(line));
    let rows = visual_rows_of_chars(&chars, width, indent);
    let effective_indent = if indent + 1 >= width { 0 } else { indent };
    // Blockquote bar to repaint on each wrapped continuation row so the gutter
    // doesn't vanish mid-quote; empty for non-blockquote lines.
    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 = if row_idx == 0 { 0 } else { effective_indent };
        let row_prefix: &[(char, Style)] = if row_idx == 0 { &[] } else { &cont_prefix };
        if let Some(cell) = paint_row(
            &chars,
            start,
            row_end,
            start,
            row_indent,
            row_prefix,
            area,
            buf,
            cur_abs_y,
            line_style,
            cursor_col_override,
        ) {
            cursor_cell = Some(cell);
        }
        cur_visual += 1;
    }

    (cur_visual - visual_y, cursor_cell)
}

/// Paint a single visual row.  `chars[start..end]` are written starting at
/// `area.x + row_indent` (after filling `row_indent` cells of hanging-indent
/// padding).  `abs_col_base` is the char-index offset to add to `rel_idx`
/// when matching against `cursor_col_override` — for wrapped continuation
/// rows this is the row's `start`; for the no-wrap fast path it's 0.
///
/// `cont_prefix` is the styled glyph run repainted at the start of the indent
/// zone (the blockquote `▎ ` bar — see [`leading_bar_prefix`]); any indent
/// cells beyond it are blank-filled in `line_style`.  It is empty for the
/// first row of a line and for non-blockquote continuations, so list-item
/// continuations keep their plain blank padding.
///
/// Returns the absolute `(x, y)` cell where the cursor override was drawn —
/// `None` when the override doesn't fall on this row.  Callers use the
/// reported cell to re-stamp the cursor on top of post-pass overlays
/// (search-match highlights, selection washes) that would otherwise bury it.
#[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;
    // Indent zone: repaint the blockquote bar(s) so the gutter persists on
    // wrapped rows, then blank-fill the remainder (e.g. a list marker's width
    // when a list item inside a quote wraps) 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;
    }
    for (rel_idx, (ch, style)) in chars[start..end].iter().enumerate() {
        let cells = char_cells(*ch) as u16;
        if cells == 0 || x >= area_end {
            // Zero-width chars (e.g. ZWJ, variation selectors, combining
            // marks) are conceptually merged into the preceding grapheme
            // by the terminal — skip without advancing `x` rather than
            // overwriting the previous cell's glyph.
            if cells == 0 {
                continue;
            }
            break;
        }
        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)) {
            // Block cursor: recolor the cell, leaving the char visible.
            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: the override column sits one past the last char,
    // so the content loop above never reaches it.  Draw it on the first
    // trailing (blank) cell so an end-of-line cursor stays visible even when
    // the block is shown rendered rather than raw — e.g. while a search flow
    // suppresses the raw cursor-block reveal, or during the jitter
    // suppression delay.  Guard on `col == chars.len()` so a word-wrap gap
    // (whose trailing cells belong to the next row's content) never matches.
    let eol_cursor = cursor_col_override.filter(|&(col, _)| col == chars.len());
    let mut fill_col = abs_col_base + (end - start);
    while x < area_end {
        if let Some(cell) = buf.cell_mut((x, abs_y)) {
            if let Some((_, s)) = eol_cursor.filter(|&(col, _)| col == fill_col) {
                // Block cursor on the trailing blank cell.
                cell.set_char(' ');
                cell.set_style(s);
                cursor_cell = Some((x, abs_y));
            } else {
                cell.set_style(line_style);
            }
        }
        x += 1;
        fill_col += 1;
    }
    cursor_cell
}

/// Compute the list of visual rows produced by wrapping `chars` at `width`
/// (in terminal cells) with a hanging `indent`.  When `indent > 0`, the
/// first row uses the full `width` and every continuation row uses
/// `width - indent`.
///
/// Returns a list of `(start, end, next_start)` tuples, where:
/// - `chars[start..end]` is the content placed on that visual row
/// - `next_start` is the index at which the next visual row begins (equal
///   to `end` — whitespace is never consumed across the break)
///
/// `width` and `indent` are cell counts; the returned indices are char
/// indices.  `render_line_with_cursor` calls this directly to drive its
/// row-by-row painting, so the renderer and visual-line navigation always
/// agree on where rows break.
pub fn visual_rows_of_chars(
    chars: &[(char, Style)],
    width: usize,
    indent: usize,
) -> Vec<(usize, usize, usize)> {
    let mut rows = Vec::new();
    if width == 0 {
        rows.push((0, chars.len(), chars.len()));
        return rows;
    }
    // If the indent leaves no room on continuation rows, ignore it — matches
    // `render_line_with_cursor`'s fallback so wrap-row counts stay in sync.
    let indent = if indent + 1 >= width { 0 } else { indent };

    let mut start = 0;
    let mut row_idx = 0usize;
    loop {
        if start >= chars.len() {
            if rows.is_empty() {
                rows.push((0, 0, 0));
            }
            break;
        }
        let row_width = if row_idx == 0 {
            width
        } else {
            width.saturating_sub(indent).max(1)
        };
        let n_chars = chars_within_cell_budget(chars, start, row_width);
        let remaining = chars.len() - start;
        let (row_end, next_start) = if n_chars >= remaining {
            (chars.len(), chars.len())
        } else {
            let window_end = start + n_chars;
            let break_rel = chars[start..window_end]
                .iter()
                .enumerate()
                .rev()
                .find(|(_, (ch, _))| !ch.is_alphanumeric())
                .map(|(i, _)| i);

            match break_rel {
                Some(bp) => {
                    let end = start + bp + 1;
                    (end, end)
                }
                None => (window_end, window_end),
            }
        };

        rows.push((start, row_end, next_start));
        if next_start >= chars.len() || next_start == start {
            break;
        }
        start = next_start;
        row_idx += 1;
    }

    if rows.is_empty() {
        rows.push((0, 0, 0));
    }

    rows
}

/// Compute the list of visual rows produced by wrapping a plain string `text`
/// at `width`.  Convenience wrapper around `visual_rows_of_chars` used by the
/// cursor/navigation code which operates on RAW buffer text — no hanging
/// indent applies (the cursor's raw line in Rendered mode and every line in
/// Raw mode follow the source layout, not the rendered layout).
pub fn visual_rows_of_str(text: &str, width: usize) -> Vec<(usize, usize, usize)> {
    let chars: Vec<(char, Style)> = text.chars().map(|c| (c, Style::default())).collect();
    visual_rows_of_chars(&chars, width, 0)
}

/// Number of visual rows a styled `Line` occupies when wrapped at `width`.
///
/// Mirrors the wrap algorithm used by `render_line`, so scroll-bound
/// calculations can match what the viewport actually draws.  Empty lines
/// always consume a single row.  Detects the line's hanging indent the same
/// way `render_line` does — list-item continuations consume more rows when
/// indented than they would under flat wrap.
pub fn visual_rows_for_line(line: &Line<'_>, width: usize) -> usize {
    if width == 0 {
        return 1;
    }
    let chars: Vec<(char, Style)> = line
        .spans
        .iter()
        .flat_map(|span| span.content.chars().map(move |c| (c, span.style)))
        .collect();
    if chars.is_empty() {
        return 1;
    }
    let indent = compute_hanging_indent(line);
    visual_rows_of_chars(&chars, width, indent).len().max(1)
}

/// Hanging-indent (in cells) for the given rendered `Line`.
///
/// The indent is the column where the first character after the list marker
/// begins on the first visual row — wrapped continuation rows are then
/// left-padded by this amount so the wrapped text aligns with the first
/// line's text column and the marker visually hangs off to its left.
///
/// Detected shapes:
///
/// 1. Rendered bullet:           `• text`           → indent = leading_ws + 2
/// 2. Raw bullet (raw-revealed): `- text`           → indent = leading_ws + 2
/// 3. Bullet + task:             `- [ ] text`       → indent = leading_ws + 6
/// 4. Ordered (rendered/raw):    `1. text`/` 1. `   → indent = leading_ws + digit_width + 2
/// 5. Continuation paragraph:    `   text`          → indent = leading_ws
///
/// Returns 0 for lines that don't match any of these shapes (plain
/// paragraphs, blockquoted content, table rows, code blocks, etc.).
pub fn compute_hanging_indent(line: &Line<'_>) -> usize {
    let chars: Vec<char> = line.spans.iter().flat_map(|s| s.content.chars()).collect();
    compute_hanging_indent_chars(&chars)
}

/// String-based variant of [`compute_hanging_indent`] for use against the
/// raw buffer text (where there are no `Line` spans available, e.g. inside
/// `EditorState::move_up_visual` / `move_down_visual`).  Same detection
/// rules — see that function for the recognized marker shapes.
pub fn compute_hanging_indent_str(text: &str) -> usize {
    let chars: Vec<char> = text.chars().collect();
    compute_hanging_indent_chars(&chars)
}

fn compute_hanging_indent_chars(chars: &[char]) -> usize {
    let mut i = 0;
    while i < chars.len() && chars[i] == ' ' {
        i += 1;
    }
    let leading = i;

    // Blockquote bar prefix: the rendered `â–Ž ` gutter, or the raw `> ` marker
    // shown when the cursor's quote line is raw-revealed.  Each level is a
    // 2-cell prefix that must hang off wrapped continuation rows — the bar is
    // repainted there (see `leading_bar_prefix`) so the gutter persists, and
    // the wrap budget matches the navigation side, which sees the raw `> `.
    // After the bar(s) an inner list marker may follow, so recurse on the
    // remainder to keep a wrapped list item inside a quote aligned too.
    if blockquote_prefix_unit(&chars[i..]) {
        let after = i + 2;
        return 2 + compute_hanging_indent_chars(&chars[after..]);
    }

    // Rendered bullet glyph (`•`) — only emitted by the renderer.
    if chars.get(i) == Some(&'•') && chars.get(i + 1) == Some(&' ') {
        return text_start_after_optional_task_prefix(chars, i + 2);
    }
    // Raw bullet glyph (`-`, `*`, `+`) — used when the cursor's list-item
    // line is shown raw inside the otherwise-rendered `RenderedView`.  We
    // hang-indent it too so the cursor's row stays visually aligned with
    // the surrounding rendered list.
    if matches!(chars.get(i), Some('-') | Some('*') | Some('+')) && chars.get(i + 1) == Some(&' ') {
        return text_start_after_optional_task_prefix(chars, i + 2);
    }
    // Ordered marker: digits + `.`/`)` + space.  Matches both the raw form
    // (`1. `) and the rendered right-aligned form (` 1. `).
    let digit_count = chars[i..].iter().take_while(|c| c.is_ascii_digit()).count();
    if digit_count > 0
        && matches!(chars.get(i + digit_count), Some('.') | Some(')'))
        && chars.get(i + digit_count + 1) == Some(&' ')
    {
        return text_start_after_optional_task_prefix(chars, i + digit_count + 2);
    }

    // Continuation paragraph or otherwise-indented text (e.g. list-item
    // child block, indented heading).  Hanging-indent at the leading-space
    // count keeps wrapped continuations flush with the indented body.
    if leading > 0 {
        return leading;
    }
    0
}

fn is_task_marker(chars: &[char], i: usize) -> bool {
    chars.get(i) == Some(&'[')
        && matches!(chars.get(i + 1), Some(' ') | Some('x') | Some('X'))
        && chars.get(i + 2) == Some(&']')
        && chars.get(i + 3) == Some(&' ')
}

fn text_start_after_optional_task_prefix(chars: &[char], pos: usize) -> usize {
    if is_task_marker(chars, pos) {
        pos + 4
    } else {
        pos
    }
}

/// True when `chars` begins with one blockquote-bar unit: the rendered gutter
/// glyph `â–Ž` or the raw `>` marker, followed by a space.  Each unit is two
/// cells wide; nesting (`â–Ž â–Ž `, `> > `) is handled by recursion in
/// [`compute_hanging_indent_chars`].
fn blockquote_prefix_unit(chars: &[char]) -> bool {
    matches!(chars.first(), Some('â–Ž') | Some('>')) && chars.get(1) == Some(&' ')
}

/// The leading run of rendered blockquote bar glyphs (`â–Ž ` units, with their
/// styles) at the start of a styled line.  Repainted into the hanging-indent
/// zone of each wrapped continuation row so the quote gutter persists across
/// the wrap.  Only the rendered `▎` glyph is captured — a raw-revealed `> `
/// line is literal source and gets plain blank padding on continuation rows.
fn leading_bar_prefix(chars: &[(char, Style)]) -> Vec<(char, Style)> {
    let mut out = Vec::new();
    let mut i = 0;
    while i + 1 < chars.len() && chars[i].0 == 'â–Ž' && chars[i + 1].0 == ' ' {
        out.push(chars[i]);
        out.push(chars[i + 1]);
        i += 2;
    }
    out
}

/// Given the visual-row layout of a line and a raw char column, return
/// `(sub_line_idx, visual_col)` — which visual row the char is on, and its
/// visual column within that row (0-based).
///
/// Cursor positions at end-of-line or within a wrap-point skip zone are mapped
/// to the nearest visible row at its end column.
pub fn sub_line_of_col(rows: &[(usize, usize, usize)], raw_col: usize) -> (usize, usize) {
    for (i, &(s, e, n)) in rows.iter().enumerate() {
        if raw_col < n {
            let row_width = e - s;
            let visual_col = raw_col.saturating_sub(s).min(row_width);
            return (i, visual_col);
        }
    }
    if let Some(&(s, e, _)) = rows.last() {
        let last_idx = rows.len() - 1;
        let row_width = e - s;
        let visual_col = raw_col.saturating_sub(s).min(row_width);
        return (last_idx, visual_col);
    }
    (0, 0)
}

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

    #[test]
    fn visual_rows_short_line() {
        let rows = visual_rows_of_str("hello", 10);
        assert_eq!(rows, vec![(0, 5, 5)]);
    }

    #[test]
    fn visual_rows_wraps_at_space() {
        // "hello world" wraps at space (col 5).
        let rows = visual_rows_of_str("hello world foo", 10);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], (0, 6, 6)); // "hello " on row 0
        assert_eq!(rows[1], (6, 15, 15)); // "world foo" on row 1
    }

    #[test]
    fn visual_rows_force_break_on_long_word() {
        // Single long word exceeds width — force break.
        let rows = visual_rows_of_str("abcdefghijklmnop", 8);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], (0, 8, 8));
        assert_eq!(rows[1], (8, 16, 16));
    }

    #[test]
    fn visual_rows_empty_string() {
        let rows = visual_rows_of_str("", 10);
        assert_eq!(rows, vec![(0, 0, 0)]);
    }

    #[test]
    fn hanging_indent_bullet() {
        let line = Line::from(vec![Span::raw("• "), Span::raw("foo bar")]);
        assert_eq!(compute_hanging_indent(&line), 2);
    }

    #[test]
    fn hanging_indent_raw_bullet() {
        let line = Line::from(vec![Span::raw("- foo bar")]);
        assert_eq!(compute_hanging_indent(&line), 2);
    }

    #[test]
    fn hanging_indent_ordered_single_digit() {
        let line = Line::from(vec![Span::raw("1. "), Span::raw("foo")]);
        assert_eq!(compute_hanging_indent(&line), 3);
    }

    #[test]
    fn hanging_indent_ordered_padded() {
        // ` 1. foo` — right-aligned single-digit when list reaches 10+.
        let line = Line::from(vec![Span::raw(" 1. "), Span::raw("foo")]);
        assert_eq!(compute_hanging_indent(&line), 4);
    }

    #[test]
    fn hanging_indent_ordered_double_digit() {
        let line = Line::from(vec![Span::raw("10. "), Span::raw("foo")]);
        assert_eq!(compute_hanging_indent(&line), 4);
    }

    #[test]
    fn hanging_indent_rendered_task_includes_bullet_and_checkbox() {
        // Tasks render as `• [ ] foo` — bullet + space + checkbox + space
        // = 6 cells of marker before the body text begins.
        let line = Line::from(vec![Span::raw("• [ ] "), Span::raw("foo")]);
        assert_eq!(compute_hanging_indent(&line), 6);
    }

    #[test]
    fn hanging_indent_task_raw_revealed() {
        // Cursor's raw line in Rendered view: `- [ ] foo`.
        let line = Line::from(vec![Span::raw("- [ ] foo")]);
        assert_eq!(compute_hanging_indent(&line), 6);
    }

    #[test]
    fn hanging_indent_nested_bullet() {
        // Outer bullet → child indent of 2 spaces, then nested bullet.
        let line = Line::from(vec![Span::raw("  • "), Span::raw("inner")]);
        assert_eq!(compute_hanging_indent(&line), 4);
    }

    #[test]
    fn hanging_indent_continuation_paragraph() {
        // List-item continuation paragraph: just leading spaces, no marker.
        let line = Line::from(vec![Span::raw("   "), Span::raw("more text")]);
        assert_eq!(compute_hanging_indent(&line), 3);
    }

    #[test]
    fn hanging_indent_plain_paragraph() {
        let line = Line::from(vec![Span::raw("Hello world")]);
        assert_eq!(compute_hanging_indent(&line), 0);
    }

    #[test]
    fn hanging_indent_blockquote() {
        // Rendered blockquote bar hangs off so wrapped quote text aligns
        // under the gutter (2 cells: glyph + space).
        let line = Line::from(vec![Span::raw("â–Ž "), Span::raw("quoted")]);
        assert_eq!(compute_hanging_indent(&line), 2);
    }

    #[test]
    fn hanging_indent_blockquote_raw_marker() {
        // The raw `> ` marker (cursor's quote line raw-revealed, and the
        // text the navigation side wraps) hangs off the same 2 cells, so
        // wrap budgets agree between the rendered bar and the raw source.
        assert_eq!(compute_hanging_indent_str("> quoted text"), 2);
    }

    #[test]
    fn hanging_indent_nested_blockquote() {
        // Two bar levels stack to a 4-cell hanging indent.
        let line = Line::from(vec![Span::raw("â–Ž â–Ž "), Span::raw("quoted")]);
        assert_eq!(compute_hanging_indent(&line), 4);
    }

    #[test]
    fn hanging_indent_list_inside_blockquote() {
        // A bullet nested in a quote: bar (2) + bullet marker (2) = 4.
        let line = Line::from(vec![Span::raw("▎ • "), Span::raw("item")]);
        assert_eq!(compute_hanging_indent(&line), 4);
    }

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

    #[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, 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())
        );
        // Continuation row 1 also starts with the bar glyph + space, then text.
        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())
        );
        // The wrapped text begins at the indent column (2), not column 0.
        assert_ne!(
            buf.cell((2, 1)).map(|c| c.symbol().to_string()),
            Some(" ".into())
        );
    }

    #[test]
    fn visual_rows_with_indent_word_aligned() {
        // First row holds "• hello " (8 chars), continuation row has width
        // 10 - 2 = 8 for indented body.  "world foo" fits in 9 chars, so
        // the wrap places "world " on row 2 and "foo" on row 3.
        let chars: Vec<(char, Style)> = "• hello world foo"
            .chars()
            .map(|c| (c, Style::default()))
            .collect();
        let rows = visual_rows_of_chars(&chars, 10, 2);
        // Row 0 width 10: breaks at the space after "hello", giving
        // "• hello " (8 chars) before consuming the trailing space.
        assert_eq!(rows[0].0, 0);
        // Row 1 width 8: "world " then break.
        assert!(rows.len() >= 2);
        assert_eq!(rows.last().map(|r| r.1), Some(17));
    }

    #[test]
    fn visual_rows_with_indent_zero_matches_flat() {
        let s = "hello world foo";
        let chars: Vec<(char, Style)> = s.chars().map(|c| (c, Style::default())).collect();
        let with_indent = visual_rows_of_chars(&chars, 10, 0);
        let flat = visual_rows_of_str(s, 10);
        assert_eq!(with_indent, flat);
    }

    #[test]
    fn visual_rows_for_line_counts_indent_extra_rows() {
        // Bullet line wrapped at width 10 — indent = 2, so continuation rows
        // are 8 chars wide.  Total visual rows must be ≥ flat count.
        let line = Line::from(vec![Span::raw("• "), Span::raw("hello world foo bar baz")]);
        let with_marker = visual_rows_for_line(&line, 10);
        let line_flat = Line::from(vec![Span::raw("hello world foo bar baz")]);
        let flat = visual_rows_for_line(&line_flat, 10);
        assert!(with_marker >= flat);
    }

    #[test]
    fn visual_rows_preserves_interior_whitespace_across_wrap() {
        // "a              b" at width 5: the wrap happens after "a    "
        // (5 chars).  The remaining spaces before "b" must NOT be swallowed.
        let rows = visual_rows_of_str("a              b", 5);
        // Row 0: "a    " (indices 0..5)
        assert_eq!(rows[0], (0, 5, 5));
        // Row 1: "     " (indices 5..10)
        assert_eq!(rows[1], (5, 10, 10));
        // Row 2: "     " (indices 10..15)
        assert_eq!(rows[2], (10, 15, 15));
        // Row 3: "b" (index 15..16)
        assert_eq!(rows[3], (15, 16, 16));
    }

    // ── Cell-width awareness ──────────────────────────────────────

    #[test]
    fn wrap_budget_is_cells_not_chars_for_wide_chars() {
        // Each emoji is 1 char / 2 cells.  At width 4, two emoji fill the
        // first row exactly; the third spills onto row 2.
        let chars: Vec<(char, Style)> = "🥇🥇🥇".chars().map(|c| (c, Style::default())).collect();
        let rows = visual_rows_of_chars(&chars, 4, 0);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], (0, 2, 2));
        assert_eq!(rows[1], (2, 3, 3));
    }

    #[test]
    fn wrap_force_breaks_when_single_wide_char_exceeds_width() {
        // Width 1 can't fit a 2-cell emoji, but the wrap loop must still
        // make progress — emit one char per row even though they overflow.
        let chars: Vec<(char, Style)> = "🥇🥇".chars().map(|c| (c, Style::default())).collect();
        let rows = visual_rows_of_chars(&chars, 1, 0);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], (0, 1, 1));
        assert_eq!(rows[1], (1, 2, 2));
    }

    #[test]
    fn render_line_paints_wide_char_using_two_cells() {
        // After painting "A🥇B" the cells must read 'A', '🥇', <skipped>, 'B'.
        // The renderer leaves the right-half cell of the wide char unwritten
        // — terminals own that half.  The next char must land 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, 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 char_idx_at_cell_col_forbidden_indent_zone_snaps_to_row_start() {
        // Continuation row of a wrapped list item: indent = 2.  Clicks on
        // cells 0 and 1 land in the virtual padding; cells 2+ are content.
        // All cells in [0..=indent] must snap to char index 0 — the first
        // content char of the row.
        let chars = ['x', 'y', 'z'];
        for cell in 0..=2 {
            assert_eq!(
                char_idx_at_cell_col(chars.iter().copied(), cell, 2),
                0,
                "indent zone cell {cell} did not snap to row start",
            );
        }
        // Cell 3 is the first content cell — lands on 'x' (index 0 in the
        // row, since acc starts at indent=2 and the first char fills cell 2).
        // Wait: walk acc=2, ch='x', w=1, acc+w=3 NOT > 3, acc=3.  Then
        // ch='y', w=1, acc+w=4 > 3, acc==3==target → return count=1.
        assert_eq!(char_idx_at_cell_col(chars.iter().copied(), 3, 2), 1);
    }

    #[test]
    fn char_idx_at_cell_col_snaps_past_wide_char() {
        // 🥇 occupies cells 0–1.  Targeting cell 1 (mid-glyph) must snap
        // past, returning index 1 (cursor *after* the emoji).  Targeting
        // cell 0 (the glyph's start) returns index 0 (cursor before).
        let chars = ['🥇', 'B'];
        assert_eq!(char_idx_at_cell_col(chars.iter().copied(), 0, 0), 0);
        assert_eq!(char_idx_at_cell_col(chars.iter().copied(), 1, 0), 1);
        assert_eq!(char_idx_at_cell_col(chars.iter().copied(), 2, 0), 1);
    }

    #[test]
    fn cell_col_at_char_idx_round_trips_with_wide_chars() {
        let chars = ['A', '🥇', 'B'];
        // Char 0 → cell 0; char 1 → cell 1 (after A); char 2 → cell 3
        // (past A and the wide emoji); char 3 → cell 4.
        assert_eq!(cell_col_at_char_idx(chars.iter().copied(), 0, 0), 0);
        assert_eq!(cell_col_at_char_idx(chars.iter().copied(), 1, 0), 1);
        assert_eq!(cell_col_at_char_idx(chars.iter().copied(), 2, 0), 3);
        assert_eq!(cell_col_at_char_idx(chars.iter().copied(), 3, 0), 4);
    }

    #[test]
    fn zero_width_combining_mark_does_not_advance_cell_cursor() {
        // 'e' + U+0301 ("é") — the combining mark has zero display width;
        // it must not consume a cell on its own.  After painting, column 1
        // is the next character ('!'), not 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, area, &mut buf, 0, false);
        assert_eq!(
            buf.cell((0, 0)).map(|c| c.symbol().to_string()),
            Some("e".into())
        );
        assert_eq!(
            buf.cell((1, 0)).map(|c| c.symbol().to_string()),
            Some("!".into())
        );
    }
}