Skip to main content

devpage_core/
markup.rs

1//! Reading a page's Markdown as text, before it is rendered: its front
2//! matter, its title, its `<Notes>`, and the scanner that finds widget tags
3//! outside code. A leaf: it depends on nothing else in devpage, so documents,
4//! rendering, widgets and checking can all use it.
5
6use std::path::Path;
7
8/// The tag a slide's speaker notes are written in.
9pub const NOTES: &str = "Notes";
10
11/// A page's front matter's YAML, and the page after it.
12pub fn split_front_matter(source: &str) -> Option<(&str, &str)> {
13    let rest = source
14        .strip_prefix("---\n")
15        .or_else(|| source.strip_prefix("---\r\n"))?;
16    let mut at = 0;
17    for line in rest.split_inclusive('\n') {
18        if line.trim_end() == "---" {
19            return Some((&rest[..at], &rest[at + line.len()..]));
20        }
21        at += line.len();
22    }
23    None
24}
25
26/// A page's title: its first level-one heading, or its file name.
27pub fn title(source: &str, path: &Path) -> String {
28    split_front_matter(source)
29        .map_or(source, |(_, page)| page)
30        .lines()
31        .find_map(|line| line.strip_prefix("# "))
32        .map(|heading| heading.trim().to_string())
33        .unwrap_or_else(|| {
34            path.file_stem()
35                .unwrap_or_default()
36                .to_string_lossy()
37                .into_owned()
38        })
39}
40
41/// One `<Notes>` block: the line it starts on, its text, trimmed, as written,
42/// and its `delivery` attribute — how the narrator should sound saying it.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Note {
45    /// The line the `<Notes>` starts on, counting from 1.
46    pub line: usize,
47    /// What it says: the text between its tags, trimmed.
48    pub text: String,
49    /// Its `delivery` attribute; `None` when it has none.
50    pub delivery: Option<String>,
51}
52
53/// Each `<Notes>…</Notes>` block in a page's Markdown, outside code and HTML
54/// comments, as found by [`expand`]. A `<Notes>` without its `</Notes>` runs
55/// to the end of the page.
56pub fn notes(source: &str) -> Vec<Note> {
57    let code = code_ranges(source);
58    let in_code = |at: usize| code.iter().any(|r| r.contains(&at));
59    let open = format!("<{NOTES}");
60    let mut found = Vec::new();
61    let mut at = 0;
62    while let Some(offset) = source[at..].find(&open) {
63        let start = at + offset;
64        at = start + 1;
65        if in_code(start) {
66            continue;
67        }
68        let Some(tag) = parse_open(&source[start..])
69            .filter(|tag| tag.name == NOTES)
70            .or_else(|| {
71                unreadable_notes(&source[start..]).map(|len| OpenTag {
72                    name: NOTES.to_string(),
73                    props: "{}".to_string(),
74                    len,
75                    self_closing: false,
76                })
77            })
78        else {
79            continue;
80        };
81        let after_open = start + tag.len;
82        let (inner, end) = if tag.self_closing {
83            ("", after_open)
84        } else {
85            match find_close(source, after_open, NOTES, &in_code) {
86                Some((close_start, close_end)) => (&source[after_open..close_start], close_end),
87                None => (&source[after_open..], source.len()),
88            }
89        };
90        found.push(Note {
91            line: source[..start].matches('\n').count() + 1,
92            text: inner.trim().to_string(),
93            delivery: tag.string_prop("delivery"),
94        });
95        at = end;
96    }
97    found
98}
99
100/// An open tag at the start of some text, `<Name a="x" b={expr}>` or `<Name …
101/// />`, as [`parse_open`] reads it.
102pub(crate) struct OpenTag {
103    /// The tag's name: the letters and digits after `<`.
104    pub(crate) name: String,
105    /// The props as a JavaScript object literal.
106    pub(crate) props: String,
107    /// Its length in bytes, through its `>`.
108    pub(crate) len: usize,
109    /// Whether it ends `/>`, so it has no content and no close tag.
110    pub(crate) self_closing: bool,
111}
112
113/// What is wrong with a `<Notes …>` whose attributes don't parse.
114pub(crate) const UNREADABLE_NOTES: &str =
115    "a <Notes> whose attributes can't be read: write delivery=\"…\" with no double quotes inside";
116
117/// The length of a `<Notes …>` open tag that [`parse_open`] can't read — an
118/// attribute with a stray quote — up to its first `>`; `None` for anything
119/// else.
120pub(crate) fn unreadable_notes(text: &str) -> Option<usize> {
121    let rest = text.strip_prefix(&format!("<{NOTES}"))?;
122    if !rest.starts_with(char::is_whitespace) || parse_open(text).is_some() {
123        return None;
124    }
125    text.find('>').map(|end| end + 1)
126}
127
128impl OpenTag {
129    /// Whether the tag has a `key` attribute, of any form.
130    pub(crate) fn has_prop(&self, key: &str) -> bool {
131        self.props.contains(&format!("\"{key}\": "))
132    }
133
134    /// The string a `key="…"` attribute holds, if the tag has one.
135    pub(crate) fn string_prop(&self, key: &str) -> Option<String> {
136        let at = self.props.find(&format!("\"{key}\": \""))? + key.len() + 4;
137        let mut strings =
138            serde_json::Deserializer::from_str(&self.props[at..]).into_iter::<String>();
139        strings.next()?.ok()
140    }
141}
142
143/// Parses `<Name a="x" b={expr} c>` or `<Name … />` at the start of `text`.
144pub(crate) fn parse_open(text: &str) -> Option<OpenTag> {
145    let chars: Vec<(usize, char)> = text.char_indices().collect();
146    let mut i = 1;
147    let mut name = String::new();
148    while let Some(&(_, c)) = chars.get(i) {
149        if c.is_ascii_alphanumeric() {
150            name.push(c);
151            i += 1;
152        } else {
153            break;
154        }
155    }
156    let mut props = Vec::new();
157    loop {
158        while chars.get(i).is_some_and(|(_, c)| c.is_whitespace()) {
159            i += 1;
160        }
161        let &(_, c) = chars.get(i)?;
162        if c == '>' {
163            return Some(OpenTag {
164                name,
165                props: format!("{{{}}}", props.join(", ")),
166                len: chars.get(i + 1).map_or(text.len(), |(at, _)| *at),
167                self_closing: false,
168            });
169        }
170        if c == '/' && chars.get(i + 1).is_some_and(|(_, c)| *c == '>') {
171            return Some(OpenTag {
172                name,
173                props: format!("{{{}}}", props.join(", ")),
174                len: chars.get(i + 2).map_or(text.len(), |(at, _)| *at),
175                self_closing: true,
176            });
177        }
178        let mut attr = String::new();
179        while let Some(&(_, c)) = chars.get(i) {
180            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
181                attr.push(c);
182                i += 1;
183            } else {
184                break;
185            }
186        }
187        if attr.is_empty() {
188            return None;
189        }
190        let key = serde_json::to_string(&attr).ok()?;
191        if chars.get(i).is_some_and(|(_, c)| *c == '=') {
192            i += 1;
193            match chars.get(i)?.1 {
194                quote @ ('"' | '\'') => {
195                    let mut value = String::new();
196                    i += 1;
197                    while let Some(&(_, c)) = chars.get(i) {
198                        i += 1;
199                        if c == quote {
200                            break;
201                        }
202                        value.push(c);
203                    }
204                    props.push(format!("{key}: {}", serde_json::to_string(&value).ok()?));
205                }
206                '{' => {
207                    let mut depth = 0;
208                    let mut expr = String::new();
209                    let mut string: Option<char> = None;
210                    while let Some(&(_, c)) = chars.get(i) {
211                        i += 1;
212                        if let Some(q) = string {
213                            if c == q {
214                                string = None;
215                            }
216                        } else if matches!(c, '"' | '\'' | '`') {
217                            string = Some(c);
218                        } else if c == '{' {
219                            depth += 1;
220                            if depth == 1 {
221                                continue;
222                            }
223                        } else if c == '}' {
224                            depth -= 1;
225                            if depth == 0 {
226                                break;
227                            }
228                        }
229                        expr.push(c);
230                    }
231                    props.push(format!("{key}: ({expr})"));
232                }
233                _ => return None,
234            }
235        } else {
236            props.push(format!("{key}: true"));
237        }
238    }
239}
240
241/// Finds `</Name>` matching an open tag, counting nested ones of the same
242/// name and skipping code.
243pub(crate) fn find_close(
244    source: &str,
245    from: usize,
246    name: &str,
247    in_code: &dyn Fn(usize) -> bool,
248) -> Option<(usize, usize)> {
249    let open = format!("<{name}");
250    let close = format!("</{name}>");
251    let mut depth = 1;
252    let mut at = from;
253    loop {
254        let next_close = source[at..].find(&close).map(|o| at + o)?;
255        let next_open = source[at..]
256            .find(&open)
257            .map(|o| at + o)
258            .filter(|&o| o < next_close);
259        if let Some(o) = next_open {
260            at = o + open.len();
261            let boundary = source[at..].starts_with(|c: char| c.is_whitespace() || c == '>');
262            if !in_code(o) && boundary {
263                depth += 1;
264            }
265            continue;
266        }
267        at = next_close + close.len();
268        if in_code(next_close) {
269            continue;
270        }
271        depth -= 1;
272        if depth == 0 {
273            return Some((next_close, at));
274        }
275    }
276}
277
278/// Byte ranges of fenced code blocks and inline code spans.
279pub(crate) fn code_ranges(source: &str) -> Vec<std::ops::Range<usize>> {
280    let mut ranges = Vec::new();
281    let mut fence: Option<(usize, String)> = None;
282    let mut offset = 0;
283    // An indented code block starts after a blank line, outside a list, and
284    // runs while lines stay indented by four spaces or a tab (or are blank).
285    let mut previous_blank = true;
286    let mut in_list = false;
287    let mut indented: Option<usize> = None;
288    for line in source.split_inclusive('\n') {
289        let trimmed = line.trim_start();
290        let blank = trimmed.is_empty();
291        let is_indented = line.starts_with("    ") || line.starts_with('\t');
292        if fence.is_none() {
293            if let Some(start) = indented {
294                if !blank && !is_indented {
295                    ranges.push(start..offset);
296                    indented = None;
297                }
298            } else if is_indented && !blank && previous_blank && !in_list {
299                indented = Some(offset);
300            }
301            if indented.is_some() {
302                previous_blank = blank;
303                offset += line.len();
304                continue;
305            }
306            if !blank && !is_indented {
307                in_list = is_list_item(trimmed);
308            }
309        }
310        previous_blank = blank;
311        let marker: String = trimmed
312            .chars()
313            .take_while(|c| *c == '`' || *c == '~')
314            .collect();
315        match &fence {
316            Some((start, open)) => {
317                if marker.len() >= open.len() && marker.starts_with(&open[..1]) {
318                    ranges.push(*start..offset + line.len());
319                    fence = None;
320                }
321            }
322            None if marker.len() >= 3 => fence = Some((offset, marker)),
323            None => {
324                // Inline code spans on this line.
325                let mut i = 0;
326                let b = line.as_bytes();
327                while i < b.len() {
328                    if b[i] == b'`' {
329                        let run = b[i..].iter().take_while(|c| **c == b'`').count();
330                        let ticks = "`".repeat(run);
331                        if let Some(end) = line[i + run..].find(&ticks) {
332                            let close = i + run + end + run;
333                            ranges.push(offset + i..offset + close);
334                            i = close;
335                            continue;
336                        }
337                        i += run;
338                    } else {
339                        i += 1;
340                    }
341                }
342            }
343        }
344        offset += line.len();
345    }
346    if let Some((start, _)) = fence {
347        ranges.push(start..source.len());
348    }
349    if let Some(start) = indented {
350        ranges.push(start..source.len());
351    }
352    // HTML comments, outside code, hide whatever they hold.
353    let mut from = 0;
354    while let Some(open) = source[from..].find("<!--") {
355        let open = from + open;
356        if ranges.iter().any(|r| r.contains(&open)) {
357            from = open + 4;
358            continue;
359        }
360        let close = source[open + 4..]
361            .find("-->")
362            .map_or(source.len(), |end| open + 4 + end + 3);
363        ranges.push(open..close);
364        from = close;
365    }
366    ranges.sort_by_key(|r| r.start);
367    ranges
368}
369
370/// Whether a line, without its indentation, starts a Markdown list item.
371pub(crate) fn is_list_item(trimmed: &str) -> bool {
372    let bullet =
373        trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with("+ ");
374    let digits = trimmed.chars().take_while(|c| c.is_ascii_digit()).count();
375    bullet || (digits > 0 && matches!(trimmed[digits..].chars().next(), Some('.' | ')')))
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    #[test]
383    fn notes_keep_their_text_without_its_indentation() {
384        let source = "# Title\n\n<Notes>\n  Say **this**, word for word.\n</Notes>\n\nAfter.\n";
385        assert_eq!(
386            notes(source),
387            vec![Note {
388                line: 3,
389                text: "Say **this**, word for word.".to_string(),
390                delivery: None
391            }]
392        );
393    }
394
395    #[test]
396    fn unclosed_notes_run_to_the_end_of_the_page() {
397        let source = "# Title\n\nShown.\n\n<Notes>\nSay this.\n</Note>\n\nAfter.\n";
398        assert_eq!(
399            notes(source)[0].text,
400            "Say this.\n</Note>\n\nAfter.".to_string()
401        );
402    }
403
404    #[test]
405    fn a_notes_delivery_is_kept() {
406        let source = "<Notes delivery=\"Honest and a little teasing: you caught them.\">\nSay this.\n</Notes>\n";
407        assert_eq!(
408            notes(source)[0].delivery.as_deref(),
409            Some("Honest and a little teasing: you caught them.")
410        );
411    }
412
413    #[test]
414    fn a_notes_with_unreadable_attributes_keeps_its_text_and_no_delivery() {
415        for source in [
416            "<Notes delivery=\"the \"aha\" moment\">\nSAYTHIS\n</Notes>\n\nAfter.\n",
417            "<Notes delivery=\"say \\\"wow\\\" now\">\nSAYTHIS\n</Notes>\n\nAfter.\n",
418            "<Notes delivery={\"warm\"}>\nSAYTHIS\n</Notes>\n",
419        ] {
420            assert_eq!(notes(source)[0].text, "SAYTHIS");
421            assert_eq!(notes(source)[0].delivery, None);
422        }
423    }
424
425    #[test]
426    fn notes_inside_code_and_comments_are_not_notes() {
427        let source = "`<Notes>x</Notes>`\n\n```\n<Notes>fenced</Notes>\n```\n\n    <Notes>indented</Notes>\n\n<!-- <Notes>hidden</Notes> -->\n";
428        assert!(notes(source).is_empty(), "{:?}", notes(source));
429    }
430
431    #[test]
432    fn every_notes_block_is_found_with_its_line() {
433        let found = notes("<Notes>one</Notes>\n\ntext\n\n<Notes>\ntwo\n</Notes>\n<Notes/>\n");
434        let found: Vec<(usize, String)> = found.into_iter().map(|n| (n.line, n.text)).collect();
435        assert_eq!(
436            found,
437            vec![
438                (1, "one".to_string()),
439                (5, "two".to_string()),
440                (8, String::new())
441            ]
442        );
443    }
444}