markdown-syntax
A no_std + alloc Rust crate that parses Markdown source into an owned AST and serializes the AST back to canonical Markdown — with opt-in, safe-by-default HTML rendering behind the html feature.
At a glance
- AST-first —
parsereturns an owned enum tree overalloc; the output verbs live on theDocumentyou hold. - Tolerant — problems are collected as diagnostics, never thrown;
parseis infallible. - One syntax — CommonMark + GFM + footnotes + alerts + math + frontmatter + wikilinks + directives +
==highlight + shortcodes, with nothing to configure. - Lean core — zero runtime dependencies,
no_std + alloc, MSRV 1.82.
Install
cargo add markdown-syntax
For the opt-in HTML renderer:
cargo add markdown-syntax --features html
Or in Cargo.toml:
[]
= "0.3"
Quickstart
use parse;
// `parse` is infallible and returns a `ParseOutput { document, diagnostics }`.
let output = parse;
assert!;
// Serialize the AST back to canonical Markdown (this is the fallible step).
let markdown = output.document.to_markdown?;
assert_eq!;
# Ok::
parse is infallible — the output verbs live on the Document you hold.
Common tasks
parse is the one way in. When you need to read diagnostics, walk the tree, or render HTML, each task is one small snippet below.
- Walk the AST
- Handle diagnostics
- Customize serialization
- Source positions (optional)
- Build an AST by hand
Walk the AST
use ;
let document = parse.document;
for block in &document.children
document.children is a Vec<Block>; block content (like Paragraph.children) is a Vec<Inline>. See the ast module, Block, and Inline.
Handle diagnostics
use ;
// Problems are collected, never thrown.
let output = parse;
for diagnostic in &output.diagnostics
span is Option<Span> because a hand-built node may lack a source location. Parser diagnostics, AST validation, and serializer/HTML pre-validation are three separate domains that share one Diagnostic type.
Customize serialization
use ;
// `SerializeOptions` is #[non_exhaustive]: mutate a default rather than using a
// struct literal.
let mut options = default;
options.line_ending = CrLf;
options.final_newline = false;
let markdown = parse.document.to_markdown_with?;
assert_eq!;
// List-marker and fence options are `None` by default, keeping the marker
// each node records; `Some` writes every list or fence with the one given.
let mut options = default;
options.bullet = Some;
assert_eq!;
// Each node is written in the spelling it records: `_` emphasis stays `_`,
// an escape stays an escape, and a literal autolink stays bare.
let document = parse.document;
assert_eq!;
# Ok::
Because SerializeOptions is #[non_exhaustive], external code cannot struct-literal-construct it (even with ..Default::default(), E0639) — mutate a default() instead.
The serializer only renders: it writes text, escapes, and character references as the AST records them and never parses its own output. A hand-built Text("*a*") is written *a*, which reads back as emphasis; build literal punctuation with Escape nodes instead. A hand-built tree that no Markdown can express — a link inside a link, say — fails validation, and to_markdown returns SerializeError::InvalidDocument with the diagnostics.
Source positions (optional)
use ;
let source = "# Title\n\nHello.";
let document = parse.document;
let index = new;
// Spans are absolute, half-open UTF-8 byte ranges; `None` for hand-built nodes.
if let Some = document.children.first
Spans are absolute half-open UTF-8 byte ranges, None for hand-built nodes. LineIndex turns a Span into 1-based LinePosition line/column.
Build an AST by hand
The prelude imports the common surface in one line:
use *;
let document = Document ;
// Hand-built nodes carry no span.
assert_eq!;
assert_eq!;
// Text is written as it is; `Escape` writes a literal punctuation char.
let escape = ;
let literal = Document ;
assert_eq!;
HTML rendering (opt-in)
The HTML renderer ships behind the non-default html feature and is safe by default: it validates the AST first, escapes raw HTML, blanks dangerous link/image protocols, and disables task-list checkboxes.
cargo add markdown-syntax --features html
// Requires `--features html`; the default doctest build has no html feature,
// so this block is `rust,ignore`.
use ;
let document = parse.document;
// Default is safe: raw HTML is escaped, dangerous link/image protocols blanked.
let safe: = document.to_html;
assert!;
// `HtmlOptions` is #[non_exhaustive]: mutate a default to opt into raw HTML.
let mut options = default;
options.allow_dangerous_html = true;
options.safe_raw_html_form = OmitPlaceholder;
let _ = document.to_html_with;
See HtmlOptions. docs.rs builds with the html feature enabled, so the renderer's API is fully documented there.
Syntax reference
parse recognizes one fixed syntax:
| Family | Constructs |
|---|---|
| CommonMark | everything, including raw HTML and indented code |
| GFM | tables, task list items, ~~ strikethrough, literal autolinks (http://, https://, www., emails, mailto:, xmpp:), alerts |
| Footnotes | [^id] references and definitions, inline ^[note] |
| Extensions | frontmatter (--- / +++), inline and block math, wikilinks ([[target|title]], embeds ![[x]]), == highlight, gemoji shortcodes (:tada:), :name / ::name / :::name directives, <details> HTML containers |
Where one node has more than one spelling, the parse records it: Emphasis and Strong record * or _, and Autolink records an angle-bracket or a literal autolink; Link is the inline [text](destination) form. A node stores each written fact once: an Autolink derives its destination() from its text, a CharacterReference decodes its value() from the reference, and a CodeInline holds only its value, its fence chosen when written.
Cargo features:
| Feature | Default | What it adds |
|---|---|---|
default |
[] (empty) |
Byte-stable no_std + alloc core: parser, AST, serializer, validation, Span/LineIndex, prelude. Zero runtime deps. |
html |
off | Opt-in, additive, safe-by-default to_html / to_html_with and the html module. Stays no_std + alloc, zero runtime deps. |
How it works
- AST-first public API —
parseproduces an ownedDocument; parser event streams and internal block operations are private, not v1 compatibility surfaces. - Owned enum tree over
alloctypes. - Optional source spans — half-open absolute byte ranges on every node,
Nonefor hand-built nodes; line/column derived viaLineIndex. - Tolerant by default — diagnostics are collected, not thrown.
Scope & limitations
In scope — the one syntax in the syntax reference. Subscript, superscript, insert, spoiler, underline, description lists, and MDX are not recognized: __a__ is strong, and the rest stay text or raw HTML.
Not in the default build: HTML rendering or sanitization, syntax highlighting, and byte-for-byte preservation of the source's authoring style. Directives (:name / ::name / :::name) are their own family and are never MDX.
Parsing, serialization, HTML rendering, and validation take linear time and bounded stack on any input; nesting past fixed limits stays literal text.
The full behavior contract — syntax, serialization, validation, HTML rendering, and the cost limits — lives in docs/specs/.
Compatibility
no_std + alloc (crate root is #![no_std] + extern crate alloc). Default features are empty; the opt-in html feature also stays no_std + alloc. Zero runtime dependencies. MSRV 1.82 (edition 2021).
Contributing & conformance
Tests live in tests/. AST→HTML correctness is measured against vendored CommonMark/GFM oracles; observe the current numbers with cargo test --features html --test html_conformance -- --nocapture.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.