Expand description
§markdown-model
markdown-model parses Markdown into an owned semantic document independent
of HTML, terminal frameworks, files, and async runtimes. It is suitable for
viewers, hover popups, indexes, outline tools, and custom renderers.
The crate uses pulldown-cmark as its parsing engine without exposing parser
events or tags. Its public contract consists of owned model types, stable
document-local navigation identities, source spans, and explicit parse limits.
Application-specific URL permissions and rendering policy deliberately remain
outside this crate.
§Status and installation
The API is version 0.1 and follows Cargo SemVer conventions. The model enums are exhaustive because renderers must decide how to represent every semantic variant; adding a variant before 1.0 may require caller changes.
Within this repository, depend on the workspace package:
[dependencies]
markdown-model = { path = "crates/markdown-model" }After a crates.io release, use:
[dependencies]
markdown-model = "0.1"No crates.io release is implied by this documentation; release preparation
must verify registry availability and ownership. The minimum supported Rust
version is 1.88. The crate has no Cargo features, performs no I/O, and depends
only on pulldown-cmark.
§Parse a document
Document::parse uses ParseLimits::default and returns an immutable,
self-contained Document:
use markdown_model::{BlockKind, Document, plain_text};
let source = "# Guide\n\nRead the [introduction](intro.md#start).";
let document = Document::parse(source)?;
assert_eq!(document.headings()[0].id().as_str(), "guide");
let link = &document.links()[0];
assert_eq!(link.destination().as_str(), "intro.md#start");
assert!(link.span().get(source).is_some());
let BlockKind::Paragraph(content) = document.blocks()[1].kind() else {
unreachable!("the example contains a paragraph");
};
assert_eq!(plain_text(content), "Read the introduction.");All model strings are owned. The document does not borrow source, so it can
be cached in an Arc<Document> after the source buffer is dropped. Parsing is
synchronous; async applications should invoke it at their blocking-work
boundary for large inputs.
§Typed model and indexes
The API gives domain concepts distinct types instead of exchanging primitive indexes and loosely related flags:
HeadingLevelis a closedH1throughH6enum.HeadingIdandLinkIdcannot be confused with arbitrary strings or indexes. Resolve a link withDocument::link.SourceSpanis a checked half-open UTF-8 byte span with a non-panickingSourceSpan::getoperation.ListKinddistinguishes ordered and unordered lists, whileTaskStatedistinguishes plain, checked, and unchecked items.CodeBlockKinddistinguishes indented blocks from fenced blocks and owns the complete fence info string.LinkDestinationexplicitly marks parser-provided destinations as untrusted data.Table,TableRow, andTableCellpreserve table structure without exposing nested anonymous vectors.
Model structs keep their fields private. Accessors preserve invariants while
allowing renderers to exhaustively match BlockKind and InlineKind.
Every block, inline, heading, and link carries a SourceSpan into the exact
input revision that was parsed.
Link IDs are contiguous and document-local. An InlineKind::Link stores the
same typed identity as its Link metadata entry. Heading IDs appear in both
the heading index and the corresponding block, so independent HTML and
terminal renderers can share anchor identity without duplicating slug logic.
§Supported Markdown
Parsing follows CommonMark with pulldown-cmark’s tables, task lists, and strikethrough extensions enabled. The model covers headings, paragraphs, styled inline content, code, links, images, breaks, rules, quotations, nested lists, task markers, and tables.
This crate does not claim complete GitHub Flavored Markdown compatibility.
Incomplete constructs follow pulldown-cmark’s readable literal fallback. Raw
HTML is represented as text or BlockKind::Literal; renderers must escape it
as ordinary text. Images remain model data and never trigger resource access.
§Heading IDs
Heading IDs follow one deterministic Unicode-aware rule:
- Lowercase the plain heading text.
- Keep Unicode alphanumeric characters,
_, and-. - Replace whitespace runs with
-and discard other punctuation. - Use
sectionif the result is empty. - Append
-1,-2, and so on until the ID is document-local unique.
IDs are stable across renderers for one parsed document, but editing heading text or order can change them.
§Resource limits and errors
The default ParseLimits accept at most 2 MiB of UTF-8 input, 64 nested
parser containers, and 200,000 parser events. The nesting value is capped at
ParseLimits::MAX_NESTING_DEPTH. Configuration fields are private so the
effective budget is fixed when the value is constructed.
use markdown_model::{Document, ParseError, ParseLimits};
let limits = ParseLimits::default()
.with_max_source_bytes(16)
.with_max_nesting_depth(8)
.with_max_events(32);
let error = Document::parse_with_limits(
"This input is longer than sixteen bytes",
limits,
)
.expect_err("the byte budget is intentionally small");
assert!(matches!(error, ParseError::TooLarge { .. }));Ordinary Markdown syntax fallback is not an error. ParseError reports only
resource-budget exhaustion, allowing callers to distinguish source size,
nesting, and event-count failures.
§Security boundary
LinkDestination is intentionally not a validated URL or filesystem path.
Different hosts have different scheme, containment, and user-intent policies,
so those decisions do not belong in a reusable syntax model. Renderers must
escape literal HTML and text for their output context. Terminal control-text
handling is provided by the terminal-specific markdown-ratatui package.
§License
Licensed under either the Apache License, Version 2.0 or the MIT license at your option.
Structs§
- Block
- A semantic block and its span in the original source.
- Document
- An owned, immutable Markdown document and its navigation indexes.
- Heading
- Heading metadata suitable for a table of contents and anchor navigation.
- Heading
Id - A unique document-local heading anchor generated by the parser.
- Inline
- A semantic inline and its span in the original source.
- Link
- Link metadata. Destinations are untrusted and must be validated before opening.
- Link
Destination - An untrusted destination reported by the Markdown parser.
- LinkId
- A contiguous document-local link identifier.
- List
Item - One list entry and its optional task marker.
- Parse
Limits - Resource bounds checked while parsing a document.
- Source
Span - A half-open UTF-8 byte span in the exact Markdown source that was parsed.
- Table
- A Markdown table with one header row and zero or more body rows.
- Table
Cell - A table cell containing parsed inline content.
- Table
Row - A table row containing cells in source order.
Enums§
- Alignment
- Column alignment declared by a table delimiter row.
- Block
Kind - Block-level Markdown structure.
- Code
Block Kind - The source form of a Markdown code block.
- Heading
Level - A CommonMark heading level.
- Inline
Kind - Inline Markdown structure. Raw HTML is represented as literal text.
- List
Kind - Whether a list is ordered and, if so, where numbering begins.
- Parse
Error - Resource exhaustion, rather than incomplete Markdown syntax, makes parsing fail.
- Task
State - The task marker attached to a list item.
Functions§
- plain_
text - Allocates readable text from inline content without resource access.