# 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:
```toml
[dependencies]
markdown-model = { path = "crates/markdown-model" }
```
After a crates.io release, use:
```toml
[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`]:
```rust
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.");
# Ok::<(), markdown_model::ParseError>(())
```
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:
- [`HeadingLevel`] is a closed `H1` through `H6` enum.
- [`HeadingId`] and [`LinkId`] cannot be confused with arbitrary strings or
indexes. Resolve a link with [`Document::link`].
- [`SourceSpan`] is a checked half-open UTF-8 byte span with a non-panicking
[`SourceSpan::get`] operation.
- [`ListKind`] distinguishes ordered and unordered lists, while [`TaskState`]
distinguishes plain, checked, and unchecked items.
- [`CodeBlockKind`] distinguishes indented blocks from fenced blocks and owns
the complete fence info string.
- [`LinkDestination`] explicitly marks parser-provided destinations as
untrusted data.
- [`Table`], [`TableRow`], and [`TableCell`] preserve 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:
1. Lowercase the plain heading text.
2. Keep Unicode alphanumeric characters, `_`, and `-`.
3. Replace whitespace runs with `-` and discard other punctuation.
4. Use `section` if the result is empty.
5. 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.
```rust
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](https://github.com/karanabe/mira/blob/master/LICENSE-APACHE)
or the [MIT license](https://github.com/karanabe/mira/blob/master/LICENSE-MIT) at
your option.
[`BlockKind`]: https://docs.rs/markdown-model/latest/markdown_model/enum.BlockKind.html
[`CodeBlockKind`]: https://docs.rs/markdown-model/latest/markdown_model/enum.CodeBlockKind.html
[`Document`]: https://docs.rs/markdown-model/latest/markdown_model/struct.Document.html
[`Document::link`]: https://docs.rs/markdown-model/latest/markdown_model/struct.Document.html#method.link
[`Document::parse`]: https://docs.rs/markdown-model/latest/markdown_model/struct.Document.html#method.parse
[`HeadingId`]: https://docs.rs/markdown-model/latest/markdown_model/struct.HeadingId.html
[`HeadingLevel`]: https://docs.rs/markdown-model/latest/markdown_model/enum.HeadingLevel.html
[`InlineKind`]: https://docs.rs/markdown-model/latest/markdown_model/enum.InlineKind.html
[`InlineKind::Link`]: https://docs.rs/markdown-model/latest/markdown_model/enum.InlineKind.html#variant.Link
[`Link`]: https://docs.rs/markdown-model/latest/markdown_model/struct.Link.html
[`LinkDestination`]: https://docs.rs/markdown-model/latest/markdown_model/struct.LinkDestination.html
[`LinkId`]: https://docs.rs/markdown-model/latest/markdown_model/struct.LinkId.html
[`ListKind`]: https://docs.rs/markdown-model/latest/markdown_model/enum.ListKind.html
[`ParseError`]: https://docs.rs/markdown-model/latest/markdown_model/enum.ParseError.html
[`ParseLimits`]: https://docs.rs/markdown-model/latest/markdown_model/struct.ParseLimits.html
[`ParseLimits::MAX_NESTING_DEPTH`]: https://docs.rs/markdown-model/latest/markdown_model/struct.ParseLimits.html#associatedconstant.MAX_NESTING_DEPTH
[`ParseLimits::default`]: https://doc.rust-lang.org/std/default/trait.Default.html#tymethod.default
[`SourceSpan`]: https://docs.rs/markdown-model/latest/markdown_model/struct.SourceSpan.html
[`SourceSpan::get`]: https://docs.rs/markdown-model/latest/markdown_model/struct.SourceSpan.html#method.get
[`Table`]: https://docs.rs/markdown-model/latest/markdown_model/struct.Table.html
[`TableCell`]: https://docs.rs/markdown-model/latest/markdown_model/struct.TableCell.html
[`TableRow`]: https://docs.rs/markdown-model/latest/markdown_model/struct.TableRow.html
[`TaskState`]: https://docs.rs/markdown-model/latest/markdown_model/enum.TaskState.html