markdown-model 0.1.0

Owned, renderer-independent Markdown documents and navigation metadata
Documentation
  • Coverage
  • 100%
    78 out of 78 items documented1 out of 1 items with examples
  • Size
  • Source code size: 58.5 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.1 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 5s Average build duration of successful builds.
  • all releases: 5s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • karanabe/mira
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • karanabe

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.");
# 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:

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.

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.