Skip to main content

unparser_shared/
markdown.rs

1//! CommonMark syntax facts every Markdown writer in the family needs.
2//!
3//! Each library renders its own document model, and how it styles a run is its own business.
4//! *Where* an emphasis delimiter may stand, and how text the document supplies — a picture's
5//! description, a link's target — has to be written so that it stays inside the construct it
6//! belongs to, are not: they are properties of CommonMark, and a writer that gets them wrong
7//! prints its syntax as text. This module answers those questions once so the writers cannot
8//! drift on them.
9//!
10//! `std`-only, like the rest of the crate root.
11
12use std::ops::Range;
13
14/// The part of a styled run that emphasis delimiters (`*`, `**`, `~~`) can wrap, given the
15/// characters the run lands between, or `None` when no part can.
16///
17/// `before` is the last character already written, `after` the first one the next piece will
18/// write (`None` at either end of the inline content). The text outside the returned range is
19/// written as-is, outside the delimiters.
20///
21/// CommonMark reads a delimiter as emphasis only when it *flanks* the text (§6.2): it may not
22/// touch whitespace on its inside, and when its inside is punctuation its outside must be
23/// whitespace, punctuation, or the end of the line. So:
24///
25/// - leading and trailing whitespace always stays outside — `**word **` is not emphasis;
26/// - leading or trailing punctuation stays outside too, with any whitespace behind it, when
27///   the run touches a letter or digit on that side — an italic `", s"` after `32` written as
28///   `32*, s*` shows its asterisks, written as `32, *s*` it does not;
29/// - a run that is nothing but whitespace, or nothing but punctuation between words, has
30///   nothing to wrap.
31///
32/// Punctuation that does not touch a word stays inside (`*i.e.,*`, `*(h)*`), so a run is not
33/// reshaped unless it has to be.
34///
35/// `text` may already be escaped: a backslash escape (`\*`) is one unit and is never split
36/// across a delimiter. Only escapes of ASCII punctuation are units, as in CommonMark.
37///
38/// ```
39/// use unparser_shared::markdown::emphasis_span;
40///
41/// let wrap = |text: &str, before, after| {
42///     emphasis_span(text, before, after).map_or(text.to_string(), |r| {
43///         format!("{}*{}*{}", &text[..r.start], &text[r.clone()], &text[r.end..])
44///     })
45/// };
46/// assert_eq!(wrap(", s", Some('2'), Some(' ')), ", *s*");
47/// assert_eq!(wrap("word ", None, Some('x')), "*word* ");
48/// assert_eq!(wrap(",", Some('8'), Some('a')), ",");
49/// assert_eq!(wrap("(h)", Some(' '), None), "*(h)*");
50/// ```
51pub fn emphasis_span(
52    text: &str,
53    before: Option<char>,
54    after: Option<char>,
55) -> Option<Range<usize>> {
56    let mut start = text.len() - text.trim_start().len();
57    let mut end = text.trim_end().len();
58    if start >= end {
59        return None;
60    }
61    let touches_a_word = |c: Option<char>| c.is_some_and(|c| !is_flanking_neutral(c));
62    if start == 0 && touches_a_word(before) {
63        start = units(text, start, end)
64            .find(|&(i, j)| !unit_is_neutral(&text[i..j]))
65            .map_or(end, |(i, _)| i);
66    }
67    if end == text.len() && touches_a_word(after) {
68        end = units(text, start, end)
69            .filter(|&(i, j)| !unit_is_neutral(&text[i..j]))
70            .last()
71            .map_or(start, |(_, j)| j);
72    }
73    (start < end).then_some(start..end)
74}
75
76/// A picture as an inline image: `![alt](destination)`.
77///
78/// The alt text is data from the document — whatever a person typed into a description box:
79/// several lines, blank lines, brackets. Written verbatim, a blank line ends the paragraph and
80/// the image reads back as literal text plus a stray paragraph, and an unbalanced `]` ends the
81/// link text early. So the alt text is flattened to one line — every run of whitespace becomes
82/// one space, the ends trimmed — and the characters that are syntax inside link text are
83/// escaped: `\`, `[`, `]`, `` ` `` (a code span would swallow the closing bracket), `<` (raw
84/// HTML or an autolink), and an `&` that would start a character reference (`&amp;` would read
85/// back as `&`). Inside a table cell `|` is escaped too, since it would end the cell. `*` and
86/// `_` are left alone: unmatched they are literal, matched they only style the text, and
87/// neither can end the image.
88///
89/// The destination is written by [`link_destination`].
90///
91/// ```
92/// use unparser_shared::markdown::image;
93///
94/// assert_eq!(
95///     image("A view\n\nof the harbour", "img/1.png", false),
96///     "![A view of the harbour](img/1.png)"
97/// );
98/// assert_eq!(image("a [draft]", "my dir/a.png", false), r"![a \[draft\]](<my dir/a.png>)");
99/// assert_eq!(image("x | y", "a.png", true), r"![x \| y](a.png)");
100/// ```
101pub fn image(alt: &str, destination: &str, in_table_cell: bool) -> String {
102    let mut out = String::with_capacity(alt.len() + destination.len() + 5);
103    out.push_str("![");
104    for (n, word) in alt.split_whitespace().enumerate() {
105        if n > 0 {
106            out.push(' ');
107        }
108        for (i, c) in word.char_indices() {
109            match c {
110                '\\' | '[' | ']' | '`' | '<' => {
111                    out.push('\\');
112                    out.push(c);
113                }
114                '&' if starts_character_reference(&word[i + 1..]) => out.push_str("\\&"),
115                '|' if in_table_cell => out.push_str("\\|"),
116                _ => out.push(c),
117            }
118        }
119    }
120    out.push_str("](");
121    out.push_str(&link_destination(destination, in_table_cell));
122    out.push(')');
123    out
124}
125
126/// A code span holding `text` exactly as given: CommonMark reads it back as `text`, every line
127/// ending in it read as one space.
128///
129/// Nothing is escaped inside a code span — a backslash there is printed (CommonMark §6.1), so
130/// the text is written as it is and the span is fenced instead:
131///
132/// - the fence is one backtick longer than the longest run of backticks in the text, so no run
133///   inside can close it;
134/// - one space pads each side when the text starts or ends with a backtick (it would join the
135///   fence) or both starts and ends with a space (a reader strips one from each side) — the
136///   reader strips the padding again;
137/// - a line ending becomes a space, so a blank line cannot end the paragraph mid-span;
138/// - inside a table cell `|` is escaped — a GFM table splits its cells before it reads code
139///   spans, and reads `\|` back as `|` inside them.
140///
141/// Empty text has no code span and gives an empty string.
142///
143/// ```
144/// use unparser_shared::markdown::code_span;
145///
146/// assert_eq!(code_span(r"C:\dir", false), r"`C:\dir`");
147/// assert_eq!(code_span("a`b", false), "``a`b``");
148/// assert_eq!(code_span("`x`", false), "`` `x` ``");
149/// assert_eq!(code_span(" a ", false), "`  a  `");
150/// assert_eq!(code_span("a | b", true), r"`a \| b`");
151/// assert_eq!(code_span("", false), "");
152/// ```
153pub fn code_span(text: &str, in_table_cell: bool) -> String {
154    if text.is_empty() {
155        return String::new();
156    }
157    let text = text.replace("\r\n", " ").replace(['\r', '\n'], " ");
158    let longest_run = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
159    let fence = "`".repeat(longest_run + 1);
160    let pad = text.starts_with('`')
161        || text.ends_with('`')
162        || (text.starts_with(' ')
163            && text.ends_with(' ')
164            && !text.trim_start_matches(' ').is_empty());
165    let pad = if pad { " " } else { "" };
166    let body = if in_table_cell {
167        text.replace('|', "\\|")
168    } else {
169        text
170    };
171    format!("{fence}{pad}{body}{pad}{fence}")
172}
173
174/// An inline link: `[label](destination)`, or `[label](destination "title")`.
175///
176/// `label` is inline Markdown the writer has already rendered — its text escaped and styled
177/// the writer's own way (`**bold**`, `<u>…</u>`, a code span). What this adds is what keeps
178/// that Markdown *inside the link*, which no display setting may turn off:
179///
180/// - an unescaped `[` or `]` is escaped — an unbalanced `]` ends the link text early, and a
181///   `[x](y)` inside it would be a second link, which CommonMark does not nest;
182/// - a line ending becomes a space, so a blank line cannot end the paragraph mid-link;
183/// - a backslash at the very end is doubled, since it would otherwise escape the closing `]`;
184/// - inside a table cell, an unescaped `|` is escaped, code spans included — a GFM table
185///   splits its cells before it reads anything else.
186///
187/// Code spans are left as they are (apart from that `|`): a code span binds more tightly than
188/// the link's brackets, so a `]` inside one does not end the link, and a backslash inside one
189/// would be printed. Backslash escapes the label already carries (`\*`, `\[`) are kept as
190/// they are. The label is not expected to hold a link, an image, an autolink or raw HTML with
191/// a bracket in it.
192///
193/// The destination is written by [`link_destination`]. The title, when there is one and it is
194/// not empty, is written in double quotes: `"` is escaped, a backslash that would escape the
195/// character after it is doubled, an `&` that would start a character reference is escaped,
196/// a line ending becomes a space, and inside a table cell `|` is escaped.
197///
198/// ```
199/// use unparser_shared::markdown::link;
200///
201/// assert_eq!(link("see [3]", "https://example.com", None, false), r"[see \[3\]](https://example.com)");
202/// assert_eq!(link("**bold** `a]b`", "u", None, false), "[**bold** `a]b`](u)");
203/// assert_eq!(link("x", "u", Some(r#"say "hi""#), false), r#"[x](u "say \"hi\"")"#);
204/// assert_eq!(link("a | b", "u", None, true), r"[a \| b](u)");
205/// ```
206pub fn link(label: &str, destination: &str, title: Option<&str>, in_table_cell: bool) -> String {
207    let mut out = String::with_capacity(label.len() + destination.len() + 4);
208    out.push('[');
209    push_link_label(&mut out, label, in_table_cell);
210    out.push_str("](");
211    out.push_str(&link_destination(destination, in_table_cell));
212    if let Some(title) = title.filter(|t| !t.is_empty()) {
213        out.push_str(" \"");
214        let mut chars = title.char_indices().peekable();
215        while let Some((i, c)) = chars.next() {
216            match c {
217                '\\' if chars.peek().is_none_or(|&(_, n)| n.is_ascii_punctuation()) => {
218                    out.push_str("\\\\")
219                }
220                '"' => out.push_str("\\\""),
221                '&' if starts_character_reference(&title[i + 1..]) => out.push_str("\\&"),
222                '|' if in_table_cell => out.push_str("\\|"),
223                '\n' | '\r' => out.push(' '),
224                _ => out.push(c),
225            }
226        }
227        out.push('"');
228    }
229    out.push(')');
230    out
231}
232
233/// Append `label` as link text — see [`link`] for what is escaped and what is kept.
234fn push_link_label(out: &mut String, label: &str, in_table_cell: bool) {
235    let chars: Vec<char> = label.chars().collect();
236    let mut i = 0;
237    while i < chars.len() {
238        let c = chars[i];
239        match c {
240            '\\' => match chars.get(i + 1) {
241                // An escape the label already carries: one unit, kept.
242                Some(&n) if n.is_ascii_punctuation() => {
243                    out.push('\\');
244                    out.push(n);
245                    i += 2;
246                    continue;
247                }
248                None => out.push_str("\\\\"),
249                Some(_) => out.push('\\'),
250            },
251            '`' => {
252                let run = chars[i..].iter().take_while(|&&b| b == '`').count();
253                if let Some(close) = closing_backticks(&chars, i + run, run) {
254                    // A code span, written as it is: no escapes inside, but a GFM cell
255                    // still splits on its `|`.
256                    for (k, &s) in chars[i..close + run].iter().enumerate() {
257                        match s {
258                            '\n' | '\r' => out.push(' '),
259                            '|' if in_table_cell && (k == 0 || chars[i + k - 1] != '\\') => {
260                                out.push_str("\\|")
261                            }
262                            _ => out.push(s),
263                        }
264                    }
265                    i = close + run;
266                } else {
267                    // No closing run of the same length: the backticks are literal.
268                    out.extend(std::iter::repeat_n('`', run));
269                    i += run;
270                }
271                continue;
272            }
273            '[' | ']' => {
274                out.push('\\');
275                out.push(c);
276            }
277            '|' if in_table_cell => out.push_str("\\|"),
278            '\n' | '\r' => out.push(' '),
279            _ => out.push(c),
280        }
281        i += 1;
282    }
283}
284
285/// Where the backtick run of exactly `len` that closes a code span opened before `from`
286/// starts, if there is one.
287fn closing_backticks(chars: &[char], from: usize, len: usize) -> Option<usize> {
288    let mut j = from;
289    while j < chars.len() {
290        if chars[j] == '`' {
291            let run = chars[j..].iter().take_while(|&&b| b == '`').count();
292            if run == len {
293                return Some(j);
294            }
295            j += run;
296        } else {
297            j += 1;
298        }
299    }
300    None
301}
302
303/// A link or image destination, written so that CommonMark reads back exactly `url` (§6.3).
304///
305/// The bare form is used when it can carry the URL: no spaces, no ASCII control characters,
306/// no `<` or `>`, and parentheses that balance — an unbalanced `)` would end the destination
307/// early, a `(` would leave it open. Anything else is written in the pointy-bracket form
308/// `<...>`, which takes spaces and any parentheses. A line ending cannot stand in either form;
309/// it is percent-encoded (`%0A`, `%0D`), the one place the URL is changed rather than
310/// escaped. In both forms a backslash that would otherwise escape the character after it — an
311/// ASCII punctuation character, or the end of the destination — is doubled; other backslashes
312/// (`C:\dir`) are literal and stay as they are. An `&` that would start a character reference
313/// is escaped, so `?a=1&amp;b` stays as written. Inside a table cell `|` is escaped, since a
314/// GFM table splits its cells before it reads links. An empty URL is `<>`.
315///
316/// A link that is not in a table cell passes `in_table_cell: false`.
317///
318/// ```
319/// use unparser_shared::markdown::link_destination;
320///
321/// assert_eq!(link_destination("https://example.com/a(b)", false), "https://example.com/a(b)");
322/// assert_eq!(link_destination("my folder/file.png", false), "<my folder/file.png>");
323/// assert_eq!(link_destination("notes).txt", false), "<notes).txt>");
324/// assert_eq!(link_destination("a<b>c", false), r"<a\<b\>c>");
325/// ```
326pub fn link_destination(url: &str, in_table_cell: bool) -> String {
327    let bare = !url.is_empty()
328        && !url
329            .chars()
330            .any(|c| c == ' ' || c == '<' || c == '>' || c.is_ascii_control())
331        && parentheses_balance(url);
332    let mut out = String::with_capacity(url.len() + 2);
333    if !bare {
334        out.push('<');
335    }
336    let mut chars = url.char_indices().peekable();
337    while let Some((i, c)) = chars.next() {
338        match c {
339            // Judged on what is written next: a line ending goes out as `%`.
340            '\\' if chars
341                .peek()
342                .is_none_or(|&(_, n)| n.is_ascii_punctuation() || n == '\n' || n == '\r') =>
343            {
344                out.push_str("\\\\")
345            }
346            '&' if starts_character_reference(&url[i + 1..]) => out.push_str("\\&"),
347            '<' | '>' => {
348                out.push('\\');
349                out.push(c);
350            }
351            '|' if in_table_cell => out.push_str("\\|"),
352            '\n' => out.push_str("%0A"),
353            '\r' => out.push_str("%0D"),
354            _ => out.push(c),
355        }
356    }
357    if !bare {
358        out.push('>');
359    }
360    out
361}
362
363/// Whether the text after an `&` makes it a character reference (§6.2) — `name;`, `#123;` or
364/// `#x1F;` — which CommonMark would replace by the character it names.
365fn starts_character_reference(rest: &str) -> bool {
366    let Some(end) = rest.find(';') else {
367        return false;
368    };
369    let body = &rest[..end];
370    if let Some(number) = body.strip_prefix('#') {
371        return match number.strip_prefix(['x', 'X']) {
372            Some(hex) => (1..=6).contains(&hex.len()) && hex.chars().all(|c| c.is_ascii_hexdigit()),
373            None => (1..=7).contains(&number.len()) && number.chars().all(|c| c.is_ascii_digit()),
374        };
375    }
376    body.starts_with(|c: char| c.is_ascii_alphabetic())
377        && (2..=32).contains(&body.len())
378        && body.chars().all(|c| c.is_ascii_alphanumeric())
379}
380
381/// Whether every `)` closes an earlier `(` and every `(` is closed. A backslash in the URL
382/// does not shield a parenthesis: [`link_destination`] writes it as a literal backslash.
383fn parentheses_balance(url: &str) -> bool {
384    let mut depth = 0usize;
385    for c in url.chars() {
386        match c {
387            '(' => depth += 1,
388            ')' => match depth.checked_sub(1) {
389                Some(d) => depth = d,
390                None => return false,
391            },
392            _ => {}
393        }
394    }
395    depth == 0
396}
397
398/// Whitespace or punctuation — what a delimiter may touch on its outside when its inside is
399/// punctuation. CommonMark's punctuation is the Unicode P and S categories; a character that
400/// is neither alphanumeric, whitespace nor a control is one of them, save for combining
401/// marks, which do not stand at a run's edge.
402fn is_flanking_neutral(c: char) -> bool {
403    c.is_whitespace() || !(c.is_alphanumeric() || c.is_control())
404}
405
406/// A unit is neutral when the character it writes is: an escape writes punctuation.
407fn unit_is_neutral(unit: &str) -> bool {
408    unit.chars().last().is_some_and(is_flanking_neutral)
409}
410
411/// The byte ranges of `text[start..end]`'s units: one character, or a backslash and the ASCII
412/// punctuation it escapes.
413fn units(text: &str, start: usize, end: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
414    let mut chars = text[start..end].char_indices().peekable();
415    std::iter::from_fn(move || {
416        let (i, c) = chars.next()?;
417        let mut j = i + c.len_utf8();
418        if c == '\\' {
419            if let Some(&(k, escaped)) = chars.peek() {
420                if escaped.is_ascii_punctuation() {
421                    j = k + escaped.len_utf8();
422                    chars.next();
423                }
424            }
425        }
426        Some((start + i, start + j))
427    })
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    /// `text` with `*` around its emphasis span.
435    fn wrap(text: &str, before: Option<char>, after: Option<char>) -> String {
436        emphasis_span(text, before, after).map_or(text.to_string(), |r| {
437            format!(
438                "{}*{}*{}",
439                &text[..r.start],
440                &text[r.clone()],
441                &text[r.end..]
442            )
443        })
444    }
445
446    #[test]
447    fn whitespace_stays_outside() {
448        assert_eq!(wrap("  word  ", Some('a'), Some('b')), "  *word*  ");
449        assert_eq!(emphasis_span("   ", None, None), None);
450        assert_eq!(emphasis_span("", None, None), None);
451    }
452
453    #[test]
454    fn leading_punctuation_against_a_word_moves_out_with_its_space() {
455        assert_eq!(wrap(", s", Some('2'), Some(' ')), ", *s*");
456    }
457
458    #[test]
459    fn trailing_punctuation_against_a_word_moves_out() {
460        assert_eq!(wrap("word.", Some(' '), Some('x')), "*word*.");
461        assert_eq!(wrap("word, ", Some(' '), Some('x')), "*word,* ");
462    }
463
464    #[test]
465    fn punctuation_between_words_alone_has_nothing_to_wrap() {
466        assert_eq!(emphasis_span(",", Some('8'), Some('a')), None);
467        assert_eq!(emphasis_span(", ", Some('8'), None), None);
468    }
469
470    #[test]
471    fn punctuation_against_space_punctuation_or_an_edge_stays_inside() {
472        assert_eq!(wrap("i.e.,", Some(' '), Some(' ')), "*i.e.,*");
473        assert_eq!(wrap("(h)", None, None), "*(h)*");
474        assert_eq!(wrap("(h)", Some('('), Some(')')), "*(h)*");
475        assert_eq!(
476            wrap("Continued pretraining.", None, Some(' ')),
477            "*Continued pretraining.*"
478        );
479    }
480
481    #[test]
482    fn a_word_on_either_side_moves_both_ends() {
483        assert_eq!(wrap("(h)", Some('Q'), Some('x')), "(*h*)");
484    }
485
486    #[test]
487    fn an_escape_is_never_split() {
488        assert_eq!(wrap(r"\*x\_", Some('a'), Some('b')), r"\**x*\_");
489    }
490
491    #[test]
492    fn a_backslash_before_a_letter_is_not_an_escape() {
493        assert_eq!(wrap(r"\a", Some('b'), None), r"\*a*");
494    }
495
496    #[test]
497    fn non_ascii_punctuation_and_letters_count() {
498        assert_eq!(wrap("“word”", Some('x'), Some('y')), "“*word*”");
499        assert_eq!(wrap("단어", Some('가'), Some('나')), "*단어*");
500    }
501}