Skip to main content

tramlines_md/markdown/
reading.rs

1//! The reading of a text (`TLMD_258` to `TLMD_260`): the text with each
2//! piece of its markup in one fixed spelling, the one that oxfmt,
3//! Prettier, and dprint write outside a word, and each byte mapped to the
4//! text as written; and the plain text, from which a slug is formed. An
5//! emphasis inside a word, which a formatter writes with `*`, reads `_x_`
6//! too, so `foo*bar*baz` reads as `foo_bar_baz` does.
7
8use std::ops::Range;
9
10use comrak::{Arena, nodes::NodeValue};
11use serde::{Deserialize, Serialize};
12
13use super::parse;
14
15/// What a text is read behind: a private-use character, which is neither
16/// a space nor punctuation, and a space. So no text starts a block, as
17/// `1. two` or `# x` alone would, and the first character of the text
18/// keeps the flanking that it has after a space.
19const LEAD: &str = "\u{E000} ";
20
21// sokf:begin reading
22/// A text in the fixed spelling of its markup: each emphasis as `_x_`,
23/// each strong emphasis as `**x**`, each code span in the shortest run of
24/// backticks that its content allows, and each escape that changes nothing
25/// as the plain character, every other character as written.
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Reading {
28    /// The text in the fixed spelling.
29    pub text: String,
30    /// `map[i]` is the offset in the text as written of byte `i` of
31    /// `text`, in order, and `map[text.len()]` the length of the text as
32    /// written.
33    pub map: Vec<usize>,
34}
35// sokf:end reading
36
37impl Reading {
38    /// The reading of a text that reads as written, such as a line of a
39    /// fence: the text itself, each byte mapped to itself.
40    pub fn written(text: &str) -> Reading {
41        Reading {
42            text: text.to_string(),
43            map: (0..=text.len()).collect(),
44        }
45    }
46
47    /// The reading, or `text` as written where the reading is empty, as a
48    /// `Reading` left at its default by a host, or by the data of an older
49    /// version, is.
50    pub fn or_written<'a>(&'a self, text: &str) -> std::borrow::Cow<'a, Reading> {
51        if self.map.is_empty() {
52            std::borrow::Cow::Owned(Reading::written(text))
53        } else {
54            std::borrow::Cow::Borrowed(self)
55        }
56    }
57
58    /// The offset in the text as written of offset `i` of the reading.
59    pub fn original(&self, i: usize) -> usize {
60        self.map
61            .get(i)
62            .or(self.map.last())
63            .copied()
64            .unwrap_or_default()
65    }
66
67    /// Whether byte `at` of `text`, the text as written, is a backslash that
68    /// the reading drops, which belongs to the character after it.
69    pub(crate) fn drops_backslash(&self, text: &str, at: usize) -> bool {
70        text.as_bytes().get(at) == Some(&b'\\') && self.map.binary_search(&at).is_err()
71    }
72
73    /// The bytes of `text`, the text as written, that a part of the reading
74    /// stands for, from `start` to `end`, the offsets of `text` that the
75    /// part's first byte and the byte after it map to. A backslash that the
76    /// reading drops belongs to the character after it, and a backtick that
77    /// the reading of a code span drops to the code span, as the map gives
78    /// it.
79    pub(crate) fn span_of(&self, text: &str, start: usize, end: usize) -> Range<usize> {
80        let start = if start > 0 && self.drops_backslash(text, start - 1) {
81            start - 1
82        } else {
83            start
84        };
85        let end = if end > start && self.drops_backslash(text, end - 1) {
86            end - 1
87        } else {
88            end
89        };
90        start..end.max(start)
91    }
92}
93
94/// One change that a reading makes to a text: the bytes `range` of the
95/// text as written, and what the reading writes in their place, which is
96/// no longer than the range.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub(crate) struct Change {
99    /// The bytes of the text as written.
100    pub range: Range<usize>,
101    /// What the reading writes in their place.
102    pub with: String,
103}
104
105// sokf:begin reading-fns
106/// The reading of `text`, read as a paragraph alone (`TLMD_259`).
107// sokf-implements: TLMD_258
108// sokf-implements: TLMD_259
109// sokf-implements: MD-14_AC-1
110pub fn reading(text: &str) -> Reading {
111    apply(text, &changes(text))
112}
113
114/// The plain text of `text`, read as a paragraph alone: the text without
115/// the markers of emphasis, code, links, and inline HTML, from which
116/// `slug` forms a slug.
117// sokf-implements: MD-14_AC-2
118pub fn plain_text(text: &str) -> String {
119    // sokf:end reading-fns
120    if !text.bytes().any(|b| b"*_`\\[]<>&!".contains(&b)) {
121        return text.to_string();
122    }
123    let arena = Arena::new();
124    let root = comrak::parse_document(&arena, &lead(text), &parse::options());
125    let collected = root.collect_text();
126    let plain = collected.strip_prefix('\u{E000}').unwrap_or(&collected);
127    plain.strip_prefix(' ').unwrap_or(plain).to_string()
128}
129
130/// `text` behind the lead, each line break read as a space, as the text of
131/// a unit joins its lines. Every byte of `text` keeps its offset after the
132/// lead.
133fn lead(text: &str) -> String {
134    format!("{LEAD}{}", text.replace(['\n', '\r'], " "))
135}
136
137/// The changes that the reading of `text` makes, in order: the respelling
138/// of each emphasis, strong emphasis, and code span, and the drop of each
139/// backslash that changes nothing, each kept only where the text with it,
140/// and with every change kept before it, renders the same HTML as the text
141/// as written (`TLMD_258`, `TLMD_260`). An emphasis inside a word is the
142/// one exception, which reads `_x_` though a `_` there opens no emphasis:
143/// the other changes are judged beside it as written, and its respelling
144/// is added after them.
145// sokf-implements: TLMD_260
146// sokf-implements: TLMD_266
147pub(crate) fn changes(text: &str) -> Vec<Change> {
148    if !text
149        .bytes()
150        .any(|b| matches!(b, b'*' | b'_' | b'`' | b'\\'))
151    {
152        return Vec::new();
153    }
154    let source = lead(text);
155    let (in_word, respellings, escapes) = proposed(text, &source);
156    if respellings.is_empty() && escapes.is_empty() {
157        return in_word;
158    }
159    let options = parse::options();
160    let html = |changes: &[Change]| {
161        let mut sorted = changes.to_vec();
162        sorted.sort_by_key(|c| c.range.start);
163        comrak::markdown_to_html(&lead(&apply(text, &sorted).text), &options)
164    };
165    let meaning = comrak::markdown_to_html(&source, &options);
166    let mut kept: Vec<Change> = Vec::new();
167    // Most texts keep every respelling, which one rendering shows; a text
168    // that doesn't keeps each one that keeps its meaning alone, in order.
169    let all: Vec<Change> = respellings.iter().flatten().cloned().collect();
170    if !respellings.is_empty() && html(&all) == meaning {
171        kept = all;
172    } else {
173        for node in respellings {
174            let with: Vec<Change> = kept.iter().chain(&node).cloned().collect();
175            if html(&with) == meaning {
176                kept = with;
177            }
178        }
179    }
180    for at in escapes {
181        let mut with = kept.clone();
182        with.push(Change {
183            range: at..at + 1,
184            with: String::new(),
185        });
186        if html(&with) == meaning {
187            kept = with;
188        }
189    }
190    // An emphasis inside a word has one spelling, `*`, so the changes
191    // judged beside it as written are judged alike in every twin.
192    kept.extend(in_word);
193    kept.sort_by_key(|c| c.range.start);
194    kept
195}
196
197/// The changes that the reading of `text`, behind the lead in `source`,
198/// proposes: the respelling of each emphasis inside a word, the respelling
199/// of each other emphasis, strong emphasis, and code span, one list for
200/// each node, and the offset of the backslash of each escape that may
201/// change nothing, in order.
202fn proposed(text: &str, source: &str) -> (Vec<Change>, Vec<Vec<Change>>, Vec<usize>) {
203    // The text as comrak reads it behind the lead, each line break a space,
204    // at the same offsets, which the changes read.
205    let flat = &source[LEAD.len()..];
206    let arena = Arena::new();
207    let root = comrak::parse_document(&arena, source, &parse::options());
208    let mut in_word = Vec::new();
209    let mut respellings = Vec::new();
210    let mut escapes = Vec::new();
211    for node in root.descendants() {
212        let ast = node.data();
213        let sp = ast.sourcepos;
214        // The source is one line, so a node of the text lies on it, after
215        // the lead.
216        if sp.start.line != 1 || sp.end.line != 1 || sp.start.column <= LEAD.len() {
217            continue;
218        }
219        let span = sp.start.column - 1 - LEAD.len()..sp.end.column.saturating_sub(LEAD.len());
220        if span.end > text.len() || span.start >= span.end {
221            continue;
222        }
223        let mut node = Vec::new();
224        match &ast.value {
225            NodeValue::Emph(_) => delimiters(flat, &span, 1, "_", &mut node),
226            NodeValue::Strong(_) => delimiters(flat, &span, 2, "**", &mut node),
227            NodeValue::Code(_) => code(flat, &span, &mut node),
228            // A backslash before a pipe stays, because a table cell needs it,
229            // and the cell's text holds it as written.
230            NodeValue::Escaped
231                if text.as_bytes()[span.start] == b'\\'
232                    && text.as_bytes().get(span.start + 1) != Some(&b'|') =>
233            {
234                escapes.push(span.start);
235            }
236            _ => {}
237        }
238        if node.is_empty() {
239            continue;
240        }
241        if matches!(ast.value, NodeValue::Emph(_)) && inside_word(flat, &span) {
242            in_word.extend(node);
243        } else {
244            respellings.push(node);
245        }
246    }
247    // A node inside another comes after it in the walk, so its changes lie
248    // between the outer node's.
249    in_word.sort_by_key(|c: &Change| c.range.start);
250    escapes.sort_unstable();
251    (in_word, respellings, escapes)
252}
253
254/// Whether the emphasis at `span` of `text` stands inside a word: a letter,
255/// a digit, or a private-use character touches it from outside, where only
256/// `*` opens or closes an emphasis, so that its reading as `_x_` reads as
257/// no emphasis (`TLMD_258`). The placeholder of a hole of a template is a
258/// private-use character, so an emphasis beside a hole reads as one inside
259/// a word does.
260fn inside_word(text: &str, span: &Range<usize>) -> bool {
261    // A letter, a digit, or a private-use character, such as the
262    // placeholder; every other character is taken for punctuation, so an
263    // emphasis that touches only such characters is judged by its HTML.
264    let word = |c: char| c.is_alphanumeric() || ('\u{E000}'..='\u{F8FF}').contains(&c);
265    let before = text[..span.start].chars().next_back();
266    let after = text[span.end..].chars().next();
267    before.is_some_and(word) || after.is_some_and(word)
268}
269
270/// The delimiters, `n` bytes at each end of `span`, of an emphasis or a
271/// strong emphasis, written as `with`.
272fn delimiters(text: &str, span: &Range<usize>, n: usize, with: &str, out: &mut Vec<Change>) {
273    let bytes = text.as_bytes();
274    let delimiter = |r: Range<usize>| bytes[r].iter().all(|b| matches!(b, b'*' | b'_'));
275    if span.len() < 2 * n
276        || !delimiter(span.start..span.start + n)
277        || !delimiter(span.end - n..span.end)
278    {
279        return;
280    }
281    for range in [span.start..span.start + n, span.end - n..span.end] {
282        if &text[range.clone()] != with {
283            out.push(Change {
284                range,
285                with: with.to_string(),
286            });
287        }
288    }
289}
290
291/// The run of backticks and the padding of the code span at `span`,
292/// written again: its content as the text holds it, without the one space
293/// that CommonMark strips at each end, in the shortest run of backticks
294/// that the content allows, with one space inside each end only where the
295/// content starts or ends with a backtick, or starts and ends with a space
296/// and holds another character (`TLMD_258`).
297fn code(text: &str, span: &Range<usize>, out: &mut Vec<Change>) {
298    let written = &text[span.clone()];
299    let n = written.bytes().take_while(|&b| b == b'`').count();
300    if n == 0
301        || written.len() < 2 * n + 1
302        || !written[written.len() - n..].bytes().all(|b| b == b'`')
303    {
304        return;
305    }
306    let content = &written[n..written.len() - n];
307    let stripped = content.len() >= 2
308        && content.starts_with(' ')
309        && content.ends_with(' ')
310        && content.bytes().any(|b| b != b' ');
311    let inner = if stripped {
312        &content[1..content.len() - 1]
313    } else {
314        content
315    };
316    let (m, pad) = crate::text::code_fence(inner);
317    let ticks = "`".repeat(m);
318    let space = if pad { " " } else { "" };
319    let strip = usize::from(stripped);
320    let open = span.start..span.start + n + strip;
321    let close = span.end - n - strip..span.end;
322    for (range, with) in [
323        (open, format!("{ticks}{space}")),
324        (close, format!("{space}{ticks}")),
325    ] {
326        if text[range.clone()] != with {
327            out.push(Change { range, with });
328        }
329    }
330}
331
332/// `text` with `changes`, in order and apart, applied, each byte of the
333/// result mapped to the byte of `text` that it stands for.
334pub(crate) fn apply(text: &str, changes: &[Change]) -> Reading {
335    let mut out = String::with_capacity(text.len());
336    let mut map = Vec::with_capacity(text.len() + 1);
337    let mut at = 0;
338    for c in changes {
339        if c.range.start < at || c.range.end > text.len() {
340            continue;
341        }
342        out.push_str(&text[at..c.range.start]);
343        map.extend(at..c.range.start);
344        out.push_str(&c.with);
345        let last = c.range.end.saturating_sub(1).max(c.range.start);
346        map.extend((0..c.with.len()).map(|k| (c.range.start + k).min(last)));
347        at = c.range.end;
348    }
349    out.push_str(&text[at..]);
350    map.extend(at..=text.len());
351    Reading { text: out, map }
352}
353
354#[cfg(test)]
355mod tests {
356    use proptest::prelude::*;
357
358    use super::*;
359
360    /// The reading of `text`, as a string.
361    fn read(text: &str) -> String {
362        reading(text).text
363    }
364
365    // sokf-tests: TLMD_258
366    #[test]
367    fn emphasis_reads_in_the_fixed_spelling() {
368        assert_eq!(read("*x* and _x_"), "_x_ and _x_");
369        assert_eq!(read("__x__ and **x**"), "**x** and **x**");
370        assert_eq!(read("foo*bar*baz"), "foo_bar_baz");
371        assert_eq!(read("***x*** and **_y_**"), "_**x**_ and **_y_**");
372        assert_eq!(read("a * b and 2*3"), "a * b and 2*3");
373        assert_eq!(read("snake_case_name"), "snake_case_name");
374        assert_eq!(read("Use *the* tool"), "Use _the_ tool");
375        assert_eq!(read("Ünï *x* é"), "Ünï _x_ é");
376        // An emphasis inside a word inside another reads alike whatever else
377        // the text holds, and judges no strong emphasis beside it.
378        assert_eq!(read("a*b *c*d*"), "a_b _c_d_");
379        assert_eq!(read("a*b *c*d* snake\\_case"), "a_b _c_d_ snake_case");
380        assert_eq!(read("a*x*__y__"), read("a*x***y**"));
381        // Beside punctuation that isn't ASCII, an emphasis is judged by its
382        // HTML.
383        assert_eq!(read("“*_init_*”"), "“*_init_*”");
384        assert_eq!(read("“*x*” and —*y*—"), "“_x_” and —_y_—");
385    }
386
387    // sokf-tests: TLMD_258
388    // sokf-tests: TLMD_261
389    #[test]
390    fn a_code_span_reads_in_its_shortest_backticks() {
391        assert_eq!(read("``#user``"), "`#user`");
392        assert_eq!(read("` | `"), "`|`");
393        assert_eq!(read("`` ` ``"), "`` ` ``");
394        assert_eq!(read("`` `x` ``"), "`` `x` ``");
395        assert_eq!(read("`  two  `"), "`  two  `");
396        assert_eq!(read("``x`y``"), "``x`y``");
397        assert_eq!(read("`*x*` and `snake\\_case`"), "`*x*` and `snake\\_case`");
398        assert_eq!(read("`  `"), "`  `");
399        // A line break inside a code span reads as a space, as a unit joins
400        // its lines.
401        assert_eq!(read("``\nfoo\n``"), "`foo`");
402    }
403
404    // sokf-tests: TLMD_260
405    #[test]
406    fn an_escape_reads_as_the_character_where_it_changes_nothing() {
407        assert_eq!(read("snake\\_case"), "snake_case");
408        assert_eq!(read("a \\* b"), "a * b");
409        assert_eq!(read("\\*x\\*"), "*x\\*");
410        assert_eq!(read("*x\\*"), "*x\\*");
411        assert_eq!(read("\\[x]"), "\\[x]");
412        assert_eq!(read("1\\. two"), "1. two");
413        assert_eq!(read("a \\\\ b"), "a \\ b");
414        assert_eq!(read("a\\|b"), "a\\|b");
415    }
416
417    // sokf-tests: TLMD_258
418    #[test]
419    fn a_link_reads_its_text_and_keeps_its_destination() {
420        assert_eq!(read("[*the* guide](u_v)"), "[_the_ guide](u_v)");
421        assert_eq!(read("[*a*](u) and ![*alt*](i)"), "[_a_](u) and ![_alt_](i)");
422        assert_eq!(read("<b>*h*</b>"), "<b>_h_</b>");
423        assert_eq!(read("[x](<a b> 'T')"), "[x](<a b> 'T')");
424    }
425
426    #[test]
427    fn a_reading_maps_each_byte_to_the_text() {
428        let r = reading("a \\_ ``b``");
429        assert_eq!(r.text, "a _ `b`");
430        assert_eq!(r.map, vec![0, 1, 3, 4, 5, 7, 8, 10]);
431        assert_eq!(reading("plain").map, vec![0, 1, 2, 3, 4, 5]);
432    }
433
434    #[test]
435    fn the_plain_text_drops_the_markers() {
436        assert_eq!(plain_text("Title *x*"), "Title x");
437        assert_eq!(plain_text("See [the guide](x)"), "See the guide");
438        assert_eq!(plain_text("What's `this`? (v2)"), "What's this? (v2)");
439        assert_eq!(plain_text("_Short_"), "Short");
440        assert_eq!(plain_text("1. Intro"), "1. Intro");
441        assert_eq!(plain_text("CLI-1_AC-2"), "CLI-1_AC-2");
442        assert_eq!(plain_text(""), "");
443    }
444
445    proptest! {
446        #![proptest_config(ProptestConfig::with_cases(256))]
447
448        /// A reading is never longer than its text, and maps in order
449        /// into it.
450        #[test]
451        fn a_reading_maps_in_order(text in "[ a-c*_`\\\\\\[\\]]{0,16}") {
452            let r = reading(&text);
453            prop_assert!(r.text.len() <= text.len());
454            prop_assert_eq!(r.map.len(), r.text.len() + 1);
455            prop_assert!(r.map.windows(2).all(|w| w[0] < w[1] || w[1] == text.len()));
456            prop_assert_eq!(*r.map.last().unwrap(), text.len());
457        }
458    }
459}