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
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
use edamame::config::Theme;
/// Snapshot tests for the Markdown renderer.
///
/// Each test parses a Markdown string, renders it, and checks the result with
/// `insta::assert_debug_snapshot!`.  Run `cargo insta review` after any change
/// that alters rendered output to review and accept updated snapshots.
use edamame::markdown::parser::parse;
use edamame::markdown::renderer::Renderer;
use edamame::markdown::table_layout::str_cells;
use proptest::prelude::*;

/// Render `md` at an arbitrary viewport width (terminal columns).
fn render_at(md: &str, viewport: usize) -> Vec<ratatui::text::Line<'static>> {
    let theme = Theme::default();
    let blocks = parse(md);
    Renderer::new(&theme)
        .with_viewport_width(viewport)
        .render(&blocks)
}

fn render(md: &str) -> Vec<ratatui::text::Line<'static>> {
    render_at(md, 80)
}

/// Collect all text content from a rendered line (spans concatenated).
fn line_text(line: &ratatui::text::Line<'_>) -> String {
    line.spans.iter().map(|s| s.content.as_ref()).collect()
}

// ── Headings ─────────────────────────────────────────────────────────────────

#[test]
fn h1_contains_text() {
    let lines = render("# Heading One\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Heading One"), "got: {text:?}");
}

#[test]
fn h1_has_rule_line() {
    let lines = render("# H1\n");
    // Second non-empty line after the heading should be the ─── rule
    let rule_line = lines.iter().find(|l| line_text(l).contains('─'));
    assert!(rule_line.is_some(), "H1 should produce a ─── rule line");
}

#[test]
fn h2_contains_text() {
    let lines = render("## Heading Two\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Heading Two"));
}

#[test]
fn h3_contains_text() {
    let lines = render("### Three\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Three"));
}

#[test]
fn h4_contains_text() {
    let lines = render("#### Four\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Four"));
}

#[test]
fn h5_contains_text() {
    let lines = render("##### Five\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Five"));
}

#[test]
fn h6_contains_text() {
    let lines = render("###### Six\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("Six"));
}

// ── Inline formatting ─────────────────────────────────────────────────────────

#[test]
fn bold_text_present() {
    let lines = render("**bold text**\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("bold text"), "got: {text:?}");
}

#[test]
fn italic_text_present() {
    let lines = render("*italic text*\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("italic text"), "got: {text:?}");
}

#[test]
fn inline_code_present() {
    let lines = render("`code_here`\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("code_here"), "got: {text:?}");
}

// ── Block elements ────────────────────────────────────────────────────────────

#[test]
fn fenced_code_block_content() {
    let lines = render("```rust\nfn main() {}\n```\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("fn main()"), "got: {text:?}");
}

#[test]
fn fenced_code_block_has_background() {
    let lines = render("```\nhello\n```\n");
    // Code block renders three rows: opening-fence placeholder, body, and
    // closing-fence placeholder.  All three carry the code-block background.
    let body_text = line_text(&lines[1]);
    assert!(
        body_text.contains("hello"),
        "Expected code content, got: {body_text:?}"
    );
    // There should be no box border characters anywhere in the block.
    let all_text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(
        !all_text.contains('╭'),
        "Unexpected box border: {all_text:?}"
    );
}

#[test]
fn fenced_code_block_language_tag() {
    let lines = render("```python\npass\n```\n");
    // Language tag is shown on its own line above the code content.
    let first_text = line_text(&lines[0]);
    assert!(
        first_text.contains("python"),
        "Expected language label, got: {first_text:?}"
    );
}

#[test]
fn blockquote_has_bar() {
    let lines = render("> A blockquote\n");
    let first_text = line_text(&lines[0]);
    assert!(
        first_text.contains('▎'),
        "Expected ▎ bar, got: {first_text:?}"
    );
}

#[test]
fn blockquote_contains_text() {
    let lines = render("> A blockquote\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("A blockquote"), "got: {text:?}");
}

/// Issue #33: a quote used to overwrite every inner span's style with
/// `blockquote_text`, so bold, italic and every other inline style inside
/// one rendered as plain quoted prose.  Each inline keeps its own styling
/// and inherits the quote's wash underneath it.
#[test]
fn blockquote_preserves_inline_styles() {
    let theme = Theme::default();
    let md = "> plain **bold** *italic* `code` ==mark== ~~struck~~ [link](https://example.com)\n";
    let lines = render(md);
    let spans = &lines[0].spans;

    let span_for = |needle: &str| {
        spans
            .iter()
            .find(|s| s.content.contains(needle))
            .unwrap_or_else(|| panic!("no span for {needle:?} in {spans:?}"))
    };

    assert_eq!(
        span_for("bold").style.add_modifier,
        theme.bold.add_modifier,
        "bold lost its modifier inside a quote"
    );
    assert_eq!(
        span_for("italic").style.add_modifier,
        theme.italic.add_modifier,
        "italic lost its modifier inside a quote"
    );
    assert_eq!(
        span_for("code").style.fg,
        theme.code_span.fg,
        "a code span lost its color inside a quote"
    );
    assert_eq!(
        span_for("code").style.bg,
        theme.code_span.bg,
        "a code span lost its own surface inside a quote"
    );
    assert_eq!(
        span_for("mark").style.bg,
        theme.highlight.bg,
        "a highlight lost its background inside a quote"
    );
    assert_eq!(
        span_for("struck").style.add_modifier,
        theme.strikethrough.add_modifier,
        "strikethrough lost its modifier inside a quote"
    );
    assert_eq!(
        span_for("link").style.fg,
        theme.link_text.fg,
        "a link lost its color inside a quote"
    );

    // The quote's own wash still reaches the plain prose and the bar, and is
    // the line-level style `line_render` fills trailing cells with.
    assert_eq!(lines[0].style.bg, theme.blockquote_text.bg);
    assert_eq!(span_for("plain").style.bg, theme.blockquote_text.bg);
    assert_eq!(span_for("▎").style.fg, theme.blockquote_bar.fg);
}

/// A quote marks its region with a background wash, not a blanket italic —
/// the italic is what left `*emphasis*` inside a quote with nothing to say.
#[test]
fn blockquote_text_is_not_italic_by_default() {
    let theme = Theme::default();
    assert!(
        !theme
            .blockquote_text
            .add_modifier
            .contains(ratatui::style::Modifier::ITALIC),
        "blockquote text should carry no blanket italic"
    );
    assert!(
        theme.blockquote_text.bg.is_some(),
        "blockquote text should carry a background wash"
    );
}

/// A nested code block keeps its own surface rather than the quote's wash.
#[test]
fn code_block_inside_a_blockquote_keeps_the_code_surface() {
    let theme = Theme::default();
    let lines = render("> ```\n> fn main() {}\n> ```\n");
    let body = lines
        .iter()
        .find(|l| line_text(l).contains("fn main"))
        .expect("code body row");
    assert_eq!(body.style.bg, theme.code_block_text.bg);
}

#[test]
fn bullet_list_marker() {
    let lines = render("- item one\n- item two\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains('•'), "Expected bullet •, got: {text:?}");
    assert!(text.contains("item one"));
    assert!(text.contains("item two"));
}

#[test]
fn ordered_list_numbers() {
    let lines = render("1. first\n2. second\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains("1."), "got: {text:?}");
    assert!(text.contains("2."), "got: {text:?}");
}

/// With reflow off, an item's first paragraph renders one row per source line, like its later
/// ones and like a top-level paragraph.  Its breaks — soft or hard — once collapsed to spaces,
/// which dropped the hard break.
#[test]
fn a_list_items_first_paragraph_renders_one_row_per_source_line() {
    let lines = render("- a\n  soft\n- b\\\n  hard\n1. c\nlazy\n");
    let text: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        text,
        ["• a", "  soft", "• b", "  hard", "1. c", "   lazy"],
        "{text:?}"
    );
}

/// A break inside emphasis or a link cuts it in two, so each source line keeps its
/// row: with reflow off a soft one does, and a hard one always does, since a hard break keeps a
/// paragraph from reflowing at any depth.  Both once rendered as a space on one row.
#[test]
fn a_break_inside_an_inline_splits_the_row() {
    let rows = |md: &str, reflow: bool| -> Vec<String> {
        let theme = Theme::default();
        Renderer::new(&theme)
            .with_viewport_width(80)
            .with_reflow_paragraphs(reflow)
            .render(&parse(md))
            .iter()
            .map(line_text)
            .collect()
    };
    assert_eq!(rows("a *b\nc* d\n", false), ["a b", "c d"]);
    assert_eq!(rows("a *b\nc* d\n", true), ["a b c d"]);
    assert_eq!(rows("[x\ny](u) ~~p\nq~~\n", false), ["x", "y p", "q"]);
    for reflow in [false, true] {
        assert_eq!(rows("*a\\\nb*\n", reflow), ["a", "b"], "reflow {reflow}");
        assert_eq!(
            rows("- **a\\\n  b** c\n", reflow),
            ["• a", "  b c"],
            "reflow {reflow}"
        );
    }
}

/// Each half of a split emphasis keeps its style, and a split link styles both halves as the
/// link, so the hit-test pairs each with it.
#[test]
fn a_split_inline_keeps_its_style_on_both_rows() {
    let theme = Theme::default();
    let lines = Renderer::new(&theme)
        .with_viewport_width(80)
        .render(&parse("*a\nb* [c\nd](u)\n"));
    let styled = |row: usize, text: &str| {
        lines[row]
            .spans
            .iter()
            .find(|s| s.content == text)
            .map(|s| s.style)
            .unwrap_or_else(|| panic!("no {text:?} on row {row}: {:?}", lines[row]))
    };
    assert_eq!(styled(0, "a"), styled(1, "b"));
    assert_eq!(styled(1, "c"), styled(2, "d"));
}

/// A blockquote renders one row per source line: a quoted blank row for each bare `>`, and none
/// the source doesn't hold.  It once put a blank between every two children and dropped an
/// empty quote, so every row below sat off from its source line.  A link reference definition
/// renders nothing, inside a quote as at top level.
#[test]
fn a_blockquote_renders_one_row_per_source_line() {
    for (src, rows) in [
        ("> q\n> ```\n> x\n> ```\n", &["▎ q", "▎", "▎  x", "▎"][..]),
        ("> a\n>\n>\n> b\n", &["▎ a", "▎", "▎", "▎ b"]),
        (">\n", &["▎"]),
        (">\n> a\n>\n", &["▎", "▎ a", "▎"]),
        ("> [d]: /url\n> b\n", &["▎ b"]),
        ("> b\n>\n> [d]: /url\n", &["▎ b", "▎"]),
        (
            "> - a\n>\n> - b\n>\n> tail\n",
            &["▎ • a", "▎", "▎ • b", "▎", "▎ tail"],
        ),
    ] {
        let text: Vec<String> = render(src)
            .iter()
            .map(|l| line_text(l).trim_end().to_owned())
            .collect();
        assert_eq!(text, rows, "{src:?}");
    }
}

#[test]
fn horizontal_rule() {
    let lines = render("---\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(text.contains('─'), "Expected ─ rule, got: {text:?}");
}

// ── Snapshot tests ────────────────────────────────────────────────────────────

#[test]
fn snapshot_all_headings() {
    let md = "# H1\n## H2\n### H3\n#### H4\n##### H5\n###### H6\n";
    let lines = render(md);
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

#[test]
fn snapshot_inline_formatting() {
    let md = "Normal **bold** *italic* `code` ~~strike~~\n";
    let lines = render(md);
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

#[test]
fn snapshot_code_block() {
    let md = "```rust\nfn hello() {\n    println!(\"hi\");\n}\n```\n";
    let lines = render(md);
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

#[test]
fn snapshot_blockquote() {
    let md = "> This is a blockquote.\n> Second line.\n";
    let lines = render(md);
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

#[test]
fn snapshot_bullet_list() {
    let md = "- Alpha\n- Beta\n- Gamma\n";
    let lines = render(md);
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

#[test]
fn empty_task_item_renders_checkbox() {
    // An empty task item (`- [ ] ` with nothing after) must still render with
    // its checkbox visible — otherwise users can create a "phantom" item by
    // pressing Enter on a task row and find the new item invisible.
    let lines = render("- [ ] ");
    let output: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        output.len(),
        1,
        "expected one rendered line, got: {output:?}"
    );
    assert!(
        output[0].contains("[ ]"),
        "empty task item should render with '[ ]', got: {output:?}"
    );
}

#[test]
fn task_item_with_non_paragraph_first_block_renders_checkbox() {
    // A task item whose first block is not a paragraph (here a nested code
    // block) must still render its checkbox on the marker line.
    let lines = render("- [ ] \n  ```\n  x\n  ```\n");
    let output: Vec<String> = lines.iter().map(line_text).collect();
    assert!(
        output[0].contains("[ ]"),
        "task item with non-paragraph first block should render '[ ]', got: {output:?}"
    );
}

#[test]
fn empty_task_item_in_middle_of_list_renders_checkbox() {
    let lines = render("- [ ] alpha\n- [ ] \n- [ ] beta\n");
    let output: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        output.len(),
        3,
        "expected three rendered lines, got: {output:?}"
    );
    for line in &output {
        assert!(
            line.contains("[ ]"),
            "every task item should render with '[ ]', got: {output:?}"
        );
    }
}

#[test]
fn single_blank_between_list_items_is_rendered_as_a_blank_line() {
    // After 2 Enters in the editor the buffer holds an empty list item
    // separated from the previous content by a single blank line.  The
    // blank line must appear as a visible blank row in the rendered
    // output — without it the user can't see why pressing Enter twice
    // had any effect.
    use edamame::document::ParsedDoc;
    let theme = Box::leak(Box::new(Theme::default())) as &'static Theme;
    let pd = ParsedDoc::build("- a\n- b\n\n- \n- c\n", theme, true, 24);
    let texts: Vec<String> = (0..pd.line_count())
        .map(|i| {
            pd.lines[i]
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect()
        })
        .collect();
    assert!(
        texts.iter().any(|t| t.is_empty()),
        "expected a blank rendered line for the single source blank, got: {texts:?}"
    );
}

#[test]
fn loose_list_blank_rows_keep_reveal_1to1_with_source_lines() {
    // The raw reveal in `RenderedView` maps a block's rendered lines onto its
    // source lines by splitting the block text on `\n`.  A loose list now
    // keeps its inter-item blanks as its own rendered lines (instead of
    // fragmenting into virtual blank blocks), so the blank-emission must add
    // exactly one rendered line per blank source line — otherwise the reveal
    // desyncs.  Single-line items isolate that guarantee from the pre-existing
    // soft-break behavior (a wrapped continuation line renders joined, which
    // affects tight and loose lists alike and is out of scope here).
    use edamame::document::ParsedDoc;
    let theme = Box::leak(Box::new(Theme::default())) as &'static Theme;
    let src = "1. a\n2. b\n\n3. c\n\n4. d\n";
    let pd = ParsedDoc::build(src, theme, true, 40);
    let range = pd
        .source_map
        .original_range_for_byte(0)
        .expect("list block range");
    let block_src = &src[range.clone()];
    // Trailing newline(s) end the block's last line; the reveal backs past
    // them (`content_end_of_block`) and never indexes a trailing empty, so
    // compare against the block's *content* lines.
    let source_lines = block_src.trim_end_matches('\n').split('\n').count();
    let rendered = pd.source_map.rendered_lines_for_byte(0);
    assert_eq!(
        rendered.end - rendered.start,
        source_lines,
        "loose list must own one rendered line per source line (src {block_src:?})"
    );
}

#[test]
fn ordered_list_with_blank_gap_stays_one_loose_list_and_keeps_the_blank() {
    // A blank line in an ordered list makes it "loose" but keeps it a
    // single list: numbering comes from pulldown-cmark (auto-incremented),
    // so a source that restarts at `1.` after the blank still renders
    // sequentially (`3. c`) — matching CommonMark rather than the old
    // split-into-two-lists behavior.  The blank row is still preserved
    // between the items for legibility.
    use edamame::document::ParsedDoc;
    let theme = Box::leak(Box::new(Theme::default())) as &'static Theme;
    let pd = ParsedDoc::build("1. a\n2. b\n\n1. c\n", theme, true, 24);
    let texts: Vec<String> = (0..pd.line_count())
        .map(|i| {
            pd.lines[i]
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect()
        })
        .collect();
    assert!(
        texts.iter().any(|t| t.starts_with("3. c")),
        "expected the loose list to number sequentially (3. c), got: {texts:?}"
    );
    assert!(
        !texts.iter().any(|t| t.starts_with("1. c")),
        "tail should not restart at 1 in a single loose list, got: {texts:?}"
    );
    // The blank between item 2 and item 3 must still render as its own row.
    let b_idx = texts.iter().position(|t| t.starts_with("2. b")).unwrap();
    let c_idx = texts.iter().position(|t| t.starts_with("3. c")).unwrap();
    assert!(
        texts[b_idx + 1..c_idx].iter().any(|t| t.is_empty()),
        "expected a blank row between the two items, got: {texts:?}"
    );
}

#[test]
fn list_item_with_code_block_containing_blank_line_renders_without_gap() {
    // Regression: a blank line inside a fenced code block embedded in a
    // list item used to trigger `split_lists_on_blank_lines`, fragmenting
    // the surrounding list and leaving a visible gap before the next bullet.
    // The fix is verified at two layers — at the AST layer the list stays
    // intact (asserted in the parser's unit tests), and at the rendered
    // layer the second bullet sits directly after the first item's last
    // continuation paragraph with no synthesized separator row in between.
    let md = "- intro\n  ```toml\n  [a]\n\n  [b]\n  ```\n  trailing\n- next item\n";
    let lines = render(md);
    let texts: Vec<String> = lines.iter().map(line_text).collect();
    let trailing_idx = texts
        .iter()
        .position(|s| s.contains("trailing"))
        .expect("trailing continuation line missing");
    let next_idx = texts
        .iter()
        .position(|s| s.contains("next item"))
        .expect("next item line missing");
    assert_eq!(
        next_idx,
        trailing_idx + 1,
        "next bullet should sit on the line immediately after the trailing continuation, got: {texts:?}"
    );
}

#[test]
fn snapshot_horizontal_rule() {
    let lines = render("---\n");
    let output: Vec<String> = lines.iter().map(line_text).collect();
    insta::assert_debug_snapshot!(output);
}

// ── Footnotes ────────────────────────────────────────────────────────────────

#[test]
fn footnote_reference_renders_as_bracketed_marker() {
    let lines = render("Claim.[^1]\n\n[^1]: Source.\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    // The reference collapses `[^1]` to the bracketed marker `[1]`; the raw
    // `[^1]` syntax is gone.
    assert!(text.contains("[1]"), "expected [1] marker, got: {text:?}");
    assert!(
        !text.contains("[^1]"),
        "raw reference syntax leaked: {text:?}"
    );
}

#[test]
fn adjacent_footnote_references_fuse_into_one_marker() {
    // `[^1][^2]` renders as a single comma-joined marker `[1,2]` rather
    // than two abutting brackets.
    let lines = render("Two.[^1][^2]\n\n[^1]: one.\n\n[^2]: two.\n");
    let para = line_text(&lines[0]);
    assert!(para.contains("[1,2]"), "expected [1,2], got: {para:?}");
    assert!(
        !para.contains("[1][2]"),
        "adjacent references should fuse: {para:?}"
    );
}

#[test]
fn three_adjacent_footnote_references_fuse_into_one_marker() {
    let lines = render("T.[^1][^2][^3]\n\n[^1]: a.\n\n[^2]: b.\n\n[^3]: c.\n");
    let para = line_text(&lines[0]);
    assert!(para.contains("[1,2,3]"), "expected [1,2,3], got: {para:?}");
}

#[test]
fn spaced_footnote_references_stay_separate_markers() {
    // Only *adjacent* references fuse — a space between them is its own
    // inline, so each keeps its own brackets.
    let lines = render("Two.[^1] [^2]\n\n[^1]: one.\n\n[^2]: two.\n");
    let para = line_text(&lines[0]);
    assert!(para.contains("[1] [2]"), "expected [1] [2], got: {para:?}");
}

#[test]
fn footnote_marker_is_plain_ascii() {
    // The marker used to be built from U+207D/U+207E superscript
    // parentheses, which most monospace fonts lack; a terminal falling back
    // to a proportional face drew the parenthesis over the digit.  Nothing
    // in the marker may leave Basic Latin.
    let lines = render("Claim.[^1][^note]\n\n[^1]: a.\n\n[^note]: b.\n");
    let para = line_text(&lines[0]);
    assert!(para.is_ascii(), "footnote marker left ASCII: {para:?}");
}

#[test]
fn footnote_definition_renders_with_back_link_and_number() {
    let lines = render("Claim.[^1]\n\n[^1]: The source text.\n");
    let def_line = lines
        .iter()
        .map(line_text)
        .find(|t| t.contains("The source text."))
        .expect("definition line missing");
    // The `  <label>.  ` leader (two leading spaces, raw label, period, two
    // trailing spaces — the rendered marker never diverges from the source
    // label) and the trailing `↩` back-link glyph at the very end.
    assert!(
        def_line.starts_with("  1.  "),
        "expected `  <label>.  ` leader: {def_line:?}"
    );
    assert!(
        def_line.trim_end().ends_with('↩'),
        "expected trailing back-link glyph: {def_line:?}"
    );
    // The glyph follows the body text, not the leader.
    let body_pos = def_line.find("The source text.").expect("body");
    let glyph_pos = def_line.find('↩').expect("glyph");
    assert!(
        glyph_pos > body_pos,
        "glyph should be after the body: {def_line:?}"
    );
}

#[test]
fn footnote_marker_matches_raw_label_without_renumbering() {
    // `[^3]` referenced before `[^1]` must keep their raw labels in the
    // rendered markers — no display resequencing.
    let lines = render("A[^3] B[^1]\n\n[^1]: one.\n\n[^3]: three.\n");
    let para = line_text(&lines[0]);
    let pos3 = para.find("[3]").expect("[3] marker");
    let pos1 = para.find("[1]").expect("[1] marker");
    assert!(
        pos3 < pos1,
        "markers follow source order, not a remap: {para:?}"
    );
}

#[test]
fn footnotes_render_in_place_not_only_at_end() {
    // A definition written mid-document renders where it appears, before
    // the following paragraph.
    let lines = render("A.[^1]\n\n[^1]: Mid.\n\nLater paragraph.\n");
    let texts: Vec<String> = lines.iter().map(line_text).collect();
    let def_idx = texts.iter().position(|t| t.contains("Mid.")).expect("def");
    let later_idx = texts
        .iter()
        .position(|t| t.contains("Later paragraph."))
        .expect("later");
    assert!(
        def_idx < later_idx,
        "definition should render before the later paragraph: {texts:?}"
    );
}

// ── Code-block column geometry ───────────────────────────────────────────────

/// Anti-drift pin between the renderer's literal pad (`format!(" {:<width$}",
/// …)`) and the `rendered_col` its row origin records, which the cursor
/// indicator, the selection overlay and the mouse hit-test all map columns
/// through (`document::row_map`).  If the renderer's prefix ever changes
/// without its origin, this fails rather than silently putting the cursor
/// beside its character again (issue #28).
///
/// **Both** of `code_body_row`'s branches are exercised, because they build
/// the row two different ways: an unhighlighted line is one `format!`-padded
/// span, a highlighted one is a hand-assembled span list that re-derives the
/// pad from `renderer::CODE_PAD_COLS` and re-slices the text per token.
/// The comments on `code_body_row` name this test as the thing that fails if
/// the two drift, so it has to actually reach the tokenized path — with
/// highlighting off, the multi-span branch is never entered at all.  The
/// multibyte case is the one that matters most there: token ranges arrive
/// from syntect as byte offsets, so a conversion slip inside `highlight`
/// shifts every column after the first non-ASCII character.
#[test]
fn code_block_render_agrees_with_its_row_origins() {
    use edamame::document::row_map::{raw_to_rendered_col, RawPos};
    use edamame::document::ParsedDoc;

    let theme = Box::leak(Box::new(Theme::default()));
    for (md, raw_line, fenced) in [
        ("```rust\nlet x = 1;\n```\n", "let x = 1;", true),
        ("Intro.\n\n    let x = 1;\n", "    let x = 1;", false),
        // Tokenized: a keyword, a function name and a string literal, so the
        // row really is split into several spans rather than one.
        (
            "```rust\nfn f() { g(\"s\"); }\n```\n",
            "fn f() { g(\"s\"); }",
            true,
        ),
        // Tokenized and multibyte, inside and outside a token.
        (
            "```rust\nlet s = \"héllo\"; // 日本語\n```\n",
            "let s = \"héllo\"; // 日本語",
            true,
        ),
    ] {
        warm_fence_languages(md);
        // Run every case with highlighting off and on, so the plain cases pin
        // the untokenized branch and the tokenized ones pin both.
        for highlighting in [false, true] {
            let doc = ParsedDoc::build_with_overrides(
                md,
                theme,
                true,
                24,
                None,
                None,
                false,
                80,
                false,
                highlighting,
                true,
                false,
                None,
            );
            let needle = raw_line.trim_start();
            let idx = doc
                .lines
                .iter()
                .position(|l| line_text(l).contains(needle))
                .unwrap_or_else(|| panic!("code body row must render ({highlighting})"));
            let rendered_chars: Vec<char> = line_text(&doc.lines[idx]).chars().collect();
            let byte = doc.source_map.original_byte_for_rendered_line(idx).unwrap();
            let block = doc.source_map.block_for_byte(byte).unwrap();
            let row = idx - doc.source_map.rendered_lines_for_block(block).start;
            // An indented block's range starts past the indent it strips, and the
            // block's first line counts from there.
            let (line, lead) = if fenced { (1, 0) } else { (0, 4) };

            for (raw_col, expected) in raw_line.chars().enumerate() {
                // Columns inside an indented block's stripped indent have no
                // rendered cell of their own; they collapse onto the first.
                if raw_col < lead {
                    continue;
                }
                let pos = RawPos {
                    line,
                    col: raw_col - lead,
                };
                let col = raw_to_rendered_col(&doc, block, row, pos).unwrap();
                assert_eq!(
                    rendered_chars.get(col).copied(),
                    Some(expected),
                    "highlighting {highlighting}: raw col {raw_col} of {raw_line:?} should \
                     render at col {col}, rendered row is {rendered_chars:?}",
                );
            }
        }
    }
}

/// The tokenized branch must also leave the *shape* of the block alone: same
/// number of rows, same text on each. Column identity (above) is what the
/// click and cursor paths need; row count is what the raw reveal and the
/// scroll arithmetic need, and neither is visible in a span-level assertion.
#[test]
fn highlighting_changes_no_text_and_no_row_count() {
    for md in [
        "```rust\nfn main() {\n    let s = \"héllo 日本語\";\n}\n```\n",
        // A block comment: cross-line parser state, so every row is tokenized.
        "```rust\n/* block\n   comment */\nlet x = 1;\n```\n",
        // Blank body lines, which take the NBSP path rather than `code_body_row`.
        "```python\n\n\nx = 1\n\n```\n",
        // A tab-indented line, where the raw and rendered widths differ.
        "```rust\n\tlet tabbed = 1;\n```\n",
    ] {
        let plain = render(md);
        let lit = render_highlighted(md);
        assert_eq!(plain.len(), lit.len(), "row count differs for {md:?}");
        for (i, (a, b)) in plain.iter().zip(&lit).enumerate() {
            assert_eq!(
                line_text(a),
                line_text(b),
                "row {i} text differs for {md:?}"
            );
        }
    }
}

// ── Frontmatter ──────────────────────────────────────────────────────────────

/// Frontmatter renders verbatim: one rendered row per source line, each
/// character in its source column.  Both halves matter — the row count is
/// what the raw reveal maps against, and the column identity is what the
/// click / selection / cursor paths assume for a metadata block.
#[test]
fn yaml_frontmatter_renders_one_verbatim_row_per_source_line() {
    let md = "---\ntitle: Foo\n\ntags:\n  - a\n---\n\n# Heading\n";
    let lines = render(md);
    let rendered: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        &rendered[..6],
        &["---", "title: Foo", "", "tags:", "  - a", "---"],
        "got: {rendered:?}",
    );
}

#[test]
fn toml_frontmatter_keeps_its_pluses_delimiters() {
    let lines = render("+++\ntitle = \"Foo\"\n+++\n\n# H\n");
    let rendered: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        &rendered[..3],
        &["+++", "title = \"Foo\"", "+++"],
        "got: {rendered:?}",
    );
}

/// The regression the extension was enabled for: frontmatter used to parse
/// as a thematic break plus a setext H2, making the file's YAML keys the
/// loudest element on the page (issue #34).
#[test]
fn frontmatter_is_not_rendered_as_a_rule_plus_heading() {
    let lines = render("---\ntitle: Foo\ndate: 2026-01-01\n---\n\nBody.\n");
    let theme = Theme::default();
    for line in &lines {
        let text = line_text(line);
        assert!(
            !text.contains("────"),
            "frontmatter must not render a rule: {text:?}",
        );
        assert!(
            line.spans.iter().all(|s| s.style != theme.h2),
            "frontmatter must not render as a heading: {text:?}",
        );
    }
}

/// A `---` that isn't frontmatter stays a thematic break: the extension
/// only claims a three-character delimiter run with a non-blank first line
/// and a closing delimiter.
#[test]
fn a_lone_dash_rule_is_still_a_horizontal_rule() {
    for md in [
        "Intro.\n\n---\n\nBody.\n",
        // Unclosed: rule + paragraph, exactly as before the extension.
        "---\ntitle: Foo\n\n# H\n",
        // A separator immediately above a heading, closed by the next
        // one.  The extensions are not anchored to the start of the
        // document on their own, so without the first-line gate this
        // pair swallows the whole section between them.
        "Intro.\n\n---\n## Section 2\n\nText.\n\n---\n## Section 3\n",
    ] {
        let lines = render(md);
        assert!(
            lines.iter().any(|l| line_text(l).contains("────")),
            "{md:?} should still render a rule, got: {:?}",
            lines.iter().map(line_text).collect::<Vec<_>>(),
        );
    }
}

/// Only the file's own opening delimiter enables an extension, so a
/// `+++` file's later `---` pair stays a rule and a heading rather than
/// becoming a second, YAML-flavored metadata block.
#[test]
fn frontmatter_does_not_claim_a_later_pair_of_the_other_flavor() {
    let lines = render("+++\na = 1\n+++\n\n---\nSection\n---\n\nEnd.\n");
    let rendered: Vec<String> = lines.iter().map(line_text).collect();
    assert_eq!(
        &rendered[..3],
        &["+++", "a = 1", "+++"],
        "got: {rendered:?}"
    );
    assert!(
        rendered.iter().any(|l| l.contains("────")),
        "the later `---` should still render a rule, got: {rendered:?}",
    );
}

/// The key half of a frontmatter line is styled apart from its value, and
/// the two spans still concatenate back to the source line byte for byte.
#[test]
fn frontmatter_key_and_value_are_styled_apart() {
    let theme = Theme::default();
    let lines = render("---\ntitle: Foo\n---\n\n# H\n");
    let row = &lines[1];
    assert_eq!(line_text(row), "title: Foo");
    assert_eq!(row.spans.len(), 2, "got: {:?}", row.spans);
    assert_eq!(row.spans[0].content.as_ref(), "title:");
    assert_eq!(row.spans[0].style, theme.frontmatter_key);
    assert_eq!(row.spans[1].content.as_ref(), " Foo");
    assert_eq!(row.spans[1].style, theme.frontmatter_value);
}

/// A line the key/value split can't read — a sequence entry, a comment, a
/// bare scalar — renders whole rather than splitting at a colon that isn't
/// a separator.
#[test]
fn frontmatter_lines_without_a_key_render_whole() {
    let lines = render("---\ntags:\n  - https://example.com\n---\n\n# H\n");
    let entry = &lines[2];
    assert_eq!(line_text(entry), "  - https://example.com");
    assert_eq!(entry.spans.len(), 1, "got: {:?}", entry.spans);
}

// ── Syntax highlighting ──────────────────────────────────────────────────────

/// Opt this thread into inline grammar compilation for every language
/// the source's fences name.
///
/// Compilation is asynchronous in production — a cold grammar renders
/// plain and a worker compiles it — so without this a render test
/// asserts on whichever grammars an *unrelated* test happened to warm
/// first, and passes or fails by test order. See
/// `markdown::highlight::warm_inline`.
fn warm_fence_languages(src: &str) {
    for line in src.lines() {
        let Some(info) = line.trim_start().strip_prefix("```") else {
            continue;
        };
        if !info.trim().is_empty() {
            edamame::markdown::highlight::warm_inline(Some(info.trim()));
        }
    }
}

/// Render with syntax highlighting on. The plain `render` helper above leaves
/// it off, matching `Renderer::new`'s default.
fn render_highlighted(md: &str) -> Vec<ratatui::text::Line<'static>> {
    warm_fence_languages(md);
    let theme = Box::leak(Box::new(Theme::default()));
    let blocks = parse(md);
    Renderer::new(theme)
        .with_syntax_highlighting(true)
        .render(&blocks)
}

/// End-to-end over the four fence shapes that decide whether a block is
/// highlighted at all: a known language, a known language carrying tool
/// metadata, an unknown one, and a bare fence.
#[test]
fn fenced_blocks_highlight_by_language_only() {
    let theme = Theme::default();
    let md = "\
```rust
fn main() {}
```

```rust,ignore
fn other() {}
```

```frobnicate
fn main() {}
```

```
fn main() {}
```
";
    let lines = render_highlighted(md);
    let keyword_rows = lines
        .iter()
        .filter(|l| {
            l.spans
                .iter()
                .any(|s| s.content.as_ref() == "fn" && s.style.fg == theme.syntax_keyword.fg)
        })
        .count();
    // The two rust fences highlight; the unknown and bare ones do not.
    assert_eq!(
        keyword_rows, 2,
        "only the rust fences should be highlighted"
    );

    // Every block still shows its text, highlighted or not.
    let all: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert_eq!(all.matches("fn main() {}").count(), 3);
    assert!(all.contains("fn other() {}"));
}

/// With highlighting off, the rendered output must be identical to what the
/// renderer produced before the feature existed — the regression guard that
/// keeps "feature off" a genuinely untouched path.
#[test]
fn highlighting_off_is_indistinguishable_from_before_the_feature() {
    let md = "```rust\nfn main() {}\nlet x = 1;\n```\n";
    let plain = render(md);
    assert!(plain.iter().all(|l| l
        .spans
        .iter()
        .all(|s| s.style.fg == plain[1].spans[0].style.fg)));
    // One span per row: the single-span line the renderer always emitted.
    assert!(plain[1].spans.len() == 1, "got {:?}", plain[1].spans);
}

// ── Math (phase 1: source-equivalent rendering) ─────────────────────────────

/// Inline `$...$` mixed into a paragraph renders as its delimited source —
/// width-identical to the raw text, so wrap and cursor columns stay aligned.
/// (Beautification is phase 2; the parser-level guarantee that `$5` prices
/// are not swallowed is covered in the lib parser tests.)
#[test]
fn inline_math_renders_source_equivalently() {
    let lines = render("Solve $x^2$ for x.\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(
        text.contains("$x^2$"),
        "inline math must render its delimited source, got: {text:?}"
    );
}

/// A `$$...$$`-only paragraph that is not promoted to an image block
/// (figures disabled, and the bare `parse` path used by help preview /
/// link scans) renders as a fenced-style ` math ` code block: a ` math `
/// language header, the formula body, and a blank closing row.  The `$$`
/// delimiters are hidden in this rendered form — they reveal only when the
/// cursor lands on the opening / closing rows (covered in `tests/ui.rs`).
#[test]
fn display_math_paragraph_renders_as_a_math_code_block_without_promotion() {
    let lines = render("$$\nx^2\n$$\n");
    let text: String = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
    assert!(
        text.contains("math") && text.contains("x^2"),
        "unpromoted display math must render as a ` math ` code block, got: {text:?}"
    );
    assert!(
        !text.contains("$$"),
        "the styled block hides the `$$` delimiters (they reveal on cursor), got: {text:?}"
    );
}

/// A `$$` block opening a list item renders the way it does in a quote, or later in the item:
/// the marker on a row of its own, then the ` math ` code block, one row per formula line
/// (#72).  It used to take the item's first-paragraph path, which joined the formula's lines
/// on one row behind the marker, `$$` delimiters and all.
#[test]
fn display_math_opening_a_list_item_renders_as_a_math_code_block() {
    let lines = render_at("- $$\n  x^2\n  y^2\n  $$\n", 40);
    let text: Vec<String> = lines.iter().map(line_text).collect();
    let trimmed: Vec<&str> = text.iter().map(|l| l.trim_end()).collect();
    assert_eq!(
        trimmed[0], "•",
        "the marker sits on a row of its own: {text:?}"
    );
    assert_eq!(
        trimmed[1].trim(),
        "math",
        "then the ` math ` label: {text:?}"
    );
    assert_eq!(trimmed[2].trim(), "x^2", "{text:?}");
    assert_eq!(trimmed[3].trim(), "y^2", "{text:?}");
    assert!(
        !text.iter().any(|l| l.contains("$$")),
        "the `$$` delimiters reveal only on cursor: {text:?}"
    );
}

/// A CRLF file's `$$` block renders as the same ` math ` block an LF file's does: pulldown-cmark
/// keeps the `\r\n` in the formula, which used to fail the delimiters-on-own-lines check and
/// left the formula joined on one paragraph row.
#[test]
fn display_math_in_a_crlf_file_renders_as_a_math_code_block() {
    for md in ["$$\r\nx^2\r\ny^2\r\n$$\r\n", "- $$\r\n  x^2\r\n  $$\r\n"] {
        let lf: Vec<String> = render(&md.replace("\r\n", "\n"))
            .iter()
            .map(line_text)
            .collect();
        let crlf: Vec<String> = render(md).iter().map(line_text).collect();
        assert_eq!(crlf, lf, "{md:?}");
        assert!(crlf.iter().any(|l| l.trim() == "math"), "{crlf:?}");
    }
}

// ── Table column widths are display columns ──────────────────────────────────

/// Terminal cells a rendered line occupies as `line_render` paints it — two per CJK glyph.
fn line_cells(line: &ratatui::text::Line<'_>) -> usize {
    str_cells(&line_text(line))
}

fn table_widths(lines: &[ratatui::text::Line<'static>]) -> Vec<usize> {
    lines
        .iter()
        .filter(|l| {
            matches!(
                line_text(l).chars().next(),
                Some('┌' | '│' | '├' | '┝' | '└')
            )
        })
        .map(line_cells)
        .collect()
}

/// A cell holding ten wide glyphs is twenty columns of content, not ten: every line of the
/// table — top rule, header, header rule, data row, bottom rule — must therefore occupy the
/// same number of terminal columns.  Measuring a cell in `chars` sizes the column at half its
/// content width, so the header row spills past the closing border.
#[test]
fn cjk_table_lines_all_span_the_border_width() {
    // Ten wide glyphs = 20 content columns; box = "│ " + 20 + " │" = 24.
    let wide = "哈".repeat(10);
    let lines = render_at(&format!("| {wide} |\n| --- |\n| 值 |\n"), 40);
    let widths = table_widths(&lines);
    assert!(
        widths.len() >= 4,
        "expected a bordered table, got {widths:?}"
    );
    assert!(
        widths.iter().all(|w| *w == 24),
        "every table line must be 24 columns wide (20 content + padding + borders), got {widths:?}"
    );
}

/// CJK prose has no spaces, but it breaks between any two glyphs — so a viewport narrower than
/// the cell content must narrow the column and wrap the glyph run, not push the table past the
/// right edge.  The budget for one column is `viewport - 4` (two pad cells, two borders).
#[test]
fn cjk_table_shrinks_into_a_narrow_viewport() {
    let wide = "哈".repeat(10);
    let lines = render_at(&format!("| {wide} |\n| --- |\n| 值 |\n"), 12);
    let widths = table_widths(&lines);
    assert!(
        widths.iter().all(|w| *w == 12),
        "every table line must fill the 12-column viewport without exceeding it, got {widths:?}"
    );
}

/// Every line of the table (rules and rows) shares one width, and that width is `expected`.
fn assert_table_width(md: &str, viewport: usize, expected: usize) {
    let widths = table_widths(&render_at(md, viewport));
    assert!(
        widths.len() >= 4,
        "expected a bordered table, got {widths:?}"
    );
    assert!(
        widths.iter().all(|w| *w == expected),
        "every table line must be {expected} cells at viewport {viewport}, got {widths:?}"
    );
}

const MIXED_TABLE: &str = "| Name | 説明 | Notes |\n|---|---|---|\n\
    | apple | 赤い果物です | crisp and sweet |\n\
    | 梨 | pear | 日本の梨はとても甘い |\n";

/// Mixed CJK / ASCII columns stay aligned as the viewport narrows, and fill it exactly while
/// the column floors (5 + 4 + 5 cells plus 10 of borders = 24) still fit.
#[test]
fn mixed_cjk_table_fills_every_viewport_down_to_its_floor() {
    for viewport in [24, 30, 40] {
        assert_table_width(MIXED_TABLE, viewport, viewport);
    }
    // Below the floor the table overflows, but still as one straight box.
    assert_table_width(MIXED_TABLE, 16, 24);
}

/// A CJK column narrows to its widest glyph: one 2-cell glyph per row in a 3-cell column.
#[test]
fn cjk_column_narrows_to_a_single_glyph() {
    let md = format!("| {} |\n| --- |\n| 値 |\n", "哈".repeat(10));
    assert_table_width(&md, 7, 7);
}

/// Emoji built from several chars size their column at the width `line_render` paints them:
/// VS16 adds nothing and a ZWJ family is its three members.
#[test]
fn multi_char_emoji_cells_stay_aligned() {
    let heart = "| a \u{2764}\u{FE0F} b |\n| --- |\n| x |\n";
    assert_table_width(heart, 80, 9);
    let family = "| \u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} fam |\n| --- |\n| x |\n";
    assert_table_width(family, 80, 14);
}

/// A cluster wider than a pinned column truncates, and the row is padded back to the column's
/// width even when the dropped glyph was wide.
#[test]
fn truncated_wide_cluster_keeps_the_row_full_width() {
    let md = "| \u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} |\n| --- |\n| x |\n\
              <!-- tui-columns: [4] -->\n";
    let lines = render_at(md, 80);
    assert!(
        lines.iter().any(|l| line_text(l).contains('…')),
        "fixture must hit the truncation path"
    );
    assert_table_width(md, 80, 8);
}

/// Cell text drawn from ASCII words, CJK, and multi-char emoji.
fn cell_text() -> impl Strategy<Value = String> {
    let piece = prop_oneof![
        Just("word"),
        Just("a"),
        Just("日本語"),
        Just("表"),
        Just("\u{2764}\u{FE0F}"),
        Just("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}"),
        Just("`code`"),
        Just("é"),
    ];
    prop::collection::vec((piece, any::<bool>()), 1..6).prop_map(|parts| {
        parts
            .into_iter()
            .map(|(p, spaced)| {
                if spaced {
                    format!("{p} ")
                } else {
                    p.to_owned()
                }
            })
            .collect::<String>()
            .trim()
            .to_owned()
    })
}

proptest! {
    /// Whatever the content and viewport, every line of a table paints the same width.
    #[test]
    fn proptest_table_lines_share_one_width(
        cells in prop::collection::vec(cell_text(), 4),
        viewport in 8usize..60,
    ) {
        let md = format!(
            "| {} | {} |\n|---|---|\n| {} | {} |\n",
            cells[0], cells[1], cells[2], cells[3]
        );
        let widths = table_widths(&render_at(&md, viewport));
        prop_assert!(widths.windows(2).all(|w| w[0] == w[1]), "{md:?} @ {viewport}: {widths:?}");
    }
}