Skip to main content

mq_markdown/node/
render.rs

1//! Rendering nodes back to Markdown.
2
3use super::*;
4use std::cell::Cell;
5
6thread_local! {
7    /// Set while the output is read again as Markdown to make HTML of it, not as MDX.
8    static HTML_TARGET: Cell<bool> = const { Cell::new(false) };
9}
10
11/// Runs `render` with the JSX elements written so that their children are Markdown in HTML.
12pub(crate) fn for_html<R>(render: impl FnOnce() -> R) -> R {
13    struct Reset(bool);
14    impl Drop for Reset {
15        fn drop(&mut self) {
16            HTML_TARGET.set(self.0);
17        }
18    }
19    let _reset = Reset(HTML_TARGET.replace(true));
20    render()
21}
22
23impl Node {
24    /// Writes the node as Markdown with the given options.
25    pub fn to_string_with(&self, options: &RenderOptions) -> String {
26        self.render_with_theme(options, &ColorTheme::PLAIN)
27    }
28
29    /// Returns a colored string representation of this node using ANSI escape codes.
30    #[cfg(feature = "color")]
31    pub fn to_colored_string_with(&self, options: &RenderOptions) -> String {
32        self.render_with_theme(options, &ColorTheme::COLORED)
33    }
34
35    pub(crate) fn render_with_theme(&self, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
36        match self {
37            Self::List(List {
38                level,
39                checked,
40                values,
41                ordered,
42                index,
43                start,
44                marker,
45                ..
46            }) => {
47                let marker = if *ordered {
48                    let delimiter = if *marker == Some(ListMarker::Paren) { ')' } else { '.' };
49                    format!("{}{}", start.unwrap_or(1) as usize + *index, delimiter)
50                } else if let Some(style) = &options.list_style {
51                    style.to_string()
52                } else {
53                    marker.and_then(ListMarker::style).unwrap_or_default().to_string()
54                };
55                let checkbox = (*checked).map(|it| if it { "[x] " } else { "[ ] " }).unwrap_or("");
56                let prefix_width = *level as usize * 2 + list_own_prefix_width(*ordered, *index, *start);
57                // Lines after the first are indented to the content of the item, whatever column they
58                // had in the source, which is not reliable after an escape.
59                let content = render_values_block(values, options, theme);
60                let content = indent_continuation(&content, prefix_width);
61                let (ms, me) = &theme.list_marker;
62                format!(
63                    "{}{}{}{} {}{}",
64                    "  ".repeat(*level as usize),
65                    ms,
66                    marker,
67                    me,
68                    checkbox,
69                    content
70                )
71            }
72            Self::TableRow(TableRow { values, .. }) => {
73                let (ts, te) = &theme.table_separator;
74                let cells = values
75                    .iter()
76                    .map(|cell| cell.render_with_theme(options, theme))
77                    .collect::<Vec<_>>()
78                    .join("|");
79                format!("{}|{}{}|", ts, te, cells)
80            }
81            Self::TableCell(TableCell { values, .. }) => render_cell_values(values, options, theme),
82            Self::TableAlign(TableAlign { align, .. }) => {
83                let (ts, te) = &theme.table_separator;
84                format!("{}|{}|{}", ts, align.iter().map(|a| a.to_string()).join("|"), te)
85            }
86            Self::Blockquote(Blockquote { values, .. }) => {
87                let (bs, be) = &theme.blockquote_marker;
88                render_values_block(values, options, theme)
89                    .split('\n')
90                    .map(|line| format!("{}> {}{}", bs, be, line))
91                    .join("\n")
92            }
93            #[cfg(feature = "callout")]
94            Self::Callout(Callout {
95                kind,
96                fold,
97                title,
98                values,
99                ..
100            }) => {
101                let (bs, be) = &theme.blockquote_marker;
102                let fold = fold.map(String::from).unwrap_or_default();
103                let header = match title.as_deref() {
104                    Some(t) if !t.is_empty() => format!("[!{}]{} {}", kind, fold, t),
105                    _ => format!("[!{}]{}", kind, fold),
106                };
107                let header_line = format!("{}> {}{}", bs, be, header);
108                if values.is_empty() {
109                    return header_line;
110                }
111                let body = render_values_block(values, options, theme);
112                if body.trim().is_empty() {
113                    header_line
114                } else {
115                    let body_lines = body
116                        .split('\n')
117                        .map(|line| format!("{}> {}{}", bs, be, line))
118                        .join("\n");
119                    format!("{}\n{}", header_line, body_lines)
120                }
121            }
122            #[cfg(feature = "embed")]
123            Self::Embed(Embed { target, display, .. }) => match display.as_deref() {
124                Some(d) if !d.is_empty() => format!("![[{}|{}]]", target, d),
125                _ => format!("![[{}]]", target),
126            },
127            Self::Code(Code {
128                value,
129                lang,
130                fence,
131                meta,
132                position,
133            }) => {
134                let (cs, ce) = &theme.code;
135                if lang.is_some() || *fence {
136                    let meta = meta.as_deref().map(|meta| format!(" {}", meta)).unwrap_or_default();
137                    let info = format!("{}{}", lang.as_deref().unwrap_or(""), meta);
138                    // Empty body skips the content line so it doesn't gain a blank one.
139                    let fence_str = code_fence(value, &info);
140                    if value.is_empty() {
141                        // Blank lines are not in the value, but the lines of the block tell of them.
142                        let blank = position
143                            .as_ref()
144                            .map_or(0, |p| p.end.line.saturating_sub(p.start.line).saturating_sub(1));
145                        format!(
146                            "{}{}{}\n{}{}{}",
147                            cs,
148                            fence_str,
149                            info,
150                            "\n".repeat(blank as usize),
151                            fence_str,
152                            ce
153                        )
154                    } else {
155                        format!("{}{}{}\n{}\n{}{}", cs, fence_str, info, value, fence_str, ce)
156                    }
157                } else {
158                    value.lines().map(|line| format!("{}    {}{}", cs, line, ce)).join("\n")
159                }
160            }
161            Self::Definition(Definition {
162                ident,
163                label,
164                url,
165                title,
166                ..
167            }) => {
168                let (us, ue) = &theme.link_url;
169                format!(
170                    "[{}]: {}{}{}{}",
171                    definition_label(label.as_deref(), ident),
172                    us,
173                    url.to_string_with(options),
174                    ue,
175                    title
176                        .as_ref()
177                        .map(|title| format!(" {}", title.to_string_with(options)))
178                        .unwrap_or_default()
179                )
180            }
181            Self::Delete(Delete { values, .. }) => {
182                let (ds, de) = &theme.delete;
183                format!("{}~~{}~~{}", ds, render_values(values, options, theme), de)
184            }
185            Self::Emphasis(Emphasis { values, .. }) => {
186                render_emphasis(values, emphasis_delimiter(values), options, theme)
187            }
188            Self::Footnote(Footnote { values, ident, .. }) => {
189                format!(
190                    "[^{}]: {}",
191                    escape_brackets(ident),
192                    render_values(values, options, theme)
193                )
194            }
195            Self::FootnoteRef(FootnoteRef { label, ident, .. }) => {
196                format!("[^{}]", reference_label(label.as_deref(), ident))
197            }
198            Self::Heading(Heading { depth, values, .. }) => {
199                let (hs, he) = &theme.heading;
200                let text = render_values(values, options, theme);
201                // A line ending at either end is not part of the heading text, so it is written as a
202                // character reference.
203                let text = {
204                    let inner = text.trim_matches('\n');
205                    let leading = text.len() - text.trim_start_matches('\n').len();
206                    let trailing = text.len() - text.trim_end_matches('\n').len();
207                    if inner.is_empty() || (leading == 0 && trailing == 0) {
208                        text.clone()
209                    } else {
210                        format!("{}{}{}", "&#10;".repeat(leading), inner, "&#10;".repeat(trailing))
211                    }
212                };
213                // Multi-line content must stay setext for depths 1-2; ATX has no setext form.
214                if text.contains('\n') && *depth <= HeadingDepth::H2 {
215                    let underline = if *depth == HeadingDepth::H1 { "===" } else { "---" };
216                    format!("{}{}\n{}{}", hs, text, underline, he)
217                } else {
218                    // A trailing `#` run reads back as an ATX closing sequence and gets
219                    // stripped as syntax rather than kept as heading text.
220                    let text = text.replace('\n', " ");
221                    // Positioned text already escaped its hash; literal text keeps its own backslashes.
222                    let last_is_positioned_text =
223                        matches!(values.last(), Some(Self::Text(Text { position: Some(_), .. })));
224                    let text = escape_trailing_hashes(text, last_is_positioned_text);
225                    format!("{}{} {}{}", hs, "#".repeat(usize::from(depth.get())), text, he)
226                }
227            }
228            Self::Html(Html { value, .. }) => {
229                let (hs, he) = &theme.html;
230                format!("{}{}{}", hs, value, he)
231            }
232            Self::Image(Image { alt, url, title, .. }) => {
233                let (is, ie) = &theme.image;
234                format!(
235                    "{}![{}]({}{}){}",
236                    is,
237                    escape_label(alt),
238                    render_link_destination(url, &options.link_url_style),
239                    title
240                        .as_deref()
241                        .map(|it| format!(" {}", render_link_title(it, &options.link_title_style)))
242                        .unwrap_or_default(),
243                    ie
244                )
245            }
246            // Shortcut is safe only if `alt` normalizes back to `ident`; `ident` is raw
247            // (already correctly escaped), so escape_label would double it up.
248            Self::ImageRef(ImageRef { alt, ident, label, .. }) => {
249                let (is, ie) = &theme.image;
250                let mismatched = crate::parser::normalize(alt) != ident.as_str();
251                if mismatched || needs_broad_escaping(alt) {
252                    format!(
253                        "{}![{}][{}]{}",
254                        is,
255                        escape_label(alt),
256                        reference_label(label.as_deref(), ident),
257                        ie
258                    )
259                } else {
260                    format!("{}![{}]{}", is, escape_label(alt), ie)
261                }
262            }
263            Self::CodeInline(CodeInline { value, .. }) => {
264                let (cs, ce) = &theme.code_inline;
265                let fence = code_span_fence(value);
266                // Padding avoids fusing with an edge backtick and protects a genuine
267                // leading+trailing space from the parser's own space-stripping rule.
268                let all_spaces = value.chars().all(|c| c == ' ');
269                if value.starts_with('`')
270                    || value.ends_with('`')
271                    || (!all_spaces && value.starts_with(' ') && value.ends_with(' '))
272                {
273                    format!("{}{} {} {}{}", cs, fence, value, fence, ce)
274                } else {
275                    format!("{}{}{}{}{}", cs, fence, value, fence, ce)
276                }
277            }
278            Self::MathInline(MathInline { value, .. }) => {
279                let (ms, me) = &theme.math;
280                let fence = math_span_fence(value);
281                // Padding keeps a dollar sign at an end from fusing with the fence, and a genuine space at
282                // both ends from being removed when it is read.
283                let all_spaces = value.chars().all(|c| c == ' ');
284                if value.starts_with('$')
285                    || value.ends_with('$')
286                    || (!all_spaces && value.starts_with(' ') && value.ends_with(' '))
287                {
288                    format!("{}{} {} {}{}", ms, fence, value, fence, me)
289                } else {
290                    format!("{}{}{}{}{}", ms, fence, value, fence, me)
291                }
292            }
293            Self::Link(Link { url, title, values, .. }) => {
294                let (ls, le) = &theme.link;
295                if title.is_none()
296                    && let Some(target) = autolink_target(url.as_str(), values)
297                {
298                    return format!("{ls}<{target}>{le}");
299                }
300                format!(
301                    "{}[{}]({}{}){}",
302                    ls,
303                    render_values(values, options, theme),
304                    url.to_string_with(options),
305                    title
306                        .as_ref()
307                        .map(|title| format!(" {}", title.to_string_with(options)))
308                        .unwrap_or_default(),
309                    le
310                )
311            }
312            #[cfg(feature = "wikilink")]
313            Self::WikiLink(WikiLink { target, text, .. }) => {
314                let (ls, le) = &theme.link;
315                match text.as_deref() {
316                    Some(t) if t != target.as_str() => format!("{}[[{}|{}]]{}", ls, target, t, le),
317                    _ => format!("{}[[{}]]{}", ls, target, le),
318                }
319            }
320            // Same reasoning as ImageRef, plus the same broad-escaping fallback.
321            Self::LinkRef(LinkRef {
322                values, ident, label, ..
323            }) => {
324                let (ls, le) = &theme.link;
325                let rendered = render_values(values, options, theme);
326                let plain = values_to_value(values);
327                // The label of a shortcut reference is its text as written, markup included.
328                let written = render_values(values, options, &ColorTheme::PLAIN);
329                let mismatched = crate::parser::normalize(&written) != ident.as_str();
330
331                if mismatched || needs_broad_escaping(&plain) {
332                    format!(
333                        "{}[{}][{}]{}",
334                        ls,
335                        rendered,
336                        reference_label(label.as_deref(), ident),
337                        le
338                    )
339                } else {
340                    format!("{}[{}]{}", ls, rendered, le)
341                }
342            }
343            Self::Math(Math { value, .. }) => {
344                let (ms, me) = &theme.math;
345                let fence = "$".repeat((longest_run(value, '$') + 1).max(2));
346                if value.is_empty() {
347                    format!("{}{}\n{}{}", ms, fence, fence, me)
348                } else {
349                    format!("{}{}\n{}\n{}{}", ms, fence, value, fence, me)
350                }
351            }
352            // Only escape text parsed from real markdown (has a position); programmatic
353            // values like JSON output or attr lookups must stay untouched.
354            Self::Text(Text { value, position }) => {
355                if position.is_some() {
356                    escape_text_with(value.clone(), options.mdx)
357                } else {
358                    value.clone()
359                }
360            }
361            Self::MdxFlowExpression(mdx_flow_expression) => {
362                format!("{{{}}}", indent_expression(&mdx_flow_expression.value))
363            }
364            Self::MdxJsxFlowElement(mdx_jsx_flow_element) => {
365                let name = mdx_jsx_flow_element.name.as_deref().unwrap_or_default();
366                let attributes = if mdx_jsx_flow_element.attributes.is_empty() {
367                    "".to_string()
368                } else {
369                    format!(
370                        " {}",
371                        mdx_jsx_flow_element
372                            .attributes
373                            .iter()
374                            .map(Self::mdx_attribute_content_to_string)
375                            .join(" ")
376                    )
377                };
378
379                if mdx_jsx_flow_element.children.is_empty() {
380                    // A fragment has no self-closing form.
381                    if name.is_empty() {
382                        format!("<{}></>", attributes)
383                    } else {
384                        format!("<{}{} />", name, attributes,)
385                    }
386                } else {
387                    // Each tag and the children sit on their own lines, or the children would read as
388                    // inline content of the tag.
389                    let children = render_values_block(&mdx_jsx_flow_element.children, options, theme);
390                    // The lines of an expression are indented as they are written, which indenting them
391                    // again would add to each time they are read.
392                    if HTML_TARGET.get() {
393                        // Blank lines end the tags as HTML blocks, so the children are Markdown.
394                        return format!("<{}{}>\n\n{}\n\n</{}>", name, attributes, children, name);
395                    }
396                    let children = if mdx_jsx_flow_element.children.iter().any(has_multiline_expression) {
397                        children
398                    } else {
399                        indent_continuation(&format!("  {}", children), 2)
400                    };
401                    format!("<{}{}>\n{}\n</{}>", name, attributes, children, name)
402                }
403            }
404            Self::MdxJsxTextElement(mdx_jsx_text_element) => {
405                let name = mdx_jsx_text_element.name.as_deref().unwrap_or_default();
406                let attributes = if mdx_jsx_text_element.attributes.is_empty() {
407                    "".to_string()
408                } else {
409                    format!(
410                        " {}",
411                        mdx_jsx_text_element
412                            .attributes
413                            .iter()
414                            .map(Self::mdx_attribute_content_to_string)
415                            .join(" ")
416                    )
417                };
418
419                if mdx_jsx_text_element.children.is_empty() {
420                    // A fragment has no self-closing form.
421                    if name.is_empty() {
422                        format!("<{}></>", attributes)
423                    } else {
424                        format!("<{}{} />", name, attributes,)
425                    }
426                } else {
427                    format!(
428                        "<{}{}>{}</{}>",
429                        name,
430                        attributes,
431                        render_values(&mdx_jsx_text_element.children, options, theme),
432                        name
433                    )
434                }
435            }
436            Self::MdxTextExpression(mdx_text_expression) => {
437                format!("{{{}}}", indent_expression(&mdx_text_expression.value))
438            }
439            Self::MdxJsEsm(mdxjs_esm) => mdxjs_esm.value.to_string(),
440            Self::Strong(Strong { values, .. }) => render_strong(values, "**", options, theme),
441            Self::Yaml(Yaml { value, .. }) => {
442                let (fs, fe) = &theme.frontmatter;
443                format!("{}---\n{}\n---{}", fs, value, fe)
444            }
445            Self::Toml(Toml { value, .. }) => {
446                let (fs, fe) = &theme.frontmatter;
447                format!("{}+++\n{}\n+++{}", fs, value, fe)
448            }
449            Self::Break(_) => "\\\n".to_string(),
450            Self::HorizontalRule(HorizontalRule { marker, .. }) => {
451                let (hs, he) = &theme.horizontal_rule;
452                let marker = match marker {
453                    Some(HorizontalRuleMarker::Dash) => '-',
454                    Some(HorizontalRuleMarker::Underscore) => '_',
455                    _ => '*',
456                };
457                format!("{hs}{marker}{marker}{marker}{he}")
458            }
459            Self::Fragment(Fragment { values }) => values
460                .iter()
461                .filter(|value| !value.is_empty() && !value.is_empty_fragment())
462                .map(|value| value.render_with_theme(options, theme))
463                .join("\n"),
464            Self::Empty => String::new(),
465        }
466    }
467
468    fn mdx_attribute_content_to_string(attr: &MdxAttributeContent) -> SmolStr {
469        match attr {
470            MdxAttributeContent::Expression(value) => format!("{{{}}}", indent_expression(value)).into(),
471            MdxAttributeContent::Property(property) => match &property.value {
472                Some(value) => match value {
473                    MdxAttributeValue::Expression(value) => {
474                        format!("{}={{{}}}", property.name, indent_expression(value)).into()
475                    }
476                    MdxAttributeValue::Literal(literal) => {
477                        format!("{}={}", property.name, quote_attribute_value(literal)).into()
478                    }
479                },
480                None => property.name.clone(),
481            },
482        }
483    }
484}
485
486/// Whether `node` or a node in it is an expression of more than one line.
487fn has_multiline_expression(node: &Node) -> bool {
488    match node {
489        Node::MdxFlowExpression(expression) => expression.value.contains('\n'),
490        Node::MdxTextExpression(expression) => expression.value.contains('\n'),
491        Node::MdxJsxTextElement(MdxJsxTextElement { attributes, .. })
492        | Node::MdxJsxFlowElement(MdxJsxFlowElement { attributes, .. })
493            if attributes.iter().any(|attribute| match attribute {
494                MdxAttributeContent::Expression(value) => value.contains('\n'),
495                MdxAttributeContent::Property(MdxJsxAttribute {
496                    value: Some(MdxAttributeValue::Expression(value)),
497                    ..
498                }) => value.contains('\n'),
499                _ => false,
500            }) =>
501        {
502            true
503        }
504        other => other.children().iter().any(has_multiline_expression),
505    }
506}
507
508/// Quotes the value of a JSX attribute with the quote it does not contain. Character references that the
509/// value holds as text are written with their `&` as a reference.
510fn quote_attribute_value(value: &str) -> String {
511    let mut escaped = String::with_capacity(value.len());
512    for (index, c) in value.char_indices() {
513        if c == '&' && starts_reference(&value[index + 1..]) {
514            escaped.push_str("&amp;");
515        } else {
516            escaped.push(c);
517        }
518    }
519    if !escaped.contains('"') {
520        format!("\"{escaped}\"")
521    } else if !escaped.contains('\'') {
522        format!("'{escaped}'")
523    } else {
524        format!("\"{}\"", escaped.replace('"', "&quot;"))
525    }
526}
527
528/// The content of an expression as it is written: the lines after the first are indented, as the
529/// indentation of up to two characters is removed from them when they are read.
530fn indent_expression(value: &str) -> String {
531    value
532        .split('\n')
533        .enumerate()
534        .map(|(index, line)| {
535            if index == 0 || line.is_empty() || line == "\r" {
536                line.to_string()
537            } else {
538                format!("  {line}")
539            }
540        })
541        .collect::<Vec<_>>()
542        .join("\n")
543}
544
545pub(crate) fn values_to_string(values: &[Node], options: &RenderOptions) -> String {
546    render_values(values, options, &ColorTheme::PLAIN)
547}
548
549/// Indents every line, the first included, by `width` spaces, except empty ones.
550pub(crate) fn indent_lines(content: &str, width: usize) -> String {
551    let pad = " ".repeat(width);
552    content
553        .split('\n')
554        .map(|line| {
555            if line.is_empty() {
556                line.to_string()
557            } else {
558                format!("{pad}{line}")
559            }
560        })
561        .collect::<Vec<_>>()
562        .join("\n")
563}
564
565/// Indents every line after the first by `width` spaces, except empty ones.
566fn indent_continuation(content: &str, width: usize) -> String {
567    let Some((first, rest)) = content.split_once('\n') else {
568        return content.to_string();
569    };
570    let pad = " ".repeat(width);
571    let mut result = String::with_capacity(content.len() + width * 2);
572    result.push_str(first);
573    for line in rest.split('\n') {
574        result.push('\n');
575        if !line.is_empty() {
576            result.push_str(&pad);
577            result.push_str(line);
578        }
579    }
580    result
581}
582
583/// The delimiter of emphasis around `values`. Emphasis nested at an edge takes the other one, or the
584/// two runs fuse into `**` and read back as strong emphasis.
585fn emphasis_delimiter(values: &[Node]) -> &'static str {
586    let edge = [values.first(), values.last()]
587        .into_iter()
588        .flatten()
589        .find_map(|node| match node {
590            Node::Emphasis(Emphasis { values, .. }) => Some(values),
591            _ => None,
592        });
593    match edge.map(|inner| emphasis_delimiter(inner)) {
594        Some("_") => "*",
595        Some(_) => "_",
596        None => "*",
597    }
598}
599
600/// Renders strong emphasis around `values` with the delimiter `delim`.
601fn render_strong(values: &[Node], delim: &str, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
602    let (ss, se) = &theme.strong;
603    let last = values.len().saturating_sub(1);
604    let content = values
605        .iter()
606        .enumerate()
607        .map(|(index, value)| match value {
608            // Emphasis at an end uses the other delimiter, or `*` and `**` fuse into `***`.
609            // An underscore does not open or close next to a letter or digit, so those keep `*`.
610            Node::Emphasis(Emphasis { values: inner, .. })
611                if (index == 0 || index == last)
612                    && !index
613                        .checked_sub(1)
614                        .is_some_and(|before| ends_with_word_char(&values[before]))
615                    && !values.get(index + 1).is_some_and(starts_with_word_char) =>
616            {
617                render_emphasis(inner, "_", options, theme)
618            }
619            value => value.render_with_theme(options, theme),
620        })
621        .collect::<String>();
622    format!("{ss}{delim}{content}{delim}{se}")
623}
624
625fn render_emphasis(values: &[Node], delim: &str, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
626    let (es, ee) = &theme.emphasis;
627    format!("{es}{delim}{}{delim}{ee}", render_values(values, options, theme))
628}
629
630/// Renders the content of a table cell on one line. A line break becomes `<br>`, and a pipe that is not
631/// escaped yet, as in code, would end the cell.
632pub(crate) fn render_cell_values(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
633    let mut rendered = render_values(values, options, theme);
634    if rendered.contains(['\n', '\r']) {
635        let flattened: Vec<Node> = values.iter().map(flatten_inline_code_lines).collect();
636        rendered = render_values(&flattened, options, theme);
637    }
638    if !rendered.contains(['|', '\n', '\r']) {
639        return rendered;
640    }
641    let mut result = String::with_capacity(rendered.len() + 4);
642    let mut escaped = false;
643    let mut chars = rendered.chars().peekable();
644    while let Some(c) = chars.next() {
645        match c {
646            '\r' | '\n' => {
647                if c == '\r' && chars.peek() == Some(&'\n') {
648                    chars.next();
649                }
650                // The backslash of a hard break would escape the `<`.
651                if escaped {
652                    result.pop();
653                }
654                result.push_str("<br>");
655                escaped = false;
656                continue;
657            }
658            '|' if !escaped => result.push('\\'),
659            _ => {}
660        }
661        escaped = c == '\\' && !escaped;
662        result.push(c);
663    }
664    result
665}
666
667/// Replaces line endings in inline code and math with spaces, as HTML does, so `<br>` never lands inside a span.
668fn flatten_inline_code_lines(node: &Node) -> Node {
669    let flat = |value: &SmolStr| -> Option<SmolStr> {
670        value
671            .contains(['\n', '\r'])
672            .then(|| value.replace("\r\n", " ").replace(['\n', '\r'], " ").into())
673    };
674    let flat_all = |values: &[Node]| values.iter().map(flatten_inline_code_lines).collect::<Vec<_>>();
675    match node {
676        Node::CodeInline(n) => match flat(&n.value) {
677            Some(value) => Node::CodeInline(CodeInline { value, ..n.clone() }),
678            None => node.clone(),
679        },
680        Node::MathInline(n) => match flat(&n.value) {
681            Some(value) => Node::MathInline(MathInline { value, ..n.clone() }),
682            None => node.clone(),
683        },
684        Node::Strong(n) => Node::Strong(Strong {
685            values: flat_all(&n.values),
686            ..n.clone()
687        }),
688        Node::Emphasis(n) => Node::Emphasis(Emphasis {
689            values: flat_all(&n.values),
690            ..n.clone()
691        }),
692        Node::Delete(n) => Node::Delete(Delete {
693            values: flat_all(&n.values),
694            ..n.clone()
695        }),
696        Node::Link(n) => Node::Link(Link {
697            values: flat_all(&n.values),
698            ..n.clone()
699        }),
700        _ => node.clone(),
701    }
702}
703
704fn ends_with_word_char(node: &Node) -> bool {
705    matches!(node, Node::Text(Text { value, .. }) if value.ends_with(|c: char| c.is_alphanumeric()))
706}
707
708fn starts_with_word_char(node: &Node) -> bool {
709    matches!(node, Node::Text(Text { value, .. }) if value.starts_with(|c: char| c.is_alphanumeric()))
710}
711
712/// Whether `second` starts where `first` ends, so the two are written next to each other.
713/// Nodes without positions are taken to touch.
714fn touches(first: &Node, second: &Node) -> bool {
715    match (first.position(), second.position()) {
716        (Some(first), Some(second)) => first.end == second.start,
717        _ => true,
718    }
719}
720
721/// Renders `value`, escaping a `!` that ends its text when `next` starts a link, which would make an image.
722///
723/// `previous` is what this function returned for the last of `before`, with `value` as `next`.
724pub(crate) fn render_before(
725    value: &Node,
726    before: &[Node],
727    previous: Option<&str>,
728    next: Option<&Node>,
729    options: &RenderOptions,
730    theme: &ColorTheme<'_>,
731) -> String {
732    // Emphasis right after other emphasis takes the other delimiter, or the two fuse into one run.
733    if let Node::Emphasis(Emphasis { values, .. }) = value
734        && matches!(before.last(), Some(Node::Emphasis(_) | Node::Strong(_)))
735        && before.last().is_some_and(|last| touches(last, value))
736        && !matches!(values.first(), Some(Node::Emphasis(_)))
737        && !matches!(values.last(), Some(Node::Emphasis(_)))
738        && !next.is_some_and(|next| touches(value, next) && starts_with_word_char(next))
739    {
740        let delim = if previous.is_some_and(|previous| previous.ends_with('_')) {
741            "*"
742        } else {
743            "_"
744        };
745        return render_emphasis(values, delim, options, theme);
746    }
747    // Strong right after emphasis that ends in `*` takes `__`, or the runs of `*` fuse.
748    if let Node::Strong(Strong { values, .. }) = value
749        && matches!(before.last(), Some(Node::Emphasis(_) | Node::Strong(_)))
750        && before.last().is_some_and(|last| touches(last, value))
751        && !next.is_some_and(|next| touches(value, next) && starts_with_word_char(next))
752        && previous.is_some_and(|previous| previous.ends_with('*'))
753    {
754        return render_strong(values, "__", options, theme);
755    }
756    // A reference followed by a colon at the start of a line would read back as a definition.
757    let after_reference = matches!(before.last(), Some(Node::LinkRef(_) | Node::FootnoteRef(_)))
758        && before.last().is_some_and(|last| touches(last, value));
759    let mut rendered = value.render_with_theme(options, theme);
760    let starts_link = next.is_some_and(|next| touches(value, next))
761        && match next {
762            Some(Node::Link(_) | Node::LinkRef(_)) => true,
763            #[cfg(feature = "wikilink")]
764            Some(Node::WikiLink(_)) => true,
765            _ => false,
766        };
767    if after_reference && matches!(value, Node::Text(_)) && rendered.starts_with(':') {
768        rendered.insert(0, '\\');
769    }
770    if starts_link && matches!(value, Node::Text(Text { position: Some(_), .. })) && rendered.ends_with('!') {
771        rendered.insert(rendered.len() - 1, '\\');
772    }
773    rendered
774}
775
776pub(crate) fn render_values(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
777    let mut pre_position: Option<Position> = None;
778    let mut previous: Option<String> = None;
779    values
780        .iter()
781        .enumerate()
782        .map(|(index, value)| {
783            let raw = render_before(
784                value,
785                &values[..index],
786                previous.as_deref(),
787                values.get(index + 1),
788                options,
789                theme,
790            );
791            let rendered = || raw.as_str();
792            if let Some(pos) = value.position() {
793                let new_line_count = pre_position
794                    .as_ref()
795                    .map(|p: &Position| pos.start.line.saturating_sub(p.end.line))
796                    .unwrap_or_default();
797
798                let space = if new_line_count > 0
799                    && pre_position
800                        .as_ref()
801                        .map(|p| pos.start.line > p.end.line)
802                        .unwrap_or_default()
803                {
804                    " ".repeat(pos.start.column.saturating_sub(1) as usize)
805                } else {
806                    "".to_string()
807                };
808
809                pre_position = Some(pos);
810
811                let piece = if space.is_empty() {
812                    format!("{}{}", "\n".repeat(new_line_count as usize), rendered())
813                } else {
814                    format!(
815                        "{}{}",
816                        "\n".repeat(new_line_count as usize),
817                        rendered().lines().map(|line| format!("{}{}", space, line)).join("\n")
818                    )
819                };
820                previous = Some(raw);
821                piece
822            } else {
823                pre_position = None;
824                let piece = raw.clone();
825                previous = Some(raw);
826                piece
827            }
828        })
829        .collect::<String>()
830}
831
832/// The number of line endings to write before `node` after `previous`, raised to a blank line where
833/// the node would otherwise read back as part of `previous`.
834pub(crate) fn separated_from(count: u32, previous: Option<&Node>, node: &Node, rendered: &str) -> u32 {
835    if count >= 2 {
836        return count;
837    }
838    // A single line ending after a block quote reads back as lazy continuation, unless the node
839    // opens with a fence, which ends the quote.
840    let fenced = matches!(node, Node::Code(Code { lang, fence, .. }) if lang.is_some() || *fence);
841    let lazy = previous.is_some_and(Node::is_blockquote_like) && !fenced;
842    // A line of dashes right under paragraph text reads back as a setext heading.
843    let setext = matches!(node, Node::HorizontalRule(_))
844        && rendered.starts_with("---")
845        && previous.is_some_and(Node::is_paragraph_text);
846    // A footnote ends where the next line starts, so a block after it needs a blank line.
847    let footnote = matches!(previous, Some(Node::Footnote(_))) && !matches!(node, Node::Footnote(_));
848    if lazy || setext || footnote { 2 } else { count }
849}
850
851/// Writes an item, or the rest of one that follows the items nested in it, inside a container.
852///
853/// `indents` holds the column of the content of each open item. It is kept out of the container loop
854/// so that the frame of that recursion stays small.
855#[inline(never)]
856fn render_list_item(
857    node: &Node,
858    item: &List,
859    rest: bool,
860    indents: &mut Vec<usize>,
861    options: &RenderOptions,
862    theme: &ColorTheme<'_>,
863) -> String {
864    if rest {
865        // Indented to the content of the item and written without a marker.
866        indents.truncate(item.level as usize + 1);
867        let indent = indents.last().copied().unwrap_or(0);
868        return indent_lines(&render_values_block(&item.values, options, theme), indent);
869    }
870    // Nested items are indented to the content of the item that holds them.
871    indents.truncate(item.level as usize);
872    let own_indent = indents.last().copied().unwrap_or(0);
873    let delta = own_indent as isize - item.level as isize * 2;
874    indents.push(own_indent + list_own_prefix_width(item.ordered, item.index, item.start));
875    reindent_all_lines(&node.render_with_theme(options, theme), delta)
876}
877
878/// Writes what separates `node` from the one written before it, and trims `rendered` when it follows
879/// the marker that holds it. Not inlined, to keep the frame of the container loop small.
880#[inline(never)]
881fn separate(
882    result: &mut String,
883    rendered: &mut String,
884    pre_position: &mut Option<Position>,
885    position: Option<Position>,
886    previous: Option<&Node>,
887    node: &Node,
888) {
889    if let Some(pos) = position {
890        let new_line_count = pre_position
891            .as_ref()
892            .map(|p: &Position| pos.start.line.saturating_sub(p.end.line))
893            .unwrap_or_default();
894        let new_line_count = separated_from(new_line_count, previous, node, rendered);
895        *pre_position = Some(pos);
896        result.push_str(&"\n".repeat(new_line_count as usize));
897        // An item that starts on the line of the marker that holds it follows it directly.
898        if new_line_count == 0 && matches!((previous, node), (Some(Node::List(_)), Node::List(_))) {
899            *rendered = rendered.trim_start().to_string();
900        }
901    } else {
902        // Text never follows text inside one paragraph, so without positions that is a new one.
903        if pre_position.is_none() && matches!((previous, node), (Some(Node::Text(_)), Node::Text(_))) {
904            result.push_str("\n\n");
905        }
906        *pre_position = None;
907    }
908}
909
910/// Like `render_values` but without column-offset–based indentation.
911///
912/// Inside blockquotes and callouts, node positions include the `> ` prefix offset,
913/// so applying column-based spacing causes double-indentation. This variant preserves
914/// blank lines between values (via newline counting) but ignores the column position.
915pub(crate) fn render_values_block(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
916    // The children of an item that come after the items nested in it, as at the top level.
917    let reordered = crate::markdown::list_order::reorder(values);
918    let (values, continuation) = match &reordered {
919        Some(reordered) => (reordered.nodes.as_slice(), reordered.continuation.as_slice()),
920        None => (values, [].as_slice()),
921    };
922    let mut result = String::new();
923    let mut pre_position: Option<Position> = None;
924    let mut index = 0;
925    // The column of the content of the open items, one for each level.
926    let mut list_indent_stack: Vec<usize> = Vec::new();
927    // The last node written, to tell paragraphs from the inline nodes of one when there are no positions.
928    let mut previous: Option<&Node> = None;
929    // What `render_before` returned for `previous`, or `None` when it is part of a table.
930    let mut previous_rendered: Option<String> = None;
931
932    while index < values.len() {
933        let first = &values[index];
934        // The cells of a table are laid out together, as at the top level.
935        let (mut rendered, position, next) = if is_table_part(first) {
936            list_indent_stack.clear();
937            render_table_run(values, index, options, theme)
938        } else if let Node::List(item) = first {
939            let rest = continuation.get(index) == Some(&true);
940            (
941                render_list_item(first, item, rest, &mut list_indent_stack, options, theme),
942                first.position(),
943                index + 1,
944            )
945        } else {
946            list_indent_stack.clear();
947            (
948                render_before(
949                    first,
950                    &values[..index],
951                    previous_rendered.as_deref(),
952                    values.get(index + 1),
953                    options,
954                    theme,
955                ),
956                first.position(),
957                index + 1,
958            )
959        };
960        index = next;
961
962        separate(&mut result, &mut rendered, &mut pre_position, position, previous, first);
963        previous = Some(&values[index - 1]);
964        result.push_str(&rendered);
965        previous_rendered = (!is_table_part(first)).then_some(rendered);
966    }
967    result
968}
969
970fn is_table_part(node: &Node) -> bool {
971    matches!(node, Node::TableCell(_) | Node::TableAlign(_))
972}
973
974/// Renders the cells and the delimiter row from `values[index]` on as one table, with its position and
975/// the index after it. Apart from the recursion, so that nesting does not pay for its locals.
976#[inline(never)]
977fn render_table_run(
978    values: &[Node],
979    index: usize,
980    options: &RenderOptions,
981    theme: &ColorTheme<'_>,
982) -> (String, Option<Position>, usize) {
983    let end = values[index..]
984        .iter()
985        .position(|node| !is_table_part(node))
986        .map_or(values.len(), |offset| index + offset);
987    let run = &values[index..end];
988    let table = crate::Markdown {
989        nodes: run.to_vec(),
990        options: options.clone(),
991    };
992    let position = match (run[0].position(), run[run.len() - 1].position()) {
993        (Some(first), Some(last)) => Some(Position {
994            start: first.start,
995            end: last.end,
996        }),
997        _ => None,
998    };
999    (
1000        table.render_with_theme(theme).trim_end_matches('\n').to_string(),
1001        position,
1002        end,
1003    )
1004}
1005
1006/// Renders a link/image destination, auto-upgrading to `<...>` (escaping `\ < >`)
1007/// when the bare form would be unsafe (empty, or contains whitespace/control/`< >`);
1008/// otherwise bare, escaping `\ ( )` since unescaped parens must balance.
1009pub(super) fn render_link_destination(url: &str, style: &UrlSurroundStyle) -> String {
1010    let needs_angle = url.is_empty()
1011        || url
1012            .chars()
1013            .any(|c| c.is_whitespace() || c.is_control() || c == '<' || c == '>');
1014
1015    if matches!(style, UrlSurroundStyle::Angle) || needs_angle {
1016        let mut result = String::with_capacity(url.len() + 2);
1017        result.push('<');
1018        for c in url.chars() {
1019            if matches!(c, '\\' | '<' | '>') {
1020                result.push('\\');
1021            }
1022            result.push(c);
1023        }
1024        result.push('>');
1025        result
1026    } else {
1027        let mut result = String::with_capacity(url.len());
1028        for c in url.chars() {
1029            if matches!(c, '\\' | '(' | ')') {
1030                result.push('\\');
1031            }
1032            result.push(c);
1033        }
1034        result
1035    }
1036}
1037
1038/// Renders a link/image title, escaping `\` and the style's delimiter(s) so the
1039/// title's own quote/paren characters can't end it early.
1040pub(super) fn render_link_title(title: &str, style: &TitleSurroundStyle) -> String {
1041    let (open, close, delims): (char, char, &[char]) = match style {
1042        TitleSurroundStyle::Double => ('"', '"', &['"']),
1043        TitleSurroundStyle::Single => ('\'', '\'', &['\'']),
1044        TitleSurroundStyle::Paren => ('(', ')', &['(', ')']),
1045    };
1046    let mut result = String::with_capacity(title.len() + 2);
1047    result.push(open);
1048    for c in title.chars() {
1049        if c == '\\' || delims.contains(&c) {
1050            result.push('\\');
1051        }
1052        result.push(c);
1053    }
1054    result.push(close);
1055    result
1056}
1057
1058/// Escapes `\ [ ]` in reference labels/idents and image alt text: plain strings
1059/// (not walked as inline nodes) that still sit inside `[...]` syntax.
1060/// True if `s` needs escaping beyond `escape_label`'s narrow `\ [ ]` set: unsafe
1061/// for a reference's implicit shortcut form, since the definition's label won't match.
1062fn needs_broad_escaping(s: &str) -> bool {
1063    s.bytes().any(|b| {
1064        matches!(
1065            b,
1066            b'`' | b'*' | b'_' | b'|' | b'~' | b'$' | b'#' | b'-' | b'+' | b'>' | b'=' | b'.' | b')' | b'!'
1067        )
1068    })
1069}
1070
1071/// Shifts every line's leading indentation by `delta` spaces (never below zero),
1072/// leaving each line's own content untouched.
1073pub(crate) fn reindent_all_lines(content: &str, delta: isize) -> String {
1074    if delta == 0 {
1075        return content.to_string();
1076    }
1077    content
1078        .split('\n')
1079        .map(|line| {
1080            if line.is_empty() {
1081                line.to_string()
1082            } else {
1083                let leading = line.bytes().take_while(|&b| b == b' ').count();
1084                let new_leading = (leading as isize + delta).max(0) as usize;
1085                format!("{}{}", " ".repeat(new_leading), &line[leading..])
1086            }
1087        })
1088        .collect::<Vec<_>>()
1089        .join("\n")
1090}
1091
1092/// The width of a list item's own marker and trailing space (not including ancestor indentation),
1093/// e.g. 2 for `"- "`, 3 for `"1. "`, 4 for `"10. "`. A checkbox is not part of it, as the content of
1094/// the item starts at the checkbox, so children are indented to the marker alone.
1095pub(crate) fn list_own_prefix_width(ordered: bool, index: usize, start: Option<u32>) -> usize {
1096    let marker_len = if ordered {
1097        (start.unwrap_or(1) as usize + index).to_string().chars().count() + 1
1098    } else {
1099        1
1100    };
1101    marker_len + 1
1102}
1103
1104fn escape_trailing_hashes(text: String, last_is_positioned_text: bool) -> String {
1105    let body = text.trim_end_matches('#');
1106    let has_trailing_hash = body.len() < text.len();
1107
1108    if !has_trailing_hash || (last_is_positioned_text && ends_with_escape(body)) {
1109        return text;
1110    }
1111    format!("{body}\\{}", &text[body.len()..])
1112}
1113
1114/// True if `s` ends with an odd run of backslashes, i.e. its last character is escaped.
1115fn ends_with_escape(s: &str) -> bool {
1116    s.bytes().rev().take_while(|&b| b == b'\\').count() % 2 == 1
1117}
1118
1119fn longest_run(s: &str, ch: char) -> usize {
1120    s.split('\n')
1121        .flat_map(|line| line.split(|c| c != ch).map(str::len))
1122        .max()
1123        .unwrap_or(0)
1124}
1125
1126/// Longest fence-char run in `value` + 1 (min 3); switches to tilde when `info`
1127/// has a backtick, since a backtick-fenced info string can't contain one.
1128fn code_fence(value: &str, info: &str) -> String {
1129    if info.contains('`') {
1130        let len = (longest_run(value, '~') + 1).max(3);
1131        "~".repeat(len)
1132    } else {
1133        let len = (longest_run(value, '`') + 1).max(3);
1134        "`".repeat(len)
1135    }
1136}
1137
1138/// The label to write in a definition: the identifier as it was written when the label is only that
1139/// without its escapes and character references, which would not read back as the same identifier.
1140fn definition_label(label: Option<&str>, ident: &str) -> String {
1141    match label {
1142        Some(label) if crate::parser::normalize(label) == ident => escape_label(label),
1143        Some(label) if crate::parser::normalize(label) == crate::parser::normalize(&crate::parser::unescape(ident)) => {
1144            ident.to_string()
1145        }
1146        Some(label) => escape_label(label),
1147        None => ident.to_string(),
1148    }
1149}
1150
1151/// The label to write in the second brackets of a full reference. The label as written is kept when it
1152/// still resolves to `ident`.
1153fn reference_label(label: Option<&str>, ident: &str) -> String {
1154    match label {
1155        Some(label) if crate::parser::normalize(label) == ident => escape_label(label),
1156        _ => ident.to_string(),
1157    }
1158}
1159
1160/// Picks an inline code span delimiter one backtick longer than the longest
1161/// backtick run in `value`, so no run inside it can be mistaken for the closing.
1162fn code_span_fence(value: &str) -> String {
1163    let mut max_run = 0;
1164    let mut cur = 0;
1165    for c in value.chars() {
1166        if c == '`' {
1167            cur += 1;
1168            max_run = max_run.max(cur);
1169        } else {
1170            cur = 0;
1171        }
1172    }
1173    "`".repeat(max_run + 1)
1174}
1175
1176/// The shortest run of dollar signs, from one, that is not the length of a run in `value`, so that no
1177/// run inside a math span can be mistaken for the closing.
1178fn math_span_fence(value: &str) -> String {
1179    let mut lengths = std::collections::HashSet::new();
1180    let mut current = 0;
1181    for c in value.chars() {
1182        if c == '$' {
1183            current += 1;
1184        } else if current > 0 {
1185            lengths.insert(current);
1186            current = 0;
1187        }
1188    }
1189    if current > 0 {
1190        lengths.insert(current);
1191    }
1192    "$".repeat((1..).find(|length| !lengths.contains(length)).unwrap_or(1))
1193}
1194
1195/// Escapes the brackets that are not escaped yet, for an identifier that keeps the escapes it was written with.
1196fn escape_brackets(s: &str) -> String {
1197    let mut result = String::with_capacity(s.len());
1198    let mut chars = s.chars().peekable();
1199    while let Some(c) = chars.next() {
1200        match c {
1201            '\\' if chars.peek().is_some_and(char::is_ascii_punctuation) => {
1202                result.push(c);
1203                result.extend(chars.next());
1204            }
1205            '[' | ']' => {
1206                result.push('\\');
1207                result.push(c);
1208            }
1209            _ => result.push(c),
1210        }
1211    }
1212    result
1213}
1214
1215fn escape_label(s: &str) -> String {
1216    if !s.bytes().any(|b| matches!(b, b'\\' | b'[' | b']')) {
1217        return s.to_string();
1218    }
1219    let mut result = String::with_capacity(s.len());
1220    for c in s.chars() {
1221        if matches!(c, '\\' | '[' | ']') {
1222            result.push('\\');
1223        }
1224        result.push(c);
1225    }
1226    result
1227}
1228
1229/// The text of an autolink for a link whose only content is its own destination, when writing that
1230/// text as a link label would need escapes. A URL in a label is read as it is, so `\_` would stay.
1231fn autolink_target(url: &str, values: &[Node]) -> Option<String> {
1232    let [Node::Text(Text { value, .. })] = values else {
1233        return None;
1234    };
1235    let target = if value == url {
1236        url
1237    } else if url.strip_prefix("mailto:") == Some(value.as_str()) && crate::parser::is_autolink_email(value) {
1238        value.as_str()
1239    } else {
1240        return None;
1241    };
1242    let plain = !target
1243        .chars()
1244        .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>'));
1245    let scheme = target.split_once(':').is_some_and(|(scheme, _)| {
1246        (2..=32).contains(&scheme.len())
1247            && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1248            && scheme
1249                .chars()
1250                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
1251    });
1252    let email = value != url;
1253    (plain && (scheme || email) && escape_text(target.to_string()) != target).then(|| target.to_string())
1254}
1255
1256/// Whether `rest`, the text after an `&`, reads as the rest of a character reference.
1257fn starts_reference(rest: &str) -> bool {
1258    let name = match rest.strip_prefix('#') {
1259        Some(number) => match number.strip_prefix(['x', 'X']) {
1260            Some(hex) => hex
1261                .split_once(';')
1262                .map(|(digits, _)| (digits, char::is_ascii_hexdigit as fn(&char) -> bool)),
1263            None => number
1264                .split_once(';')
1265                .map(|(digits, _)| (digits, char::is_ascii_digit as fn(&char) -> bool)),
1266        },
1267        None => rest
1268            .split_once(';')
1269            .map(|(name, _)| (name, char::is_ascii_alphanumeric as fn(&char) -> bool)),
1270    };
1271    name.is_some_and(|(name, is_valid)| !name.is_empty() && name.chars().all(|c| is_valid(&c)))
1272}
1273
1274fn is_email_local(c: char) -> bool {
1275    c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+')
1276}
1277
1278/// Whether `rest`, the text after an `@`, starts with a domain that makes an email address of the text
1279/// before it.
1280fn is_email_domain(rest: &str) -> bool {
1281    let domain = rest
1282        .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
1283        .next()
1284        .unwrap_or_default();
1285    domain
1286        .split_once('.')
1287        .is_some_and(|(label, after)| !label.is_empty() && after.starts_with(|c: char| c.is_ascii_alphanumeric()))
1288}
1289
1290/// Re-escapes markdown-significant characters so plain text can't be reinterpreted as
1291/// syntax on re-parse. `# - + > =` only unsafe at line start, `. )` only after leading digits;
1292/// a leading `\t` and runs of 2+ `\n` (only possible via decoded entities) use `&#N;` instead.
1293fn escape_text(value: String) -> String {
1294    escape_text_with(value, false)
1295}
1296
1297/// Whether a line-initial `c` followed by `rest` can open a heading, list item, thematic
1298/// break or setext underline. `-10%` and `#tag` stay plain.
1299fn is_block_marker(c: char, rest: &str) -> bool {
1300    match rest.chars().next() {
1301        None | Some(' ' | '\t' | '\n') => true,
1302        Some(next) => matches!(c, '#' | '-' | '=') && next == c,
1303    }
1304}
1305
1306/// Whether `text` starts with the `import ` or `export ` that makes a block ESM in MDX.
1307fn starts_esm(text: &str) -> bool {
1308    text.starts_with("import ") || text.starts_with("export ")
1309}
1310
1311/// `escape_text`, and for MDX also the braces and the `import` or `export` that starts a line.
1312fn escape_text_with(value: String, mdx: bool) -> String {
1313    // Skip the copy when nothing needs escaping; byte scan avoids UTF-8 decoding.
1314    let needs_escaping = value.bytes().any(|b| {
1315        matches!(
1316            b,
1317            b'\\'
1318                | b'`'
1319                | b'*'
1320                | b'_'
1321                | b'['
1322                | b']'
1323                | b'|'
1324                | b'~'
1325                | b'$'
1326                | b'#'
1327                | b'-'
1328                | b'+'
1329                | b'>'
1330                | b'<'
1331                | b'='
1332                | b'.'
1333                | b')'
1334                | b'\n'
1335                | b'\t'
1336                | b'&'
1337                | b'@'
1338        )
1339    });
1340    let mdx_special = mdx && (value.contains('{') || value.contains("import ") || value.contains("export "));
1341    if !needs_escaping && !mdx_special {
1342        return value;
1343    }
1344
1345    let mut result = String::with_capacity(value.len());
1346    let mut at_line_start = true;
1347    // True while in an unbroken digit run since line start (ordered-list marker number).
1348    let mut leading_digits = false;
1349    let mut chars = value
1350        .char_indices()
1351        .map(|(index, c)| (c, &value[index + c.len_utf8()..]))
1352        .peekable();
1353    let mut previous = None;
1354
1355    while let Some((c, rest)) = chars.next() {
1356        match c {
1357            '\n' if chars.peek().is_some_and(|(next, _)| *next == '\n') => {
1358                result.push_str("&#10;");
1359                at_line_start = true;
1360                leading_digits = false;
1361                continue;
1362            }
1363            '\t' if at_line_start => {
1364                result.push_str("&#9;");
1365                at_line_start = false;
1366                leading_digits = false;
1367                continue;
1368            }
1369            '\\' | '`' | '*' | '_' | '[' | ']' | '|' | '~' | '$' | '<' => result.push('\\'),
1370            '{' if mdx => result.push('\\'),
1371            // The first letter as a character reference keeps the line from starting an ESM block.
1372            'i' | 'e' if mdx && at_line_start && starts_esm(&value[value.len() - rest.len() - 1..]) => {
1373                result.push_str(if c == 'i' { "&#105;" } else { "&#101;" });
1374                at_line_start = false;
1375                leading_digits = false;
1376                previous = Some(c);
1377                continue;
1378            }
1379            '>' if at_line_start => result.push('\\'),
1380            '#' | '-' | '+' | '=' if at_line_start && is_block_marker(c, rest) => result.push('\\'),
1381            '.' | ')' if leading_digits => result.push('\\'),
1382            '&' if starts_reference(rest) => result.push('\\'),
1383            '@' if previous.is_some_and(is_email_local) && is_email_domain(rest) => result.push('\\'),
1384            _ => {}
1385        }
1386        result.push(c);
1387        previous = Some(c);
1388
1389        let is_digit = c.is_ascii_digit();
1390        leading_digits = if at_line_start {
1391            is_digit
1392        } else {
1393            leading_digits && is_digit
1394        };
1395        at_line_start = c == '\n';
1396    }
1397
1398    result
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403    use super::*;
1404    use proptest::prelude::*;
1405    use rstest::rstest;
1406
1407    #[rstest]
1408    #[case::heading_marker("## not a heading", "\\## not a heading")]
1409    #[case::heading_seven_hashes_still_escaped("####### x", "\\####### x")]
1410    #[case::emphasis_star("*not emphasis*", "\\*not emphasis\\*")]
1411    #[case::emphasis_underscore("_not emphasis_", "\\_not emphasis\\_")]
1412    #[case::code_span("`not code`", "\\`not code\\`")]
1413    #[case::link_brackets("[not a link](x)", "\\[not a link\\](x)")]
1414    #[case::list_marker("- not a list item", "\\- not a list item")]
1415    #[case::negative_number("-10%", "-10%")]
1416    #[case::hashtag("#tag", "#tag")]
1417    #[case::plus_number("+1", "+1")]
1418    #[case::double_dash("--", "\\--")]
1419    #[case::blockquote_marker("> not a quote", "\\> not a quote")]
1420    #[case::table_pipe("| not a table |", "\\| not a table \\|")]
1421    #[case::strikethrough("~not strikethrough~", "\\~not strikethrough\\~")]
1422    #[case::math("$not math$", "\\$not math\\$")]
1423    #[case::plus_list_marker("+ not a list item", "\\+ not a list item")]
1424    #[case::ordered_list_dot("5. not a list", "5\\. not a list")]
1425    #[case::ordered_list_paren("5) not a list", "5\\) not a list")]
1426    #[case::setext_h1_underline("Foo\n===", "Foo\n\\===")]
1427    #[case::hash_not_at_line_start("a#b", "a#b")]
1428    #[case::dash_not_at_line_start("a-b", "a-b")]
1429    #[case::plus_not_at_line_start("a+b", "a+b")]
1430    #[case::gt_not_at_line_start("a>b", "a>b")]
1431    #[case::eq_not_at_line_start("a=b", "a=b")]
1432    #[case::dot_not_after_leading_digits("a5. b", "a5. b")]
1433    #[case::dot_after_broken_digit_run("5x3. b", "5x3. b")]
1434    #[case::escapes_after_embedded_newline("a\n# b", "a\n\\# b")]
1435    #[case::plain_text_unchanged("plain text", "plain text")]
1436    #[case::literal_backslash_is_doubled("a\\b", "a\\\\b")]
1437    #[case::empty_string("", "")]
1438    #[case::bang_before_bracket_only_bracket_escaped("![bar]", "!\\[bar\\]")]
1439    #[case::bang_at_value_end_not_escaped("foo!", "foo!")]
1440    #[case::consecutive_newlines_become_entity("foo\n\nbar", "foo&#10;\nbar")]
1441    #[case::three_consecutive_newlines("foo\n\n\nbar", "foo&#10;&#10;\nbar")]
1442    #[case::single_newline_unchanged("foo\nbar", "foo\nbar")]
1443    #[case::leading_tab_becomes_entity("\tfoo", "&#9;foo")]
1444    #[case::tab_not_at_line_start_unchanged("foo\tbar", "foo\tbar")]
1445    #[case::angle_bracket_escaped("<br/> not a tag", "\\<br/> not a tag")]
1446    // `&` is deliberately left unescaped: see KNOWN_FAILURES in gfm_roundtrip_fidelity.rs (#591).
1447    #[case::ampersand_not_escaped("a&b", "a&b")]
1448    fn test_escape_text(#[case] input: &str, #[case] expected: &str) {
1449        assert_eq!(escape_text(input.to_string()), expected);
1450    }
1451
1452    #[rstest]
1453    #[case::plain("plain", "plain")]
1454    #[case::brackets("[a][b]", "\\[a\\]\\[b\\]")]
1455    #[case::backslash("a\\b", "a\\\\b")]
1456    fn test_escape_label(#[case] input: &str, #[case] expected: &str) {
1457        assert_eq!(escape_label(input), expected);
1458    }
1459
1460    #[rstest]
1461    #[case::no_newline_unchanged("abc", 2, "abc")]
1462    #[case::continuation_indented("a\nb", 2, "a\n  b")]
1463    #[case::empty_lines_untouched("a\n\nb", 2, "a\n\n  b")]
1464    #[case::first_line_never_indented("  a\nb", 3, "  a\n   b")]
1465    fn test_indent_continuation(#[case] content: &str, #[case] width: usize, #[case] expected: &str) {
1466        assert_eq!(indent_continuation(content, width), expected);
1467    }
1468
1469    #[rstest]
1470    #[case::no_backticks("", 1)]
1471    #[case::single_run("foo`bar", 2)]
1472    #[case::longer_run("foo``bar", 3)]
1473    fn test_code_span_fence(#[case] value: &str, #[case] expected_len: usize) {
1474        assert_eq!(code_span_fence(value), "`".repeat(expected_len));
1475    }
1476
1477    #[rstest]
1478    #[case::no_backticks_minimum_three("plain", "", 3)]
1479    #[case::body_run_escalates("aaa\n```", "", 4)]
1480    fn test_code_fence(#[case] value: &str, #[case] info: &str, #[case] expected_len: usize) {
1481        assert_eq!(code_fence(value, info), "`".repeat(expected_len));
1482    }
1483
1484    #[rstest]
1485    #[case::info_backtick_switches_to_tilde("plain", "a`b", 3)]
1486    #[case::info_backtick_run_switches_to_tilde("plain", "a``b", 3)]
1487    #[case::body_tilde_run_escalates_within_tilde_fence("aaa\n~~~", "a`b", 4)]
1488    fn test_code_fence_tilde(#[case] value: &str, #[case] info: &str, #[case] expected_len: usize) {
1489        assert_eq!(code_fence(value, info), "~".repeat(expected_len));
1490    }
1491
1492    proptest! {
1493        // Every backslash escape_text inserts precedes exactly the character it
1494        // protects, and pre-existing backslashes are doubled, so blindly dropping
1495        // each backslash and keeping the character after it must recover the
1496        // original string, for any input. Tabs and repeated newlines go through a
1497        // separate entity-based path (see test_escape_text), excluded here.
1498        #[test]
1499        fn escape_text_is_losslessly_invertible(
1500            s in prop::collection::vec(any::<char>(), 0..60)
1501                .prop_map(|cs| cs.into_iter().collect::<String>())
1502                .prop_filter("excludes entity-escaped tab/newline-run cases", |s| {
1503                    !s.contains('\t') && !s.contains("\n\n")
1504                })
1505        ) {
1506            let escaped = escape_text(s.clone());
1507            prop_assert_eq!(naive_unescape(&escaped), s);
1508        }
1509
1510        // Rendering must never panic, whatever the heading text (arbitrary Unicode,
1511        // possibly ending in a run of `#`): this is a UTF-8 char-boundary regression
1512        // guard for the trailing-`#` escape logic.
1513        #[test]
1514        fn heading_render_never_panics_on_unicode_text(
1515            body in prop::collection::vec(any::<char>(), 0..20).prop_map(|cs| cs.into_iter().collect::<String>()),
1516            hashes in 0usize..5,
1517            depth in 1u8..=6,
1518        ) {
1519            let value = format!("{}{}", body, "#".repeat(hashes));
1520            let node = Node::Heading(Heading { depth: HeadingDepth::saturating(i64::from(depth)), values: vec![value.into()], position: None });
1521            let _ = node.to_string_with(&RenderOptions::default());
1522        }
1523
1524        #[test]
1525        fn escape_label_is_losslessly_invertible(
1526            s in prop::collection::vec(any::<char>(), 0..40).prop_map(|cs| cs.into_iter().collect::<String>())
1527        ) {
1528            let escaped = escape_label(&s);
1529            prop_assert_eq!(naive_unescape(&escaped), s);
1530        }
1531
1532        // A Link's destination, rendered through the real writer and re-parsed by the
1533        // real markdown parser, must recover the original URL string: the concrete
1534        // bug class from the GFM spec-suite fidelity check (spaces/parens/angle
1535        // brackets silently corrupting or breaking the link on round-trip).
1536        #[test]
1537        fn link_url_round_trips_through_parser(
1538            url in prop::collection::vec(
1539                prop::sample::select(vec!['a', 'b', '1', ' ', '(', ')', '<', '>', '\\']),
1540                1..12,
1541            ).prop_map(|cs| cs.into_iter().collect::<String>())
1542        ) {
1543            let doc = format!("[text]({})\n", render_link_destination(&url, &UrlSurroundStyle::None));
1544            let parsed = crate::Markdown::from_markdown_str(&doc).unwrap();
1545            let link = parsed.nodes.iter().find_map(|n| match n {
1546                Node::Link(l) => Some(l.url.as_str().to_string()),
1547                _ => None,
1548            });
1549            prop_assert_eq!(link, Some(url));
1550        }
1551
1552    }
1553
1554    fn naive_unescape(s: &str) -> String {
1555        let mut result = String::with_capacity(s.len());
1556        let mut chars = s.chars();
1557        while let Some(c) = chars.next() {
1558            if c == '\\'
1559                && let Some(next) = chars.next()
1560            {
1561                result.push(next);
1562                continue;
1563            }
1564            result.push(c);
1565        }
1566        result
1567    }
1568}