Skip to main content

markdown_model/
model.rs

1use std::{fmt, ops::Range};
2
3/// A CommonMark heading level.
4///
5/// Using a closed enum prevents renderer code from receiving levels outside
6/// the `1..=6` range defined by Markdown and HTML.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
8pub enum HeadingLevel {
9    /// A level-one heading (`#`).
10    H1,
11    /// A level-two heading (`##`).
12    H2,
13    /// A level-three heading (`###`).
14    H3,
15    /// A level-four heading (`####`).
16    H4,
17    /// A level-five heading (`#####`).
18    H5,
19    /// A level-six heading (`######`).
20    H6,
21}
22
23impl HeadingLevel {
24    /// Returns the numeric heading level in the inclusive range `1..=6`.
25    pub const fn get(self) -> u8 {
26        match self {
27            Self::H1 => 1,
28            Self::H2 => 2,
29            Self::H3 => 3,
30            Self::H4 => 4,
31            Self::H5 => 5,
32            Self::H6 => 6,
33        }
34    }
35}
36
37impl fmt::Display for HeadingLevel {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        self.get().fmt(f)
40    }
41}
42
43/// A unique document-local heading anchor generated by the parser.
44#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
45pub struct HeadingId(String);
46
47impl HeadingId {
48    pub(crate) fn from_generated(value: String) -> Self {
49        Self(value)
50    }
51
52    /// Returns the generated anchor as a string slice.
53    pub fn as_str(&self) -> &str {
54        &self.0
55    }
56}
57
58impl AsRef<str> for HeadingId {
59    fn as_ref(&self) -> &str {
60        self.as_str()
61    }
62}
63
64impl fmt::Display for HeadingId {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        self.0.fmt(f)
67    }
68}
69
70/// A contiguous document-local link identifier.
71///
72/// IDs are meaningful only with the [`Document`] that produced them. Resolve
73/// one with [`Document::link`] instead of indexing a slice manually.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
75pub struct LinkId(usize);
76
77impl LinkId {
78    pub(crate) const fn from_index(index: usize) -> Self {
79        Self(index)
80    }
81
82    /// Returns the zero-based document-local index.
83    pub const fn index(self) -> usize {
84        self.0
85    }
86}
87
88impl fmt::Display for LinkId {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        self.0.fmt(f)
91    }
92}
93
94/// A half-open UTF-8 byte span in the exact Markdown source that was parsed.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub struct SourceSpan {
97    start: usize,
98    end: usize,
99}
100
101impl SourceSpan {
102    pub(crate) fn from_range(range: Range<usize>) -> Self {
103        debug_assert!(range.start <= range.end);
104        Self {
105            start: range.start,
106            end: range.end,
107        }
108    }
109
110    /// Returns the inclusive starting byte offset.
111    pub const fn start(self) -> usize {
112        self.start
113    }
114
115    /// Returns the exclusive ending byte offset.
116    pub const fn end(self) -> usize {
117        self.end
118    }
119
120    /// Returns the span length in UTF-8 bytes.
121    pub const fn len(self) -> usize {
122        self.end - self.start
123    }
124
125    /// Returns whether the span contains no bytes.
126    pub const fn is_empty(self) -> bool {
127        self.start == self.end
128    }
129
130    /// Returns an ordinary range for APIs that consume byte ranges.
131    pub const fn range(self) -> Range<usize> {
132        self.start..self.end
133    }
134
135    /// Borrows this span from its original source when it is still valid.
136    ///
137    /// `None` indicates that the span is out of bounds or not on UTF-8
138    /// boundaries, which normally means it was applied to another revision.
139    pub fn get(self, source: &str) -> Option<&str> {
140        source.get(self.range())
141    }
142}
143
144/// An untrusted destination reported by the Markdown parser.
145///
146/// Parsing this value grants no authority. Callers must classify and validate
147/// it for their own navigation, filesystem, or network boundary.
148#[derive(Clone, Debug, PartialEq, Eq, Hash)]
149pub struct LinkDestination(String);
150
151impl LinkDestination {
152    pub(crate) fn from_parser(value: String) -> Self {
153        Self(value)
154    }
155
156    /// Returns the untrusted destination text.
157    pub fn as_str(&self) -> &str {
158        &self.0
159    }
160}
161
162impl AsRef<str> for LinkDestination {
163    fn as_ref(&self) -> &str {
164        self.as_str()
165    }
166}
167
168impl fmt::Display for LinkDestination {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        self.0.fmt(f)
171    }
172}
173
174/// An owned, immutable Markdown document and its navigation indexes.
175///
176/// Construct a document with [`Document::parse`] or
177/// [`Document::parse_with_limits`]. Blocks, headings, and links all refer to
178/// the same parse, so renderers can share heading and link identities without
179/// rebuilding indexes. Cloning a document performs a deep clone; use
180/// [`std::sync::Arc`] when several consumers should share one allocation.
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct Document {
183    pub(crate) blocks: Vec<Block>,
184    pub(crate) headings: Vec<Heading>,
185    pub(crate) links: Vec<Link>,
186}
187
188impl Document {
189    /// Returns the top-level semantic blocks in source order.
190    ///
191    /// Blocks nested inside quotations and list items are available through
192    /// [`BlockKind::Quote`] and [`ListItem::blocks`].
193    pub fn blocks(&self) -> &[Block] {
194        &self.blocks
195    }
196
197    /// Returns the heading index in source order.
198    pub fn headings(&self) -> &[Heading] {
199        &self.headings
200    }
201
202    /// Returns links in parse traversal order.
203    pub fn links(&self) -> &[Link] {
204        &self.links
205    }
206
207    /// Resolves a document-local link identifier.
208    ///
209    /// Returns `None` when the identifier's index is outside this document.
210    /// Because IDs are document-local indexes, callers must not reuse one with
211    /// another document or revision.
212    pub fn link(&self, id: LinkId) -> Option<&Link> {
213        self.links.get(id.index())
214    }
215}
216
217/// A semantic block and its span in the original source.
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub struct Block {
220    pub(crate) kind: BlockKind,
221    pub(crate) span: SourceSpan,
222}
223
224impl Block {
225    /// Returns the block's semantic content.
226    pub fn kind(&self) -> &BlockKind {
227        &self.kind
228    }
229
230    /// Returns the block's source span.
231    pub const fn span(&self) -> SourceSpan {
232        self.span
233    }
234}
235
236/// Whether a list is ordered and, if so, where numbering begins.
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum ListKind {
239    /// A list whose items use bullets.
240    Unordered,
241    /// A numbered list beginning at the supplied ordinal.
242    Ordered {
243        /// The first displayed ordinal.
244        start: u64,
245    },
246}
247
248/// The task marker attached to a list item.
249#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
250pub enum TaskState {
251    /// The list item has no task marker.
252    #[default]
253    Plain,
254    /// The item has an unchecked task marker.
255    Unchecked,
256    /// The item has a checked task marker.
257    Checked,
258}
259
260/// The source form of a Markdown code block.
261#[derive(Clone, Debug, PartialEq, Eq)]
262pub enum CodeBlockKind {
263    /// A code block introduced by indentation.
264    Indented,
265    /// A fenced code block and its complete info string.
266    Fenced(String),
267}
268
269impl CodeBlockKind {
270    /// Returns the fence info string, or `None` for indented code.
271    pub fn info(&self) -> Option<&str> {
272        match self {
273            Self::Indented => None,
274            Self::Fenced(info) => Some(info),
275        }
276    }
277}
278
279/// Block-level Markdown structure.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub enum BlockKind {
282    /// A paragraph; soft and hard breaks are preserved in its inlines.
283    Paragraph(Vec<Inline>),
284    /// A heading, whose anchor is also in the document's heading index.
285    Heading {
286        /// CommonMark heading level.
287        level: HeadingLevel,
288        /// Unique document-local anchor generated from the plain label.
289        id: HeadingId,
290        /// Parsed heading label, without its block delimiter.
291        content: Vec<Inline>,
292    },
293    /// A block quotation, potentially containing lists or other quotes.
294    Quote(Vec<Block>),
295    /// An ordered or unordered list.
296    List {
297        /// The list's marker and numbering policy.
298        kind: ListKind,
299        /// List entries in source order.
300        items: Vec<ListItem>,
301    },
302    /// A fenced or indented code block.
303    Code {
304        /// Whether the block was indented or fenced, including fence info.
305        kind: CodeBlockKind,
306        /// Literal code content without the surrounding fence or indentation.
307        text: String,
308    },
309    /// A table.
310    Table(Table),
311    /// A thematic break.
312    Rule,
313    /// Raw HTML or an unsupported block, rendered literally rather than executed.
314    Literal(String),
315}
316
317/// One list entry and its optional task marker.
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct ListItem {
320    pub(crate) task: TaskState,
321    pub(crate) blocks: Vec<Block>,
322}
323
324impl ListItem {
325    /// Returns the item's task-marker state.
326    pub const fn task(&self) -> TaskState {
327        self.task
328    }
329
330    /// Returns nested blocks owned by this item.
331    pub fn blocks(&self) -> &[Block] {
332        &self.blocks
333    }
334}
335
336/// Column alignment declared by a table delimiter row.
337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
338pub enum Alignment {
339    /// No explicit alignment (renderers normally use left alignment).
340    #[default]
341    None,
342    /// Left aligned.
343    Left,
344    /// Center aligned.
345    Center,
346    /// Right aligned.
347    Right,
348}
349
350/// A table cell containing parsed inline content.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct TableCell(Vec<Inline>);
353
354impl TableCell {
355    pub(crate) fn from_inlines(inlines: Vec<Inline>) -> Self {
356        Self(inlines)
357    }
358
359    /// Returns the cell's inline content.
360    pub fn inlines(&self) -> &[Inline] {
361        &self.0
362    }
363}
364
365/// A table row containing cells in source order.
366#[derive(Clone, Debug, PartialEq, Eq)]
367pub struct TableRow(Vec<TableCell>);
368
369impl TableRow {
370    pub(crate) fn from_cells(cells: Vec<TableCell>) -> Self {
371        Self(cells)
372    }
373
374    /// Returns cells in column order.
375    pub fn cells(&self) -> &[TableCell] {
376        &self.0
377    }
378}
379
380/// A Markdown table with one header row and zero or more body rows.
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct Table {
383    alignments: Vec<Alignment>,
384    header: TableRow,
385    rows: Vec<TableRow>,
386}
387
388impl Table {
389    pub(crate) fn new(alignments: Vec<Alignment>, header: TableRow, rows: Vec<TableRow>) -> Self {
390        Self {
391            alignments,
392            header,
393            rows,
394        }
395    }
396
397    /// Returns declared column alignments.
398    pub fn alignments(&self) -> &[Alignment] {
399        &self.alignments
400    }
401
402    /// Returns the table header.
403    pub const fn header(&self) -> &TableRow {
404        &self.header
405    }
406
407    /// Returns body rows in source order.
408    pub fn rows(&self) -> &[TableRow] {
409        &self.rows
410    }
411}
412
413/// A semantic inline and its span in the original source.
414#[derive(Clone, Debug, PartialEq, Eq)]
415pub struct Inline {
416    pub(crate) kind: InlineKind,
417    pub(crate) span: SourceSpan,
418}
419
420impl Inline {
421    /// Returns the inline's semantic content.
422    pub fn kind(&self) -> &InlineKind {
423        &self.kind
424    }
425
426    /// Returns the inline's source span.
427    pub const fn span(&self) -> SourceSpan {
428        self.span
429    }
430}
431
432/// Inline Markdown structure. Raw HTML is represented as literal text.
433#[derive(Clone, Debug, PartialEq, Eq)]
434pub enum InlineKind {
435    /// Ordinary text or escaped raw HTML.
436    Text(String),
437    /// Emphasized child inlines.
438    Emphasis(Vec<Inline>),
439    /// Strong child inlines.
440    Strong(Vec<Inline>),
441    /// Struck-through child inlines.
442    Strikethrough(Vec<Inline>),
443    /// Inline code, without source delimiters.
444    Code(String),
445    /// A navigable link.
446    Link {
447        /// Document-local link identity.
448        id: LinkId,
449        /// Parsed link label.
450        content: Vec<Inline>,
451    },
452    /// An image destination and parsed alternative text; no resource is fetched.
453    Image {
454        /// Untrusted destination reported by the parser.
455        destination: LinkDestination,
456        /// Optional Markdown title.
457        title: Option<String>,
458        /// Parsed alternative text.
459        alt: Vec<Inline>,
460    },
461    /// A source newline, normally rendered as a space.
462    SoftBreak,
463    /// An explicit line break.
464    HardBreak,
465}
466
467/// Heading metadata suitable for a table of contents and anchor navigation.
468#[derive(Clone, Debug, PartialEq, Eq)]
469pub struct Heading {
470    pub(crate) id: HeadingId,
471    pub(crate) level: HeadingLevel,
472    pub(crate) text: String,
473    pub(crate) span: SourceSpan,
474}
475
476impl Heading {
477    /// Returns the generated, document-local anchor.
478    pub const fn id(&self) -> &HeadingId {
479        &self.id
480    }
481
482    /// Returns the heading level.
483    pub const fn level(&self) -> HeadingLevel {
484        self.level
485    }
486
487    /// Returns the plain text label without emphasis delimiters.
488    pub fn text(&self) -> &str {
489        &self.text
490    }
491
492    /// Returns the source span including Markdown delimiters.
493    pub const fn span(&self) -> SourceSpan {
494        self.span
495    }
496}
497
498/// Link metadata. Destinations are untrusted and must be validated before opening.
499#[derive(Clone, Debug, PartialEq, Eq)]
500pub struct Link {
501    pub(crate) id: LinkId,
502    pub(crate) destination: LinkDestination,
503    pub(crate) title: Option<String>,
504    pub(crate) text: String,
505    pub(crate) span: SourceSpan,
506}
507
508impl Link {
509    /// Returns the document-local link identity.
510    pub const fn id(&self) -> LinkId {
511        self.id
512    }
513
514    /// Returns the untrusted destination.
515    pub const fn destination(&self) -> &LinkDestination {
516        &self.destination
517    }
518
519    /// Returns the optional Markdown title.
520    pub fn title(&self) -> Option<&str> {
521        self.title.as_deref()
522    }
523
524    /// Returns the plain text label.
525    pub fn text(&self) -> &str {
526        &self.text
527    }
528
529    /// Returns the source span including Markdown delimiters.
530    pub const fn span(&self) -> SourceSpan {
531        self.span
532    }
533}
534
535/// Allocates readable text from inline content without resource access.
536///
537/// Styling containers and link destinations are omitted, image alternative
538/// text is retained, and soft and hard breaks both become an ASCII space. The
539/// result is not sanitized for a particular output device; terminal consumers
540/// should filter control characters before rendering untrusted text.
541pub fn plain_text(inlines: &[Inline]) -> String {
542    let mut out = String::new();
543    for inline in inlines {
544        match inline.kind() {
545            InlineKind::Text(s) | InlineKind::Code(s) => out.push_str(s),
546            InlineKind::Emphasis(c)
547            | InlineKind::Strong(c)
548            | InlineKind::Strikethrough(c)
549            | InlineKind::Link { content: c, .. }
550            | InlineKind::Image { alt: c, .. } => out.push_str(&plain_text(c)),
551            InlineKind::SoftBreak | InlineKind::HardBreak => out.push(' '),
552        }
553    }
554    out
555}