A Markdown parser and HTML renderer: CommonMark 0.31, GitHub Flavored Markdown and the common extensions.
import encoding.markdown
Markdown is the plain text format behind READMEs, wikis, blogs and notes. This package reads it into a tree and writes HTML from the tree. It is written in Salam, needs nothing else, and is checked against the official test suites: all 652 examples of the CommonMark 0.31.2 specification and all the extension examples of the GFM specification give exactly the HTML the specifications show.
"Markdown" is really a family of dialects, so Options says which one to read. The presets below are the usual choices.
Preset
What it reads
CommonMark
The CommonMark 0.31.2 specification, raw HTML allowed. This is also what the 2004 Markdown of John Gruber means once its open cases are settled.
Original
The same core with no extensions, for text written for Markdown.pl. The bugs of that script are not copied, so a few odd corners render the CommonMark way.
The common part of Pandoc Markdown: smart punctuation, front matter, math, sub and superscript, definition lists, footnotes, attributes, fenced divs.
Full
Every extension of this package at once, raw HTML off.
DefaultOptions
A friendly default for user text: GFM style extensions, footnotes, alerts, math and emoji, raw HTML off.
Article
For blog posts and lessons: front matter, attributes, heading ids, tables, task lists, strikethrough, autolinks, footnotes and alerts, raw HTML off.
Besides CommonMark itself, these are supported and each can be switched on its own: tables, strikethrough, task lists, extended autolinks, tag filter, footnotes (with inline notes and several references to one note), definition lists, abbreviations, heading ids, attributes {#id .class key=value}, math, highlight ==x==, insert ++x++, subscript, superscript, emoji shortcodes, alert callouts, fenced divs :::, wiki links, YAML and TOML front matter and smart punctuation.
Markdown to HTML in one call
ToHtml turns text into HTML. It uses DefaultOptions, which leaves raw HTML out, so it is safe to call on text typed by users. The heading got an id, the checkbox and the footnote came from the extensions.
encoding-markdown-guide-basics.salam
import encoding.markdown
funcmain:
src := "# Release notes\n\nVersion **2.0** is *out*. It adds:\n\n- tables\n- task lists\n- [x] footnotes[^1]\n\n[^1]: Yes, really.\n"print markdown.ToHtml(src)
end
ToHtmlWith takes the options as a second argument. The CommonMark preset gives the standard rules: setext and ATX headings, reference links, loose and tight lists, block quotes, indented code, hard breaks, entities and raw HTML blocks.
Tables take their alignment from the colons in the second row, rows with too few cells are padded and extra cells dropped, and \| puts a pipe in a cell. Task lists, strikethrough and bare addresses become checkboxes, del elements and links.
encoding-markdown-guide-gfm.salam
import encoding.markdown
funcmain:
src := "| Name | Qty | Price |\n|:-----|----:|:-----:|\n| Tea | 2 | 3.50 |\n| Milk | 10 | 1.20 |\n\n~~old price~~ new price\n\n- [x] shipped\n- [ ] paid\n\nDocs live at www.example.com/docs and https://example.org.\n"print markdown.ToHtmlWith(src, markdown.GFM())
end
The Full preset turns everything on. Footnote definitions can be several paragraphs long and are collected at the end of the page with a back link for each reference. An alert is a block quote that starts with [!NOTE], [!TIP], [!IMPORTANT], [!WARNING] or [!CAUTION]. Math is only marked up as \(...\) and \[...\] inside a span or div with the class math, so KaTeX or MathJax on the page can draw it.
encoding-markdown-guide-extensions.salam
import encoding.markdown
funcmain:
src := "Salam[^note] is typed.\n\n[^note]: A compiled language.\n\nTerm\n: Its definition\n\n*[SQL]: Structured Query Language\n\nUse SQL, or ==highlight==, H~2~O, x^2^ and :rocket:.\n\n> [!TIP]\n> Start small.\n\n## Install {#install .anchor}\n\nEuler: $e^{i\\pi} + 1 = 0$\n"print markdown.ToHtmlWith(src, markdown.Full())
end
A dialect decides what the characters mean. The text below has strikethrough, a bare address, a task and a footnote; each preset reads it differently, and CommonMark leaves all of it as written.
Markdown allows raw HTML, so a comment box that renders Markdown is a place for script injection. Keep unsafe_html off (the default of ToHtml, DefaultOptions, Full and Safe): raw tags become a comment, and links to javascript:, vbscript:, file: and data: (except small images) get an empty address. Nesting is limited, so a hostile text of a hundred thousand brackets or quotes cannot overflow the stack, and the time is linear in the size of the text.
safe:
<p>Hello <!-- raw HTML omitted -->alert(1)<!-- raw HTML omitted --> <a href="">click</a> <!-- raw HTML omitted -->bold<!-- raw HTML omitted --></p>
unsafe:
<p>Hello <script>alert(1)</script> <a href="javascript:alert(2)">click</a> <b>bold</b></p>
still hostile-input proof:
true
The presets CommonMark, Original, GFM, GitHub, Extra and Pandoc allow raw HTML because the specifications they follow do. For untrusted text wrap them in Safe.
Blocks for a server rendered page
A server function can only send plain data to a page: numbers, booleans, text, structs and vectors. A Document is not that, so ToBlocks parses the text and returns a Vector<Block>. The list is flat: a heading, paragraph, code block or table cell is one Block, its inline text is a list of Span runs, and the content of a quote, list, item or table follows it with a larger depth. The front matter at the top of a post is the first block, with its keys in fields. With the default Article options raw HTML is left out and dangerous addresses are emptied.
encoding-markdown-guide-blocks.salam
import encoding.markdown
import encoding.json
funcmain:
src := "---\ntitle: A first post\ndate: 2026-11-11\n---\n## Setup {#setup}\n\nRead the **[guide](/learn/)** first.\n"
blocks := markdown.ToBlocks(src)
println markdown.FrontMatterValue(blocks, "title")
each b in blocks:
println b.kind, b.level, "#" + b.id
each s in b.spans:
println" span:", s.kind, s.address, "[" + s.text + "]"endendmut copy := Vector {} asVector<markdown.Block>
try:
json.Unmarshal(json.Marshal(blocks), copy)
println"over the wire:", copy.Len(), "blocks"catch e:
println e.message
end
markdown.FreeBlocks(blocks)
end
Output
A first post
front_matter 0 #
heading 2 #setup
span: text [Setup]
paragraph 0 #
span: text [Read the ]
span: link /learn/ [guide]
span: text [ first.]
over the wire: 3 blocks
Walking the tree
Parse gives a Document. Root, FirstChild, NextSibling and Kind walk it, Headings and Toc build a table of contents, FrontMatter returns the header block and ToText returns what the reader sees. Free the document with Free and the list of headings with FreeHeadings.
encoding-markdown-guide-tree.salam
import encoding.markdown
funcmain:
src := "---\ntitle: Guide\n---\n# Intro\n\nText.\n\n## Setup\n\n### Linux\n\n## Usage\n"mut o := markdown.DefaultOptions()
o.frontmatter = true
d := markdown.Parse(src, o)
println"front matter:", markdown.FrontMatter(d)
hs := markdown.Headings(d)
repeat hs.Len() in i:
h := hs.Get(i)
println h.level, h.id, h.text
endprint markdown.Toc(d, 2, 3)
println markdown.ToText(d)
markdown.FreeHeadings(hs)
markdown.Free(d)
end
Output
front matter: title: Guide
1 intro Intro
2 setup Setup
3 linux Linux
2 usage Usage
<ul>
<li><a href="#setup">Setup</a>
<ul>
<li><a href="#linux">Linux</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a></li>
</ul>
Intro
Text.
Setup
Linux
Usage
What people get wrong:
•
Feeding user text to CommonMark() or GitHub() and sending the result to a page. Those allow raw HTML; use ToHtml or Safe.
•
Expecting the same HTML as another library byte for byte. The text of each element is the same, but the layout of newlines and attributes follows the specifications, and extensions are not standardised.
•
Forgetting that the extension switches are separate: footnotes, tables and the rest are off in CommonMark(), and [^1] is then an ordinary reference link.
A run of inline text inside a heading, paragraph, term or table cell.
Name
Type
Description
kind
str = ""
text, emph, strong, strike, code, link, image, break, footnote, math, display_math, html, highlight, insert, subscript, superscript or abbr. A text inside a link is always a link; the flags below keep the other styles.
text
str = ""
The visible text; for an image its alternative text, for a footnote its number.
address
str = ""
Where a link goes, the source of an image, or #fn-1 for a footnote. A formula inside a link has the link address too. Empty for a dangerous address such as javascript: unless raw HTML is on.
title
str = ""
The title of a link or image, or the long form of an abbreviation.
link
str = ""
For an image inside a link, the address of that link.
strong
bool = false
The run is bold.
emph
bool = false
The run is italic.
strike
bool = false
The run is struck through.
code
bool = false
The run is inline code.
encoding-markdown-ToBlocks.salam
import encoding.markdown
import encoding.json
funcmain:
src := "---\ntitle: A first post\ndate: 2026-11-11\n---\n## Setup {#setup}\n\nRead the **[guide](/learn/)** first.\n"
blocks := markdown.ToBlocks(src)
println markdown.FrontMatterValue(blocks, "title")
each b in blocks:
println b.kind, b.level, "#" + b.id
each s in b.spans:
println" span:", s.kind, s.address, "[" + s.text + "]"endendmut copy := Vector {} asVector<markdown.Block>
try:
json.Unmarshal(json.Marshal(blocks), copy)
println"over the wire:", copy.Len(), "blocks"catch e:
println e.message
end
markdown.FreeBlocks(blocks)
end
Output
A first post
front_matter 0 #
heading 2 #setup
span: text [Setup]
paragraph 0 #
span: text [Read the ]
span: link /learn/ [guide]
span: text [ first.]
over the wire: 3 blocks
Everything that decides how Markdown is read and written. Start from a preset (DefaultOptions, CommonMark, GFM, GitHub, Extra, Pandoc, Full) and switch single fields.
Name
Type
Description
unsafe_html
bool = false
Pass raw HTML in the text through to the output. Off by default so text from users cannot inject markup.
hardbreaks
bool = false
Render every line break in a paragraph as a br tag.
nobreaks
bool = false
Render soft line breaks as a space.
smart
bool = false
Curly quotes, en and em dashes and ellipses.
tables
bool = false
GFM pipe tables.
strikethrough
bool = false
~~text~~ becomes a del element.
tasklists
bool = false
- [ ] and - [x] items become checkboxes.
autolinks
bool = false
Bare www. addresses, http(s):// and ftp:// addresses and email addresses become links.
tagfilter
bool = false
Escape the dangerous tags the GFM specification lists (script, style, iframe and a few more) in raw HTML.
footnotes
bool = false
[^label] references, [^label]: definitions and ^[inline notes].
deflists
bool = false
Term lines followed by : definition lines.
heading_ids
bool = false
Give every heading a GitHub style id, made unique with -1, -2 and so on.
math
bool = false
$inline$, $$display$$ and $$ blocks.
highlight
bool = false
==text== becomes a mark element.
insert
bool = false
++text++ becomes an ins element.
subscript
bool = false
~text~ becomes a sub element.
superscript
bool = false
^text^ becomes a sup element.
emoji
bool = false
:name: shortcodes become emoji.
alerts
bool = false
> [!NOTE] style callouts.
attributes
bool = false
{#id .class key=value} after headings, links, images and code fence info strings.
frontmatter
bool = false
Read a --- (YAML) or +++ (TOML) block at the very top into FrontMatter instead of the page.
abbreviations
bool = false
*[ABBR]: title definitions.
containers
bool = false
::: name fenced divs.
wikilinks
bool = false
[[Page]] and [[Page|label]] links.
code_class_prefix
str = "language-"
Prefix of the class given to fenced code, language- by default.
The options for a blog post or a lesson: front matter, {#id} attributes, heading ids, tables, strikethrough, task lists, autolinks, footnotes and alerts, with raw HTML turned off. ToBlocks uses these.
Turns a parsed Document into a flat list of plain structs that can be returned by a server function. The list owns copies of every text, so the Document can be freed at once. Release the list with FreeBlocks.
The options most programs want: CommonMark plus tables, strikethrough, task lists, autolinks, footnotes, heading ids, alerts, math and emoji, with raw HTML turned off.
The original Markdown of John Gruber: the CommonMark core with raw HTML allowed and no extensions. Details where the old Markdown.pl differs are in the guide.
GitHub Flavored Markdown as the GFM specification defines it: CommonMark plus tables, strikethrough, task lists, extended autolinks and the tag filter.
The commonly used part of Pandoc Markdown: smart punctuation, front matter, math, sub and superscript, definition lists, footnotes, attributes and fenced divs.