Skip to main content

tramlines_md/markdown/
body.rs

1//! The parsed body: blocks with units as grammar `block` and `unit` read
2//! them, plus positioned headings, links, footnotes and definitions.
3
4use std::{borrow::Cow, ops::Range};
5
6use serde::{Deserialize, Serialize};
7
8use super::{Anchor, Change, Dialect, Reading, apply, parse, plain_text, reading, slug};
9use crate::{RepoPath, text};
10
11/// One variant per grammar `block.kind` value.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum BlockKind {
14    /// Paragraphs.
15    Prose,
16    /// A bullet list.
17    BulletList,
18    /// An ordered list.
19    NumberedList,
20    /// A GFM table.
21    Table,
22    /// A code block.
23    Code,
24    /// A block quote.
25    Blockquote,
26    /// A paragraph of images only.
27    Image,
28    /// The host's region: a block its open and close markers bound.
29    Region,
30    /// An HTML block.
31    Html,
32    /// A horizontal rule.
33    ThematicBreak,
34    /// Link reference definitions at the top level of the body, outside
35    /// the generated block.
36    References,
37    /// A repeating sequence of blocks; matched by the checker, never parsed.
38    Group,
39    /// A heading inside an item or a quote, which is no heading of the
40    /// document; parsed, and named by no schema.
41    Heading,
42}
43
44impl BlockKind {
45    /// The grammar's name for the kind, the host's region as `region`.
46    pub fn name(self) -> &'static str {
47        match self {
48            BlockKind::Prose => "prose",
49            BlockKind::BulletList => "bullet-list",
50            BlockKind::NumberedList => "numbered-list",
51            BlockKind::Table => "table",
52            BlockKind::Code => "code",
53            BlockKind::Blockquote => "blockquote",
54            BlockKind::Image => "image",
55            BlockKind::Region => "region",
56            BlockKind::Html => "html",
57            BlockKind::ThematicBreak => "thematic-break",
58            BlockKind::References => "references",
59            BlockKind::Group => "group",
60            BlockKind::Heading => "heading",
61        }
62    }
63
64    /// The grammar's name for the kind, the host's region by the name its
65    /// dialect gives it.
66    pub fn name_in(self, dialect: &Dialect) -> &'static str {
67        match (self, dialect.region) {
68            (BlockKind::Region, Some(region)) => region,
69            _ => self.name(),
70        }
71    }
72
73    /// The kind's name in `dialect` after its article, as a sentence names
74    /// a block: "a bullet-list".
75    pub(crate) fn spoken_in(self, dialect: &Dialect) -> String {
76        let name = self.name_in(dialect);
77        format!("{} {name}", text::article(name))
78    }
79
80    /// The kind the grammar names `s`, as `dialect` names the region.
81    pub fn parse_in(s: &str, dialect: &Dialect) -> Option<Self> {
82        if dialect.region == Some(s) {
83            return Some(BlockKind::Region);
84        }
85        Self::parse(s).filter(|k| *k != BlockKind::Region)
86    }
87
88    /// The kind the grammar names `s`.
89    pub fn parse(s: &str) -> Option<Self> {
90        [
91            BlockKind::Prose,
92            BlockKind::BulletList,
93            BlockKind::NumberedList,
94            BlockKind::Table,
95            BlockKind::Code,
96            BlockKind::Blockquote,
97            BlockKind::Image,
98            BlockKind::Region,
99            BlockKind::Html,
100            BlockKind::ThematicBreak,
101            BlockKind::References,
102            BlockKind::Group,
103        ]
104        .into_iter()
105        .find(|k| k.name() == s)
106    }
107}
108
109// sokf:begin block-detail
110/// The per-kind facts grammar `block` keys test.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112pub enum BlockDetail {
113    /// Nothing beyond the kind.
114    None,
115    /// A code block's tag and fence length; an indented block has an empty
116    /// tag and fence 0.
117    Code {
118        /// The first word of the info string.
119        lang: String,
120        /// The number of backticks or tildes.
121        fence: usize,
122    },
123    /// A table's header row.
124    Table {
125        /// The header cells, as written.
126        columns: Vec<String>,
127        /// The reading of each header cell (`TLMD_258`).
128        #[serde(default)]
129        readings: Vec<String>,
130    },
131    /// A region's open-marker target, as written.
132    Region {
133        /// The target text.
134        target: String,
135    },
136    /// The headings inside a blockquote, which the quote does not read as
137    /// its paragraphs, each with its lines and its style.
138    Quote {
139        /// Each heading.
140        headings: Vec<Heading>,
141    },
142}
143// sokf:end block-detail
144
145/// One part of a body.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct Block {
148    /// The kind.
149    pub kind: BlockKind,
150    /// The line the block starts on.
151    pub line: usize,
152    /// The line the block ends on.
153    pub end_line: usize,
154    /// Paragraphs, items, rows, or the one unit of a code or HTML block.
155    pub units: Vec<Unit>,
156    /// The per-kind facts.
157    pub detail: BlockDetail,
158    /// Lines carrying inline HTML other than a comment.
159    pub html_lines: Vec<usize>,
160}
161
162impl Block {
163    /// A block of `kind` holding `units`, with no per-kind facts and no
164    /// inline HTML.
165    pub(crate) fn new(kind: BlockKind, line: usize, end_line: usize, units: Vec<Unit>) -> Self {
166        Block {
167            kind,
168            line,
169            end_line,
170            units,
171            detail: BlockDetail::None,
172            html_lines: Vec::new(),
173        }
174    }
175}
176
177// sokf:begin unit
178/// A paragraph, an item, a row, or an image.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180pub struct Unit {
181    /// The text as written, lines joined by one space.
182    pub text: String,
183    /// The reading of `text`, each byte mapped to a byte of `text`
184    /// (`TLMD_258`): the text itself for a unit that is not a paragraph, an
185    /// item, a table row, or a heading inside an item or a quote.
186    #[serde(default)]
187    pub reading: Reading,
188    /// The line the unit's own text starts on: for a list item whose first
189    /// paragraph starts below its marker, after a link reference definition
190    /// or the marker alone, the line of that paragraph (`TLMD_290`). An item
191    /// that opens with an HTML block keeps the line of its marker.
192    pub line: usize,
193    /// The line the unit's own text ends on: a paragraph's last line, an
194    /// item's first paragraph's last line.
195    #[serde(default)]
196    pub end_line: usize,
197    /// What a list item carries beyond its own text.
198    pub nested: Vec<Block>,
199    /// Where each piece of `text` lies, in order: empty for a unit that is
200    /// not a paragraph, an item, a table row, or a heading inside an item or
201    /// a quote, whose pieces leave out the hashes that its text starts with.
202    #[serde(default)]
203    pub pieces: Vec<Piece>,
204}
205// sokf:end unit
206
207/// The start of one piece of a unit's text: a line of a paragraph or of a
208/// heading, or a table cell. The piece runs on unbroken in its line.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
210pub struct Piece {
211    /// The byte offset in the unit's text.
212    pub offset: usize,
213    /// The file line.
214    pub line: usize,
215    /// The byte column in the line, anchors removed.
216    pub col: usize,
217}
218
219impl Unit {
220    /// A unit of `text` from `line` to `end_line`, with nothing nested and
221    /// no pieces mapped.
222    pub(crate) fn leaf(text: String, line: usize, end_line: usize) -> Self {
223        Unit {
224            reading: Reading::written(&text),
225            text,
226            line,
227            end_line,
228            nested: Vec::new(),
229            pieces: Vec::new(),
230        }
231    }
232
233    /// The file line and byte column of `offset` in the text, anchors
234    /// removed; `None` for a unit with no pieces.
235    pub fn position(&self, offset: usize) -> Option<(usize, usize)> {
236        position(&self.pieces, offset)
237    }
238
239    /// Whether `offset` lies in the text that joins two pieces, the space
240    /// that joins two lines or the ` | ` that joins two cells, which no piece
241    /// covers: only spaces and pipes stand between it and the next piece.
242    pub(crate) fn in_joint(&self, offset: usize) -> bool {
243        self.pieces
244            .iter()
245            .find(|p| p.offset > offset)
246            .and_then(|next| self.text.get(offset..next.offset))
247            .is_some_and(|gap| !gap.is_empty() && gap.bytes().all(|b| b == b' ' || b == b'|'))
248    }
249
250    /// The file line and byte column of the first piece of the text at or
251    /// after `offset`, anchors removed; `None` where none starts there.
252    pub(crate) fn position_after(&self, offset: usize) -> Option<(usize, usize)> {
253        let piece = self.pieces.iter().find(|p| p.offset >= offset)?;
254        Some((piece.line, piece.col))
255    }
256}
257
258/// The file line and byte column of `offset` in a text whose pieces are
259/// `pieces`; `None` where it has none.
260pub(super) fn position(pieces: &[Piece], offset: usize) -> Option<(usize, usize)> {
261    let piece = pieces.iter().rev().find(|p| p.offset <= offset)?;
262    Some((piece.line, piece.col + (offset - piece.offset)))
263}
264
265// sokf:begin heading
266/// A heading.
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct Heading {
269    /// 1 to 6.
270    pub level: u8,
271    /// The text as written.
272    pub text: String,
273    /// The reading of `text`, each byte mapped to a byte of `text`
274    /// (`TLMD_258`).
275    #[serde(default)]
276    pub reading: Reading,
277    /// The slug of the plain text of the heading (`TLMD_101`).
278    pub slug: String,
279    /// The line of the heading, or of a setext heading's first line.
280    pub line: usize,
281    /// The last line: the underline of a setext heading.
282    pub end_line: usize,
283    /// Whether the heading is setext.
284    pub setext: bool,
285}
286// sokf:end heading
287
288impl Heading {
289    /// A heading of `text`, with its reading and the slug of its plain
290    /// text, from `line` to `end_line`.
291    // sokf-implements: MD-3_AC-15
292    // sokf-implements: MD-3_AC-16
293    // sokf-implements: TLMD_101
294    pub(crate) fn new(
295        level: u8,
296        text: String,
297        reading: Reading,
298        (line, end_line): (usize, usize),
299        setext: bool,
300    ) -> Self {
301        Heading {
302            level,
303            reading,
304            slug: slug(&plain_text(&text)),
305            text,
306            line,
307            end_line,
308            setext,
309        }
310    }
311}
312
313// sokf:begin link-target
314/// The forms a body link takes.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub enum LinkTarget {
317    /// `[text][<scheme>:<rest>]`, a reference in the host's scheme: the
318    /// label after `<scheme>:`, which the host resolves.
319    Host(String),
320    /// A reference-style link whose label is in no host scheme and matches
321    /// no definition.
322    Reference(String),
323    /// A `/`-rooted path.
324    Repo {
325        /// The path, without the query, the fragment, and the trailing `/`
326        /// characters of the link.
327        path: RepoPath,
328        /// The text after `#`.
329        fragment: Option<String>,
330        /// Whether the path of the link, before any `?` or `#`, ends with
331        /// `/`: the path then names only a directory, which the host checks.
332        #[serde(default)]
333        dir: bool,
334    },
335    /// A path resolved from the containing file.
336    Relative {
337        /// The path as written, without its query and its fragment.
338        target: String,
339        /// The text after `#`.
340        fragment: Option<String>,
341    },
342    /// An absolute URL.
343    Url(String),
344    /// A `#fragment` alone.
345    Anchor(String),
346    /// A `/`-rooted path that is not a valid repository path: one with an
347    /// empty, a `.`, or a `..` segment. The link as written.
348    Invalid(String),
349}
350// sokf:end link-target
351
352/// A body link or image.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354pub struct Link {
355    /// Where it points.
356    pub target: LinkTarget,
357    /// The line.
358    pub line: usize,
359    /// Whether it is an image.
360    pub is_image: bool,
361    /// The last line the link covers: a link may wrap.
362    #[serde(default)]
363    pub end_line: usize,
364    /// An inline link's destination as written, from `](` to the closing
365    /// `)`, when it lies on one line: what a repair replaces to respell it.
366    /// `None` for a reference-style link.
367    #[serde(default)]
368    pub inline: Option<String>,
369}
370
371impl Link {
372    /// The first and the last line the link covers.
373    pub fn lines(&self) -> (usize, usize) {
374        (self.line, self.end_line.max(self.line))
375    }
376}
377
378// sokf:begin code-block
379/// A code block of a body, at any depth of quotes, lists, and footnotes.
380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381pub struct CodeBlock {
382    /// The bytes of the block's lines in the body as written: from the
383    /// start of its first line, which holds the opening fence of a fenced
384    /// block, to the end of its last line, which holds the closing fence
385    /// where the block has one, before that line's ending. The range holds
386    /// no blank line after the block's last line. The offsets count from the start of the text that
387    /// `markdown::parse` takes, before it blanks a region or the trailer or
388    /// removes an anchor; `Document::parse` gives it the body after the
389    /// frontmatter, with CRLF and a carriage return alone read as LF. A
390    /// line ends at a line feed, at a carriage return and a line feed, or at
391    /// a carriage return alone.
392    pub bytes: Range<usize>,
393    /// Whether the block is fenced; an indented block is not.
394    pub fenced: bool,
395}
396// sokf:end code-block
397
398/// A parsed body.
399#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
400pub struct Body {
401    /// The blocks, in order, headings excluded.
402    pub blocks: Vec<Block>,
403    /// The headings, in order.
404    pub headings: Vec<Heading>,
405    /// Every link and image, include interiors and the definition block
406    /// excluded.
407    pub links: Vec<Link>,
408    /// Footnote references: label and line.
409    pub footnote_refs: Vec<(String, usize)>,
410    /// Footnote definitions: label and line.
411    pub footnote_defs: Vec<(String, usize)>,
412    /// The link reference definitions outside the generated block, those
413    /// in a list item or a quote among them, as comrak reads them: label,
414    /// destination as written, and the line of the label, in order.
415    pub ref_defs: Vec<(String, String, usize)>,
416    /// Lines carrying inline HTML other than a comment.
417    pub inline_html: Vec<usize>,
418    /// Line ranges of fenced and indented code, inclusive: the lines of
419    /// each entry of `code_blocks`.
420    pub fenced: Vec<(usize, usize)>,
421    /// Every code block, at any depth of quotes, lists, and footnotes, in
422    /// the order of the document; none inside a region or the trailer.
423    #[serde(default)]
424    pub code_blocks: Vec<CodeBlock>,
425    /// Byte ranges a code span covers: line, start, end. A span crossing
426    /// lines records one entry per line.
427    #[serde(default)]
428    pub code_spans: Vec<(usize, usize, usize)>,
429    /// Byte ranges a link's text and destination cover: line, start, end,
430    /// as `code_spans`.
431    #[serde(default)]
432    pub link_spans: Vec<(usize, usize, usize)>,
433    /// The generated anchors, removed from the text before it was parsed
434    /// (`TLMD_107`).
435    #[serde(default)]
436    pub anchors: Vec<Anchor>,
437    /// Each change that the readings of the units and the headings make on
438    /// one line, in order: the line, the start and the end of the bytes
439    /// that it replaces in the line without its anchors, and what the
440    /// reading writes in their place.
441    #[serde(default)]
442    pub reading_changes: Vec<(usize, usize, usize, String)>,
443    /// The line the body starts on.
444    pub first_line: usize,
445}
446
447impl Body {
448    /// Each heading inside a list item or a quote, at any depth, in the
449    /// order of the document, with the slug of `TLMD_101`. Such a heading is
450    /// part of its block, not a heading of the document (`TLMD_173`), but a
451    /// host that resolves a link to it needs it.
452    // sokf-implements: MD-3_AC-8
453    pub fn nested_headings(&self) -> Vec<Heading> {
454        let mut out = headings_in(&self.blocks);
455        out.sort_by_key(|h| h.line);
456        out
457    }
458
459    /// The blocks between `from` (exclusive) and `to` (exclusive), as a
460    /// section's body.
461    pub fn blocks_between(&self, from: usize, to: usize) -> Vec<&Block> {
462        self.blocks
463            .iter()
464            .filter(|b| b.line > from && b.line < to)
465            .collect()
466    }
467
468    /// Whether `line` lies inside fenced or indented code.
469    pub fn in_code(&self, line: usize) -> bool {
470        self.fenced.iter().any(|&(s, e)| s <= line && line <= e)
471    }
472
473    /// `text`, the line numbered `line` as written, without the generated
474    /// anchors the parse removed from it.
475    pub fn clean_line<'a>(&self, line: usize, text: &'a str) -> std::borrow::Cow<'a, str> {
476        let mut on_line: Vec<&Anchor> = self.anchors.iter().filter(|a| a.line == line).collect();
477        if on_line.is_empty() {
478            return std::borrow::Cow::Borrowed(text);
479        }
480        on_line.sort_by_key(|a| std::cmp::Reverse(a.raw_col));
481        let mut out = text.to_string();
482        for a in on_line {
483            let end = a.raw_col + a.rendered().len();
484            if end <= out.len() && out.is_char_boundary(a.raw_col) && out.is_char_boundary(end) {
485                out.replace_range(a.raw_col..end, "");
486            }
487        }
488        std::borrow::Cow::Owned(out)
489    }
490
491    /// `text`, the line numbered `line` without its anchors, in its reading:
492    /// each change that the readings of the units and the headings make on
493    /// the line applied, each byte mapped to its byte of `text`.
494    // sokf-implements: TLMD_111
495    pub fn read_line(&self, line: usize, text: &str) -> Reading {
496        let first = self.reading_changes.partition_point(|c| c.0 < line);
497        let changes: Vec<Change> = self.reading_changes[first..]
498            .iter()
499            .take_while(|c| c.0 == line)
500            .map(|(_, start, end, with)| Change {
501                range: *start..*end,
502                with: with.clone(),
503            })
504            .collect();
505        apply(text, &changes)
506    }
507
508    /// Whether byte `col` of `line` lies inside a code span.
509    pub fn in_code_span(&self, line: usize, col: usize) -> bool {
510        self.code_spans
511            .iter()
512            .any(|&(l, s, e)| l == line && s <= col && col < e)
513    }
514
515    /// The byte ranges of the text of `unit` that lie inside a code span,
516    /// a span that crosses lines included, from the ranges the parse
517    /// records. A unit with no pieces, such as a line of a fence, has none.
518    // sokf-implements: TLMD_111
519    // sokf-implements: TLMD_112
520    pub(crate) fn code_in(&self, unit: &Unit) -> Vec<std::ops::Range<usize>> {
521        let mut out = Vec::new();
522        for (k, piece) in unit.pieces.iter().enumerate() {
523            // A piece runs to where the next one starts in the text, and,
524            // where the next is a cell on the same line, to that cell's
525            // column, so a separator never reaches into the next cell.
526            let next = unit.pieces.get(k + 1);
527            let width = next.map_or(unit.text.len(), |p| p.offset) - piece.offset;
528            let mut stop_col = piece.col + width;
529            if let Some(p) = next.filter(|p| p.line == piece.line) {
530                stop_col = stop_col.min(p.col);
531            }
532            let first = self
533                .code_spans
534                .partition_point(|&(line, _, _)| line < piece.line);
535            for &(_, start, end) in self.code_spans[first..]
536                .iter()
537                .take_while(|&&(line, _, _)| line == piece.line)
538            {
539                let from = start.max(piece.col);
540                let to = end.min(stop_col);
541                if from < to {
542                    out.push(piece.offset + (from - piece.col)..piece.offset + (to - piece.col));
543                }
544            }
545        }
546        out
547    }
548
549    /// Whether byte `col` of `line` lies strictly inside a code span or a
550    /// link, and where that span starts.
551    pub fn span_around(&self, line: usize, col: usize) -> Option<usize> {
552        self.code_spans
553            .iter()
554            .chain(&self.link_spans)
555            .filter(|&&(l, s, e)| l == line && s < col && col < e)
556            .map(|&(_, s, _)| s)
557            .min()
558    }
559
560    /// `text`, the line numbered `line`, with every code span overwritten
561    /// by a run of backticks, as `mask_code` reads it. Lengths, byte
562    /// offsets, and line numbers are kept, so a finding still points where the text is.
563    // sokf-implements: TLMD_111
564    // sokf-implements: TLMD_112
565    pub fn mask_spans<'a>(&self, line: usize, text: &'a str) -> Cow<'a, str> {
566        // A span that crosses onto this line is recorded from its first
567        // column, so it leaves the indent and the quote markers before
568        // the code as they are, where a unit's text leaves them out.
569        let lead = text.len() - parse::strip_prefix(text).len();
570        let spans: Vec<std::ops::Range<usize>> = self
571            .code_spans
572            .iter()
573            .filter(|&&(l, _, _)| l == line)
574            .map(|&(_, s, e)| if s == 0 { lead.min(e)..e } else { s..e })
575            .collect();
576        mask_code(text, &spans)
577    }
578}
579
580/// `text` with each of `code`, byte ranges of it that lie in a code span,
581/// read as a run of backticks one byte for each byte, which is what every
582/// ban reads (`TLMD_111`). A backtick is what the text already holds
583/// at the edges of a code span, so a ban finds no word of the code and no
584/// gap where it was: a ban on a space before a comma, or on a word that a
585/// space and the code follow, matches only what the text holds.
586// sokf-implements: TLMD_111
587pub(crate) fn mask_code<'a>(text: &'a str, code: &[std::ops::Range<usize>]) -> Cow<'a, str> {
588    if code.is_empty() {
589        return Cow::Borrowed(text);
590    }
591    let mut out = text.to_string();
592    for r in code {
593        // A range covers whole characters, so the text stays UTF-8.
594        let start = text.floor_char_boundary(r.start.min(text.len()));
595        let end = text.ceil_char_boundary(r.end.min(text.len()));
596        out.replace_range(start..end, &"`".repeat(end - start));
597    }
598    Cow::Owned(out)
599}
600
601/// The headings inside `blocks` at any depth, through quotes and the
602/// blocks inside items, each with its lines and its style.
603pub(super) fn headings_in(blocks: &[Block]) -> Vec<Heading> {
604    let mut out = Vec::new();
605    for b in blocks {
606        match (&b.kind, &b.detail) {
607            (BlockKind::Heading, _) => out.extend(b.units.iter().map(nested_heading)),
608            (_, BlockDetail::Quote { headings }) => out.extend(headings.iter().cloned()),
609            _ => {
610                for u in &b.units {
611                    out.extend(headings_in(&u.nested));
612                }
613            }
614        }
615    }
616    out
617}
618
619/// The heading that `unit`, a heading inside an item or a quote, holds. Its
620/// text starts with its hashes and a space, which give its level, and it is
621/// setext where it spans more than one line, because an ATX heading has
622/// one line.
623fn nested_heading(unit: &Unit) -> Heading {
624    let (hashes, text) = unit.text.split_once(' ').unwrap_or((&unit.text, ""));
625    let level = u8::try_from(hashes.len()).unwrap_or(6);
626    Heading::new(
627        level,
628        text.to_string(),
629        reading(text),
630        (unit.line, unit.end_line),
631        unit.end_line > unit.line,
632    )
633}
634
635#[cfg(test)]
636mod tests {
637    use super::*;
638
639    #[test]
640    fn nested_headings_are_the_headings_inside_an_item_or_a_quote() {
641        let text = "# Top\n\n> ## Inner\n>\n> Text.\n\n- ## In item\n- Set\n  text\n  ---\n";
642        let segments = crate::markdown::segments(text, 1, &Dialect::default());
643        let body = crate::markdown::parse(text, 1, &segments, &Dialect::default());
644        let nested = body.nested_headings();
645        let seen: Vec<(usize, u8, &str, &str)> = nested
646            .iter()
647            .map(|h| (h.line, h.level, h.text.as_str(), h.slug.as_str()))
648            .collect();
649        assert_eq!(
650            seen,
651            vec![
652                (3, 2, "Inner", "inner"),
653                (7, 2, "In item", "in-item"),
654                (8, 2, "Set text", "set-text")
655            ]
656        );
657        assert_eq!(body.headings.len(), 1);
658    }
659
660    #[test]
661    fn kinds_round_trip_through_their_names() {
662        for name in [
663            "prose",
664            "bullet-list",
665            "numbered-list",
666            "table",
667            "code",
668            "blockquote",
669            "image",
670            "region",
671            "html",
672            "thematic-break",
673            "references",
674            "group",
675        ] {
676            assert_eq!(BlockKind::parse(name).unwrap().name(), name);
677        }
678        assert!(BlockKind::parse("paragraph").is_none());
679        let host = Dialect {
680            region: Some("include"),
681            ..Dialect::default()
682        };
683        assert_eq!(
684            BlockKind::parse_in("include", &host),
685            Some(BlockKind::Region)
686        );
687        assert_eq!(BlockKind::parse_in("region", &host), None);
688        assert_eq!(BlockKind::Region.name_in(&host), "include");
689        assert_eq!(BlockKind::parse_in("include", &Dialect::default()), None);
690    }
691
692    #[test]
693    fn blocks_between_and_in_code() {
694        let block = |line| Block {
695            kind: BlockKind::Prose,
696            line,
697            end_line: line,
698            units: vec![],
699            detail: BlockDetail::None,
700            html_lines: vec![],
701        };
702        let body = Body {
703            blocks: vec![block(2), block(5), block(9)],
704            fenced: vec![(4, 6)],
705            ..Body::default()
706        };
707        let lines: Vec<usize> = body.blocks_between(1, 9).iter().map(|b| b.line).collect();
708        assert_eq!(lines, vec![2, 5]);
709        assert!(body.in_code(5));
710        assert!(!body.in_code(7));
711    }
712}