markdown-model 0.1.0

Owned, renderer-independent Markdown documents and navigation metadata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
use std::{fmt, ops::Range};

/// A CommonMark heading level.
///
/// Using a closed enum prevents renderer code from receiving levels outside
/// the `1..=6` range defined by Markdown and HTML.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum HeadingLevel {
    /// A level-one heading (`#`).
    H1,
    /// A level-two heading (`##`).
    H2,
    /// A level-three heading (`###`).
    H3,
    /// A level-four heading (`####`).
    H4,
    /// A level-five heading (`#####`).
    H5,
    /// A level-six heading (`######`).
    H6,
}

impl HeadingLevel {
    /// Returns the numeric heading level in the inclusive range `1..=6`.
    pub const fn get(self) -> u8 {
        match self {
            Self::H1 => 1,
            Self::H2 => 2,
            Self::H3 => 3,
            Self::H4 => 4,
            Self::H5 => 5,
            Self::H6 => 6,
        }
    }
}

impl fmt::Display for HeadingLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(f)
    }
}

/// A unique document-local heading anchor generated by the parser.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct HeadingId(String);

impl HeadingId {
    pub(crate) fn from_generated(value: String) -> Self {
        Self(value)
    }

    /// Returns the generated anchor as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for HeadingId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for HeadingId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A contiguous document-local link identifier.
///
/// IDs are meaningful only with the [`Document`] that produced them. Resolve
/// one with [`Document::link`] instead of indexing a slice manually.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LinkId(usize);

impl LinkId {
    pub(crate) const fn from_index(index: usize) -> Self {
        Self(index)
    }

    /// Returns the zero-based document-local index.
    pub const fn index(self) -> usize {
        self.0
    }
}

impl fmt::Display for LinkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A half-open UTF-8 byte span in the exact Markdown source that was parsed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SourceSpan {
    start: usize,
    end: usize,
}

impl SourceSpan {
    pub(crate) fn from_range(range: Range<usize>) -> Self {
        debug_assert!(range.start <= range.end);
        Self {
            start: range.start,
            end: range.end,
        }
    }

    /// Returns the inclusive starting byte offset.
    pub const fn start(self) -> usize {
        self.start
    }

    /// Returns the exclusive ending byte offset.
    pub const fn end(self) -> usize {
        self.end
    }

    /// Returns the span length in UTF-8 bytes.
    pub const fn len(self) -> usize {
        self.end - self.start
    }

    /// Returns whether the span contains no bytes.
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }

    /// Returns an ordinary range for APIs that consume byte ranges.
    pub const fn range(self) -> Range<usize> {
        self.start..self.end
    }

    /// Borrows this span from its original source when it is still valid.
    ///
    /// `None` indicates that the span is out of bounds or not on UTF-8
    /// boundaries, which normally means it was applied to another revision.
    pub fn get(self, source: &str) -> Option<&str> {
        source.get(self.range())
    }
}

/// An untrusted destination reported by the Markdown parser.
///
/// Parsing this value grants no authority. Callers must classify and validate
/// it for their own navigation, filesystem, or network boundary.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LinkDestination(String);

impl LinkDestination {
    pub(crate) fn from_parser(value: String) -> Self {
        Self(value)
    }

    /// Returns the untrusted destination text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for LinkDestination {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for LinkDestination {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// An owned, immutable Markdown document and its navigation indexes.
///
/// Construct a document with [`Document::parse`] or
/// [`Document::parse_with_limits`]. Blocks, headings, and links all refer to
/// the same parse, so renderers can share heading and link identities without
/// rebuilding indexes. Cloning a document performs a deep clone; use
/// [`std::sync::Arc`] when several consumers should share one allocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Document {
    pub(crate) blocks: Vec<Block>,
    pub(crate) headings: Vec<Heading>,
    pub(crate) links: Vec<Link>,
}

impl Document {
    /// Returns the top-level semantic blocks in source order.
    ///
    /// Blocks nested inside quotations and list items are available through
    /// [`BlockKind::Quote`] and [`ListItem::blocks`].
    pub fn blocks(&self) -> &[Block] {
        &self.blocks
    }

    /// Returns the heading index in source order.
    pub fn headings(&self) -> &[Heading] {
        &self.headings
    }

    /// Returns links in parse traversal order.
    pub fn links(&self) -> &[Link] {
        &self.links
    }

    /// Resolves a document-local link identifier.
    ///
    /// Returns `None` when the identifier's index is outside this document.
    /// Because IDs are document-local indexes, callers must not reuse one with
    /// another document or revision.
    pub fn link(&self, id: LinkId) -> Option<&Link> {
        self.links.get(id.index())
    }
}

/// A semantic block and its span in the original source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
    pub(crate) kind: BlockKind,
    pub(crate) span: SourceSpan,
}

impl Block {
    /// Returns the block's semantic content.
    pub fn kind(&self) -> &BlockKind {
        &self.kind
    }

    /// Returns the block's source span.
    pub const fn span(&self) -> SourceSpan {
        self.span
    }
}

/// Whether a list is ordered and, if so, where numbering begins.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ListKind {
    /// A list whose items use bullets.
    Unordered,
    /// A numbered list beginning at the supplied ordinal.
    Ordered {
        /// The first displayed ordinal.
        start: u64,
    },
}

/// The task marker attached to a list item.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TaskState {
    /// The list item has no task marker.
    #[default]
    Plain,
    /// The item has an unchecked task marker.
    Unchecked,
    /// The item has a checked task marker.
    Checked,
}

/// The source form of a Markdown code block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CodeBlockKind {
    /// A code block introduced by indentation.
    Indented,
    /// A fenced code block and its complete info string.
    Fenced(String),
}

impl CodeBlockKind {
    /// Returns the fence info string, or `None` for indented code.
    pub fn info(&self) -> Option<&str> {
        match self {
            Self::Indented => None,
            Self::Fenced(info) => Some(info),
        }
    }
}

/// Block-level Markdown structure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BlockKind {
    /// A paragraph; soft and hard breaks are preserved in its inlines.
    Paragraph(Vec<Inline>),
    /// A heading, whose anchor is also in the document's heading index.
    Heading {
        /// CommonMark heading level.
        level: HeadingLevel,
        /// Unique document-local anchor generated from the plain label.
        id: HeadingId,
        /// Parsed heading label, without its block delimiter.
        content: Vec<Inline>,
    },
    /// A block quotation, potentially containing lists or other quotes.
    Quote(Vec<Block>),
    /// An ordered or unordered list.
    List {
        /// The list's marker and numbering policy.
        kind: ListKind,
        /// List entries in source order.
        items: Vec<ListItem>,
    },
    /// A fenced or indented code block.
    Code {
        /// Whether the block was indented or fenced, including fence info.
        kind: CodeBlockKind,
        /// Literal code content without the surrounding fence or indentation.
        text: String,
    },
    /// A table.
    Table(Table),
    /// A thematic break.
    Rule,
    /// Raw HTML or an unsupported block, rendered literally rather than executed.
    Literal(String),
}

/// One list entry and its optional task marker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ListItem {
    pub(crate) task: TaskState,
    pub(crate) blocks: Vec<Block>,
}

impl ListItem {
    /// Returns the item's task-marker state.
    pub const fn task(&self) -> TaskState {
        self.task
    }

    /// Returns nested blocks owned by this item.
    pub fn blocks(&self) -> &[Block] {
        &self.blocks
    }
}

/// Column alignment declared by a table delimiter row.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Alignment {
    /// No explicit alignment (renderers normally use left alignment).
    #[default]
    None,
    /// Left aligned.
    Left,
    /// Center aligned.
    Center,
    /// Right aligned.
    Right,
}

/// A table cell containing parsed inline content.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableCell(Vec<Inline>);

impl TableCell {
    pub(crate) fn from_inlines(inlines: Vec<Inline>) -> Self {
        Self(inlines)
    }

    /// Returns the cell's inline content.
    pub fn inlines(&self) -> &[Inline] {
        &self.0
    }
}

/// A table row containing cells in source order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableRow(Vec<TableCell>);

impl TableRow {
    pub(crate) fn from_cells(cells: Vec<TableCell>) -> Self {
        Self(cells)
    }

    /// Returns cells in column order.
    pub fn cells(&self) -> &[TableCell] {
        &self.0
    }
}

/// A Markdown table with one header row and zero or more body rows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Table {
    alignments: Vec<Alignment>,
    header: TableRow,
    rows: Vec<TableRow>,
}

impl Table {
    pub(crate) fn new(alignments: Vec<Alignment>, header: TableRow, rows: Vec<TableRow>) -> Self {
        Self {
            alignments,
            header,
            rows,
        }
    }

    /// Returns declared column alignments.
    pub fn alignments(&self) -> &[Alignment] {
        &self.alignments
    }

    /// Returns the table header.
    pub const fn header(&self) -> &TableRow {
        &self.header
    }

    /// Returns body rows in source order.
    pub fn rows(&self) -> &[TableRow] {
        &self.rows
    }
}

/// A semantic inline and its span in the original source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Inline {
    pub(crate) kind: InlineKind,
    pub(crate) span: SourceSpan,
}

impl Inline {
    /// Returns the inline's semantic content.
    pub fn kind(&self) -> &InlineKind {
        &self.kind
    }

    /// Returns the inline's source span.
    pub const fn span(&self) -> SourceSpan {
        self.span
    }
}

/// Inline Markdown structure. Raw HTML is represented as literal text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InlineKind {
    /// Ordinary text or escaped raw HTML.
    Text(String),
    /// Emphasized child inlines.
    Emphasis(Vec<Inline>),
    /// Strong child inlines.
    Strong(Vec<Inline>),
    /// Struck-through child inlines.
    Strikethrough(Vec<Inline>),
    /// Inline code, without source delimiters.
    Code(String),
    /// A navigable link.
    Link {
        /// Document-local link identity.
        id: LinkId,
        /// Parsed link label.
        content: Vec<Inline>,
    },
    /// An image destination and parsed alternative text; no resource is fetched.
    Image {
        /// Untrusted destination reported by the parser.
        destination: LinkDestination,
        /// Optional Markdown title.
        title: Option<String>,
        /// Parsed alternative text.
        alt: Vec<Inline>,
    },
    /// A source newline, normally rendered as a space.
    SoftBreak,
    /// An explicit line break.
    HardBreak,
}

/// Heading metadata suitable for a table of contents and anchor navigation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Heading {
    pub(crate) id: HeadingId,
    pub(crate) level: HeadingLevel,
    pub(crate) text: String,
    pub(crate) span: SourceSpan,
}

impl Heading {
    /// Returns the generated, document-local anchor.
    pub const fn id(&self) -> &HeadingId {
        &self.id
    }

    /// Returns the heading level.
    pub const fn level(&self) -> HeadingLevel {
        self.level
    }

    /// Returns the plain text label without emphasis delimiters.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the source span including Markdown delimiters.
    pub const fn span(&self) -> SourceSpan {
        self.span
    }
}

/// Link metadata. Destinations are untrusted and must be validated before opening.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Link {
    pub(crate) id: LinkId,
    pub(crate) destination: LinkDestination,
    pub(crate) title: Option<String>,
    pub(crate) text: String,
    pub(crate) span: SourceSpan,
}

impl Link {
    /// Returns the document-local link identity.
    pub const fn id(&self) -> LinkId {
        self.id
    }

    /// Returns the untrusted destination.
    pub const fn destination(&self) -> &LinkDestination {
        &self.destination
    }

    /// Returns the optional Markdown title.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Returns the plain text label.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the source span including Markdown delimiters.
    pub const fn span(&self) -> SourceSpan {
        self.span
    }
}

/// Allocates readable text from inline content without resource access.
///
/// Styling containers and link destinations are omitted, image alternative
/// text is retained, and soft and hard breaks both become an ASCII space. The
/// result is not sanitized for a particular output device; terminal consumers
/// should filter control characters before rendering untrusted text.
pub fn plain_text(inlines: &[Inline]) -> String {
    let mut out = String::new();
    for inline in inlines {
        match inline.kind() {
            InlineKind::Text(s) | InlineKind::Code(s) => out.push_str(s),
            InlineKind::Emphasis(c)
            | InlineKind::Strong(c)
            | InlineKind::Strikethrough(c)
            | InlineKind::Link { content: c, .. }
            | InlineKind::Image { alt: c, .. } => out.push_str(&plain_text(c)),
            InlineKind::SoftBreak | InlineKind::HardBreak => out.push(' '),
        }
    }
    out
}