Markup.Carve (Markup.Carve v0.1.0)

Copy Markdown View Source

Carve for Markup, backed by the Rust carve-rs engine.

Adding {:markup_carve, "~> 0.1"} to your deps registers the :carve language with Markup:

Examples

iex> Markup.to_html("Hello *world*!", language: :carve)
{:ok, "<p>Hello <strong>world</strong>!</p>"}

iex> Markup.to_html!("# Hi", language: :carve, render: [sections: false])
"<h1 id=\"Hi\">Hi</h1>"

iex> Markup.to_html("/hi/", language: :carve)
{:ok, "<p><em>hi</em></p>"}

iex> {:ok, doc} = Markup.parse_document("Hello *world*", language: :carve)
iex> doc.nodes
[%Markup.Carve.Paragraph{nodes: [%Markup.Carve.Text{literal: "Hello "}, %Markup.Carve.Strong{nodes: [%Markup.Carve.Text{literal: "world"}]}]}]

iex> Markup.convert("/hi/ *there*", :markdown, language: :carve)
{:ok, "*hi* **there**\n"}

iex> Markup.convert("/hi/ *there*", :plain_text, language: :carve)
{:ok, "hi there\n"}

:carve output writes canonical Carve 0.2 source. Given source, it runs carve-rs's formatter; given a document, it writes the (possibly edited) tree back to Carve. Carve 0.2 spells headings with =, so Markdown-style # headings are rewritten:

iex> Markup.convert("#  Title", :carve, language: :carve)
{:ok, "= Title\n"}

Tree

Nodes are Markup.Carve.* structs (see Markup.Carve.Heading, Markup.Carve.Paragraph, …) decoded from carve's 2.0 tree format. Headings are top-level blocks; <section> wrapping happens at render time (render: [sections: true]). Bare-atom selectors match a Markup.Node kind first (so :strikethrough finds both Markup.Carve.Strike and Markup.Carve.Delete), and otherwise resolve under Markup.Carve:

iex> doc = Markup.parse_document!("Hello *world*", language: :carve)
iex> doc[Markup.Carve.Strong]
[%Markup.Carve.Strong{nodes: [%Markup.Carve.Text{literal: "world"}]}]
iex> doc[:text] |> Enum.map(& &1.literal)
["Hello ", "world"]

Child lists are nodes, text and code content is literal, and link and image targets are url, as in the other languages. carve's JSON calls them children, value, href and src. A code block's language is syntax. Extension nodes (Markup.Carve.BlockExtension, Markup.Carve.InlineExtension) keep their fallback, which renders when no extension claims them.

Sigil

iex> import Markup.Sigil
iex> ~MU"*a*"carveHTML
"<p><strong>a</strong></p>"

Sanitizing

sanitize: merges over default_sanitize_options/0. Plugins build safe Markup.Carve.Raw nodes with Markup.safe_html/2:

iex> Markup.safe_html("<script>x</script><b onclick=\"y\">hi</b>", language: :carve)
"<b>hi</b>"

iex> Markup.safe_html("<a>&</a>", language: :carve, sanitize: nil, escape: true)
"&lt;a&gt;&amp;&lt;/a&gt;"

iex> Markup.safe_html("<pre>A{b}</pre>", language: :carve, sanitize: nil, heex: true)
"<pre>A&lbrace;b&rbrace;</pre>"

Streaming

With Markup.stream/2 each block renders on its own, so a footnote reference only resolves if its definition is in the same block.

iex> ["# Hel", "lo\n\nPara"]
...> |> Markup.stream(language: :carve)
...> |> Enum.map(fn {id, doc} -> {id, Markup.to_html!(doc, render: [sections: false])} end)
[{0, "<h1 id=\"Hel\">Hel</h1>"}, {0, "<h1 id=\"Hello\">Hello</h1>"}, {1, "<p>Para</p>"}]

Code block decorators

Block attributes on a code block control highlighting and are never rendered:

{theme=github_dark pre_class="a b" highlight_lines="1,3-5" highlight_lines_style="background: #ff0" highlight_lines_class=hl include_highlights=true}
```elixir
IO.puts("hi")
```

Without syntax_highlight:, pre_class becomes a class on the code block and the other decorators are ignored.

HEEx

HEEx tags (<.link>, <Mod.fun>, <:slot>), {@expr} expressions and <%= %> blocks are recognized outside code; Carve brace syntax like {.class}, [Tab]{kbd}, {^sup^} or a block attribute line ({loose}) is left alone, so write {@name} rather than a bare {name} alone on a line. Explicit `...`{=heex} and ```=heex raw blocks also work.

Braces in the rendered HTML (text, code, attributes, raw html) become &lbrace;/&rbrace;, except inside <script> and <style>.

Private keys

Markup.Carve.Raw is written verbatim, so while rendering for HEEx (private :heex), build its HTML with Markup.safe_html(html, language: :carve, heex: true).

Options

  • :extensions (list of term/0) - carve-rs standard extensions, in registration order: a name or {name, options}, e.g. [:table_of_contents, heading_permalinks: [symbol: "§"]]. Names are Markup.Carve.extensions/0. Options (omitted keys keep the engine default): autolink (allowed_schemes), citations (mode: :numbered | :author_date), code_group (mode: :css | :aria, wrapper_class, panel_class, label_class, radio_class, id_prefix, group_label), color_swatch (position: :before | :after | :none, shape: :square | :round | :ring, tint, reveal), external_links (target, rel, nofollow), fenced_render (languages, css_class, tag: :pre | :div, content_mode: :text | :json, wrap_in_figure, figure_class, label), the fenced_render_* presets (css_class, tag, wrap_in_figure, figure_class, label), heading_numbers (min_level, label, crossref: :number | :number_title | :title), heading_permalinks (symbol, css_class, aria_label, levels, prepend, show_on_hover, copy_to_clipboard, lowercase_ids), heading_reference (css_class), index (backref_label), link_policy (allowed_schemes, denied_schemes, allowed_domains, denied_domains, allow_external, allow_internal, rel, base_host), math_block (language), smart_quotes (locale, open_double_quote, close_double_quote, open_single_quote, close_single_quote), tab_normalize (width), table_of_contents (min_level, max_level, list_type: :ul | :ol, css_class, position: :top | :bottom, collapsible, summary, open), tabs (mode: :css | :aria), wikilinks (css_class, new_window). Putting the option again merges by name: a repeated name replaces its entry in place. The default value is [].

  • :parse (keyword/0) - carve-rs parser options. The default value is [heading_ids: :keep_case, positions: false].

    • :positions (boolean/0) - Record pos (lines, columns and UTF-8 byte offsets) on every node. The default value is false.

    • :heading_ids - How generated heading ids are spelled: :off generates none; :lower lowercases; the :ascii* modes transliterate to ASCII (:ascii_strict drops what can't be transliterated). The default value is :keep_case.

  • :render (keyword/0) - carve-rs renderer options. The default value is [align_tables: false, heading_shift: 0, soft_break: :newline, smart_typography: true, symbols: %{}, tag_url: nil, mention_url: nil, allow_raw: false, profile: :full, raw_html: false, mode: :interactive, source_lines: false, sections: true].

    • :sections (boolean/0) - Wrap headings and their content in <section>. The default value is true.

    • :source_lines (boolean/0) - Add data-source-line to blocks. The default value is false.

    • :mode - HTML render mode; :static flattens interactive constructs. The default value is :interactive.

    • :raw_html (boolean/0) - Emit raw HTML written in the source (`x`{=html}, ```=html). Off by default, as in carve-rs, which then renders it as code. Markup.Carve.Raw nodes from plugins aren't affected. The default value is false.

    • :profile - carve-rs feature-restriction profile for untrusted input. Any profile other than :full rejects Markup.Carve.Raw nodes unless allow_raw: true. The default value is :full.

    • :allow_raw (boolean/0) - Render Markup.Carve.Raw nodes from plugins under a restricting profile:. Markup.Carve.Raw is written verbatim and bypasses the profile, so without this such a document fails with reason :raw_not_allowed. Enable only if every plugin that emits Markup.Carve.Raw is trusted. The default value is false.

    • :mention_url - URL template for @user mentions; {name} is replaced, e.g. "https://example.com/{name}". The default value is nil.

    • :tag_url - URL template for #tags; {name} is replaced. The default value is nil.

    • :symbols (map of String.t/0 keys and String.t/0 values) - :name: replacements, emitted as trusted raw HTML. Never build them from user input. The default value is %{}.

    • :smart_typography (boolean/0) - Write smart punctuation as glyphs; false keeps the characters as typed. The default value is true.

    • :soft_break - How a soft line break is written in HTML. The default value is :newline.

    • :heading_shift - Add this to every heading's level when rendering. The default value is 0.

    • :align_tables (boolean/0) - :carve output only: align table columns. The default value is false.

  • :syntax_highlight - Code block highlighting, e.g. [engine: :syntect] or [engine: :lumis]. nil disables it. The default value is nil.

Summary

Functions

The carve-rs standard extension names accepted by the :extensions option.

Lints Carve source, returning carve-rs's diagnostics in source order.

Functions

extensions()

@spec extensions() :: [atom()]

The carve-rs standard extension names accepted by the :extensions option.

iex> :table_of_contents in Markup.Carve.extensions()
true

lint(source, opts \\ [])

@spec lint(String.t(), keyword()) :: [Markup.Carve.LintWarning.t()]

Lints Carve source, returning carve-rs's diagnostics in source order.

Offsets in each Markup.Carve.LintWarning are UTF-8 byte offsets into source.

iex> [warning] = Markup.Carve.lint("{#orphan}\n")
iex> warning.rule
"unattached-block-attribute"

Options

  • :extensions (list of term/0) - As the :extensions option. The default value is [].

  • :parse (keyword/0) - As the :parse option. The default value is [].

  • :raw_html (boolean/0) - As render: [raw_html: ...]. The default value is false.

  • :rules - Turn catalog rules on or off by id, e.g. %{"caption-looking-paragraph" => :off}. The default value is %{}.

  • :platforms - Also check portability to these platforms. The default value is [].

  • :upgrade (boolean/0) - Also report the Carve 0.1 migration notices. The default value is false.