Carve for Markup, backed by the Rust
carve-rs engine.
Adding {:markup_carve, "~> 0.1"} to your deps registers the :carve
language with Markup:
Markup.to_html/2andMarkup.convert/3render source or aMarkup.Documentto:html,:markdown,:plain_text,:ansior:carveMarkup.parse_document/2returns a tree ofMarkup.Carve.*nodes- carve-rs extensions, profiles and safe mode (see the options below)
- syntax highlighting with syntect or Lumis, with code block decorators
- HTML sanitization (ammonia)
- HEEx components and expressions (
Markup.to_heex/2,~MU"..."carveHEEX) - streaming of chunked input (
Markup.stream/2) - linting (
lint/2)
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)
"<a>&</a>"
iex> Markup.safe_html("<pre>A{b}</pre>", language: :carve, sanitize: nil, heex: true)
"<pre>A{b}</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
{/}, 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 ofterm/0) - carve-rs standard extensions, in registration order: a name or{name, options}, e.g.[:table_of_contents, heading_permalinks: [symbol: "§"]]. Names areMarkup.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), thefenced_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) - Recordpos(lines, columns and UTF-8 byte offsets) on every node. The default value isfalse.:heading_ids- How generated heading ids are spelled::offgenerates none;:lowerlowercases; the:ascii*modes transliterate to ASCII (:ascii_strictdrops 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 istrue.:source_lines(boolean/0) - Adddata-source-lineto blocks. The default value isfalse.:mode- HTML render mode;:staticflattens 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.Rawnodes from plugins aren't affected. The default value isfalse.:profile- carve-rs feature-restriction profile for untrusted input. Any profile other than:fullrejectsMarkup.Carve.Rawnodes unlessallow_raw: true. The default value is:full.:allow_raw(boolean/0) - RenderMarkup.Carve.Rawnodes from plugins under a restrictingprofile:.Markup.Carve.Rawis written verbatim and bypasses the profile, so without this such a document fails with reason:raw_not_allowed. Enable only if every plugin that emitsMarkup.Carve.Rawis trusted. The default value isfalse.:mention_url- URL template for@usermentions;{name}is replaced, e.g."https://example.com/{name}". The default value isnil.:tag_url- URL template for#tags;{name}is replaced. The default value isnil.:symbols(map ofString.t/0keys andString.t/0values) -: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;falsekeeps the characters as typed. The default value istrue.: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 is0.:align_tables(boolean/0) -:carveoutput only: align table columns. The default value isfalse.
:syntax_highlight- Code block highlighting, e.g.[engine: :syntect]or[engine: :lumis].nildisables it. The default value isnil.
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
@spec extensions() :: [atom()]
The carve-rs standard extension names accepted by the :extensions option.
iex> :table_of_contents in Markup.Carve.extensions()
true
@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 ofterm/0) - As the:extensionsoption. The default value is[].:parse(keyword/0) - As the:parseoption. The default value is[].:raw_html(boolean/0) - Asrender: [raw_html: ...]. The default value isfalse.: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 isfalse.