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 link or image destination, written so that CommonMark reads back exactly `url` (§6.3).
127///
128/// The bare form is used when it can carry the URL: no spaces, no ASCII control characters,
129/// no `<` or `>`, and parentheses that balance — an unbalanced `)` would end the destination
130/// early, a `(` would leave it open. Anything else is written in the pointy-bracket form
131/// `<...>`, which takes spaces and any parentheses. A line ending cannot stand in either form;
132/// it is percent-encoded (`%0A`, `%0D`), the one place the URL is changed rather than
133/// escaped. In both forms a backslash that would otherwise escape the character after it — an
134/// ASCII punctuation character, or the end of the destination — is doubled; other backslashes
135/// (`C:\dir`) are literal and stay as they are. An `&` that would start a character reference
136/// is escaped, so `?a=1&amp;b` stays as written. Inside a table cell `|` is escaped, since a
137/// GFM table splits its cells before it reads links. An empty URL is `<>`.
138///
139/// A link that is not in a table cell passes `in_table_cell: false`.
140///
141/// ```
142/// use unparser_shared::markdown::link_destination;
143///
144/// assert_eq!(link_destination("https://example.com/a(b)", false), "https://example.com/a(b)");
145/// assert_eq!(link_destination("my folder/file.png", false), "<my folder/file.png>");
146/// assert_eq!(link_destination("notes).txt", false), "<notes).txt>");
147/// assert_eq!(link_destination("a<b>c", false), r"<a\<b\>c>");
148/// ```
149pub fn link_destination(url: &str, in_table_cell: bool) -> String {
150    let bare = !url.is_empty()
151        && !url
152            .chars()
153            .any(|c| c == ' ' || c == '<' || c == '>' || c.is_ascii_control())
154        && parentheses_balance(url);
155    let mut out = String::with_capacity(url.len() + 2);
156    if !bare {
157        out.push('<');
158    }
159    let mut chars = url.char_indices().peekable();
160    while let Some((i, c)) = chars.next() {
161        match c {
162            // Judged on what is written next: a line ending goes out as `%`.
163            '\\' if chars
164                .peek()
165                .is_none_or(|&(_, n)| n.is_ascii_punctuation() || n == '\n' || n == '\r') =>
166            {
167                out.push_str("\\\\")
168            }
169            '&' if starts_character_reference(&url[i + 1..]) => out.push_str("\\&"),
170            '<' | '>' => {
171                out.push('\\');
172                out.push(c);
173            }
174            '|' if in_table_cell => out.push_str("\\|"),
175            '\n' => out.push_str("%0A"),
176            '\r' => out.push_str("%0D"),
177            _ => out.push(c),
178        }
179    }
180    if !bare {
181        out.push('>');
182    }
183    out
184}
185
186/// Whether the text after an `&` makes it a character reference (§6.2) — `name;`, `#123;` or
187/// `#x1F;` — which CommonMark would replace by the character it names.
188fn starts_character_reference(rest: &str) -> bool {
189    let Some(end) = rest.find(';') else {
190        return false;
191    };
192    let body = &rest[..end];
193    if let Some(number) = body.strip_prefix('#') {
194        return match number.strip_prefix(['x', 'X']) {
195            Some(hex) => (1..=6).contains(&hex.len()) && hex.chars().all(|c| c.is_ascii_hexdigit()),
196            None => (1..=7).contains(&number.len()) && number.chars().all(|c| c.is_ascii_digit()),
197        };
198    }
199    body.starts_with(|c: char| c.is_ascii_alphabetic())
200        && (2..=32).contains(&body.len())
201        && body.chars().all(|c| c.is_ascii_alphanumeric())
202}
203
204/// Whether every `)` closes an earlier `(` and every `(` is closed. A backslash in the URL
205/// does not shield a parenthesis: [`link_destination`] writes it as a literal backslash.
206fn parentheses_balance(url: &str) -> bool {
207    let mut depth = 0usize;
208    for c in url.chars() {
209        match c {
210            '(' => depth += 1,
211            ')' => match depth.checked_sub(1) {
212                Some(d) => depth = d,
213                None => return false,
214            },
215            _ => {}
216        }
217    }
218    depth == 0
219}
220
221/// Whitespace or punctuation — what a delimiter may touch on its outside when its inside is
222/// punctuation. CommonMark's punctuation is the Unicode P and S categories; a character that
223/// is neither alphanumeric, whitespace nor a control is one of them, save for combining
224/// marks, which do not stand at a run's edge.
225fn is_flanking_neutral(c: char) -> bool {
226    c.is_whitespace() || !(c.is_alphanumeric() || c.is_control())
227}
228
229/// A unit is neutral when the character it writes is: an escape writes punctuation.
230fn unit_is_neutral(unit: &str) -> bool {
231    unit.chars().last().is_some_and(is_flanking_neutral)
232}
233
234/// The byte ranges of `text[start..end]`'s units: one character, or a backslash and the ASCII
235/// punctuation it escapes.
236fn units(text: &str, start: usize, end: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
237    let mut chars = text[start..end].char_indices().peekable();
238    std::iter::from_fn(move || {
239        let (i, c) = chars.next()?;
240        let mut j = i + c.len_utf8();
241        if c == '\\' {
242            if let Some(&(k, escaped)) = chars.peek() {
243                if escaped.is_ascii_punctuation() {
244                    j = k + escaped.len_utf8();
245                    chars.next();
246                }
247            }
248        }
249        Some((start + i, start + j))
250    })
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    /// `text` with `*` around its emphasis span.
258    fn wrap(text: &str, before: Option<char>, after: Option<char>) -> String {
259        emphasis_span(text, before, after).map_or(text.to_string(), |r| {
260            format!(
261                "{}*{}*{}",
262                &text[..r.start],
263                &text[r.clone()],
264                &text[r.end..]
265            )
266        })
267    }
268
269    #[test]
270    fn whitespace_stays_outside() {
271        assert_eq!(wrap("  word  ", Some('a'), Some('b')), "  *word*  ");
272        assert_eq!(emphasis_span("   ", None, None), None);
273        assert_eq!(emphasis_span("", None, None), None);
274    }
275
276    #[test]
277    fn leading_punctuation_against_a_word_moves_out_with_its_space() {
278        assert_eq!(wrap(", s", Some('2'), Some(' ')), ", *s*");
279    }
280
281    #[test]
282    fn trailing_punctuation_against_a_word_moves_out() {
283        assert_eq!(wrap("word.", Some(' '), Some('x')), "*word*.");
284        assert_eq!(wrap("word, ", Some(' '), Some('x')), "*word,* ");
285    }
286
287    #[test]
288    fn punctuation_between_words_alone_has_nothing_to_wrap() {
289        assert_eq!(emphasis_span(",", Some('8'), Some('a')), None);
290        assert_eq!(emphasis_span(", ", Some('8'), None), None);
291    }
292
293    #[test]
294    fn punctuation_against_space_punctuation_or_an_edge_stays_inside() {
295        assert_eq!(wrap("i.e.,", Some(' '), Some(' ')), "*i.e.,*");
296        assert_eq!(wrap("(h)", None, None), "*(h)*");
297        assert_eq!(wrap("(h)", Some('('), Some(')')), "*(h)*");
298        assert_eq!(
299            wrap("Continued pretraining.", None, Some(' ')),
300            "*Continued pretraining.*"
301        );
302    }
303
304    #[test]
305    fn a_word_on_either_side_moves_both_ends() {
306        assert_eq!(wrap("(h)", Some('Q'), Some('x')), "(*h*)");
307    }
308
309    #[test]
310    fn an_escape_is_never_split() {
311        assert_eq!(wrap(r"\*x\_", Some('a'), Some('b')), r"\**x*\_");
312    }
313
314    #[test]
315    fn a_backslash_before_a_letter_is_not_an_escape() {
316        assert_eq!(wrap(r"\a", Some('b'), None), r"\*a*");
317    }
318
319    #[test]
320    fn non_ascii_punctuation_and_letters_count() {
321        assert_eq!(wrap("“word”", Some('x'), Some('y')), "“*word*”");
322        assert_eq!(wrap("단어", Some('가'), Some('나')), "*단어*");
323    }
324}