API Reference

CommonMark.AdmonitionRule — Type
AdmonitionRule()

Parse admonition blocks (notes, warnings, tips, etc.).

Not enabled by default. Uses !!! syntax with a category and optional title.

!!! note "Custom Title"
    This is an admonition block.
    It can contain multiple paragraphs.

!!! warning
    Default title is the category name.
source
CommonMark.AsteriskEmphasisRule — Type
AsteriskEmphasisRule()

Parse emphasis using asterisks (* and **).

Enabled by default. Single for italic, double for bold.

*italic* and **bold** and ***both***
source
CommonMark.AttributeRule — Type
AttributeRule()

Parse attribute syntax to attach metadata to elements.

Block attributes go above the target element. Inline attributes go after. Uses {#id .class key=value} syntax.

{#custom-id .highlight}
# Heading

{.note}
Paragraph with attributes.

[Link](url){target=_blank}
source
CommonMark.AtxHeadingRule — Type
AtxHeadingRule()

Parse ATX-style headings (# Heading).

Enabled by default. Supports levels 1-6 with corresponding number of # characters.

# Heading 1
## Heading 2
### Heading 3
source
CommonMark.AutoIdentifierRule — Type
AutoIdentifierRule()

Automatically generate IDs for headings.

Not enabled by default. IDs are slugified from heading text. Duplicate IDs get numeric suffixes. Headings with explicit IDs (via AttributeRule) are preserved.

# My Heading        → <h1 id="my-heading">
# My Heading        → <h1 id="my-heading-1"> (duplicate)
# Custom {#my-id}   → <h1 id="my-id"> (with AttributeRule)
source
CommonMark.AutolinkRule — Type
AutolinkRule()

Parse autolinks (<url> and <email@example.com>).

Enabled by default. URLs must include a scheme.

<https://example.com>
<user@example.com>
source
CommonMark.BlockQuoteRule — Type
BlockQuoteRule()

Parse block quotes (> quoted text).

Enabled by default. Block quotes can be nested and contain other block elements.

> This is a block quote.
>
> > Nested quote.
source
CommonMark.CitationRule — Type
CitationRule()

Parse citation references using @key or [@key] syntax.

Not enabled by default. Citations can be bare (@smith2020) or bracketed ([@smith2020]). Requires a bibliography to be configured for rendering.

According to @smith2020, this is true.

Multiple citations: [@smith2020; @jones2021]
source
CommonMark.DefinitionListRule — Type
DefinitionListRule()

Parse definition lists (Pandoc-compatible syntax).

Not enabled by default. Terms are plain paragraph lines, definitions start with : followed by 1-3 spaces or a tab.

Term 1
:   Definition 1a
:   Definition 1b

Term 2
:   Definition 2
source
CommonMark.DollarMathRule — Type
DollarMathRule()

Parse LaTeX math with dollar sign delimiters (without backticks).

Not enabled by default. Inline math uses $...$, display math uses $$...$$.

Inline: $E = mc^2$

Display:
$$
\int_0^\infty e^{-x^2} dx
$$
source
CommonMark.FencedCodeBlockRule — Type
FencedCodeBlockRule()

Parse fenced code blocks (triple backticks or tildes).

Enabled by default. Supports optional language identifier.

```julia
println("Hello")
```
source
CommonMark.FencedDivRule — Type
FencedDivRule()

Parse Pandoc-style fenced divs (::: class blocks).

Not enabled by default. Creates generic container elements with CSS classes. Divs can be nested by using more colons.

::: warning
This is a warning div.
:::

:::: outer
::: inner
Nested divs.
:::
::::
source
CommonMark.FootnoteRule — Type
FootnoteRule()

Parse footnote definitions and references.

Not enabled by default. Define footnotes with [^id]: and reference with [^id].

Here is a footnote reference[^1].

[^1]: This is the footnote content.
source
CommonMark.FrontMatterRule — Type
FrontMatterRule(; yaml=identity, toml=identity, json=identity)

Parse YAML, TOML, or JSON front matter at document start.

Not enabled by default. Front matter is delimited by --- (YAML), +++ (TOML), or ;;; (JSON). Pass parser functions for each format.

---
title: My Document
author: Jane Doe
---

Document content here.

Use frontmatter to extract the parsed data.

source
CommonMark.GitHubAlert — Type

GitHub-style alert. Build with Node(GitHubAlert, category, children...; title="optional"). Categories: note, tip, important, warning, caution.

source
CommonMark.GitHubAlertRule — Type
GitHubAlertRule()

Parse GitHub-style alert blockquotes.

Not enabled by default. Converts blockquotes starting with [!TYPE] into styled alert boxes. Supported types: NOTE, TIP, IMPORTANT, WARNING, CAUTION.

> [!NOTE]
> This is a note alert.

> [!WARNING]
> This is a warning alert.
source
CommonMark.GridTable — Type

Grid table container. Same children as Table (TableHeader, TableBody, TableFoot, TableRow, TableCell).

source
CommonMark.GridTableRule — Type
GridTableRule()

Parse Pandoc-style grid tables with multi-line cells and block content.

Not enabled by default. Grid tables use + and - for borders and | for column separators. Header rows use = instead of - in the separator. Footer rows are enclosed by = separators at the bottom of the table.

+-------+-------+
| Cell  | Cell  |
+=======+=======+
| Body  | Body  |
+-------+-------+

Supports multi-line cells with block content (paragraphs, lists, code blocks).

source
CommonMark.HtmlBlockRule — Type
HtmlBlockRule()

Parse raw HTML blocks.

Enabled by default. Recognizes common HTML tags and passes them through unchanged.

<div class="warning">
  <p>Raw HTML content</p>
</div>
source
CommonMark.HtmlEntityRule — Type
HtmlEntityRule()

Parse HTML entities (&amp;, &#123;, &#x7B;).

Enabled by default. Converts entities to their Unicode equivalents.

&copy; &amp; &#60; &#x3C;
source
CommonMark.HtmlInlineRule — Type
HtmlInlineRule()

Parse inline HTML tags.

Enabled by default. Passes through raw HTML tags unchanged.

This has <em>inline HTML</em> tags.
source
CommonMark.ImageRule — Type
ImageRule()

Parse inline and reference images.

Enabled by default. Same syntax as links but prefixed with !.

![alt text](image.png)
![alt text][ref]

[ref]: image.png
source
CommonMark.InlineCodeRule — Type
InlineCodeRule()

Parse inline code spans (backtick-delimited).

Enabled by default. Uses matching backtick counts for nesting.

Use `code` inline or `` `backticks` `` inside.
source
CommonMark.Link — Type

Hyperlink. Build with Node(Link, children...; dest="url", title="optional").

source
CommonMark.LinkRule — Type
LinkRule()

Parse inline and reference links.

Enabled by default. Supports both inline [text](url) and reference [text][ref] styles.

[inline link](https://example.com)
[reference link][ref]

[ref]: https://example.com
source
CommonMark.List — Type

Bullet or ordered list. Build with Node(List, items...; ordered=false, start=1, tight=true).

source
CommonMark.ListItemRule — Type
ListItemRule()

Parse list items (bulleted and ordered lists).

Enabled by default. Supports -, +, * for bullets and 1., 1) for ordered.

- Item one
- Item two

1. First
2. Second
source
CommonMark.MarkRule — Type
MarkRule()

Parse marked/highlighted text (==highlighted==).

Not enabled by default. Uses double equals to mark highlighted text. Follows Pandoc +mark extension syntax.

==This text is highlighted.==
source
CommonMark.MathRule — Type
MathRule()

Parse LaTeX math in double-backtick code spans and fenced code blocks.

Not enabled by default. Inline math uses double backticks (``...``), display math uses math ``` fenced blocks.

Inline: ``E = mc^2``

Display:
```math
\int_0^\infty e^{-x^2} dx
```
source
CommonMark.Node — Method
Node(data::AbstractDict) -> Node

Construct a CommonMark AST from a Pandoc AST JSON dictionary.

The input should be a parsed JSON dictionary with "pandoc-api-version", "meta", and "blocks" keys. Use JSON.parse(str) to convert a JSON string first.

Inverse of json(Dict, ast).

Examples

using JSON
data = JSON.parse(json_string)
ast = Node(data)

# Round-trip:
ast2 = Node(json(Dict, ast))
source
CommonMark.Node — Method

Reference definition. Build with Node(ReferenceDefinition; label, dest, title="").

source
CommonMark.Node — Method

Reference-style image. Build with Node(ReferenceImage, children...; dest, label, title="", style=:full).

source
CommonMark.Node — Method

Reference-style link. Build with Node(ReferenceLink, children...; dest, label, title="", style=:full).

source
CommonMark.Node — Method

Unresolved reference. Build with Node(UnresolvedReference, children...; label, style=:shortcut, image=false).

source
CommonMark.Parser — Type
Parser(; enable=[], disable=[])

Create a CommonMark parser with default block and inline rules enabled.

Keywords

  • enable::Vector: Rules to enable after defaults (extensions like TableRule())
  • disable::Vector: Rules to disable from defaults (runs before enable)

The parser can be called directly on a string to produce an AST, which can then be rendered to various output formats using html, latex, term, markdown, notebook, or typst.

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
html(ast)  # "<h1>Hello</h1>\n<p>World</p>\n"

Enable extensions at construction:

p = Parser(enable=[TableRule(), MathRule()])

Disable default rules:

p = Parser(disable=[SetextHeadingRule()])

Equivalent to chaining enable! and disable! calls.

source
CommonMark.RawContentRule — Type
RawContentRule(; formats...)

Parse format-specific raw content blocks.

Not enabled by default. Uses `content`{=format} syntax for inline and fenced blocks with {=format} for blocks. The _inline or _block suffix is added automatically based on context.

`<span>html</span>`{=html}

```{=latex}
\textbf{LaTeX content}

Default formats: `html`, `latex`, `typst`.
source
CommonMark.ReferenceLinkRule — Type
ReferenceLinkRule()

Preserve reference link style in the AST.

Not enabled by default. By default, reference links are resolved to inline links during parsing. This rule preserves the original reference style (full, collapsed, or shortcut) for roundtrip rendering.

[full style][ref]
[collapsed style][]
[shortcut style]

[ref]: https://example.com

AST Node Types

When enabled, this rule produces these node types:

  • ReferenceLink / ReferenceImage - resolved reference links with fields:

    • destination::String - the URL
    • title::String - optional title
    • label::String - the reference label
    • style::Symbol - :full, :collapsed, or :shortcut
  • ReferenceDefinition - block node for [label]: url definitions

  • UnresolvedReference - references with undefined labels:

    • label::String - the reference label
    • style::Symbol - :full, :collapsed, or :shortcut
    • image::Bool - true for ![...] syntax

Finding Undefined References

The UnresolvedReference type enables programmatic detection of broken links:

p = Parser()
enable!(p, ReferenceLinkRule())
ast = p(markdown_text)

undefined = [n.t for (n, entering) in ast
             if entering && n.t isa CommonMark.UnresolvedReference]
# Each has: label, style (:full/:collapsed/:shortcut), image (Bool)
source
CommonMark.SetextHeadingRule — Type
SetextHeadingRule()

Parse setext-style headings (underlined with = or -).

Enabled by default. Only supports levels 1 and 2.

Heading 1
=========

Heading 2
---------
source
CommonMark.ShortcodeRule — Type
ShortcodeRule(; open="{{<", close=">}}", handlers=Dict{String,Function}())

Parse shortcodes with configurable delimiters.

Not enabled by default. Default delimiters match Quarto/Hugo syntax.

Handlers run at parse time: handler(name, args, kwargs, ctx::ShortcodeContext) -> Node. args is a Vector{String} of positional arguments, kwargs is a Vector{Pair{String,String}} of named key=value arguments. Quoted strings preserve spaces; backslash escapes work inside quotes. If a handler returns a Node, it replaces the shortcode in the AST. If no handler matches, the shortcode node is preserved for write-time handling via the writer transform system.

Inline: Text {{< ref "page" >}} here.
Block (standalone): {{< pagebreak >}}
source
CommonMark.StrikethroughRule — Type
StrikethroughRule()

Parse strikethrough text (~~deleted~~).

Not enabled by default. Uses double tildes to mark deleted text.

~~This text is struck through.~~
source
CommonMark.SubscriptRule — Type
SubscriptRule()

Parse subscript text (~subscript~).

Not enabled by default. Uses single tildes to mark subscript text.

H~2~O renders as H₂O
source
CommonMark.SuperscriptRule — Type
SuperscriptRule()

Parse superscript text (^superscript^).

Not enabled by default. Uses carets to mark superscript text.

x^2^ renders as x²
source
CommonMark.Table — Type

Table container. Build with Node(Table, header, body_rows...; align=[:left, :center, :right]).

source
CommonMark.TableRule — Type
TableRule()

Parse GitHub Flavored Markdown pipe tables.

Not enabled by default. Tables use | to separate columns and require a header separator row.

| Header 1 | Header 2 |
|----------|----------|
| Cell 1   | Cell 2   |

Alignment can be specified with : in the separator row:

  • :--- left align
  • :---: center align
  • ---: right align
source
CommonMark.TaskListRule — Type
TaskListRule()

Parse GitHub-style task list items.

Not enabled by default. Converts list items starting with [ ] or [x] into interactive checkboxes in HTML output.

- [ ] Unchecked item
- [x] Checked item
- Regular item
source
CommonMark.ThematicBreakRule — Type
ThematicBreakRule()

Parse thematic breaks (horizontal rules).

Enabled by default. Requires 3+ of *, -, or _ characters.

***

---

___
source
CommonMark.TypographyRule — Type
TypographyRule(; double_quotes=true, single_quotes=true, ellipses=true, dashes=true)

Convert ASCII punctuation to typographic equivalents.

Not enabled by default. Converts:

  • "..." to "..." (curly double quotes)
  • '...' to '...' (curly single quotes)
  • ... to … (ellipsis)
  • -- to – and --- to — (en/em dashes)

Disable specific conversions with keyword arguments.

source
CommonMark.UnderscoreEmphasisRule — Type
UnderscoreEmphasisRule()

Parse emphasis using underscores (_ and __).

Enabled by default. Single for italic, double for bold.

_italic_ and __bold__ and ___both___
source
CommonMark._index_at_column — Method

Return the string index corresponding to a given column (textwidth) offset. Stops before exceeding col columns, so the returned index is always valid.

source
CommonMark.append_child — Method
append_child(parent::Node, child::Node)

Add child as the last child of parent. Unlinks child from any previous location.

source
CommonMark.ast_equal — Method
ast_equal(a::Node, b::Node)

Compare two AST nodes for structural equality. Ignores source positions and parser state, comparing only the semantic content: container types, literals, and tree structure.

source
CommonMark.container_equal — Method
container_equal(a::AbstractContainer, b::AbstractContainer)

Compare two container types for equality, checking type and all fields.

source
CommonMark.default_transform — Method
default_transform(mime, container, node, entering, writer)

Default transform - passes through node unchanged. Users can define methods dispatching on container types to transform nodes.

Example

function my_transform(::MIME"text/html", link::Link, node, entering, writer)
    if entering
        dest = transform_url(link.destination)
        (Node(Link; dest = dest, title = link.title), entering)
    else
        (node, entering)
    end
end
my_transform(mime, ::AbstractContainer, node, entering, writer) =
    (node, entering)
source
CommonMark.disable! — Method
disable!(parser, rule)
disable!(parser, rules)

Disable a parsing rule or collection of rules from the parser.

This removes the specified rules and re-enables all remaining rules. Useful for removing default CommonMark behavior.

Returns the parser for method chaining.

Examples

p = Parser()
disable!(p, SetextHeadingRule())  # Only allow ATX-style headings
disable!(p, [HtmlBlockRule(), HtmlInlineRule()])  # Disable raw HTML

See also: enable!, Parser

source
CommonMark.enable! — Method
enable!(parser, rule)
enable!(parser, rules)

Enable a parsing rule or collection of rules in the parser.

Rules can be core CommonMark rules (e.g., AtxHeadingRule) or extension rules (e.g., TableRule, AdmonitionRule).

Returns the parser for method chaining.

Examples

p = Parser()
enable!(p, TableRule())
enable!(p, [FootnoteRule(), AdmonitionRule()])

See also: disable!, Parser

source
CommonMark.frontmatter — Method
frontmatter(ast::Node) -> Dict{String,Any}

Extract front matter data from a parsed document.

Returns an empty dictionary if no front matter is present. Requires FrontMatterRule to be enabled during parsing. Supports YAML (---), TOML (+++), and JSON (;;;) delimiters.

Examples

p = Parser()
enable!(p, FrontMatterRule(yaml=YAML.load))
ast = p("""
---
title: My Document
author: Jane Doe
---
# Content
""")
frontmatter(ast)  # Dict("title" => "My Document", "author" => "Jane Doe")
source
CommonMark.html — Method
html(ast::Node) -> String
html(filename::String, ast::Node)
html(io::IO, ast::Node)

Render a CommonMark AST to HTML.

Keyword Arguments

  • softbreak::String = "\n": String to use for soft line breaks
  • safe::Bool = false: Escape potentially unsafe HTML content
  • sourcepos::Bool = false: Include source position data attributes

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
html(ast)  # "<h1>Hello</h1>\n<p>World</p>\n"
source
CommonMark.json — Method
json(ast::Node; dicttype=Dict) -> String
json(filename::String, ast::Node; dicttype=Dict)
json(io::IO, ast::Node; dicttype=Dict)
json(::Type{<:AbstractDict}, ast::Node) -> AbstractDict

Render a CommonMark AST to Pandoc AST JSON format.

The output can be piped to pandoc -f json -t <format> to convert to any format Pandoc supports (docx, epub, rst, asciidoc, etc.).

The dicttype keyword argument controls the dictionary type used internally. Use OrderedCollections.OrderedDict for deterministic key ordering.

Pass a dict type as the first argument to return the dict directly without JSON string serialization: json(Dict, ast).

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
output = json(ast)
# Use with: echo $output | pandoc -f json -t docx -o out.docx

# Get dict directly (no JSON string):
d = json(Dict, ast)
source
CommonMark.latex — Method
latex(ast::Node) -> String
latex(filename::String, ast::Node)
latex(io::IO, ast::Node)

Render a CommonMark AST to LaTeX.

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
latex(ast)  # "\\section{Hello}\n\nWorld\n"
source
CommonMark.literal_width — Method

What is the width of the literal text stored in node and all of it's child nodes. Used to determine alignment for rendering nodes such as centered.

source
CommonMark.markdown — Method
markdown(ast::Node) -> String
markdown(filename::String, ast::Node)
markdown(io::IO, ast::Node)

Render a CommonMark AST back to Markdown text.

Useful for normalizing Markdown formatting or for roundtrip testing. Output uses opinionated formatting. Hard breaks use two trailing spaces.

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
markdown(ast)  # "# Hello\n\nWorld\n"
source
CommonMark.notebook — Method
notebook(ast::Node) -> String
notebook(filename::String, ast::Node)
notebook(io::IO, ast::Node)

Render a CommonMark AST to a Jupyter notebook (.ipynb format).

Code blocks are converted to code cells, and other content becomes Markdown cells.

Examples

p = Parser()
ast = p("# Title\n\n```julia\nprintln(\"Hello\")\n```")
notebook("output.ipynb", ast)
source
CommonMark.prepend_child — Method
prepend_child(parent::Node, child::Node)

Add child as the first child of parent. Unlinks child from any previous location.

source
CommonMark.print_literal — Method

Literal printing of a of parts. Behaviour depends on when .wrap is active at the moment, which is set in Paragraph rendering.

source
CommonMark.print_margin — Method

Print out all the current segments present in the margin buffer.

Each time a segment gets printed it's count is reduced. When a segment has a count of zero it won't be printed and instead spaces equal to it's width are printed. For persistent printing a count of -1 should be used.

source
CommonMark.push_margin! — Function

Adds a new segment to the margin buffer, but will only print out for the given number of count calls to print_margin. After count calls it will instead print out spaces equal to the width of text.

source
CommonMark.push_margin! — Function

Adds a new segment to the margin buffer. This segment is persistent and thus will print on every margin print.

source
CommonMark.push_margin! — Method

Adds new segmant to the margin buffer. count determines how many time initial is printed. After that, the width of rest is printed instead.

source
CommonMark.term — Method
term(ast::Node) -> String
term(filename::String, ast::Node)
term(io::IO, ast::Node)

Render a CommonMark AST for terminal display with ANSI formatting.

Includes colored syntax highlighting for code blocks when a highlighter is configured.

Examples

p = Parser()
ast = p("# Hello\n\n**World**")
term(ast)  # Returns ANSI-formatted string
source
CommonMark.text — Method
text(s::AbstractString) -> Node

Create a Text node containing the given string.

source
CommonMark.typst — Method
typst(ast::Node) -> String
typst(filename::String, ast::Node)
typst(io::IO, ast::Node)

Render a CommonMark AST to Typst markup.

Examples

p = Parser()
ast = p("# Hello\n\nWorld")
typst(ast)
source
CommonMark.unlink — Method
unlink(node::Node)

Remove node from its parent, updating sibling links. Safe to call on unlinked nodes.

source
CommonMark.@cm_str — Macro
cm""

A string macro for markdown text that implements standard string interpolation. Returns a parsed markdown AST with the values of the interpolation expressions embedded in the AST.

value = "interpolated"
cm"Some *$(value)* text."

The default syntax rules used for parsing are:

  • AdmonitionRule
  • AttributeRule
  • AutoIdentifierRule
  • CitationRule
  • FootnoteRule
  • MathRule
  • RawContentRule
  • TableRule
  • TypographyRule

which matches closely with the default syntax supported in Markdown.@md_str.

Info

The DollarMathRule is not enabled since it conflicts with the interpolation syntax. Use double backticks and math language literal blocks for maths that is provided by the MathRule.

A custom Parser can be invoked when using cm"" by providing a suffix to the macro call, for example:

more = "more"
cm"Some **$(uppercase(more))** text."none

where the suffixed none will invoke a basic Parser with no additional syntax rules enabled!. To use your own custom parser, for example to only enable the TypographyRule, you can suffix the call with a named function from the current module's global scope that returns the Parser object with the required rules enabled:

custom() = enable!(Parser(), TypographyRule())

It can then be used as

str = "custom"
cm"A '$(titlecase(str))' parser..."custom
source
CommonMark.@docstring_parser — Macro
@docstring_parser
@docstring_parser parser
Experimental

This macro is experimental and subject to change without notice.

Install CommonMark parser for all docstrings in the calling module. Call at module top-level after all docstrings are defined.

Optionally pass a custom Parser with extensions enabled:

@docstring_parser Parser(enable=[MathRule()])
source