Skip to main content

tramlines_md/markdown/
segments.rs

1//! Finds a host's region and trailer markers outside the fenced code
2//! blocks that comrak reads, before block grouping, so generated content
3//! never reaches block matching.
4
5use std::{fmt::Write as _, ops::Range};
6
7use serde::{Deserialize, Serialize};
8
9use super::{Dialect, Marker, code, link_definitions};
10
11/// A region as found on disk: the host's marker pair and what lies
12/// between.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Region {
15    /// The open marker's target, as written.
16    pub target: String,
17    /// The line of the open marker.
18    pub open_line: usize,
19    /// The line of the close marker.
20    pub close_line: usize,
21    /// The lines between the markers, each ending with `\n`.
22    pub content: String,
23}
24
25/// The generated block of reference definitions that ends a document, as
26/// found on disk.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct DefinitionBlock {
29    /// The line of the marker.
30    pub line: usize,
31    /// The reference definitions after it, as comrak reads them, each one
32    /// over all its lines: label and destination as written.
33    pub entries: Vec<(String, String)>,
34    /// Whether anything but a definition at the top level follows the
35    /// marker.
36    pub trailing: bool,
37    /// The text from the marker line to the end of the body.
38    pub text: String,
39}
40
41/// The markers of one body.
42#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Segments {
44    /// The regions, in order.
45    pub regions: Vec<Region>,
46    /// The definition block.
47    pub definition: Option<DefinitionBlock>,
48    /// The line of an open marker with no close marker.
49    pub unclosed: Option<usize>,
50    /// Lines of close markers with no open marker.
51    pub stray_closes: Vec<usize>,
52}
53
54impl Segments {
55    /// Whether `line` lies strictly inside a region.
56    pub fn in_region(&self, line: usize) -> bool {
57        self.regions
58            .iter()
59            .any(|i| i.open_line < line && line < i.close_line)
60            || self.unclosed.is_some_and(|open| line > open)
61    }
62
63    /// Whether `line` lies in the definition block.
64    pub fn in_definition(&self, line: usize) -> bool {
65        self.definition.as_ref().is_some_and(|d| line >= d.line)
66    }
67
68    /// Whether `line` is generated content or a marker.
69    pub fn is_generated(&self, line: usize) -> bool {
70        self.in_region(line)
71            || self.in_definition(line)
72            || self
73                .regions
74                .iter()
75                .any(|i| i.open_line == line || i.close_line == line)
76    }
77}
78
79/// Find the markers of `body`, whose first line is file line `first_line`,
80/// as `dialect` spells them.
81// sokf-implements: TLMD_13
82// sokf-implements: TLMD_14
83// sokf-implements: TLMD_16
84pub fn segments(body: &str, first_line: usize, dialect: &Dialect) -> Segments {
85    let mut out = Segments::default();
86    let lines: Vec<&str> = body.lines().collect();
87    // The bytes of each fenced code block, which only a marker needs.
88    let mut fences: Option<Vec<Range<usize>>> = None;
89    let mut open: Option<(String, usize, usize)> = None; // target, line, index
90    let mut start = 0;
91    for (i, raw) in body.split_inclusive('\n').enumerate() {
92        let line = lines[i];
93        let file_line = first_line + i;
94        let at = start;
95        start += raw.len();
96        let marker = dialect.marker(line).filter(|_| {
97            // The fences are in order and apart, so the one that could hold
98            // the line is the first that ends after it starts.
99            let fences = fences.get_or_insert_with(|| code::fenced(body));
100            let k = fences.partition_point(|f| f.end <= at);
101            !fences.get(k).is_some_and(|f| f.contains(&at))
102        });
103        match marker {
104            Some(Marker::Open(target)) if open.is_none() => {
105                open = Some((target, file_line, i));
106            }
107            Some(Marker::Close) => match open.take() {
108                Some((target, open_line, open_index)) => {
109                    let content: String =
110                        lines[open_index + 1..i]
111                            .iter()
112                            .fold(String::new(), |mut out, l| {
113                                let _ = writeln!(out, "{l}");
114                                out
115                            });
116                    out.regions.push(Region {
117                        target,
118                        open_line,
119                        close_line: file_line,
120                        content,
121                    });
122                }
123                None => out.stray_closes.push(file_line),
124            },
125            Some(Marker::Trailer) if open.is_none() => {
126                out.definition = Some(definition(&lines[i..], file_line));
127                return finish(out, open.as_ref());
128            }
129            Some(Marker::Open(_) | Marker::Trailer) | None => {}
130        }
131    }
132    finish(out, open.as_ref())
133}
134
135fn finish(mut out: Segments, open: Option<&(String, usize, usize)>) -> Segments {
136    if let Some(&(_, line, _)) = open {
137        out.unclosed = Some(line);
138    }
139    out
140}
141
142/// The trailer whose marker is the first of `lines`, at file line `line`.
143/// Its definitions read as comrak reads them, so one whose destination or
144/// title a formatter moves to a later line is one entry.
145// sokf-implements: TLMD_268
146// sokf-implements: MD-3_AC-17
147fn definition(lines: &[&str], line: usize) -> DefinitionBlock {
148    // A definition reads as one at the top level, whatever its indent, and
149    // one in a quote or an item is other content.
150    let after: Vec<&str> = lines[1..].iter().map(|l| l.trim_start()).collect();
151    let top: Vec<_> = link_definitions::read(&after)
152        .defs
153        .into_iter()
154        .filter(|d| after[d.first].starts_with('['))
155        .collect();
156    // Every line with text that no definition at the top level takes,
157    // a `>` alone among them, trails the trailer.
158    let taken = |i: usize| top.iter().any(|d| d.first <= i && i <= d.last);
159    let trailing = after
160        .iter()
161        .enumerate()
162        .any(|(i, l)| !l.trim().is_empty() && !taken(i));
163    let entries = top.into_iter().map(|d| (d.label, d.dest)).collect();
164    let text: String = lines.iter().fold(String::new(), |mut out, l| {
165        let _ = writeln!(out, "{l}");
166        out
167    });
168    DefinitionBlock {
169        line,
170        entries,
171        trailing,
172        text,
173    }
174}
175
176/// Parse `[label]: destination` on one line, without the lines that a
177/// definition's destination or title can take after it.
178pub fn ref_def(line: &str) -> Option<(String, String)> {
179    let t = line.trim();
180    let rest = t.strip_prefix('[')?;
181    let end = rest.find("]:")?;
182    let label = &rest[..end];
183    if label.is_empty() || label.contains('[') {
184        return None;
185    }
186    let dest = rest[end + 2..].trim();
187    let dest = dest.split_whitespace().next()?;
188    Some((label.to_string(), dest.to_string()))
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    const HOST: Dialect = Dialect {
196        namespace: "host",
197        region: Some("include"),
198        trailer: Some("links"),
199        scheme: Some("host"),
200    };
201
202    fn segments(body: &str, first_line: usize) -> Segments {
203        super::segments(body, first_line, &HOST)
204    }
205
206    #[test]
207    fn finds_includes_and_the_definition_block() {
208        let body = "intro\n\n<!-- host:include a -->\n\nbody a\n\n<!-- /host:include -->\n\n```\n<!-- host:include fenced -->\n```\n\n<!-- host:links -->\n\n[host:a]: /k/a.md\n[host:b#c]: /k/b.md#c\n";
209        let s = segments(body, 10);
210        assert_eq!(s.regions.len(), 1);
211        let inc = &s.regions[0];
212        assert_eq!(inc.target, "a");
213        assert_eq!((inc.open_line, inc.close_line), (12, 16));
214        assert_eq!(inc.content, "\nbody a\n\n");
215        let def = s.definition.clone().unwrap();
216        assert_eq!(def.line, 22);
217        assert_eq!(
218            def.entries,
219            vec![
220                ("host:a".to_string(), "/k/a.md".to_string()),
221                ("host:b#c".to_string(), "/k/b.md#c".to_string())
222            ]
223        );
224        assert!(!def.trailing);
225        assert!(def.text.starts_with("<!-- host:links -->\n"));
226        assert!(s.unclosed.is_none());
227        assert!(s.in_region(14));
228        assert!(!s.in_region(12));
229        assert!(s.in_definition(23));
230        assert!(s.is_generated(12));
231        assert!(!s.is_generated(11));
232    }
233
234    #[test]
235    fn unclosed_and_stray_markers() {
236        let s = segments(
237            "<!-- /host:include -->\n<!-- host:include a -->\nx\n<!-- host:include b -->\n",
238            1,
239        );
240        assert_eq!(s.stray_closes, vec![1]);
241        assert_eq!(s.unclosed, Some(2));
242        assert!(s.regions.is_empty(), "{:?}", s.regions);
243        assert!(s.in_region(3));
244        // A links marker inside an open include is content, not the block.
245        let s = segments(
246            "<!-- host:include a -->\n<!-- host:links -->\n<!-- /host:include -->\n",
247            1,
248        );
249        assert!(s.definition.is_none());
250        assert_eq!(s.regions.len(), 1);
251    }
252
253    #[test]
254    fn definition_block_with_trailing_content() {
255        let s = segments("x\n<!-- host:links -->\n[host:a]: /a.md\nnot a def\n", 1);
256        let def = s.definition.unwrap();
257        assert!(def.trailing);
258        assert_eq!(def.entries.len(), 1);
259    }
260
261    // A definition of the trailer whose destination or title a formatter
262    // moves to a later line is one entry, and nothing trails it.
263    // sokf-tests: TLMD_14
264    // sokf-tests: TLMD_268
265    // sokf-tests: MD-3_AC-17
266    #[test]
267    fn a_wrapped_definition_of_the_trailer_is_one_entry() {
268        for after in [
269            "[host:a]: /k/a.md\n[host:b#c]: /k/b.md#c \"T\"\n",
270            "[host:a]:\n  /k/a.md\n[host:b#c]:\n  /k/b.md#c\n  \"T\"\n",
271            "[host:a]: /k/a.md\n\n[host:b#c]: /k/b.md#c\n\"T\"\n",
272            "    [host:a]: /k/a.md\n[host:b#c]: /k/b.md#c \"T\nU\"\n",
273        ] {
274            let s = segments(&format!("x\n\n<!-- host:links -->\n\n{after}"), 1);
275            let def = s.definition.unwrap();
276            assert!(!def.trailing, "{after:?}");
277            assert_eq!(
278                def.entries,
279                vec![
280                    ("host:a".to_string(), "/k/a.md".to_string()),
281                    ("host:b#c".to_string(), "/k/b.md#c".to_string())
282                ],
283                "{after:?}"
284            );
285        }
286        let s = segments("<!-- host:links -->\n[host:a]: <k a.md>\n", 1);
287        let def = s.definition.unwrap();
288        assert!(!def.trailing);
289        assert_eq!(
290            def.entries,
291            vec![("host:a".to_string(), "<k a.md>".to_string())]
292        );
293        // A label alone, a definition in a quote or an item, and a title
294        // that never closes trail the trailer.
295        for after in [
296            "[host:a]:\n",
297            "> [host:a]: /k/a.md\n",
298            "[host:a]: /k/a.md\n>\n",
299            "- [host:a]: /k/a.md\n",
300            "[host:a]: /k/a.md \"T\n",
301        ] {
302            let s = segments(&format!("<!-- host:links -->\n{after}"), 1);
303            assert!(s.definition.unwrap().trailing, "{after:?}");
304        }
305    }
306
307    // sokf-tests: TLMD_16
308    #[test]
309    fn fences_hide_markers_including_tildes_and_longer_closers() {
310        let body = "~~~\n<!-- host:links -->\n~~~\n````md\n```\n<!-- host:include a -->\n````\n- ```\n  <!-- host:include a -->\n  ```\n<!-- host:links -->\n";
311        let s = segments(body, 1);
312        assert!(s.regions.is_empty(), "{:?}", s.regions);
313        assert_eq!(s.definition.unwrap().line, 11);
314    }
315
316    /// The target of each region of `body`.
317    fn targets(body: &str) -> Vec<String> {
318        segments(body, 1)
319            .regions
320            .into_iter()
321            .map(|r| r.target)
322            .collect()
323    }
324
325    // sokf-tests: TLMD_16
326    #[test]
327    fn a_fence_in_a_footnote_hides_a_marker() {
328        let body = "Text[^1].\n\n[^1]: Note.\n\n    ```\n    <!-- host:include a -->\n    <!-- /host:include -->\n    ```\n";
329        let found = targets(body);
330        assert!(found.is_empty(), "{found:?}");
331    }
332
333    // sokf-tests: TLMD_16
334    #[test]
335    fn a_fence_ends_with_the_quote_or_the_item_that_holds_it() {
336        let region = "\n<!-- host:include a -->\nx\n<!-- /host:include -->\n";
337        for fence in [
338            "> - ```\n>   code\n",
339            "- a\n  - b\n\n    > ```\n    > code\n",
340            ">\t```\n>\tcode\n",
341            "- ```\n  code\n",
342        ] {
343            assert_eq!(targets(&format!("{fence}{region}")), ["a"], "{fence:?}");
344        }
345    }
346
347    // sokf-tests: TLMD_16
348    #[test]
349    fn only_a_fence_hides_a_marker() {
350        // A line of backticks inside an indented block, or after a fence's
351        // info string holds a backtick, opens no fence.
352        for text in ["    ```\n", "``` a ` b\n", "``\n"] {
353            let body = format!("{text}\n<!-- host:include a -->\nx\n<!-- /host:include -->\n");
354            assert_eq!(targets(&body), ["a"], "{text:?}");
355        }
356    }
357
358    #[test]
359    fn ref_defs() {
360        assert_eq!(ref_def("[a]: /x"), Some(("a".into(), "/x".into())));
361        assert_eq!(
362            ref_def("[a]: /x \"title\""),
363            Some(("a".into(), "/x".into()))
364        );
365        assert_eq!(ref_def("[a]:"), None);
366        assert_eq!(ref_def("[]: x"), None);
367        assert_eq!(ref_def("[a][b]: x"), None);
368        assert_eq!(ref_def("text"), None);
369    }
370}