Markup.Carve
Carve 0.2 for Markup.
The carve-rs engine (crate carve-lang
0.2) does the parsing and rendering through a Rustler NIF. This package adds Carve's
parser, its renderers, syntax highlighting, sanitize defaults and linting; the
document API, plugins, HEEx, the sigil and streaming come from markup (see its docs).
| markup_carve | Carve language | carve-lang |
|---|---|---|
| 0.1.x | 0.2 | 0.2.0 |
The NIF pins carve-lang exactly (=0.2.0 in
native/markup_carve_nif/Cargo.toml), because carve-rs can change :carve output
in any 0.2.x release.
Installation
def deps do
[
{:markup, "~> 0.1"},
{:markup_carve, "~> 0.1"}
]
end
The language id is :carve.
Markup.to_html("hello *world*!", language: :carve)
# => {:ok, "<p>hello <strong>world</strong>!</p>"}
Markup.to_html!("= Hi", language: :carve, render: [sections: false])
# => "<h1 id=\"Hi\">Hi</h1>"
Carve 0.2 spells headings = Title, == Section and so on. The engine still reads
# Title, but the :carve writer rewrites it.
Options
Options are grouped like MDEx's; see Markup.Carve for the full list.
parse:-positions(recordposon every node) andheading_ids(:keep_case,:lower,:offand the:ascii*transliterations).render:-sections(wrap headings in<section>, defaulttrue),source_lines,mode(:interactiveor:static, which flattens interactive constructs),raw_html,profile,allow_raw,mention_url,tag_url,symbols,smart_typography,soft_break,heading_shiftandalign_tables(:carveoutput).
Untrusted input
Raw HTML in the source (`x`{=html}, ```=html) renders as code unless
you pass raw_html: true. profile: applies one of carve-rs's feature-restriction
profiles (:full, the default, :article, :comment or :minimal), and source over
the profile's length limit is an error:
Markup.to_html("`<b>x</b>`{=html}", language: :carve)
# => {:ok, "<p><b>x</b></p>"}
Markup.to_html("= Head\n\ntext", language: :carve, render: [profile: :comment])
# => {:ok, "<p># Head</p>\n<p>text</p>"}
Markup.to_html(String.duplicate("a", 10_001), language: :carve, render: [profile: :minimal])
# => {:error, %Markup.Carve.Error{reason: {:profile_violation, "..."}}}
The length limit only applies to source. A parsed document has no source length, so rendering it under a profile still filters constructs, but never fails on length.
carve-rs never sees the Markup.Carve.Raw nodes that plugins inject, so a profile
can't police them. Under any profile but :full, a document that still holds a
Markup.Carve.Raw after the plugin steps fails with reason :raw_not_allowed. Pass
render: [allow_raw: true] only if you trust every plugin that adds them.
Syntax-highlighted code isn't affected.
symbols: values are emitted as trusted raw HTML, so never build them from user input.
Extensions
You turn on carve-rs's standard extensions by name, in registration order, with options for the ones that take them:
Markup.to_html!("= Intro\n\n== Usage\n",
language: :carve,
extensions: [:table_of_contents, heading_permalinks: [symbol: "§"]],
render: [sections: false]
)
# => "<nav class=\"toc\" aria-label=\"Table of contents\">\n <ul>\n <li><a href=\"#Intro\">Intro</a>…"
Markup.Carve.extensions()
# => [:autolink, :citations, :code_callouts, :code_group, …]
Unknown names and keys raise. Passing extensions: again merges by name. Extensions
and profiles also apply when you render an edited document.
Diagram fences are one extension per language (:fenced_render_mermaid,
:fenced_render_d2, …), or fenced_render: [languages: [...]] for your own list.
Nodes
Nodes (Markup.Carve.Heading, Markup.Carve.Paragraph, Markup.Carve.Strong, …)
mirror Carve's 2.0 tree format. Attributes are %Markup.Carve.Attributes{}, and with
parse: [positions: true] each node gets a %Markup.Carve.Pos{}. Child lists are
named nodes, text and code content is literal, and link and image targets are
url, even where carve's JSON says children, value, href or src. A code
block's language is syntax.
doc = Markup.parse_document!("= Hi\n\nSome *bold* text", language: :carve)
doc[:strong]
# => [%Markup.Carve.Strong{nodes: [%Markup.Carve.Text{literal: "bold"}]}]
doc
|> Markup.Document.update_nodes(:strong, &%Markup.Carve.Emphasis{nodes: &1.nodes})
|> Markup.to_html!()
# => "<section id=\"Hi\">\n <h1>Hi</h1>\n <p>Some <em>bold</em> text</p>\n</section>"
Headings are top-level blocks in the tree; the <section> wrapping happens at render
time. Plugins inject HTML with Markup.Carve.Raw (build the content with
Markup.safe_html/2), and under a restricting profile it needs allow_raw: true.
An enabled extension turns what it claims into a Markup.Carve.BlockExtension or
Markup.Carve.InlineExtension. Its content lives in slots, a list of
Markup.Carve.Slot nodes, and that's what it renders from; fallback only renders
when nothing claims the node. Selectors and update_nodes/3 reach into both.
Syntax highlighting
The :syntect engine is built in. Lumis needs
{:lumis, "~> 0.10"} plus a parser package such as {:lumis_wasm_elixir, "~> 0.26"}.
Markup.to_html!(source, language: :carve, syntax_highlight: [engine: :syntect, opts: [theme: "Dracula"]])
Markup.to_html!(source,
language: :carve,
syntax_highlight: [engine: :lumis, opts: [formatter: {:html_inline, theme: "onedark"}]]
)
Passing syntax_highlight: again merges into the current settings (including opts:),
and nil turns highlighting off.
Code blocks take decorators as Carve block attributes on the line above the fence:
{theme=Dracula pre_class="a b" highlight_lines="1,3-5" highlight_lines_class=hl}
```elixir
IO.puts("hi")
```
| Decorator | Effect |
|---|---|
theme |
Overrides the configured theme (syntect, Lumis :html_inline / :terminal) |
pre_class |
Extra classes on <pre> |
highlight_lines |
Lines to highlight: comma-separated N or N-M; invalid entries are skipped |
highlight_lines_style |
Inline style for highlighted lines |
highlight_lines_class |
Extra class for highlighted lines |
include_highlights |
true adds a data-highlight attribute with the scope name (Lumis :html_inline / :html_multi_themes only) |
Decorators never show up in the output. Without syntax_highlight:, pre_class still
becomes a class on <pre> and the rest are ignored. If an enabled extension renders a
code block's language (mermaid with :fenced_render_mermaid, math with
:math_block), the block is left to that extension.
Sanitization
sanitize: [] uses Markup.Carve.default_sanitize_options/0. The defaults keep
carve's own footnote, section and task-list markup. Anything outside the allowlist,
such as phx-update, is removed unless you allow it, for example with
add_tag_attributes: or add_generic_attribute_prefixes:.
HEEx
Carve's own brace syntax ({.class}, [Tab]{kbd}, {^sup^}, {,sub,}, {:fr},
{~old~>new~}, …) is left alone in HEEx templates. A bare {name} alone on a line is
a Carve block attribute line, so write {@name} or put the expression inline. Braces
in the rendered HTML become entities, except inside <script> and <style>.
Markup.to_heex!("Hi {@name}", language: :carve, assigns: %{name: "Ann"})
Outputs
Besides :html, Carve renders to :markdown, :plain_text, :ansi and :carve
(~MU modifiers carveMD, carveTEXT, carveANSI, carveCARVE):
Markup.convert!("/hi/ *there* {=mark=}", :markdown, language: :carve)
# => "*hi* **there** <mark>mark</mark>\n"
Markup.convert!("= Title\n\n/hi/ *there*", :plain_text, language: :carve)
# => "Title\n\nhi there\n"
Markup.convert!("*bold*", :ansi, language: :carve)
Markup.convert!("= Title\n\n- a\n- b", :carve, language: :carve)
# => "= Title\n\n- a\n- b\n"
:carve output is carve-rs's canonical writer. Given a document, it writes the
(possibly edited) tree back to Carve source.
Linting
Markup.Carve.lint("{#orphan}\n")
# => [%Markup.Carve.LintWarning{line: 1, column: 1, rule: "unattached-block-attribute",
# severity: "warning", message: "This attribute line reaches no block: …",
# start_offset: 0, end_offset: 9}]
Markup.Carve.lint(source, rules: %{"caption-looking-paragraph" => :off}, platforms: [:github])
start_offset and end_offset are UTF-8 byte offsets, so
binary_part(source, w.start_offset, w.end_offset - w.start_offset) is the flagged text.
Streaming
Each streamed block renders on its own, so a footnote reference only resolves when its definition is in the same block.
Not exposed
A few carve-rs features aren't bound here: static-mode build renderers (diagram and
math callbacks), mention and tag resolver functions, host code block renderers,
{{ include }} expansion, the importers (HTML, Markdown, GFM and Djot to Carve), the
ProseMirror bridge, and tree diffs and patches.
Building from source
Releases download a precompiled NIF. Set MARKUP_CARVE_BUILD=1 (and add
{:rustler, "~> 0.38"}) to build it locally; dev and test always build it.
See also
This package ports carvex into Markup. Carvex in turn ports djot to Carve, and is heavily "inspired" by the excellent mdex package.