#[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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseOptions {
pub frontmatter: bool,
}
impl ParseOptions {
#[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 }
}
}
#[derive(Debug, Clone)]
pub struct Markdown {
pub nodes: Vec<Node>,
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))
}
}
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 {
pub fn new(nodes: Vec<Node>) -> Self {
Self {
nodes,
options: RenderOptions::default(),
}
}
pub fn set_options(&mut self, options: RenderOptions) {
self.options = options;
}
#[cfg(feature = "color")]
pub fn to_colored_string(&self) -> String {
self.render_with_theme(&ColorTheme::COLORED)
}
#[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;
let mut list_indent_stack: Vec<usize> = Vec::new();
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 {
buffer.push('\n');
} else 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);
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)
{
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(_)))
{
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);
let value =
if new_line_count == 0 && matches!(node, Node::List(_)) && matches!(prev_node, Some(Node::List(_)))
{
value.trim_start().to_string()
} else {
value
};
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 };
}
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');
}
if matches!(nodes.first(), Some(Node::HorizontalRule(_)))
&& buffer.starts_with("---\n")
&& buffer[4..].lines().any(|line| line == "---")
{
buffer.replace_range(..3, "***");
}
buffer
}
pub fn from_mdx_str(content: &str) -> miette::Result<Self> {
Self::from_mdx_str_with(content, ParseOptions::default())
}
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()
},
})
}
pub fn to_html(&self) -> String {
to_html(&crate::node::for_html(|| self.to_string()))
}
pub fn to_text(&self) -> String {
let mut result = String::with_capacity(self.nodes.len() * 20); for node in &self.nodes {
result.push_str(&node.value());
result.push('\n');
}
result
}
#[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))
}
#[cfg(feature = "html-to-markdown")]
pub fn from_html_str(content: &str) -> miette::Result<Self> {
Self::from_html_str_with_options(content, ConversionOptions::default())
}
#[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| {
markdown.options.list_style = Some(ListStyle::Dash);
markdown
})
}
pub fn from_markdown_str(content: &str) -> miette::Result<Self> {
Self::from_markdown_str_with(content, ParseOptions::default())
}
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(),
})
}
}
fn parse_nodes(content: &str, options: ParseOptions) -> miette::Result<Vec<Node>> {
crate::parser::parse_with(content, options.frontmatter)
}
fn parse_mdx_nodes(content: &str, options: ParseOptions) -> miette::Result<Vec<Node>> {
crate::parser::parse_mdx_with(content, options.frontmatter)
}
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("", 1, "\n")]
#[case::image_with_title("", 1, "\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"
)]
#[case::table_min_width_left("| A |\n|:--|\n| 1 |\n", 3, "| A |\n| :- |\n| 1 |\n")]
#[case::table_min_width_right("| A |\n|--:|\n| 1 |\n", 3, "| A |\n| -: |\n| 1 |\n")]
#[case::table_min_width_center("| A |\n|:-:|\n| 1 |\n", 3, "| A |\n| :-: |\n| 1 |\n")]
#[case::table_empty_cell("| A | |\n|---|---|\n| 1 | 2 |\n", 5, "| A | |\n| - | - |\n| 1 | 2 |\n")]
#[case::table_ragged_row("| A | B |\n|---|---|\n| 1 |\n", 4, "| A | B |\n| - | - |\n| 1 |\n")]
#[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"
)]
#[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")]
#[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")]
#[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")
)]
#[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")
)]
#[cfg_attr(feature = "callout", case::plain_blockquote("> plain quote", 1, "> plain quote\n"))]
#[case::blockquote_with_list("> - item 1\n> - item 2", 1, "> - item 1\n> - item 2\n")]
#[case::fence_switches_to_tilde_on_backtick_in_info("~~~ aa ``` ~~~\nfoo\n~~~", 1, "~~~aa ``` ~~~\nfoo\n~~~\n")]
#[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")]
#[case::list_tight_despite_marker_on_own_line("-\n foo\n-\n bar", 2, "- foo\n- bar\n")]
#[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")]
#[case::quote_after_an_unclosed_fence_in_an_item("- ```\n a\n> q\n", 2, "- ```\n a\n ```\n> q\n")]
#[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")]
#[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")]
#[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")]
#[case::code_after_list_uses_fence(" - one\n\n two", 2, "- one\n\n```\n two\n```\n")]
#[case::blockquote_in_list_continuation(
"> 1. > Blockquote\ncontinued here.",
1,
"> 1. > Blockquote\n> > continued here.\n"
)]
#[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:?}");
}
#[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")]
#[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("## #\n", "## \\#\n")]
#[case("### ##\n", "### \\##\n")]
#[case("## a #\n", "## a \\#\n")]
#[case("## \\\\#\n", "## \\\\\\#\n")]
#[case("## \\\\##\n", "## \\\\\\##\n")]
#[case("## あ #\n", "## あ \\#\n")]
#[case("## あ\\\\#\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("## #\n", "<h2>#</h2>\n")]
#[case("### ##\n", "<h3>##</h3>\n")]
#[case("## a #\n", "<h2>a #</h2>\n")]
#[case("## a ##\n", "<h2>a ##</h2>\n")]
#[case("# # #\n", "<h1># #</h1>\n")]
#[case("## \\\\#\n", "<h2>\\#</h2>\n")]
#[case("## \\\\##\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("<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("", "\x1b[35m\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() {
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");
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");
assert_eq!(theme.heading, ColorTheme::COLORED.heading);
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);
}
}