MDExNative (MDExNative v0.1.3)

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, streaming, additional syntax highlighting features, extra formats, MD sigil, and more.

But this project offers direct access to underlying Rust crates when you don't need all those features, or need a bit more performance, or less dependencies.

Installation

Add :mdex_native to your dependencies:

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

See more in examples.

Development

export MDEX_NATIVE_BUILD=1
mix setup
mix test

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")

Syntax Highlighting

Syntax Highlighting of code blocks is enabled by passing the :syntax_highlight option:

markdown = """
# My Example

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

options = [
  # other comrak options...
  syntax_highlight: [
    engine: :lumis,
    opts: [
      formatter:
        {:html_inline,
         theme: "github_light",
         pre_class: "code-block-example"}
    ]
  ]
]

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

Note that :syntax_highlight is not a built-in Comrak option but it was added in MDExNative for convenience, and only Lumis is supported at the moment.

All Lumis formatters and its options can be found on Lumis formatter docs, or you can just omit or pass syntax_highlight: nil to disable syntax highlighting.

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>"