mq-markdown 0.10.2

Markdown parsing and manipulation utilities for mq
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
#[cfg(feature = "html-to-markdown")]
use crate::html_to_markdown;
#[cfg(feature = "html-to-markdown")]
use crate::html_to_markdown::ConversionOptions;
#[cfg(feature = "html-to-markdown")]
use crate::node::ListStyle;
use crate::node::{
    Code, ColorTheme, Node, Position, RenderOptions, TableAlign, TableCell, indent_lines, list_own_prefix_width,
    reindent_all_lines, render_before, render_cell_values, render_values_block, separated_from,
};
#[cfg(any(feature = "json", feature = "html-to-markdown"))]
use miette::miette;
use std::{fmt, str::FromStr};
use table_layout::{TableLayout, write_padded_cell};

pub(crate) mod list_order;
mod table_layout;

/// What reading Markdown or MDX turns on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseOptions {
    /// Read YAML between `---` lines, or TOML between `+++` lines, at the start of the input as frontmatter.
    /// Without it these lines are a rule and text, or a heading.
    pub frontmatter: bool,
}

impl ParseOptions {
    /// Sets whether frontmatter at the start of the input is read as such.
    #[must_use]
    pub fn with_frontmatter(mut self, frontmatter: bool) -> Self {
        self.frontmatter = frontmatter;
        self
    }
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self { frontmatter: true }
    }
}

/// A Markdown document.
#[derive(Debug, Clone)]
pub struct Markdown {
    /// The top-level nodes.
    pub nodes: Vec<Node>,
    /// Options used when writing the nodes.
    pub options: RenderOptions,
}

impl FromStr for Markdown {
    type Err = miette::Error;

    fn from_str(content: &str) -> Result<Self, Self::Err> {
        Self::from_markdown_str(content)
    }
}

impl fmt::Display for Markdown {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.render_with_theme(&ColorTheme::PLAIN))
    }
}

/// The line where the block before a node ends. An item that ends in a fence without a closing one
/// ends at the start of the line after it, which is not yet a line of its own.
fn last_line(position: &Position, node: Option<&Node>) -> u32 {
    if matches!(node, Some(Node::List(_))) && position.end.column == 1 && position.end.line > position.start.line {
        position.end.line - 1
    } else {
        position.end.line
    }
}

impl Markdown {
    /// Creates a document from `nodes`.
    pub fn new(nodes: Vec<Node>) -> Self {
        Self {
            nodes,
            options: RenderOptions::default(),
        }
    }

    /// Sets the options used when writing the nodes.
    pub fn set_options(&mut self, options: RenderOptions) {
        self.options = options;
    }

    /// Returns a colored string representation of the markdown using ANSI escape codes.
    #[cfg(feature = "color")]
    pub fn to_colored_string(&self) -> String {
        self.render_with_theme(&ColorTheme::COLORED)
    }

    /// Returns a colored string representation using the given color theme.
    #[cfg(feature = "color")]
    pub fn to_colored_string_with_theme(&self, theme: &ColorTheme<'_>) -> String {
        self.render_with_theme(theme)
    }

    pub(crate) fn render_with_theme(&self, theme: &ColorTheme<'_>) -> String {
        let mut pre_position: Option<Position> = None;
        let mut is_first = true;
        let mut current_table_row: Option<usize> = None;
        let mut in_table = false;
        let mut current_table: Option<TableLayout> = None;
        // Sibling list items only carry a `level`, not a parent link; reconstructs
        // nested-list indentation from the nearest open ancestor at each level.
        let mut list_indent_stack: Vec<usize> = Vec::new();
        // What `render_before` returned for the node before, to pick a delimiter that does not fuse with it.
        let mut previous_rendered: Option<String> = None;

        let reordered = list_order::reorder(&self.nodes);
        let nodes: &[Node] = reordered.as_ref().map_or(&self.nodes, |reordered| &reordered.nodes);
        let is_continuation = |index: usize| {
            reordered
                .as_ref()
                .is_some_and(|reordered| reordered.continuation[index])
        };
        let mut buffer = String::with_capacity(nodes.len() * 50);

        for (i, node) in nodes.iter().enumerate() {
            let prev_node = i.checked_sub(1).and_then(|j| nodes.get(j));

            if let Node::TableCell(TableCell {
                row, column, values, ..
            }) = node
            {
                let is_new_table = current_table.as_ref().is_none_or(|t| i >= t.end);
                if is_new_table {
                    current_table = Some(TableLayout::compute(nodes, &self.options, i));
                }
                let table = current_table.as_ref().unwrap();
                let align = table.align_for(*column);
                let width = table.width_for(*column);

                let value = render_cell_values(values, &self.options, theme);
                let plain_width = table.plain_width_at(*row, *column);

                let is_new_row = current_table_row != Some(*row);

                if is_new_row {
                    if current_table_row.is_some() {
                        buffer.push_str(" |\n");
                    }
                    if is_new_table {
                        if in_table {
                            // Adjacent table: restore the blank line GFM needs to keep them separate.
                            buffer.push('\n');
                        } else if let Some(pos) = node.position() {
                            // Insert newlines before the first row of a table
                            let mut new_line_count = pre_position
                                .as_ref()
                                .map(|p| pos.start.line.saturating_sub(last_line(p, prev_node)))
                                .unwrap_or_else(|| if is_first { 0 } else { 1 })
                                .min(2);
                            // A footnote ends where the next line starts, and a single newline after a
                            // block quote reads back as lazy continuation: a table needs a blank line.
                            if new_line_count < 2
                                && i > 0
                                && matches!(prev_node, Some(Node::Footnote(_) | Node::Blockquote(_)))
                            {
                                new_line_count = 2;
                            }
                            for _ in 0..new_line_count {
                                buffer.push('\n');
                            }
                        }
                    }
                    current_table_row = Some(*row);
                    buffer.push_str("| ");
                } else {
                    buffer.push_str(" | ");
                }

                if self.options.table_padding {
                    write_padded_cell(&mut buffer, &value, plain_width, width, &align);
                } else {
                    buffer.push_str(&value);
                }

                let next_node = nodes.get(i + 1);
                let next_is_different_row = next_node.is_none_or(
                    |next| !matches!(next, Node::TableCell(TableCell { row: next_row, .. }) if *next_row == *row),
                );

                if next_is_different_row {
                    buffer.push_str(" |\n");
                    current_table_row = None;
                }

                pre_position = node.position();
                is_first = false;
                in_table = true;
                continue;
            }

            if let Node::TableAlign(TableAlign { .. }) = node {
                if current_table.as_ref().is_none_or(|t| i >= t.end) {
                    current_table = Some(TableLayout::compute(nodes, &self.options, i));
                }
                let table = current_table.as_ref().unwrap();
                buffer.push_str(&table.render_separator());
                buffer.push('\n');
                pre_position = node.position();
                is_first = false;
                in_table = true;
                continue;
            }

            current_table_row = None;
            current_table = None;
            in_table = false;

            let previous = previous_rendered.take();
            let mut plain = false;
            let value = if let Node::List(list) = node
                && is_continuation(i)
            {
                // The rest of an item after its nested items, aligned with the content of the item.
                list_indent_stack.truncate(list.level as usize + 1);
                let indent = list_indent_stack.last().copied().unwrap_or(0);
                indent_lines(&render_values_block(&list.values, &self.options, theme), indent)
            } else if let Node::List(list) = node {
                while list_indent_stack.len() > list.level as usize {
                    list_indent_stack.pop();
                }
                let own_indent = list_indent_stack.last().copied().unwrap_or(0);
                let delta = own_indent as isize - list.level as isize * 2;
                let own_width = own_indent + list_own_prefix_width(list.ordered, list.index, list.start);
                list_indent_stack.push(own_width);
                reindent_all_lines(&node.render_with_theme(&self.options, theme), delta)
            } else if let Node::Code(code) = node
                && !code.fence
                && matches!(prev_node, Some(Node::List(_)))
            {
                // Fenced avoids its fixed 4-space indent colliding with the list's own.
                list_indent_stack.clear();
                Node::Code(Code {
                    fence: true,
                    ..code.clone()
                })
                .render_with_theme(&self.options, theme)
            } else {
                list_indent_stack.clear();
                plain = true;
                render_before(
                    node,
                    &nodes[..i],
                    previous.as_deref(),
                    nodes.get(i + 1),
                    &self.options,
                    theme,
                )
            };
            previous_rendered = plain.then(|| value.clone());

            if value.is_empty() || value == "\n" {
                pre_position = None;
                continue;
            }

            if let Some(pos) = node.position() {
                let mut new_line_count = pre_position
                    .as_ref()
                    .map(|p| pos.start.line.saturating_sub(last_line(p, prev_node)))
                    .unwrap_or_else(|| if is_first { 0 } else { 1 })
                    .min(2);

                new_line_count = separated_from(new_line_count, prev_node, node, &value);

                // An item that starts on the line of the marker that holds it follows it directly.
                let value =
                    if new_line_count == 0 && matches!(node, Node::List(_)) && matches!(prev_node, Some(Node::List(_)))
                    {
                        value.trim_start().to_string()
                    } else {
                        value
                    };

                // Same-list adjacent items separate by `spread`, not source line gap.
                if let Node::List(cur_list) = node
                    && let Some(Node::List(prev_list)) = prev_node
                    && cur_list.level == prev_list.level
                    && cur_list.ordered == prev_list.ordered
                    && cur_list.index.checked_sub(1) == Some(prev_list.index)
                {
                    new_line_count = if cur_list.spread { 2 } else { 1 };
                }

                // The last row of a table ends with its own line ending, so one more makes the blank line.
                if matches!(prev_node, Some(Node::TableCell(_) | Node::TableAlign(_))) {
                    new_line_count = 1;
                }

                pre_position = Some(pos.clone());

                for _ in 0..new_line_count {
                    buffer.push('\n');
                }
                buffer.push_str(&value);
            } else {
                if !is_first {
                    buffer.push('\n');
                    if prev_node.is_some_and(Node::is_blockquote_like) {
                        buffer.push('\n');
                    }
                }
                pre_position = None;
                buffer.push_str(&value);
            }

            if is_first {
                is_first = false;
            }
        }

        if !buffer.is_empty() && !buffer.ends_with('\n') {
            buffer.push('\n');
        }
        // A rule of dashes first and a line of three dashes later would read as frontmatter.
        if matches!(nodes.first(), Some(Node::HorizontalRule(_)))
            && buffer.starts_with("---\n")
            && buffer[4..].lines().any(|line| line == "---")
        {
            buffer.replace_range(..3, "***");
        }
        buffer
    }

    /// Reads MDX with the default options.
    pub fn from_mdx_str(content: &str) -> miette::Result<Self> {
        Self::from_mdx_str_with(content, ParseOptions::default())
    }

    /// Reads MDX with the given options.
    pub fn from_mdx_str_with(content: &str, options: ParseOptions) -> miette::Result<Self> {
        Ok(Self {
            nodes: parse_mdx_nodes(content, options)?,
            options: RenderOptions {
                mdx: true,
                ..RenderOptions::default()
            },
        })
    }

    /// Renders the document as HTML.
    pub fn to_html(&self) -> String {
        to_html(&crate::node::for_html(|| self.to_string()))
    }

    /// Returns the plain text of each node, one per line.
    pub fn to_text(&self) -> String {
        let mut result = String::with_capacity(self.nodes.len() * 20); // Reasonable estimate
        for node in &self.nodes {
            result.push_str(&node.value());
            result.push('\n');
        }
        result
    }

    /// Serializes the nodes to a JSON string.
    #[cfg(feature = "json")]
    pub fn to_json(&self) -> miette::Result<String> {
        let nodes = self
            .nodes
            .iter()
            .filter(|node| !node.is_empty() && !node.is_empty_fragment())
            .collect::<Vec<_>>();
        serde_json::to_string_pretty(&nodes).map_err(|e| miette!("Failed to serialize to JSON: {}", e))
    }

    /// Converts HTML to Markdown, then reads it with the default options.
    #[cfg(feature = "html-to-markdown")]
    pub fn from_html_str(content: &str) -> miette::Result<Self> {
        Self::from_html_str_with_options(content, ConversionOptions::default())
    }

    /// Converts HTML to Markdown with the given options, then reads it.
    #[cfg(feature = "html-to-markdown")]
    pub fn from_html_str_with_options(content: &str, options: ConversionOptions) -> miette::Result<Self> {
        html_to_markdown::convert_html_to_markdown(content, options)
            .map_err(|e| miette!(e))
            .and_then(|md_string| Self::from_markdown_str(&md_string))
            .map(|mut markdown| {
                // The converter's `*` bullets are an artifact, not a source style to preserve.
                markdown.options.list_style = Some(ListStyle::Dash);
                markdown
            })
    }

    /// Reads Markdown with the default options.
    pub fn from_markdown_str(content: &str) -> miette::Result<Self> {
        Self::from_markdown_str_with(content, ParseOptions::default())
    }

    /// Reads Markdown with the given options.
    pub fn from_markdown_str_with(content: &str, options: ParseOptions) -> miette::Result<Self> {
        let nodes = parse_nodes(content, options)?;

        Ok(Self {
            nodes,
            options: RenderOptions::default(),
        })
    }
}

/// Parses `content` into nodes.
fn parse_nodes(content: &str, options: ParseOptions) -> miette::Result<Vec<Node>> {
    crate::parser::parse_with(content, options.frontmatter)
}

/// Parses `content` as MDX into nodes.
fn parse_mdx_nodes(content: &str, options: ParseOptions) -> miette::Result<Vec<Node>> {
    crate::parser::parse_mdx_with(content, options.frontmatter)
}

/// Converts Markdown to HTML.
///
/// Everything that is parsed is rendered: GFM tables, task list items, strikethrough, footnotes and
/// autolink literals, math, and raw HTML. Frontmatter is left out.
pub fn to_html(s: &str) -> String {
    crate::parser::to_html(s)
}

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

    use crate::{ListStyle, TitleSurroundStyle, UrlSurroundStyle};

    use super::*;

    #[rstest]
    #[case::header("# Title", 1, "# Title\n")]
    #[case::header("# Title\nParagraph", 2, "# Title\nParagraph\n")]
    #[case::header("# Title\n\nParagraph", 2, "# Title\n\nParagraph\n")]
    #[case::list("- Item 1\n- Item 2", 2, "- Item 1\n- Item 2\n")]
    #[case::list_nested_sublist_after_blank_line_stays_nested("1.  foo\n\n    - bar", 2, "1. foo\n\n   - bar\n")]
    #[case::list_ordered_nested_in_ordered_uses_own_marker_width(
        "10.  foo\n\n     1. bar",
        2,
        "10. foo\n\n    1. bar\n"
    )]
    #[case::list_code_block_as_first_child_is_indented(
        "1. ```\n   foo\n   ```\n\n   bar",
        1,
        "1. ```\n   foo\n   ```\n\n   bar\n"
    )]
    #[case::list_code_block_first_child_multibyte_content(
        "1. ```\n   あいう\n   ```",
        1,
        "1. ```\n   あいう\n   ```\n"
    )]
    #[case::quote("> Quote\n>Second line", 1, "> Quote\n> Second line\n")]
    #[case::code("```rust\nlet x = 1;\n```", 1, "```rust\nlet x = 1;\n```\n")]
    #[case::toml("+++\n[test]\ntest = 1\n+++", 1, "+++\n[test]\ntest = 1\n+++\n")]
    #[case::code_inline("`inline`", 1, "`inline`\n")]
    #[case::math_inline("$math$", 1, "$math$\n")]
    #[case::math("$$\nmath\n$$", 1, "$$\nmath\n$$\n")]
    #[case::html("<div>test</div>", 1, "<div>test</div>\n")]
    #[case::footnote("[^a]: b", 1, "[^a]: b\n")]
    #[case::definition("[a]: b", 1, "[a]: b\n")]
    #[case::footnote("[^a]: b", 1, "[^a]: b\n")]
    #[case::footnote_ref("[^a]: b\n\n[^a]", 2, "[^a]: b\n\n[^a]\n")]
    #[case::image("![a](b)", 1, "![a](b)\n")]
    #[case::image_with_title("![a](b \"c\")", 1, "![a](b \"c\")\n")]
    #[case::image_ref("[a]: b\n\n ![c][a]", 2, "[a]: b\n\n![c][a]\n")]
    #[case::yaml(
        "---\ntitle: Test\ndescription: YAML front matter\n---\n",
        1,
        "---\ntitle: Test\ndescription: YAML front matter\n---\n"
    )]
    #[case::link("[a](b)", 1, "[a](b)\n")]
    #[case::link_ref("[a]: b\n\n[c][a]", 2, "[a]: b\n\n[c][a]\n")]
    #[case::break_("a\\b", 1, "a\\\\b\n")]
    #[case::delete("~~a~~", 1, "~~a~~\n")]
    #[case::emphasis("*a*", 1, "*a*\n")]
    #[case::horizontal_rule("---", 1, "---\n")]
    #[case::horizontal_rule_star("***", 1, "***\n")]
    #[case::horizontal_rule_underscore("___", 1, "___\n")]
    #[case::list_star("* a\n* b", 2, "* a\n* b\n")]
    #[case::list_plus("+ a\n+ b", 2, "+ a\n+ b\n")]
    #[case::list_ordered_paren("3) a\n4) b", 2, "3) a\n4) b\n")]
    #[case::table(
        "| Column1 | Column2 | Column3 |\n|:--------|:--------:|---------:|\n| Left    | Center  | Right   |\n",
        7,
        "| Column1 | Column2 | Column3 |\n| :------ | :-----: | ------: |\n| Left    | Center  |   Right |\n"
    )]
    #[case::table_after_paragraph(
        "Paragraph\n\n| A | B |\n|---|---|\n| 1 | 2 |\n",
        6,
        "Paragraph\n\n| A | B |\n| - | - |\n| 1 | 2 |\n"
    )]
    #[case::table_after_heading(
        "# Title\n\n| A | B |\n|---|---|\n| 1 | 2 |\n",
        6,
        "# Title\n\n| A | B |\n| - | - |\n| 1 | 2 |\n"
    )]
    #[case::table_column_padding(
        "| Name | Age |\n|---|---|\n| Alexander | 5 |\n| Bo | 42 |\n",
        7,
        "| Name      | Age |\n| --------- | --- |\n| Alexander | 5   |\n| Bo        | 42  |\n"
    )]
    #[case::table_column_padding_wide_chars(
        "| 名前 | 年齢 |\n|---|---|\n| 太郎 | 5 |\n",
        5,
        "| 名前 | 年齢 |\n| ---- | ---- |\n| 太郎 | 5    |\n"
    )]
    // Content width (1) is below the Left-align floor (2); the floor, not
    // the content, must decide the column width.
    #[case::table_min_width_left("| A |\n|:--|\n| 1 |\n", 3, "| A  |\n| :- |\n| 1  |\n")]
    // Same, for the Right-align floor (2).
    #[case::table_min_width_right("| A |\n|--:|\n| 1 |\n", 3, "|  A |\n| -: |\n|  1 |\n")]
    // Same, for the Center-align floor (3): must not collapse to the
    // invalid `::` marker.
    #[case::table_min_width_center("| A |\n|:-:|\n| 1 |\n", 3, "|  A  |\n| :-: |\n|  1  |\n")]
    // An empty cell must still pad out to its column's width.
    #[case::table_empty_cell("| A | |\n|---|---|\n| 1 | 2 |\n", 5, "| A |   |\n| - | - |\n| 1 | 2 |\n")]
    // A data row with fewer cells than the header must render only the
    // cells present, without panicking or misaligning later rows.
    #[case::table_ragged_row("| A | B |\n|---|---|\n| 1 |\n", 4, "| A | B |\n| - | - |\n| 1 |\n")]
    // adjacent tables have no separator node between them; the renderer must still
    // keep the blank line, or re-parsing merges them into one table.
    #[case::tables_adjacent(
        "| A | B |\n|---|---|\n| 1 | 2 |\n\n| C | D |\n|---|---|\n| 3 | 4 |\n",
        10,
        "| A | B |\n| - | - |\n| 1 | 2 |\n\n| C | D |\n| - | - |\n| 3 | 4 |\n"
    )]
    // the line ending of the last row is part of the blank line before what follows
    #[case::table_then_paragraph("| A |\n|---|\n| 1 |\n\npara\n", 4, "| A |\n| - |\n| 1 |\n\npara\n")]
    #[case::table_then_rule("| A |\n|---|\n| 1 |\n---\n", 4, "| A |\n| - |\n| 1 |\n\n---\n")]
    // adjacent tables of different widths must not share column layout.
    #[case::tables_adjacent_different_widths(
        "| A | B |\n|---|---|\n| 1 | 2 |\n\n| C |\n|---|\n| 3 |\n",
        8,
        "| A | B |\n| - | - |\n| 1 | 2 |\n\n| C |\n| - |\n| 3 |\n"
    )]
    #[case::excessive_blank_lines("# Title\n\n\n\nParagraph", 2, "# Title\n\nParagraph\n")]
    #[case::three_blank_lines("Para 1\n\n\n\n\nPara 2", 2, "Para 1\n\nPara 2\n")]
    // GFM autolink literal: link text is the same URL, must not nest on round-trip
    #[case::link_url_as_text(
        "[https://example.com](https://example.com)",
        1,
        "[https://example.com](https://example.com)\n"
    )]
    #[cfg_attr(feature = "wikilink", case::wikilink("[[target]]", 1, "[[target]]\n"))]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_with_text("[[target|display text]]", 1, "[[target|display text]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_same_text("[[target|target]]", 1, "[[target]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_with_md_ext("[[target.md]]", 1, "[[target.md]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_spaces("[[Three laws of motion]]", 1, "[[Three laws of motion]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_in_paragraph("before [[target]] after", 3, "before [[target]] after\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_at_start("[[target]] after", 2, "[[target]] after\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_at_end("before [[target]]", 2, "before [[target]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_multiple("[[a]] and [[b]]", 3, "[[a]] and [[b]]\n")
    )]
    #[cfg_attr(
        feature = "wikilink",
        case::wikilink_in_heading("# See [[target]]", 1, "# See [[target]]\n")
    )]
    // callout round-trips
    #[cfg_attr(
        feature = "callout",
        case::callout_note("> [!NOTE]\n> body", 1, "> [!NOTE]\n> body\n")
    )]
    #[cfg_attr(
        feature = "callout",
        case::callout_with_title("> [!WARNING] My Title\n> content", 1, "> [!WARNING] My Title\n> content\n")
    )]
    #[cfg_attr(feature = "callout", case::callout_empty_body("> [!TIP]", 1, "> [!TIP]\n"))]
    #[cfg_attr(
        feature = "callout",
        case::callout_multiline("> [!NOTE]\n> line 1\n> line 2", 1, "> [!NOTE]\n> line 1\n> line 2\n")
    )]
    // plain blockquote stays Blockquote, not treated as callout
    #[cfg_attr(feature = "callout", case::plain_blockquote("> plain quote", 1, "> plain quote\n"))]
    // plain blockquote with list items: second item must not be over-indented
    #[case::blockquote_with_list("> - item 1\n> - item 2", 1, "> - item 1\n> - item 2\n")]
    // backtick fence switches to tilde when the info string itself has a backtick
    #[case::fence_switches_to_tilde_on_backtick_in_info("~~~ aa ``` ~~~\nfoo\n~~~", 1, "~~~aa ``` ~~~\nfoo\n~~~\n")]
    // a sibling right after a block quote needs a blank line, or it's read as lazy continuation
    #[case::blockquote_sibling_gets_blank_line_separator("> bar\n>\nbaz", 2, "> bar\n\nbaz\n")]
    #[case::dash_rule_under_text_stays_a_rule("Foo\n--- -\n", 2, "Foo\n\n---\n")]
    #[case::dash_rule_under_emphasis_stays_a_rule("*Foo*\n- - -\n", 2, "*Foo*\n\n---\n")]
    #[case::star_rule_under_text_needs_no_blank_line("Foo\n***\n", 2, "Foo\n***\n")]
    #[cfg_attr(
        feature = "wikilink",
        case::dash_rule_under_wikilink_stays_a_rule("[[note]]\n- - -\n", 2, "[[note]]\n\n---\n")
    )]
    #[cfg_attr(
        feature = "embed",
        case::dash_rule_under_embed_stays_a_rule("![[note]]\n- - -\n", 2, "![[note]]\n\n---\n")
    )]
    #[case::dash_rule_under_inline_html_stays_a_rule("<b>x</b>\n- - -\n", 4, "<b>x</b>\n\n---\n")]
    // items whose marker sits alone on its own line must stay tight, not go loose
    #[case::list_tight_despite_marker_on_own_line("-\n  foo\n-\n  bar", 2, "- foo\n- bar\n")]
    // an empty task item must not take the paragraph after it
    #[case::empty_task_item_then_paragraph("- [ ] \n\npara", 2, "- [ ] \n\npara\n")]
    #[case::empty_checked_ordered_task_item_then_paragraph("1. [x] \n\npara", 2, "1. [x] \n\npara\n")]
    // a fence that is not closed ends with its item, and what follows needs a line of its own
    #[case::quote_after_an_unclosed_fence_in_an_item("- ```\n  a\n> q\n", 2, "- ```\n  a\n  ```\n> q\n")]
    // emphasis next to emphasis, or nested at its edge, keeps its own run of delimiters
    #[case::adjacent_emphasis("_*_*] x*_", 3, "*\\**_\\] x_\\_\n")]
    #[case::emphasis_in_emphasis_at_an_edge("***a*b*", 2, "\\*_*a*b_\n")]
    #[case::emphasis_after_emphasis_after_a_nested_one("\\**_*a***b**)", 4, "\\*_\\_*a*_*b*\\*)\n")]
    #[case::strong_after_emphasis("*a*__b__", 2, "*a*__b__\n")]
    #[case::emphasis_in_the_next_paragraph("*a*\n\n*b*", 2, "*a*\n\n*b*\n")]
    #[case::strong_in_the_next_paragraph("*a*\n\n**b**", 2, "*a*\n\n**b**\n")]
    #[case::emphasis_nested_three_deep("***a***", 1, "***a***\n")]
    #[case::reference_then_colon_is_not_a_definition("[x] a\n\n[x]: /u", 3, "[x] a\n\n[x]: /u\n")]
    #[case::bang_before_a_link_in_the_next_paragraph("a!\n\n[b](u)", 2, "a!\n\n[b](u)\n")]
    #[case::colon_after_a_reference_in_the_next_paragraph("[x]\n\n:a\n\n[x]: /u", 3, "[x]\n\n:a\n\n[x]: /u\n")]
    // lists in a block quote: items on one line, the rest of an item after nested ones, nested under an ordered one
    #[case::quote_list_in_list_on_one_line("> - - - x", 1, "> - - - x\n")]
    #[case::quote_paragraph_after_nested_item("> - a\n>   - b\n>\n>   para", 1, "> - a\n>   - b\n> \n>   para\n")]
    #[case::quote_bullet_nested_under_ordered("> 1. a\n>    - b", 1, "> 1. a\n>    - b\n")]
    // inside a container a block after a quote or footnote needs a blank line, and empty math stays empty
    #[case::quote_after_nested_quote("> > a\n> >\n> b", 1, "> > a\n> \n> b\n")]
    #[case::fence_after_quote_in_item("- a\n  > b\n  ```\n  c\n  ```\n- d", 2, "- a\n  > b\n  ```\n  c\n  ```\n- d\n")]
    #[case::paragraph_after_footnote_in_item("- [^1]: b\n\n  c", 1, "- [^1]: b\n\n  c\n")]
    #[case::empty_math("$$\n$$", 1, "$$\n$$\n")]
    // an indented code block right after a list must not read back as list continuation
    #[case::code_after_list_uses_fence(" -    one\n\n     two", 2, "- one\n\n```\n two\n```\n")]
    // a block quote nested in a list item needs its continuation line's own indent
    #[case::blockquote_in_list_continuation(
        "> 1. > Blockquote\ncontinued here.",
        1,
        "> 1. > Blockquote\n>    > continued here.\n"
    )]
    // embed round-trips
    #[cfg_attr(feature = "embed", case::embed_plain("![[note.md]]", 1, "![[note.md]]\n"))]
    #[cfg_attr(
        feature = "embed",
        case::embed_with_display("![[image.png|400]]", 1, "![[image.png|400]]\n")
    )]
    #[cfg_attr(
        feature = "embed",
        case::embed_in_paragraph("See ![[note]] and read more.", 3, "See ![[note]] and read more.\n")
    )]
    #[cfg_attr(
        all(feature = "embed", feature = "wikilink"),
        case::embed_and_wikilink("![[embed]] and [[link]]", 3, "![[embed]] and [[link]]\n")
    )]
    fn test_markdown_from_str(#[case] input: &str, #[case] expected_nodes: usize, #[case] expected_output: &str) {
        let md = input.parse::<Markdown>().unwrap();
        assert_eq!(md.nodes.len(), expected_nodes);
        assert_eq!(md.to_string(), expected_output);
    }

    #[rstest]
    #[case::mdx("{test}", 1, "{test}\n")]
    #[case::mdx("<a />", 1, "<a />\n")]
    #[case::mdx("<MyComponent {...props}/>", 1, "<MyComponent {...props} />\n")]
    #[case::mdx("text<MyComponent {...props}/>text", 3, "text<MyComponent {...props} />text\n")]
    #[case::mdx(
        "<Chart color=\"#fcb32c\" year={year} />",
        1,
        "<Chart color=\"#fcb32c\" year={year} />\n"
    )]
    #[case::dash_rule_under_text_expression("a {b}\n- - -\n", 3, "a {b}\n\n---\n")]
    #[case::dash_rule_under_jsx_text("a <b />\n- - -\n", 3, "a <b />\n\n---\n")]
    fn test_markdown_from_mdx_str(#[case] input: &str, #[case] expected_nodes: usize, #[case] expected_output: &str) {
        let md = Markdown::from_mdx_str(input).unwrap();
        assert_eq!(md.nodes.len(), expected_nodes);
        assert_eq!(md.to_string(), expected_output);
    }

    #[cfg(feature = "callout")]
    #[rstest]
    #[case("> [!NOTE]\n> body")]
    #[case("> [!WARNING] Custom Title\n> line 1\n> line 2")]
    #[case("> [!TIP]")]
    #[case("> plain blockquote")]
    fn test_callout_round_trip_idempotent(#[case] input: &str) {
        let first = input.parse::<Markdown>().unwrap().to_string();
        let second = first.parse::<Markdown>().unwrap().to_string();
        assert_eq!(first, second, "callout round-trip must be idempotent for {input:?}");
    }

    #[cfg(feature = "embed")]
    #[rstest]
    #[case("![[note.md]]")]
    #[case("![[image.png|400]]")]
    #[case("![[note#Heading]]")]
    #[case("See ![[note]] for details.")]
    fn test_embed_round_trip_idempotent(#[case] input: &str) {
        let first = input.parse::<Markdown>().unwrap().to_string();
        let second = first.parse::<Markdown>().unwrap().to_string();
        assert_eq!(first, second, "embed round-trip must be idempotent for {input:?}");
    }

    /// Round-tripping a link whose text equals its URL must be idempotent,
    /// not nest as `[[url](url)](url)`.
    #[test]
    fn test_link_url_as_text_is_idempotent() {
        let input = "[https://example.com](https://example.com)";
        let first = input.parse::<Markdown>().unwrap().to_string();
        let second = first.parse::<Markdown>().unwrap().to_string();
        assert_eq!(first, second, "round-trip must be idempotent");
        assert_eq!(first, "[https://example.com](https://example.com)\n");
    }

    #[rstest]
    #[case::paragraphs_in_an_item("- a\n\n  b\n\n  c\n", "- a\n\n  b\n\n  c\n")]
    // the order of a paragraph after a nested list is lost, but its content is not
    #[case::paragraph_after_a_nested_list("- a\n\n  - n\n\n  para\n", "- a\n\n  para\n  - n\n")]
    #[case::paragraphs_in_an_ordered_item("1. a\n\n   b\n", "1. a\n\n   b\n")]
    #[case::paragraphs_in_a_quote_in_an_item("- > a\n  >\n  > b\n", "- > a\n  > \n  > b\n")]
    fn test_paragraphs_stay_apart_without_positions(#[case] input: &str, #[case] expected: &str) {
        let mut md = Markdown::from_markdown_str(input).unwrap();
        md.nodes.iter_mut().for_each(Node::strip_positions);
        assert_eq!(md.to_string(), expected);
    }

    #[test]
    fn test_markdown_to_html() {
        let md = "# Hello".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert_eq!(html, "<h1>Hello</h1>\n");
    }

    #[rstest]
    #[case("## &#35;\n", "## \\#\n")]
    #[case("### &#35;&#35;\n", "### \\##\n")]
    #[case("## a &#35;\n", "## a \\#\n")]
    #[case("## \\\\&#35;\n", "## \\\\\\#\n")]
    #[case("## \\\\&#35;&#35;\n", "## \\\\\\##\n")]
    #[case("## あ &#35;\n", "## あ \\#\n")]
    #[case("## あ\\\\&#35;\n", "## あ\\\\\\#\n")]
    fn test_heading_hash_markdown_roundtrip(#[case] input: &str, #[case] expected: &str) {
        let rendered = input.parse::<Markdown>().unwrap().to_string();
        assert_eq!(rendered.trim_end(), expected.trim_end());
        assert_eq!(rendered.parse::<Markdown>().unwrap().to_string(), rendered);
    }

    #[test]
    fn test_heading_literal_backslash_hash_constructed() {
        let node = crate::Node::Heading(crate::Heading {
            depth: crate::HeadingDepth::H2,
            values: vec!["\\#".into()],
            position: None,
        });
        let rendered = node.to_string();
        assert_eq!(rendered, "## \\\\#");
        let reparsed = rendered.parse::<Markdown>().unwrap();
        assert_eq!(reparsed.to_html(), "<h2>\\#</h2>\n");
    }

    #[rstest]
    #[case("## &#35;\n", "<h2>#</h2>\n")]
    #[case("### &#35;&#35;\n", "<h3>##</h3>\n")]
    #[case("## a &#35;\n", "<h2>a #</h2>\n")]
    #[case("## a &#35;&#35;\n", "<h2>a ##</h2>\n")]
    #[case("# &#35; &#35;\n", "<h1># #</h1>\n")]
    #[case("## \\\\&#35;\n", "<h2>\\#</h2>\n")]
    #[case("## \\\\&#35;&#35;\n", "<h2>\\##</h2>\n")]
    fn test_to_html_heading_hash_only(#[case] input: &str, #[case] expected: &str) {
        assert_eq!(input.parse::<Markdown>().unwrap().to_html(), expected);
    }

    #[test]
    fn test_to_html_gfm_table() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(html.contains("<table>"), "expected <table> tag in: {html}");
        assert!(html.contains("<thead>"), "expected <thead> in: {html}");
        assert!(html.contains("<tbody>"), "expected <tbody> in: {html}");
        assert!(html.contains("<th>A</th>"), "expected <th>A</th> in: {html}");
        assert!(html.contains("<td>1</td>"), "expected <td>1</td> in: {html}");
    }

    fn cell_source(values: Vec<Node>) -> String {
        let cell = Node::TableCell(crate::node::TableCell {
            column: 0,
            row: 0,
            values,
            position: None,
        });
        format!("| h |\n|---|\n|{}|", cell)
    }

    #[test]
    fn test_table_cell_break_html_roundtrip() {
        let src = cell_source(vec![
            "a".to_string().into(),
            Node::Break(crate::node::Break { position: None }),
            "b".to_string().into(),
        ]);
        let html = src.parse::<Markdown>().unwrap().to_html();
        assert!(html.contains("<td>a<br"), "expected a real line break in: {html}");
        assert!(!html.contains("&lt;br"), "<br> must not be escaped in: {html}");
    }

    #[test]
    fn test_table_cell_code_newline_html_roundtrip() {
        let src = cell_source(vec![Node::CodeInline(crate::node::CodeInline {
            value: "a\nb".into(),
            position: None,
        })]);
        let html = src.parse::<Markdown>().unwrap().to_html();
        assert!(
            html.contains("<code>a b</code>"),
            "expected code with a space in: {html}"
        );
    }

    #[test]
    fn test_to_html_gfm_table_alignment() {
        let md = "| L | C | R |\n|:---|:---:|---:|\n| a | b | c |"
            .parse::<Markdown>()
            .unwrap();
        let html = md.to_html();
        assert!(
            html.contains("align=\"left\"") || html.contains("style=\"text-align:left\"") || html.contains("<table>"),
            "table with alignment rendered: {html}"
        );
    }

    #[test]
    fn test_to_html_gfm_strikethrough() {
        let md = "~~deleted~~".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(html.contains("<del>deleted</del>"), "expected <del> in: {html}");
    }

    #[test]
    fn test_to_html_gfm_task_list() {
        let md = "- [ ] Unchecked\n- [x] Checked".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(html.contains("<input"), "expected <input> in: {html}");
        assert!(html.contains("type=\"checkbox\""), "expected checkbox in: {html}");
        assert!(html.contains("checked"), "expected checked attribute in: {html}");
    }

    #[test]
    fn test_to_html_math_inline() {
        let md = "Inline math: $E = mc^2$".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(
            html.contains("math") && html.contains("E = mc^2"),
            "expected math content in: {html}"
        );
    }

    #[test]
    fn test_to_html_math_block() {
        let md = "$$\n\\frac{1}{2}\n$$".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(
            html.contains("math") && html.contains("\\frac{1}{2}"),
            "expected math block in: {html}"
        );
    }

    #[test]
    fn test_to_html_footnote() {
        let md = "Footnote[^1]\n\n[^1]: Definition".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(
            html.contains("footnote") || html.contains("fn"),
            "expected footnote in: {html}"
        );
    }

    #[test]
    fn test_to_html_html_passthrough() {
        let md = "<kbd>Ctrl</kbd>+<kbd>C</kbd>".parse::<Markdown>().unwrap();
        let html = md.to_html();
        assert!(
            html.contains("<kbd>Ctrl</kbd>"),
            "expected <kbd> passthrough in: {html}"
        );
    }

    #[test]
    fn test_to_html_standalone_gfm_table() {
        let input = "| H1 | H2 |\n|---|---|\n| a | b |";
        let html = to_html(input);
        assert!(
            html.contains("<table>"),
            "expected <table> from standalone to_html: {html}"
        );
    }

    #[test]
    fn test_markdown_to_text() {
        let md = "# Hello\n\nWorld".parse::<Markdown>().unwrap();
        let text = md.to_text();
        assert_eq!(text, "Hello\nWorld\n");
    }

    #[test]
    fn test_render_options() {
        let mut md = "- Item 1\n- Item 2".parse::<Markdown>().unwrap();
        assert_eq!(md.options, RenderOptions::default());

        md.set_options(RenderOptions {
            list_style: Some(ListStyle::Plus),
            ..RenderOptions::default()
        });
        assert_eq!(md.options.list_style, Some(ListStyle::Plus));

        let pretty = md.to_string();
        assert!(pretty.contains("+ Item 1"));
    }

    #[test]
    fn test_display_simple() {
        let md = "# Header\nParagraph".parse::<Markdown>().unwrap();
        assert_eq!(md.to_string(), "# Header\nParagraph\n");
    }

    #[test]
    fn test_display_with_empty_nodes() {
        let md = "# Header\nContent".parse::<Markdown>().unwrap();
        assert_eq!(md.to_string(), "# Header\nContent\n");
    }

    #[test]
    fn test_display_with_newlines() {
        let md = "# Header\n\nParagraph 1\n\nParagraph 2".parse::<Markdown>().unwrap();
        assert_eq!(md.to_string(), "# Header\n\nParagraph 1\n\nParagraph 2\n");
    }

    #[test]
    fn test_display_format_lists() {
        let md = "- Item 1\n- Item 2\n- Item 3".parse::<Markdown>().unwrap();
        assert_eq!(md.to_string(), "- Item 1\n- Item 2\n- Item 3\n");
    }

    #[rstest]
    #[case::none(
        "| Name | Age |\n|---|---|\n| Alexander | 5 |\n",
        "| Name | Age |\n| --- | --- |\n| Alexander | 5 |\n"
    )]
    #[case::aligned(
        "| A | B | C |\n|:--|--:|:-:|\n| 1 | 2 | 3 |\n",
        "| A | B | C |\n| :-- | --: | :-: |\n| 1 | 2 | 3 |\n"
    )]
    #[case::ragged_row("| A | B |\n|---|---|\n| 1 |\n", "| A | B |\n| --- | --- |\n| 1 |\n")]
    fn test_table_without_padding(#[case] input: &str, #[case] expected: &str) {
        let mut md = input.parse::<Markdown>().unwrap();
        md.set_options(RenderOptions {
            table_padding: false,
            ..RenderOptions::default()
        });
        assert_eq!(md.to_string(), expected);
    }

    #[test]
    fn test_display_with_different_list_styles() {
        let mut md = "- Item 1\n- Item 2".parse::<Markdown>().unwrap();

        md.set_options(RenderOptions {
            list_style: Some(ListStyle::Star),
            link_title_style: TitleSurroundStyle::default(),
            link_url_style: UrlSurroundStyle::default(),
            ..RenderOptions::default()
        });

        let formatted = md.to_string();
        assert!(formatted.contains("* Item 1"));
        assert!(formatted.contains("* Item 2"));
    }

    #[test]
    fn test_display_with_ordered_list() {
        let md = "1. Item 1\n2. Item 2\n\n3. Item 2".parse::<Markdown>().unwrap();
        let formatted = md.to_string();

        assert!(formatted.contains("1. Item 1"));
        assert!(formatted.contains("2. Item 2"));
        assert!(formatted.contains("3. Item 2"));
    }
}

#[cfg(test)]
#[cfg(feature = "color")]
mod color_tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case::heading("# Title", "\x1b[1m\x1b[36m# Title\x1b[0m\n")]
    #[case::emphasis("*italic*", "\x1b[3m\x1b[33m*italic*\x1b[0m\n")]
    #[case::strong("**bold**", "\x1b[1m**bold**\x1b[0m\n")]
    #[case::code_inline("`code`", "\x1b[32m`code`\x1b[0m\n")]
    #[case::code_block("```rust\nlet x = 1;\n```", "\x1b[32m```rust\nlet x = 1;\n```\x1b[0m\n")]
    #[case::link("[text](url)", "\x1b[4m\x1b[34m[text](url)\x1b[0m\n")]
    #[case::image("![alt](url)", "\x1b[35m![alt](url)\x1b[0m\n")]
    #[case::delete("~~deleted~~", "\x1b[31m\x1b[2m~~deleted~~\x1b[0m\n")]
    #[case::horizontal_rule("---", "\x1b[2m---\x1b[0m\n")]
    #[case::blockquote("> quote", "\x1b[2m> \x1b[0mquote\n")]
    #[case::math_inline("$x^2$", "\x1b[32m$x^2$\x1b[0m\n")]
    #[case::list("- item", "\x1b[33m-\x1b[0m item\n")]
    fn test_to_colored_string(#[case] input: &str, #[case] expected: &str) {
        let md = input.parse::<Markdown>().unwrap();
        assert_eq!(md.to_colored_string(), expected);
    }

    #[test]
    fn test_colored_table_padding_ignores_ansi_codes_in_width() {
        // The "**A**" cell is colored (ANSI-wrapped) but only 5 display columns wide,
        // one short of the "Bolded" header: padding must be computed from the
        // plain-text width, not the byte length of the ANSI-wrapped string.
        let md = "| H | Bolded |\n|---|---|\n| x | **A** |\n"
            .parse::<Markdown>()
            .unwrap();
        assert_eq!(
            md.to_colored_string(),
            "| H | Bolded |\n| - | ------ |\n| x | \x1b[1m**A**\x1b[0m  |\n"
        );
    }

    #[test]
    fn test_colored_output_contains_ansi_codes() {
        let md = "# Hello\n\n**bold** and *italic*".parse::<Markdown>().unwrap();
        let colored = md.to_colored_string();

        assert!(colored.contains("\x1b["));
        assert!(colored.contains("\x1b[0m"));
    }

    #[test]
    fn test_plain_output_has_no_ansi_codes() {
        let md = "# Hello\n\n**bold** and *italic*".parse::<Markdown>().unwrap();
        let plain = md.to_string();

        assert!(!plain.contains("\x1b["));
    }

    #[test]
    fn test_parse_colors_overrides_specified_keys() {
        let theme = ColorTheme::parse_colors("heading=1;31:code=34");
        assert_eq!(theme.heading.0, "\x1b[1;31m");
        assert_eq!(theme.heading.1, "\x1b[0m");
        assert_eq!(theme.code.0, "\x1b[34m");
        assert_eq!(theme.code.1, "\x1b[0m");
        // Unspecified keys remain default
        assert_eq!(theme.emphasis, ColorTheme::COLORED.emphasis);
    }

    #[test]
    fn test_parse_colors_ignores_invalid_entries() {
        let theme = ColorTheme::parse_colors("heading=abc:code=32:=:badformat");
        // Invalid "abc" is skipped, heading stays default
        assert_eq!(theme.heading, ColorTheme::COLORED.heading);
        // Valid "32" is applied
        assert_eq!(theme.code.0, "\x1b[32m");
        assert_eq!(theme.code.1, "\x1b[0m");
    }

    #[test]
    fn test_parse_colors_ignores_unknown_keys() {
        let theme = ColorTheme::parse_colors("unknown=31:heading=33");
        assert_eq!(theme.heading.0, "\x1b[33m");
        assert_eq!(theme.heading.1, "\x1b[0m");
    }

    #[test]
    fn test_parse_colors_all_keys() {
        let theme = ColorTheme::parse_colors(
            "heading=1:code=2:code_inline=3:emphasis=4:strong=5:link=6:link_url=7:\
             image=8:blockquote=9:delete=10:hr=11:html=12:frontmatter=13:list=14:\
             table=15:math=16",
        );
        assert_eq!(theme.heading.0, "\x1b[1m");
        assert_eq!(theme.code.0, "\x1b[2m");
        assert_eq!(theme.code_inline.0, "\x1b[3m");
        assert_eq!(theme.emphasis.0, "\x1b[4m");
        assert_eq!(theme.strong.0, "\x1b[5m");
        assert_eq!(theme.link.0, "\x1b[6m");
        assert_eq!(theme.link_url.0, "\x1b[7m");
        assert_eq!(theme.image.0, "\x1b[8m");
        assert_eq!(theme.blockquote_marker.0, "\x1b[9m");
        assert_eq!(theme.delete.0, "\x1b[10m");
        assert_eq!(theme.horizontal_rule.0, "\x1b[11m");
        assert_eq!(theme.html.0, "\x1b[12m");
        assert_eq!(theme.frontmatter.0, "\x1b[13m");
        assert_eq!(theme.list_marker.0, "\x1b[14m");
        assert_eq!(theme.table_separator.0, "\x1b[15m");
        assert_eq!(theme.math.0, "\x1b[16m");
    }

    #[test]
    fn test_parse_colors_empty_string() {
        let theme = ColorTheme::parse_colors("");
        assert_eq!(theme.heading, ColorTheme::COLORED.heading);
    }

    #[test]
    fn test_colored_string_with_custom_theme() {
        let theme = ColorTheme::parse_colors("heading=1;31");
        let md = "# Title".parse::<Markdown>().unwrap();
        let colored = md.to_colored_string_with_theme(&theme);
        assert_eq!(colored, "\x1b[1;31m# Title\x1b[0m\n");
    }
}

#[cfg(test)]
#[cfg(feature = "json")]
mod json_tests {
    use rstest::rstest;

    use super::*;

    #[test]
    fn test_to_json_simple() {
        let md = "# Hello".parse::<Markdown>().unwrap();
        let json = md.to_json().unwrap();
        assert!(json.contains("\"type\": \"Heading\""));
        assert!(json.contains("\"depth\": 1"));
        assert!(json.contains("\"values\":"));
    }

    #[test]
    fn test_to_json_mdx_attributes() {
        let md = Markdown::from_mdx_str("<a b=\"c\" d={e} f {...g} />").unwrap();
        let json: serde_json::Value = serde_json::from_str(&md.to_json().unwrap()).unwrap();
        let attributes = &json[0]["attributes"];
        assert_eq!(
            attributes[0],
            serde_json::json!({"type": "property", "value": {"type": "MdxJsxAttribute", "name": "b", "value": {"type": "literal", "value": "c"}}})
        );
        assert_eq!(
            attributes[1],
            serde_json::json!({"type": "property", "value": {"type": "MdxJsxAttribute", "name": "d", "value": {"type": "expression", "value": "e"}}})
        );
        assert_eq!(
            attributes[2],
            serde_json::json!({"type": "property", "value": {"type": "MdxJsxAttribute", "name": "f", "value": null}})
        );
        assert_eq!(
            attributes[3],
            serde_json::json!({"type": "expression", "value": "...g"})
        );
    }

    #[test]
    fn test_to_json_complex() {
        let md = "# Header\n\n- Item 1\n- Item 2\n\n*Emphasis* and **Strong**"
            .parse::<Markdown>()
            .unwrap();
        let json = md.to_json().unwrap();

        assert!(json.contains("\"type\": \"Heading\""));
        assert!(json.contains("\"type\": \"List\""));
        assert!(json.contains("\"type\": \"Strong\""));
        assert!(json.contains("\"type\": \"Emphasis\""));
    }

    #[test]
    fn test_to_json_code_blocks() {
        let md = "```rust\nfn main() {\n    println!(\"Hello\");\n}\n```"
            .parse::<Markdown>()
            .unwrap();
        let json = md.to_json().unwrap();

        assert!(json.contains("\"type\": \"Code\""));
        assert!(json.contains("\"lang\": \"rust\""));
        assert!(json.contains("\"value\": \"fn main() {\\n    println!(\\\"Hello\\\");\\n}\""));
    }

    #[test]
    fn test_to_json_table() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |".parse::<Markdown>().unwrap();
        let json = md.to_json().unwrap();

        assert!(json.contains("\"type\": \"TableCell\""));
    }

    #[rstest]
    #[case("<h1>Hello</h1>", 1, "# Hello\n")]
    #[case("<p>Paragraph</p>", 1, "Paragraph\n")]
    #[case("<ul><li>Item 1</li><li>Item 2</li></ul>", 2, "- Item 1\n- Item 2\n")]
    #[case("<ol><li>First</li><li>Second</li></ol>", 2, "1. First\n2. Second\n")]
    #[case("<blockquote>Quote</blockquote>", 1, "> Quote\n")]
    #[case("<code>inline</code>", 1, "`inline`\n")]
    #[case("<pre><code>block</code></pre>", 1, "```\nblock\n```\n")]
    #[case("<table><tr><td>A</td><td>B</td></tr></table>", 3, "| A | B |\n| - | - |\n")]
    #[cfg(feature = "html-to-markdown")]
    fn test_markdown_from_html(#[case] input: &str, #[case] expected_nodes: usize, #[case] expected_output: &str) {
        let md = Markdown::from_html_str(input).unwrap();
        assert_eq!(md.nodes.len(), expected_nodes);
        assert_eq!(md.to_string(), expected_output);
    }
}