Taskcore
Parse a Markdown text
Also called convert Markdown to HTML, render Markdown, Markdown to HTML.
Convert a text in a subset of CommonMark (headings, paragraphs, lists, fenced code, emphasis, code spans and links) to the same HTML that a CommonMark converter gives.
- Evidence
- Code in 5 languages
Task
Convert a Markdown text to HTML, with the rules of CommonMark 0.31.2. The text uses a subset of Markdown: ATX headings (# to ######), paragraphs, bullet lists with - , fenced code with backticks, emphasis and strong emphasis with *, code spans, inline links, backslash escapes and hard line breaks. The output must be the same HTML that a CommonMark converter gives for the text, character for character.
For example, this text:
# Release notes
Version **2.1** adds one *small* feature:
- a `--dry-run` flag
- a [manual](https://example.com/manual)
```sh
tool --dry-run
```
gives this HTML:
<h1>Release notes</h1>
<p>Version <strong>2.1</strong> adds one <em>small</em> feature:</p>
<ul>
<li>a <code>--dry-run</code> flag</li>
<li>a <a href="https://example.com/manual">manual</a></li>
</ul>
<pre><code class="language-sh">tool --dry-run
</code></pre>
The subset leaves out block quotes, ordered lists, indented code, setext headings, thematic breaks, raw HTML, autolinks, images, reference links, character references and _ emphasis. The file contract.yaml lists the exact rules of the input. In the subset, each construct has a clear start, so a small parser can give the same output as a full one.
Solutions
All the solutions use the two phases of the CommonMark parsing strategy. In the first phase, "lines of input are consumed and the block structure of the document" is built.1 "In the second phase, the raw text contents of paragraphs and headings are parsed into sequences of Markdown inline elements".1
The block phase reads the lines in order. A line that starts with three or more backticks opens a fenced code block, which runs to a closing fence, which "must be at least as long as the opening fence", or to the end of the text.1 The lines in it are escaped and are not parsed. A heading line gives one <h1> to <h6> element, and a closing sequence of # characters is removed. A - line starts a list, and a list is loose if "any of its constituent list items are separated by blank lines".1 The items of a loose list are wrapped in <p>. All other lines make a paragraph, which runs until a blank line or the start of a fence, a heading or a list.
The inline phase reads the text of each heading, paragraph and list item from left to right:
- Backslash escapes. "Any ASCII punctuation character may be backslash-escaped".1 A backslash at the end of a line gives
<br />. - Code spans. "A code span begins with a backtick string and ends with a backtick string of equal length."1 In the content, "line endings are converted to spaces".1 Then, if the content "both begins and ends with a space character, but does not consist entirely of space characters, a single space character is removed from the front and back."1 A backtick string with no closing string of the same length is plain text.
- Links.
[text](url)gives<a href="url">. The text is parsed again for emphasis and code spans. - Line breaks. A line ending "that is preceded by two or more spaces and does not occur at the end of a block is parsed as a hard line break".1 The spaces at the end of every line are removed.
- Emphasis. Each run of
*becomes a delimiter. The parser looks at the characters before and after the run, and the start or the end of the text counts as white space. A run is left-flanking if it is "not followed by Unicode whitespace", and either not followed by a Unicode punctuation character, or "followed by a Unicode punctuation character and preceded by Unicode whitespace or a Unicode punctuation character".1 A right-flanking run is the mirror of this. A left-flanking run can open emphasis, and a right-flanking run can close it. After the scan, the parser matches each closer with the nearest opener before it, as in the "process emphasis" procedure of the spec. Two characters from each run give<strong>, and one gives<em>. Each other character is written with&,<,>and"escaped.
The flanking rules need two classes of characters. "A Unicode whitespace character is a character in the Unicode Zs general category, or a tab ( U+0009 ), line feed ( U+000A ), form feed ( U+000C ), or carriage return ( U+000D )."1 A Unicode punctuation character is a character in the P (punctuation) or S (symbol) general categories.1 Each language has a function for the general category:
- Python.
unicodedata.category"Returns the general category assigned to the character chr as string."2 The code tests whether the category starts withPorS, or isZs. - JavaScript and TypeScript (Node.js). The regular expressions
[\p{P}\p{S}]and\p{Zs}test the category.\pis "only supported in Unicode-aware mode", so the expressions have theuflag.3Array.from(text)splits the text into an array of code points, because the string iterator "yields the Unicode code points of the string value as individual strings".4 The TypeScript file adds types only. - Go.
unicode.IsPunct"reports whether the rune is a Unicode punctuation character (category P )".5unicode.IsSymbol"reports whether the rune is a symbolic character", andunicode.Zsis the set of characters "in category Zs (Separator, space)".5 The text is converted to a[]rune, and Go'sregexppackage handles the block patterns. - C#.
string.EnumerateRunesgives the text asRunevalues.Rune.IsPunctuationandRune.IsSymbolreturn whether a rune "is categorized as a punctuation mark" or "as a symbol character".6
Java, Rust, C, C++ and Bash have no Markdown parser in their standard library, so this page has no solution in those languages. The file matrix.yaml names a CommonMark library for each one.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the Markdown text and the HTML that the solution must return. The HTML of each case comes from commonmark.js 0.31.2.
heading-and-paragraph,paragraph-lines,bullet-list,fenced-code,code-spanandlink: the common shapes. The lines of a paragraph stay on separate lines in the HTML.empty,blank-lines-onlyandno-final-newline: an empty text or a text of blank lines gives an empty string, and a text with no LF at the end gives the same HTML as one with it.paragraph-ends-at-block: a heading or a fence ends a paragraph with no blank line before it.html-chars:a < b & "c" > dbecomesa < b & "c" > d.backslash-escape:\*not emphasis\*gives*not emphasis*.intraword-starandintraword-underscore:foo*bar*bazgives emphasis in a word, butsnake_case_namestays as it is. The subset has no_emphasis, and in CommonMark "Emphasis with _ is not allowed inside words".1star-with-spaces: ina * b * c, each*has a space on both sides, so it cannot open or close emphasis.triple-star,unmatched-starandrule-of-three:***both***gives<em><strong>both</strong></em>,**foo*gives*<em>foo</em>, and*foo**bar**baz*gives<em>foo<strong>bar</strong>baz</em>. The last case needs the rule that "the sum of the lengths of the delimiter runs containing the opening and closing delimiters must not be a multiple of 3 unless both lengths are multiples of 3".1punctuation-flanking:*"quoted"*gives emphasis, but ina*"b"*the first*has a letter before it and a quotation mark after it, so it cannot open.code-span-backticks,code-span-precedenceandunclosed-backtick:ab `` `` holds a backtick. In `` *ab* `` the` in the code span is not a delimiter, because "Code span backticks have higher precedence than any other inline constructs except HTML tags and autolinks."1hard-break-spaces,hard-break-backslashandtrailing-spaces: two spaces or a backslash at the end of a line give<br />, but not at the end of a paragraph.heading-closing,heading-emptyandnot-a-heading:## Title ##gives<h2>Title</h2>,#alone gives an empty<h1>, and#hashtagand seven#characters give paragraphs.list-interrupts-paragraphandloose-list: a-line ends a paragraph, and a blank line between items makes the list loose.unclosed-fence,longer-fence,fence-info-wordsandfence-keeps-markup: a fence with no end runs to the end of the text, a fence of four backticks holds a line of three, only the first word of the info string becomes the class, and#and*in the code stay as they are.link-with-emphasis,not-a-linkandlink-ampersand: emphasis can be inside a link or around it,[a] (u)with a space is not a link, and the&in a URL becomes&.non-ascii:Zürich *東京* 🙂keeps each character.
Pitfalls
- A regular expression for each construct gives the wrong HTML. A converter can replace
**...**and then*...*with regular expressions. Such a converter does not use the flanking rules, they change the text inside code spans, and they do not escape HTML:
This code runs but gives a wrong answer on purpose.
import re
def naive(text):
text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
return re.sub(r"\*(.+?)\*", r"<em>\1</em>", text)
for text in ["a * b * c", "*a `*` b*", "2 < 3"]:
print(naive(text))
a <em> b </em> c
<em>a `</em>` b*
2 < 3
CommonMark gives a * b * c, <em>a <code>*</code> b</em> and 2 < 3. The solutions scan each inline text once and decide about emphasis only after all the code spans and links are known.
-
A parser that reads each line alone breaks code blocks. A line in a fenced code block is code, also if it starts with
#or-. The parser must know whether a fence is open before it looks at the line. The casefence-keeps-markuptests this. -
The text in the HTML must be escaped. If the converter writes
<,>and&as they are, a text such as<script>runs in the browser of each reader. See Cross-site scripting. The solutions escape all text, also the code and the URLs. -
A full converter passes raw HTML through. CommonMark allows raw HTML in the text. The README of commonmark.js says: "The library does not attempt to sanitize link attributes or raw HTML."7 Its
safeoption replaces raw HTML with comments, and it replaces "potentially unsafe URLs in links and images (those beginning withjavascript:,vbscript:,file:, and with a few exceptionsdata:)" with empty strings.7 The README of cmark says: "By default, the library will scrub raw HTML and potentially dangerous links".8 For its unsafe option, the README says "we recommend you use a HTML sanitizer specific to your needs".8 If the text comes from users, use the safe mode of the library or a sanitizer. -
A JavaScript string index is a UTF-16 code unit, not a character. A character outside the BMP, such as an emoji, is two code units, and each one alone is not punctuation:
This code runs but gives a wrong answer on purpose.
const isPunct = (c) => /^[\p{P}\p{S}]$/u.test(c);
const text = "🙂*";
console.log(text.length, Array.from(text).length);
console.log(isPunct(text[text.length - 2]), isPunct(Array.from(text)[0]));
3 2
false true
The second line shows that the emoji matches [\p{P}\p{S}], so it is a Unicode punctuation character for the flanking rules. A parser that reads text[i - 1] sees half of it and decides differently about the * after it. The JavaScript and TypeScript solutions use Array.from, and the C# solution uses Rune, because "some of the char methods won't work correctly on char instances that are in the surrogate range."6 The contract keeps such characters away from * runs, so each case has one HTML result.
Related tasks
- Markdown: the Markdown format and its history.
- CommonMark: the CommonMark spec and its reference implementations.
- Cross-site scripting: why HTML output must escape the text.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-a-markdown-text/.
"""Convert a text in a subset of CommonMark to HTML."""
import re
import unicodedata
HEADING = re.compile(r"(#{1,6})(?:[ \t]+(.*?))?[ \t]*$")
CLOSING = re.compile(r"(?:^|[ \t]+)#+[ \t]*$")
FENCE = re.compile(r"(`{3,})[ \t]*([^`]*?)[ \t]*$")
ITEM = re.compile(r"- (.*)$")
URL = re.compile(r"[A-Za-z0-9\-._~:/?#=&+%]+")
PUNCTUATION = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
def escape(text):
return (text.replace("&", "&").replace("<", "<")
.replace(">", ">").replace('"', """))
def markdown_to_html(text):
lines = text.removesuffix("\n").split("\n") if text else []
out = []
i = 0
while i < len(lines):
line = lines[i]
if line.strip(" \t") == "":
i += 1
elif FENCE.match(line):
i = code_block(lines, i, out)
elif HEADING.match(line):
m = HEADING.match(line)
level = len(m.group(1))
content = CLOSING.sub("", m.group(2) or "")
out.append(f"<h{level}>{inlines(content)}</h{level}>\n")
i += 1
elif ITEM.match(line):
i = bullet_list(lines, i, out)
else:
i = paragraph(lines, i, out)
return "".join(out)
def starts_block(line):
return (line.strip(" \t") == "" or FENCE.match(line) is not None
or HEADING.match(line) is not None or ITEM.match(line) is not None)
def code_block(lines, i, out):
m = FENCE.match(lines[i])
fence = m.group(1)
info = m.group(2).split()
attr = f' class="language-{escape(info[0])}"' if info else ""
body = []
i += 1
while i < len(lines):
close = lines[i].rstrip(" \t")
if close.startswith(fence) and close.strip("`") == "":
i += 1
break
body.append(escape(lines[i]) + "\n")
i += 1
out.append(f"<pre><code{attr}>{''.join(body)}</code></pre>\n")
return i
def bullet_list(lines, i, out):
items = []
loose = False
while i < len(lines):
m = ITEM.match(lines[i])
if m is None:
break
items.append(inlines(m.group(1).strip(" \t")))
i += 1
j = i
while j < len(lines) and lines[j].strip(" \t") == "":
j += 1
if j > i and j < len(lines) and ITEM.match(lines[j]):
loose = True
i = j
out.append("<ul>\n")
for item in items:
out.append(f"<li>\n<p>{item}</p>\n</li>\n" if loose else f"<li>{item}</li>\n")
out.append("</ul>\n")
return i
def paragraph(lines, i, out):
start = i
i += 1
while i < len(lines) and not starts_block(lines[i]):
i += 1
text = "\n".join(lines[start:i]).rstrip(" \t")
out.append(f"<p>{inlines(text)}</p>\n")
return i
def is_space(c):
return c in "\t\n\f\r" or unicodedata.category(c) == "Zs"
def is_punct(c):
return unicodedata.category(c)[0] in "PS"
def inlines(text):
nodes = []
delims = []
buf = []
def flush():
if buf:
nodes.append("".join(buf))
buf.clear()
i = 0
while i < len(text):
c = text[i]
if c == "\\" and i + 1 < len(text) and text[i + 1] in PUNCTUATION:
buf.append(escape(text[i + 1]))
i += 2
elif c == "\\" and i + 1 < len(text) and text[i + 1] == "\n":
buf.append("<br />\n")
i += 2
elif c == "\n":
line = "".join(buf)
stripped = line.rstrip(" ")
buf[:] = [stripped, "<br />\n" if len(line) - len(stripped) >= 2 else "\n"]
i += 1
elif c == "`":
j = i
while j < len(text) and text[j] == "`":
j += 1
run = text[i:j]
close = re.compile(r"(?<!`)" + run + r"(?!`)").search(text, j)
if close is None:
buf.append(run)
i = j
else:
code = text[j:close.start()].replace("\n", " ")
if len(code) >= 2 and code[0] == " " and code[-1] == " " and code.strip(" "):
code = code[1:-1]
buf.append(f"<code>{escape(code)}</code>")
i = close.end()
elif c == "[":
end = link_end(text, i)
if end is None:
buf.append("[")
i += 1
else:
close, url_end = end
label = inlines(text[i + 1:close])
url = escape(text[close + 2:url_end])
buf.append(f'<a href="{url}">{label}</a>')
i = url_end + 1
elif c == "*":
j = i
while j < len(text) and text[j] == "*":
j += 1
before = text[i - 1] if i > 0 else "\n"
after = text[j] if j < len(text) else "\n"
left = not is_space(after) and (
not is_punct(after) or is_space(before) or is_punct(before))
right = not is_space(before) and (
not is_punct(before) or is_space(after) or is_punct(after))
flush()
delims.append({"node": len(nodes), "count": j - i, "length": j - i,
"open": left, "close": right, "active": True,
"opens": [], "closes": []})
nodes.append(None)
i = j
else:
buf.append(escape(c))
i += 1
flush()
emphasis(delims)
for d in delims:
nodes[d["node"]] = ("".join(d["closes"]) + "*" * d["count"]
+ "".join(reversed(d["opens"])))
return "".join(nodes)
def link_end(text, i):
close = text.find("]", i + 1)
if close < 0 or "[" in text[i + 1:close] or not text.startswith("(", close + 1):
return None
m = URL.match(text, close + 2)
if m is None or not text.startswith(")", m.end()):
return None
return close, m.end()
def emphasis(delims):
k = 0
while k < len(delims):
closer = delims[k]
if not closer["active"] or not closer["close"]:
k += 1
continue
opener = None
for j in range(k - 1, -1, -1):
d = delims[j]
if not d["active"] or not d["open"]:
continue
if (d["close"] or closer["open"]) and (d["length"] + closer["length"]) % 3 == 0 \
and not (d["length"] % 3 == 0 and closer["length"] % 3 == 0):
continue
opener = (j, d)
break
if opener is None:
if not closer["open"]:
closer["active"] = False
k += 1
continue
j, d = opener
use = 2 if d["count"] >= 2 and closer["count"] >= 2 else 1
tag = "strong" if use == 2 else "em"
d["count"] -= use
closer["count"] -= use
d["opens"].append(f"<{tag}>")
closer["closes"].append(f"</{tag}>")
for m in range(j + 1, k):
delims[m]["active"] = False
if d["count"] == 0:
d["active"] = False
if closer["count"] == 0:
closer["active"] = False
k += 1
test_markdown_to_html.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-a-markdown-text/.
import json
import pathlib
import pytest
from markdown_to_html import markdown_to_html
CASES = pathlib.Path(__file__).resolve().parents[2] / "cases"
def load(name):
with open(CASES / name, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
@pytest.mark.parametrize("case", load("basic.jsonl") + load("edge.jsonl"), ids=lambda c: c["name"])
def test_cases(case):
assert markdown_to_html(case["args"]["text"]) == case["expect"]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
// Converts a text in a subset of CommonMark to HTML.
public static class MarkdownToHtml
{
private static readonly Regex Heading = new(@"^(#{1,6})(?:[ \t]+(.*?))?[ \t]*$");
private static readonly Regex Closing = new(@"(?:^|[ \t]+)#+[ \t]*$");
private static readonly Regex Fence = new(@"^(`{3,})[ \t]*([^`]*?)[ \t]*$");
private static readonly Regex Item = new(@"^- (.*)$");
private static readonly Regex Url = new(@"^[A-Za-z0-9\-._~:/?#=&+%]+");
private const string Punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
private static string Escape(string text) =>
text.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """);
private static bool IsBlank(string line) => line.Trim(' ', '\t').Length == 0;
private static bool StartsBlock(string line) =>
IsBlank(line) || Fence.IsMatch(line) || Heading.IsMatch(line) || Item.IsMatch(line);
public static string Convert(string text)
{
string[] lines = text.Length == 0 ? [] : (text.EndsWith('\n') ? text[..^1] : text).Split('\n');
var output = new StringBuilder();
int i = 0;
while (i < lines.Length)
{
string line = lines[i];
Match m;
if (IsBlank(line))
{
i++;
}
else if (Fence.IsMatch(line))
{
i = CodeBlock(lines, i, output);
}
else if ((m = Heading.Match(line)).Success)
{
int level = m.Groups[1].Length;
string content = Closing.Replace(m.Groups[2].Value, "");
output.Append($"<h{level}>{Inlines(content)}</h{level}>\n");
i++;
}
else if (Item.IsMatch(line))
{
i = BulletList(lines, i, output);
}
else
{
i = Paragraph(lines, i, output);
}
}
return output.ToString();
}
private static int CodeBlock(string[] lines, int i, StringBuilder output)
{
Match m = Fence.Match(lines[i]);
string fence = m.Groups[1].Value;
string[] info = m.Groups[2].Value.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
string attr = info.Length > 0 ? $" class=\"language-{Escape(info[0])}\"" : "";
output.Append($"<pre><code{attr}>");
for (i++; i < lines.Length; i++)
{
string close = lines[i].TrimEnd(' ', '\t');
if (close.StartsWith(fence, StringComparison.Ordinal) && close.Trim('`').Length == 0)
{
i++;
break;
}
output.Append(Escape(lines[i])).Append('\n');
}
output.Append("</code></pre>\n");
return i;
}
private static int BulletList(string[] lines, int i, StringBuilder output)
{
var items = new List<string>();
bool loose = false;
while (i < lines.Length)
{
Match m = Item.Match(lines[i]);
if (!m.Success)
{
break;
}
items.Add(Inlines(m.Groups[1].Value.Trim(' ', '\t')));
i++;
int j = i;
while (j < lines.Length && IsBlank(lines[j]))
{
j++;
}
if (j > i && j < lines.Length && Item.IsMatch(lines[j]))
{
loose = true;
i = j;
}
}
output.Append("<ul>\n");
foreach (string item in items)
{
output.Append(loose ? $"<li>\n<p>{item}</p>\n</li>\n" : $"<li>{item}</li>\n");
}
output.Append("</ul>\n");
return i;
}
private static int Paragraph(string[] lines, int i, StringBuilder output)
{
int start = i;
for (i++; i < lines.Length && !StartsBlock(lines[i]); i++)
{
}
string text = string.Join("\n", lines[start..i]).TrimEnd(' ', '\t');
output.Append($"<p>{Inlines(text)}</p>\n");
return i;
}
private static bool IsSpace(Rune r) =>
r.Value is '\t' or '\n' or '\f' or '\r' || Rune.GetUnicodeCategory(r) == UnicodeCategory.SpaceSeparator;
private static bool IsPunct(Rune r) => Rune.IsPunctuation(r) || Rune.IsSymbol(r);
private sealed class Delimiter
{
public int Node, Count, Length;
public bool Open, Close, Active = true;
public List<string> Opens = [], Closes = [];
}
private static string Join(List<Rune> cs, int start, int end)
{
var sb = new StringBuilder();
for (int k = start; k < end; k++)
{
sb.Append(cs[k].ToString());
}
return sb.ToString();
}
// cs is a list of runes, so that a character outside the BMP is one element.
private static string Inlines(string text)
{
var cs = text.EnumerateRunes().ToList();
var nodes = new List<string>();
var delims = new List<Delimiter>();
var buf = new StringBuilder();
void Flush()
{
if (buf.Length > 0)
{
nodes.Add(buf.ToString());
buf.Clear();
}
}
int i = 0;
while (i < cs.Count)
{
int c = cs[i].Value;
if (c == '\\' && i + 1 < cs.Count && cs[i + 1].Value < 128 && Punctuation.Contains((char)cs[i + 1].Value))
{
buf.Append(Escape(cs[i + 1].ToString()));
i += 2;
}
else if (c == '\\' && i + 1 < cs.Count && cs[i + 1].Value == '\n')
{
buf.Append("<br />\n");
i += 2;
}
else if (c == '\n')
{
string line = buf.ToString();
string stripped = line.TrimEnd(' ');
buf.Clear().Append(stripped).Append(line.Length - stripped.Length >= 2 ? "<br />\n" : "\n");
i++;
}
else if (c == '`')
{
int j = i;
while (j < cs.Count && cs[j].Value == '`')
{
j++;
}
int close = ClosingRun(cs, j, j - i);
if (close < 0)
{
buf.Append('`', j - i);
i = j;
continue;
}
string code = Join(cs, j, close).Replace('\n', ' ');
if (code.Length >= 2 && code[0] == ' ' && code[^1] == ' ' && code.Trim(' ').Length > 0)
{
code = code[1..^1];
}
buf.Append($"<code>{Escape(code)}</code>");
i = close + (j - i);
}
else if (c == '[')
{
if (!LinkEnd(cs, i, out int close, out int urlEnd))
{
buf.Append('[');
i++;
continue;
}
string label = Inlines(Join(cs, i + 1, close));
buf.Append($"<a href=\"{Escape(Join(cs, close + 2, urlEnd))}\">{label}</a>");
i = urlEnd + 1;
}
else if (c == '*')
{
int j = i;
while (j < cs.Count && cs[j].Value == '*')
{
j++;
}
Rune before = i > 0 ? cs[i - 1] : new Rune('\n');
Rune after = j < cs.Count ? cs[j] : new Rune('\n');
bool left = !IsSpace(after) && (!IsPunct(after) || IsSpace(before) || IsPunct(before));
bool right = !IsSpace(before) && (!IsPunct(before) || IsSpace(after) || IsPunct(after));
Flush();
delims.Add(new Delimiter { Node = nodes.Count, Count = j - i, Length = j - i, Open = left, Close = right });
nodes.Add("");
i = j;
}
else
{
buf.Append(Escape(cs[i].ToString()));
i++;
}
}
Flush();
Emphasis(delims);
foreach (Delimiter d in delims)
{
var opens = new List<string>(d.Opens);
opens.Reverse();
nodes[d.Node] = string.Concat(d.Closes) + new string('*', d.Count) + string.Concat(opens);
}
return string.Concat(nodes);
}
// ClosingRun returns the index of the next run of exactly n backticks at or after j, or -1.
private static int ClosingRun(List<Rune> cs, int j, int n)
{
while (j < cs.Count)
{
if (cs[j].Value != '`')
{
j++;
continue;
}
int k = j;
while (k < cs.Count && cs[k].Value == '`')
{
k++;
}
if (k - j == n)
{
return j;
}
j = k;
}
return -1;
}
private static bool LinkEnd(List<Rune> cs, int i, out int close, out int urlEnd)
{
close = -1;
urlEnd = -1;
for (int k = i + 1; k < cs.Count; k++)
{
if (cs[k].Value == '[')
{
return false;
}
if (cs[k].Value == ']')
{
close = k;
break;
}
}
if (close < 0 || close + 1 >= cs.Count || cs[close + 1].Value != '(')
{
return false;
}
Match m = Url.Match(Join(cs, close + 2, cs.Count));
if (!m.Success)
{
return false;
}
urlEnd = close + 2 + m.Length;
return urlEnd < cs.Count && cs[urlEnd].Value == ')';
}
private static void Emphasis(List<Delimiter> delims)
{
int k = 0;
while (k < delims.Count)
{
Delimiter closer = delims[k];
if (!closer.Active || !closer.Close)
{
k++;
continue;
}
int j = k - 1;
for (; j >= 0; j--)
{
Delimiter o = delims[j];
if (!o.Active || !o.Open)
{
continue;
}
if ((o.Close || closer.Open) && (o.Length + closer.Length) % 3 == 0
&& !(o.Length % 3 == 0 && closer.Length % 3 == 0))
{
continue;
}
break;
}
if (j < 0)
{
if (!closer.Open)
{
closer.Active = false;
}
k++;
continue;
}
Delimiter d = delims[j];
int use = d.Count >= 2 && closer.Count >= 2 ? 2 : 1;
string tag = use == 2 ? "strong" : "em";
d.Count -= use;
closer.Count -= use;
d.Opens.Add($"<{tag}>");
closer.Closes.Add($"</{tag}>");
for (int m = j + 1; m < k; m++)
{
delims[m].Active = false;
}
if (d.Count == 0)
{
d.Active = false;
}
if (closer.Count == 0)
{
closer.Active = false;
k++;
}
}
}
}
MarkdownToHtmlTests.cs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
using System.Runtime.CompilerServices;
using System.Text.Json;
using Xunit;
public sealed class MarkdownToHtmlTests
{
private static string CasesDir([CallerFilePath] string file = "") =>
Path.Combine(Path.GetDirectoryName(file)!, "..", "..", "cases");
private static IEnumerable<JsonElement> Load(string name) =>
File.ReadLines(Path.Combine(CasesDir(), name))
.Where(line => line.Trim().Length > 0)
.Select(line => JsonDocument.Parse(line).RootElement);
public static TheoryData<string, string, string> Cases()
{
var data = new TheoryData<string, string, string>();
foreach (JsonElement c in Load("basic.jsonl").Concat(Load("edge.jsonl")))
{
data.Add(c.GetProperty("name").GetString()!, c.GetProperty("args").GetProperty("text").GetString()!,
c.GetProperty("expect").GetString()!);
}
return data;
}
[Theory]
[MemberData(nameof(Cases))]
public void Converts(string name, string text, string expect)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(expect, MarkdownToHtml.Convert(text));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
// Convert a text in a subset of CommonMark to HTML.
const HEADING = /^(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
const CLOSING = /(?:^|[ \t]+)#+[ \t]*$/;
const FENCE = /^(`{3,})[ \t]*([^`]*?)[ \t]*$/;
const ITEM = /^- (.*)$/;
const URL = /^[A-Za-z0-9\-._~:/?#=&+%]+/;
const PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
const escape = (text) =>
text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
const isBlank = (line) => line.replace(/[ \t]/g, "") === "";
export function markdownToHtml(text) {
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
let m;
if (isBlank(line)) {
i += 1;
} else if (FENCE.test(line)) {
i = codeBlock(lines, i, out);
} else if ((m = HEADING.exec(line))) {
const level = m[1].length;
const content = (m[2] ?? "").replace(CLOSING, "");
out.push(`<h${level}>${inlines(content)}</h${level}>\n`);
i += 1;
} else if (ITEM.test(line)) {
i = bulletList(lines, i, out);
} else {
i = paragraph(lines, i, out);
}
}
return out.join("");
}
const startsBlock = (line) => isBlank(line) || FENCE.test(line) || HEADING.test(line) || ITEM.test(line);
function codeBlock(lines, i, out) {
const m = FENCE.exec(lines[i]);
const fence = m[1];
const info = m[2].split(/[ \t]+/).filter((w) => w !== "");
const attr = info.length > 0 ? ` class="language-${escape(info[0])}"` : "";
const body = [];
i += 1;
while (i < lines.length) {
const close = lines[i].replace(/[ \t]+$/, "");
if (close.startsWith(fence) && close.replaceAll("`", "") === "") {
i += 1;
break;
}
body.push(escape(lines[i]) + "\n");
i += 1;
}
out.push(`<pre><code${attr}>${body.join("")}</code></pre>\n`);
return i;
}
function bulletList(lines, i, out) {
const items = [];
let loose = false;
while (i < lines.length) {
const m = ITEM.exec(lines[i]);
if (m === null) break;
items.push(inlines(m[1].replace(/^[ \t]+|[ \t]+$/g, "")));
i += 1;
let j = i;
while (j < lines.length && isBlank(lines[j])) j += 1;
if (j > i && j < lines.length && ITEM.test(lines[j])) {
loose = true;
i = j;
}
}
out.push("<ul>\n");
for (const item of items) {
out.push(loose ? `<li>\n<p>${item}</p>\n</li>\n` : `<li>${item}</li>\n`);
}
out.push("</ul>\n");
return i;
}
function paragraph(lines, i, out) {
const start = i;
i += 1;
while (i < lines.length && !startsBlock(lines[i])) i += 1;
const text = lines.slice(start, i).join("\n").replace(/[ \t]+$/, "");
out.push(`<p>${inlines(text)}</p>\n`);
return i;
}
const isSpace = (c) => /^[\t\n\f\r\p{Zs}]$/u.test(c);
const isPunct = (c) => /^[\p{P}\p{S}]$/u.test(c);
// cs is an array of code points, so that a character outside the BMP is one element.
function inlines(text) {
const cs = Array.from(text);
const nodes = [];
const delims = [];
let buf = [];
const flush = () => {
if (buf.length > 0) {
nodes.push(buf.join(""));
buf = [];
}
};
let i = 0;
while (i < cs.length) {
const c = cs[i];
if (c === "\\" && i + 1 < cs.length && PUNCTUATION.includes(cs[i + 1])) {
buf.push(escape(cs[i + 1]));
i += 2;
} else if (c === "\\" && cs[i + 1] === "\n") {
buf.push("<br />\n");
i += 2;
} else if (c === "\n") {
const line = buf.join("");
const stripped = line.replace(/ +$/, "");
buf = [stripped, line.length - stripped.length >= 2 ? "<br />\n" : "\n"];
i += 1;
} else if (c === "`") {
let j = i;
while (j < cs.length && cs[j] === "`") j += 1;
const close = closingRun(cs, j, j - i);
if (close < 0) {
buf.push("`".repeat(j - i));
i = j;
} else {
let code = cs.slice(j, close).join("").replaceAll("\n", " ");
if (code.length >= 2 && code.startsWith(" ") && code.endsWith(" ") && code.trim() !== "") {
code = code.slice(1, -1);
}
buf.push(`<code>${escape(code)}</code>`);
i = close + (j - i);
}
} else if (c === "[") {
const end = linkEnd(cs, i);
if (end === null) {
buf.push("[");
i += 1;
} else {
const [close, urlEnd] = end;
const label = inlines(cs.slice(i + 1, close).join(""));
const url = escape(cs.slice(close + 2, urlEnd).join(""));
buf.push(`<a href="${url}">${label}</a>`);
i = urlEnd + 1;
}
} else if (c === "*") {
let j = i;
while (j < cs.length && cs[j] === "*") j += 1;
const before = i > 0 ? cs[i - 1] : "\n";
const after = j < cs.length ? cs[j] : "\n";
const left = !isSpace(after) && (!isPunct(after) || isSpace(before) || isPunct(before));
const right = !isSpace(before) && (!isPunct(before) || isSpace(after) || isPunct(after));
flush();
delims.push({ node: nodes.length, count: j - i, length: j - i, open: left, close: right, active: true, opens: [], closes: [] });
nodes.push(null);
i = j;
} else {
buf.push(escape(c));
i += 1;
}
}
flush();
emphasis(delims);
for (const d of delims) {
nodes[d.node] = d.closes.join("") + "*".repeat(d.count) + d.opens.toReversed().join("");
}
return nodes.join("");
}
// closingRun returns the index of the next run of exactly n backticks at or after j, or -1.
function closingRun(cs, j, n) {
while (j < cs.length) {
if (cs[j] !== "`") {
j += 1;
continue;
}
let k = j;
while (k < cs.length && cs[k] === "`") k += 1;
if (k - j === n) return j;
j = k;
}
return -1;
}
function linkEnd(cs, i) {
const close = cs.indexOf("]", i + 1);
if (close < 0 || cs.slice(i + 1, close).includes("[") || cs[close + 1] !== "(") return null;
const m = URL.exec(cs.slice(close + 2).join(""));
if (m === null) return null;
const urlEnd = close + 2 + Array.from(m[0]).length;
return cs[urlEnd] === ")" ? [close, urlEnd] : null;
}
function emphasis(delims) {
let k = 0;
while (k < delims.length) {
const closer = delims[k];
if (!closer.active || !closer.close) {
k += 1;
continue;
}
let j = k - 1;
for (; j >= 0; j -= 1) {
const d = delims[j];
if (!d.active || !d.open) continue;
if ((d.close || closer.open) && (d.length + closer.length) % 3 === 0 && !(d.length % 3 === 0 && closer.length % 3 === 0)) continue;
break;
}
if (j < 0) {
if (!closer.open) closer.active = false;
k += 1;
continue;
}
const d = delims[j];
const use = d.count >= 2 && closer.count >= 2 ? 2 : 1;
const tag = use === 2 ? "strong" : "em";
d.count -= use;
closer.count -= use;
d.opens.push(`<${tag}>`);
closer.closes.push(`</${tag}>`);
for (let m = j + 1; m < k; m += 1) delims[m].active = false;
if (d.count === 0) d.active = false;
if (closer.count === 0) {
closer.active = false;
k += 1;
}
}
}
markdownToHtml.test.js 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { markdownToHtml } from "./markdownToHtml.js";
const load = (name) =>
readFileSync(new URL(`../../cases/${name}`, import.meta.url), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(markdownToHtml(c.args.text), c.expect);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
// Convert a text in a subset of CommonMark to HTML.
const HEADING = /^(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
const CLOSING = /(?:^|[ \t]+)#+[ \t]*$/;
const FENCE = /^(`{3,})[ \t]*([^`]*?)[ \t]*$/;
const ITEM = /^- (.*)$/;
const URL = /^[A-Za-z0-9\-._~:/?#=&+%]+/;
const PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
const escape = (text: string): string =>
text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
const isBlank = (line: string): boolean => line.replace(/[ \t]/g, "") === "";
export function markdownToHtml(text: string): string {
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
const out: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
let m: RegExpExecArray | null;
if (isBlank(line)) {
i += 1;
} else if (FENCE.test(line)) {
i = codeBlock(lines, i, out);
} else if ((m = HEADING.exec(line))) {
const level = m[1].length;
const content = (m[2] ?? "").replace(CLOSING, "");
out.push(`<h${level}>${inlines(content)}</h${level}>\n`);
i += 1;
} else if (ITEM.test(line)) {
i = bulletList(lines, i, out);
} else {
i = paragraph(lines, i, out);
}
}
return out.join("");
}
const startsBlock = (line: string): boolean => isBlank(line) || FENCE.test(line) || HEADING.test(line) || ITEM.test(line);
function codeBlock(lines: string[], i: number, out: string[]): number {
const m = FENCE.exec(lines[i])!;
const fence = m[1];
const info = m[2].split(/[ \t]+/).filter((w) => w !== "");
const attr = info.length > 0 ? ` class="language-${escape(info[0])}"` : "";
const body: string[] = [];
i += 1;
while (i < lines.length) {
const close = lines[i].replace(/[ \t]+$/, "");
if (close.startsWith(fence) && close.replaceAll("`", "") === "") {
i += 1;
break;
}
body.push(escape(lines[i]) + "\n");
i += 1;
}
out.push(`<pre><code${attr}>${body.join("")}</code></pre>\n`);
return i;
}
function bulletList(lines: string[], i: number, out: string[]): number {
const items: string[] = [];
let loose = false;
while (i < lines.length) {
const m = ITEM.exec(lines[i]);
if (m === null) break;
items.push(inlines(m[1].replace(/^[ \t]+|[ \t]+$/g, "")));
i += 1;
let j = i;
while (j < lines.length && isBlank(lines[j])) j += 1;
if (j > i && j < lines.length && ITEM.test(lines[j])) {
loose = true;
i = j;
}
}
out.push("<ul>\n");
for (const item of items) {
out.push(loose ? `<li>\n<p>${item}</p>\n</li>\n` : `<li>${item}</li>\n`);
}
out.push("</ul>\n");
return i;
}
function paragraph(lines: string[], i: number, out: string[]): number {
const start = i;
i += 1;
while (i < lines.length && !startsBlock(lines[i])) i += 1;
const text = lines.slice(start, i).join("\n").replace(/[ \t]+$/, "");
out.push(`<p>${inlines(text)}</p>\n`);
return i;
}
const isSpace = (c: string): boolean => /^[\t\n\f\r\p{Zs}]$/u.test(c);
const isPunct = (c: string): boolean => /^[\p{P}\p{S}]$/u.test(c);
// cs is an array of code points, so that a character outside the BMP is one element.
interface Delimiter {
node: number;
count: number;
length: number;
open: boolean;
close: boolean;
active: boolean;
opens: string[];
closes: string[];
}
function inlines(text: string): string {
const cs = Array.from(text);
const nodes: (string | null)[] = [];
const delims: Delimiter[] = [];
let buf: string[] = [];
const flush = () => {
if (buf.length > 0) {
nodes.push(buf.join(""));
buf = [];
}
};
let i = 0;
while (i < cs.length) {
const c = cs[i];
if (c === "\\" && i + 1 < cs.length && PUNCTUATION.includes(cs[i + 1])) {
buf.push(escape(cs[i + 1]));
i += 2;
} else if (c === "\\" && cs[i + 1] === "\n") {
buf.push("<br />\n");
i += 2;
} else if (c === "\n") {
const line = buf.join("");
const stripped = line.replace(/ +$/, "");
buf = [stripped, line.length - stripped.length >= 2 ? "<br />\n" : "\n"];
i += 1;
} else if (c === "`") {
let j = i;
while (j < cs.length && cs[j] === "`") j += 1;
const close = closingRun(cs, j, j - i);
if (close < 0) {
buf.push("`".repeat(j - i));
i = j;
} else {
let code = cs.slice(j, close).join("").replaceAll("\n", " ");
if (code.length >= 2 && code.startsWith(" ") && code.endsWith(" ") && code.trim() !== "") {
code = code.slice(1, -1);
}
buf.push(`<code>${escape(code)}</code>`);
i = close + (j - i);
}
} else if (c === "[") {
const end = linkEnd(cs, i);
if (end === null) {
buf.push("[");
i += 1;
} else {
const [close, urlEnd] = end;
const label = inlines(cs.slice(i + 1, close).join(""));
const url = escape(cs.slice(close + 2, urlEnd).join(""));
buf.push(`<a href="${url}">${label}</a>`);
i = urlEnd + 1;
}
} else if (c === "*") {
let j = i;
while (j < cs.length && cs[j] === "*") j += 1;
const before = i > 0 ? cs[i - 1] : "\n";
const after = j < cs.length ? cs[j] : "\n";
const left = !isSpace(after) && (!isPunct(after) || isSpace(before) || isPunct(before));
const right = !isSpace(before) && (!isPunct(before) || isSpace(after) || isPunct(after));
flush();
delims.push({ node: nodes.length, count: j - i, length: j - i, open: left, close: right, active: true, opens: [], closes: [] });
nodes.push(null);
i = j;
} else {
buf.push(escape(c));
i += 1;
}
}
flush();
emphasis(delims);
for (const d of delims) {
nodes[d.node] = d.closes.join("") + "*".repeat(d.count) + d.opens.toReversed().join("");
}
return nodes.join("");
}
// closingRun returns the index of the next run of exactly n backticks at or after j, or -1.
function closingRun(cs: string[], j: number, n: number): number {
while (j < cs.length) {
if (cs[j] !== "`") {
j += 1;
continue;
}
let k = j;
while (k < cs.length && cs[k] === "`") k += 1;
if (k - j === n) return j;
j = k;
}
return -1;
}
function linkEnd(cs: string[], i: number): [number, number] | null {
const close = cs.indexOf("]", i + 1);
if (close < 0 || cs.slice(i + 1, close).includes("[") || cs[close + 1] !== "(") return null;
const m = URL.exec(cs.slice(close + 2).join(""));
if (m === null) return null;
const urlEnd = close + 2 + Array.from(m[0]).length;
return cs[urlEnd] === ")" ? [close, urlEnd] : null;
}
function emphasis(delims: Delimiter[]): void {
let k = 0;
while (k < delims.length) {
const closer = delims[k];
if (!closer.active || !closer.close) {
k += 1;
continue;
}
let j = k - 1;
for (; j >= 0; j -= 1) {
const d = delims[j];
if (!d.active || !d.open) continue;
if ((d.close || closer.open) && (d.length + closer.length) % 3 === 0 && !(d.length % 3 === 0 && closer.length % 3 === 0)) continue;
break;
}
if (j < 0) {
if (!closer.open) closer.active = false;
k += 1;
continue;
}
const d = delims[j];
const use = d.count >= 2 && closer.count >= 2 ? 2 : 1;
const tag = use === 2 ? "strong" : "em";
d.count -= use;
closer.count -= use;
d.opens.push(`<${tag}>`);
closer.closes.push(`</${tag}>`);
for (let m = j + 1; m < k; m += 1) delims[m].active = false;
if (d.count === 0) d.active = false;
if (closer.count === 0) {
closer.active = false;
k += 1;
}
}
}
markdownToHtml.test.ts 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { markdownToHtml } from "./markdownToHtml.ts";
const load = (name) =>
readFileSync(new URL(`../../cases/${name}`, import.meta.url), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(markdownToHtml(c.args.text), c.expect);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
// Package markdowntohtml converts a text in a subset of CommonMark to HTML.
package markdowntohtml
import (
"regexp"
"strings"
"unicode"
)
var (
heading = regexp.MustCompile(`^(#{1,6})(?:[ \t]+(.*?))?[ \t]*$`)
closing = regexp.MustCompile(`(?:^|[ \t]+)#+[ \t]*$`)
fence = regexp.MustCompile("^(`{3,})[ \t]*([^`]*?)[ \t]*$")
item = regexp.MustCompile(`^- (.*)$`)
url = regexp.MustCompile(`^[A-Za-z0-9\-._~:/?#=&+%]+`)
)
const punctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
var escaper = strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """)
func escape(text string) string { return escaper.Replace(text) }
func isBlank(line string) bool { return strings.Trim(line, " \t") == "" }
func startsBlock(line string) bool {
return isBlank(line) || fence.MatchString(line) || heading.MatchString(line) || item.MatchString(line)
}
// MarkdownToHTML returns the HTML for text.
func MarkdownToHTML(text string) string {
var lines []string
if text != "" {
lines = strings.Split(strings.TrimSuffix(text, "\n"), "\n")
}
var out strings.Builder
for i := 0; i < len(lines); {
line := lines[i]
switch {
case isBlank(line):
i++
case fence.MatchString(line):
i = codeBlock(lines, i, &out)
case heading.MatchString(line):
m := heading.FindStringSubmatch(line)
level := string(rune('0' + len(m[1])))
content := closing.ReplaceAllString(m[2], "")
out.WriteString("<h" + level + ">" + inlines(content) + "</h" + level + ">\n")
i++
case item.MatchString(line):
i = bulletList(lines, i, &out)
default:
i = paragraph(lines, i, &out)
}
}
return out.String()
}
func codeBlock(lines []string, i int, out *strings.Builder) int {
m := fence.FindStringSubmatch(lines[i])
attr := ""
if info := strings.Fields(m[2]); len(info) > 0 {
attr = ` class="language-` + escape(info[0]) + `"`
}
out.WriteString("<pre><code" + attr + ">")
for i++; i < len(lines); i++ {
end := strings.TrimRight(lines[i], " \t")
if strings.HasPrefix(end, m[1]) && strings.Trim(end, "`") == "" {
i++
break
}
out.WriteString(escape(lines[i]) + "\n")
}
out.WriteString("</code></pre>\n")
return i
}
func bulletList(lines []string, i int, out *strings.Builder) int {
var items []string
loose := false
for i < len(lines) {
m := item.FindStringSubmatch(lines[i])
if m == nil {
break
}
items = append(items, inlines(strings.Trim(m[1], " \t")))
i++
j := i
for j < len(lines) && isBlank(lines[j]) {
j++
}
if j > i && j < len(lines) && item.MatchString(lines[j]) {
loose = true
i = j
}
}
out.WriteString("<ul>\n")
for _, it := range items {
if loose {
out.WriteString("<li>\n<p>" + it + "</p>\n</li>\n")
} else {
out.WriteString("<li>" + it + "</li>\n")
}
}
out.WriteString("</ul>\n")
return i
}
func paragraph(lines []string, i int, out *strings.Builder) int {
start := i
for i++; i < len(lines) && !startsBlock(lines[i]); i++ {
}
text := strings.TrimRight(strings.Join(lines[start:i], "\n"), " \t")
out.WriteString("<p>" + inlines(text) + "</p>\n")
return i
}
func isSpace(r rune) bool {
return r == '\t' || r == '\n' || r == '\f' || r == '\r' || unicode.Is(unicode.Zs, r)
}
func isPunct(r rune) bool { return unicode.IsPunct(r) || unicode.IsSymbol(r) }
type delimiter struct {
node, count, length int
open, close, active bool
opens, closes []string
}
// inlines works on runes, so that a character outside the BMP is one element.
func inlines(text string) string {
cs := []rune(text)
var nodes []string
var delims []*delimiter
var buf strings.Builder
flush := func() {
if buf.Len() > 0 {
nodes = append(nodes, buf.String())
buf.Reset()
}
}
for i := 0; i < len(cs); {
c := cs[i]
switch {
case c == '\\' && i+1 < len(cs) && strings.ContainsRune(punctuation, cs[i+1]):
buf.WriteString(escape(string(cs[i+1])))
i += 2
case c == '\\' && i+1 < len(cs) && cs[i+1] == '\n':
buf.WriteString("<br />\n")
i += 2
case c == '\n':
line := buf.String()
stripped := strings.TrimRight(line, " ")
buf.Reset()
buf.WriteString(stripped)
if len(line)-len(stripped) >= 2 {
buf.WriteString("<br />\n")
} else {
buf.WriteString("\n")
}
i++
case c == '`':
j := i
for j < len(cs) && cs[j] == '`' {
j++
}
end := closingRun(cs, j, j-i)
if end < 0 {
buf.WriteString(strings.Repeat("`", j-i))
i = j
break
}
code := strings.ReplaceAll(string(cs[j:end]), "\n", " ")
if len(code) >= 2 && code[0] == ' ' && code[len(code)-1] == ' ' && strings.Trim(code, " ") != "" {
code = code[1 : len(code)-1]
}
buf.WriteString("<code>" + escape(code) + "</code>")
i = end + (j - i)
case c == '[':
end, urlEnd, ok := linkEnd(cs, i)
if !ok {
buf.WriteString("[")
i++
break
}
label := inlines(string(cs[i+1 : end]))
buf.WriteString(`<a href="` + escape(string(cs[end+2:urlEnd])) + `">` + label + "</a>")
i = urlEnd + 1
case c == '*':
j := i
for j < len(cs) && cs[j] == '*' {
j++
}
before, after := '\n', '\n'
if i > 0 {
before = cs[i-1]
}
if j < len(cs) {
after = cs[j]
}
left := !isSpace(after) && (!isPunct(after) || isSpace(before) || isPunct(before))
right := !isSpace(before) && (!isPunct(before) || isSpace(after) || isPunct(after))
flush()
delims = append(delims, &delimiter{node: len(nodes), count: j - i, length: j - i, open: left, close: right, active: true})
nodes = append(nodes, "")
i = j
default:
buf.WriteString(escape(string(c)))
i++
}
}
flush()
emphasis(delims)
for _, d := range delims {
s := strings.Join(d.closes, "") + strings.Repeat("*", d.count)
for k := len(d.opens) - 1; k >= 0; k-- {
s += d.opens[k]
}
nodes[d.node] = s
}
return strings.Join(nodes, "")
}
// closingRun returns the index of the next run of exactly n backticks at or after j, or -1.
func closingRun(cs []rune, j, n int) int {
for j < len(cs) {
if cs[j] != '`' {
j++
continue
}
k := j
for k < len(cs) && cs[k] == '`' {
k++
}
if k-j == n {
return j
}
j = k
}
return -1
}
func linkEnd(cs []rune, i int) (end, urlEnd int, ok bool) {
end = -1
for k := i + 1; k < len(cs); k++ {
if cs[k] == ']' {
end = k
break
}
if cs[k] == '[' {
return 0, 0, false
}
}
if end < 0 || end+1 >= len(cs) || cs[end+1] != '(' {
return 0, 0, false
}
m := url.FindString(string(cs[end+2:]))
if m == "" {
return 0, 0, false
}
urlEnd = end + 2 + len([]rune(m))
if urlEnd >= len(cs) || cs[urlEnd] != ')' {
return 0, 0, false
}
return end, urlEnd, true
}
func emphasis(delims []*delimiter) {
for k := 0; k < len(delims); {
closer := delims[k]
if !closer.active || !closer.close {
k++
continue
}
j := k - 1
for ; j >= 0; j-- {
d := delims[j]
if !d.active || !d.open {
continue
}
if (d.close || closer.open) && (d.length+closer.length)%3 == 0 && !(d.length%3 == 0 && closer.length%3 == 0) {
continue
}
break
}
if j < 0 {
if !closer.open {
closer.active = false
}
k++
continue
}
d := delims[j]
use, tag := 1, "em"
if d.count >= 2 && closer.count >= 2 {
use, tag = 2, "strong"
}
d.count -= use
closer.count -= use
d.opens = append(d.opens, "<"+tag+">")
closer.closes = append(closer.closes, "</"+tag+">")
for m := j + 1; m < k; m++ {
delims[m].active = false
}
if d.count == 0 {
d.active = false
}
if closer.count == 0 {
closer.active = false
k++
}
}
}
markdown_to_html_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-a-markdown-text/.
package markdowntohtml
import (
"bufio"
"encoding/json"
"os"
"path/filepath"
"testing"
)
type testCase struct {
Name string `json:"name"`
Args struct {
Text string `json:"text"`
} `json:"args"`
Expect string `json:"expect"`
}
func load(t *testing.T, name string) []testCase {
t.Helper()
f, err := os.Open(filepath.Join("..", "..", "cases", name))
if err != nil {
t.Fatal(err)
}
defer f.Close()
var cases []testCase
s := bufio.NewScanner(f)
for s.Scan() {
if len(s.Bytes()) == 0 {
continue
}
var c testCase
if err := json.Unmarshal(s.Bytes(), &c); err != nil {
t.Fatal(err)
}
cases = append(cases, c)
}
if err := s.Err(); err != nil {
t.Fatal(err)
}
return cases
}
func TestCases(t *testing.T) {
for _, c := range append(load(t, "basic.jsonl"), load(t, "edge.jsonl")...) {
t.Run(c.Name, func(t *testing.T) {
if got := MarkdownToHTML(c.Args.Text); got != c.Expect {
t.Fatalf("got %q, want %q", got, c.Expect)
}
})
}
}
References
- J. MacFarlane, CommonMark Spec, Version 0.31.2, January 2024, 2.1 Characters and lines; 4.2 ATX headings; 4.5 Fenced code blocks; 5.3 Lists; 6.1 Backslash escapes; 6.1 Code spans; 6.2 Emphasis and strong emphasis; 6.7 Hard line breaks; Appendix A parsing strategy
- The Python Standard Library, unicodedata, unicodedata.category
- MDN Web Docs, Character class escape: \p{...}, \P{...}, Description
- MDN Web Docs, String.prototype[Symbol.iterator](), Return value
- Go standard library, package unicode, IsPunct; IsSymbol; Zs
- .NET API reference, Rune Struct, Remarks (When to use the Rune type); IsPunctuation; IsSymbol
- commonmark.js, the CommonMark reference implementation in JavaScript (README), Usage (the safe option); A note on security
- cmark, the CommonMark reference implementation in C (README), Security
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag J59DAF Edit this page History Report an error Markdown