MDExNative (MDExNative v0.1.2)

Copy Markdown View Source

MDExNative

Native foundation for MDEx

It wraps the following Rust crates:

  • comrak for Markdown parsing and rendering
  • ammonia for HTML sanitization
  • lumis for syntax highlighting

Most applications should use MDEx directly to benefit from Plugins, Document AST, Phoenix LiveView integration, additional syntax highlighting features, extra formats, MD sigil, and more.

This project offers direct access to underlying Rust projects.

Installation

Add :mdex_native to your dependencies:

def deps do
  [
    {:mdex_native, "~> 0.1"}
  ]
end

Precompiled NIFs are used by default. To build the NIF locally:

MDEX_NATIVE_BUILD=1 mix compile

Packages

MDExNative.Comrak

Markdown parsing and rendering.

html = MDExNative.Comrak.markdown_to_html("# Hello")

Comrak options are accepted as keyword lists. See comrak::Options.

html = MDExNative.Comrak.markdown_to_html("- [x] done", extension: [tasklist: true])

It also exposes XML, CommonMark, AST parsing, and heading anchor helpers.

xml = MDExNative.Comrak.markdown_to_xml("# Hello", render: [sourcepos: true])
anchor = MDExNative.Comrak.anchorize("Hello World")

MDExNative.Ammonia

HTML sanitization.

html = ~s|<script>alert("xss")</script><p>Hello <strong>MDEx</strong></p>|

MDExNative.Ammonia.safe_html(html)
#=> "<p>Hello <strong>MDEx</strong></p>"

MDExNative.Lumis

Syntax highlighting options for Comrak rendering. The native Rust LumisAdapter implements Comrak's SyntaxHighlighterAdapter and is installed when :syntax_highlight options are passed to MDExNative.Comrak.

markdown = """
```elixir
IO.puts("Hello from Lumis")
```
"""

options = [syntax_highlight: MDExNative.Lumis.default_options()]

html = MDExNative.Comrak.markdown_to_html(markdown, options)

Examples

Run the examples from the project root:

elixir examples/markdown_to_html.exs
elixir examples/ammonia_safe_html.exs
# others...