#commonmark #parse #render #tokenize

markdown

CommonMark compliant markdown parser in Rust with ASTs and extensions

21 releases (3 breaking)

1.0.0-alpha.16 Dec 5, 2023
1.0.0-alpha.15 Nov 20, 2023
1.0.0-alpha.14 Sep 20, 2023
1.0.0-alpha.11 Jul 10, 2023
0.0.1 Jan 25, 2015

#13 in Parser implementations

Download history 7210/week @ 2023-10-31 7961/week @ 2023-11-07 8742/week @ 2023-11-14 8377/week @ 2023-11-21 9366/week @ 2023-11-28 9379/week @ 2023-12-05 8657/week @ 2023-12-12 6025/week @ 2023-12-19 4671/week @ 2023-12-26 7336/week @ 2024-01-02 7875/week @ 2024-01-09 7833/week @ 2024-01-16 7973/week @ 2024-01-23 7395/week @ 2024-01-30 8364/week @ 2024-02-06 7544/week @ 2024-02-13

32,642 downloads per month
Used in 103 crates (56 directly)

MIT license

1MB
19K SLoC





markdown-rs

Build Coverage GitHub docs.rs crates.io

👉 Note: this is a new crate that reuses an old name. The old crate (0.3.0 and lower) has a bunch of problems. Make sure to use the new crate, currently in alpha at 1.0.0-alpha.16.

CommonMark compliant markdown parser in Rust with ASTs and extensions.

Feature highlights

  • compliant (100% to CommonMark)
  • extensions (100% GFM, 100% MDX, frontmatter, math)
  • safe (100% safe Rust, also 100% safe HTML by default)
  • robust (2300+ tests, 100% coverage, fuzz testing)
  • ast (mdast)

When should I use this?

  • If you just want to turn markdown into HTML (with maybe a few extensions)
  • If you want to do really complex things with markdown

What is this?

markdown-rs is an open source markdown parser written in Rust. It’s implemented as a state machine (#![no_std] + alloc) that emits concrete tokens, so that every byte is accounted for, with positional info. The API then exposes this information as an AST, which is easier to work with, or it compiles directly to HTML.

While most markdown parsers work towards compliancy with CommonMark (or GFM), this project goes further by following how the reference parsers (cmark, cmark-gfm) work, which is confirmed with thousands of extra tests.

Other than CommonMark and GFM, this project also supports common extensions to markdown such as MDX, math, and frontmatter.

This Rust crate has a sibling project in JavaScript: micromark (and mdast-util-from-markdown for the AST).

P.S. if you want to compile MDX, use mdxjs-rs.

Questions

Contents

Install

With Rust (rust edition 2018+, ±version 1.56+), install with cargo:

cargo add markdown@1.0.0-alpha.16

👉 Note: this is a new crate that reuses an old name. The old crate (0.3.0 and lower) has a bunch of problems. Make sure to use the new crate, currently in alpha at 1.0.0-alpha.16.

Use

fn main() {
    println!("{}", markdown::to_html("## Hello, *world*!"));
}

Yields:

<h2>Hello, <em>world</em>!</h2>

Extensions (in this case GFM):

fn main() -> Result<(), String> {
    println!(
        "{}",
        markdown::to_html_with_options(
            "* [x] contact@example.com ~~strikethrough~~",
            &markdown::Options::gfm()
        )?
    );

    Ok(())
}

Yields:

<ul>
  <li>
    <input checked="" disabled="" type="checkbox" />
    <a href="mailto:contact@example.com">contact@example.com</a>
    <del>strikethrough</del>
  </li>
</ul>

Syntax tree (mdast):

fn main() -> Result<(), String> {
    println!(
        "{:?}",
        markdown::to_mdast("# Hey, *you*!", &markdown::ParseOptions::default())?
    );

    Ok(())
}

Yields:

Root { children: [Heading { children: [Text { value: "Hey, ", position: Some(1:3-1:8 (2-7)) }, Emphasis { children: [Text { value: "you", position: Some(1:9-1:12 (8-11)) }], position: Some(1:8-1:13 (7-12)) }, Text { value: "!", position: Some(1:13-1:14 (12-13)) }], position: Some(1:1-1:14 (0-13)), depth: 1 }], position: Some(1:1-1:14 (0-13)) }

API

markdown-rs exposes to_html, to_html_with_options, to_mdast, Options, and a few other structs and enums.

See the crate docs for more info.

Extensions

markdown-rs supports extensions to CommonMark. These extensions are maintained in this project. They are not enabled by default but can be turned on with options.

  • frontmatter
  • GFM
    • autolink literal
    • footnote
    • strikethrough
    • table
    • tagfilter
    • task list item
  • math
  • MDX
    • ESM
    • expressions
    • JSX

It is not a goal of this project to support lots of different extensions. It’s instead a goal to support very common and mostly standardized extensions.

Project

markdown-rs is maintained as a single monolithic crate.

Overview

The process to parse markdown looks like this:

                    markdown-rs
+-------------------------------------------------+
|            +-------+         +---------+--html- |
| -markdown->+ parse +-events->+ compile +        |
|            +-------+         +---------+-mdast- |
+-------------------------------------------------+

File structure

The files in src/ are as follows:

  • construct/*.rs — CommonMark, GFM, and other extension constructs used in markdown
  • util/*.rs — helpers often needed when parsing markdown
  • event.rs — things with meaning happening somewhere
  • lib.rs — public API
  • mdast.rs — syntax tree
  • parser.rs — turn a string of markdown into events
  • resolve.rs — steps to process events
  • state.rs — steps of the state machine
  • subtokenize.rs — handle content in other content
  • to_html.rs — turns events into a string of HTML
  • to_mdast.rs — turns events into a syntax tree
  • tokenizer.rs — glue the states of the state machine together
  • unist.rs — point and position, used in mdast

Test

markdown-rs is tested with the ~650 CommonMark tests and more than 1k extra tests confirmed with CM reference parsers. Then there’s even more tests for GFM and other extensions. These tests reach all branches in the code, which means that this project has 100% code coverage. Fuzz testing is used to check for things that might fall through coverage.

The following bash scripts are useful when working on this project:

  • generate code (latest CM tests and Unicode info):
    cargo run --manifest-path generate/Cargo.toml
    
  • run examples:
    RUST_BACKTRACE=1 RUST_LOG=trace cargo run --features log --example lib
    
  • format:
    cargo fmt && cargo fix --all-targets
    
  • lint:
    cargo fmt --check && cargo clippy --examples --tests --benches --all-features
    
  • test:
    RUST_BACKTRACE=1 cargo test
    
  • docs:
    cargo doc --document-private-items
    
  • fuzz:
    cargo install cargo-fuzz
    cargo install honggfuzz
    cargo +nightly fuzz run markdown_libfuzz
    cargo hfuzz run markdown_honggfuzz
    

Version

markdown-rs follows SemVer.

Security

The typical security aspect discussed for markdown is cross-site scripting (XSS) attacks. Markdown itself is safe if it does not include embedded HTML or dangerous protocols in links/images (such as javascript: or data:). markdown-rs makes any markdown safe by default, even if HTML is embedded or dangerous protocols are used, as it encodes or drops them. Turning on the allow_dangerous_html or allow_dangerous_protocol options for user-provided markdown opens you up to XSS attacks.

An aspect related to XSS for security is syntax errors: markdown itself has no syntax errors. Some syntax extensions (specifically, only MDX) do include syntax errors. For that reason, to_html_with_options returns Result<String, String>, of which the error is a simple string indicating where the problem happened, what occurred, and what was expected instead. Make sure to handle your errors when using MDX.

Another security aspect is DDoS attacks. For example, an attacker could throw a 100mb file at markdown-rs, in which case it’s going to take a long while to finish. It is also possible to crash markdown-rs with smaller payloads, notably when thousands of links, images, emphasis, or strong are opened but not closed. It is wise to cap the accepted size of input (500kb can hold a big book) and to process content in a different thread so that it can be stopped when needed.

For more information on markdown sanitation, see improper-markup-sanitization.md by @chalker.

Contribute

See contributing.md for ways to help. See support.md for ways to get help. See code-of-conduct.md for how to communicate in and around this project.

Sponsor

Support this effort and give back by sponsoring:

Thanks

Special thanks go out to:

  • micromark — same as markdown-rs but in JavaScript
  • mdxjs-rs — wraps markdown-rs to compile MDX to JavaScript

License

MIT © Titus Wormer

Dependencies