Markdown to HTML Converter — Python source
Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""markdown-to-html — escape-first CommonMark subset → HTML renderer. Python
port (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
rules run (raw HTML never passes through; security first), via the shared
five-char escaper inlined here (`&` first so the entities we emit are never
re-escaped). Supported blocks: #-headings (1-6), --- /***/ ___ rules, ```
fenced code (markdown inert inside), > blockquotes (recursive), - * +
unordered lists, N. ordered lists (source numbers stripped), paragraphs
(soft line breaks joined with \n). Inline precedence: code spans first
(placeholder-protected), then images, links, bold, italic, strikethrough —
non-greedy pairs. Not supported (by design, documented): raw HTML, tables,
setext headings, nested lists, footnotes, autolinks. Empty or whitespace-only
input is NOT an error — the tool shows nothing. Never raises — errors travel
in the result dict.
"""
import re
_HEADING = re.compile(r"^(#{1,6}) (.*)$")
_HR = re.compile(r"^(---+|\*\*\*+|___+)\s*$")
_UL = re.compile(r"^[-*+] ")
_OL = re.compile(r"^\d+\. ")
_CODE_SPAN = re.compile(r"`([^`]+)`")
_IMAGE = re.compile(r"!\[([^\]]*)\]\(([^)\s]+)\)")
_LINK = re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)")
def _encode_html(text):
"""Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first
so the entities we emit are never re-escaped."""
return (
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("'", "'")
.replace('"', """)
)
def _render_inline(s):
"""Inline pass: code spans first (placeholder-protected), then images,
links, bold, italic, strikethrough — non-greedy pairs."""
codes = []
text = _CODE_SPAN.sub(lambda m: _stash(m.group(1), codes), s)
text = _encode_html(text)
text = _IMAGE.sub(lambda m: f'<img src="{m.group(2)}" alt="{m.group(1)}">', text)
text = _LINK.sub(lambda m: f'<a href="{m.group(2)}">{m.group(1)}</a>', text)
text = re.sub(r"\*\*([^*]+)\*\*", lambda m: f"<strong>{m.group(1)}</strong>", text)
text = re.sub(r"__([^_]+)__", lambda m: f"<strong>{m.group(1)}</strong>", text)
text = re.sub(r"\*([^*]+)\*", lambda m: f"<em>{m.group(1)}</em>", text)
text = re.sub(r"_([^_]+)_", lambda m: f"<em>{m.group(1)}</em>", text)
text = re.sub(r"~~([^~]+)~~", lambda m: f"<del>{m.group(1)}</del>", text)
# lambdas everywhere: captured text must never be read as a template
return re.sub(r"\x00(\d+)\x00", lambda m: codes[int(m.group(1))], text)
def _stash(code, codes):
codes.append(f"<code>{_encode_html(code)}</code>")
return f"\x00{len(codes) - 1}\x00"
def _is_block_start(line):
"""True when a line STARTS a new block — the paragraph terminator. Any new
block type must register here and in the render_block dispatch below."""
return bool(
_HEADING.match(line)
or _HR.match(line)
or line.startswith("```")
or line.startswith("> ")
or _UL.match(line)
or _OL.match(line)
)
def _render_block(lines, out):
"""Render consecutive lines (one blank-line-separated chunk)."""
i = 0
while i < len(lines):
line = lines[i]
heading = _HEADING.match(line)
if heading:
level = len(heading.group(1))
out.append(f"<h{level}>{_render_inline(heading.group(2).strip())}</h{level}>")
i += 1
continue
if _HR.match(line):
out.append("<hr>")
i += 1
continue
if line.startswith("```"):
lang = line[3:].strip()
body = []
i += 1
while i < len(lines) and not lines[i].startswith("```"):
body.append(lines[i])
i += 1
i += 1 # past the closing fence (or past the end of an unclosed fence)
cls = f' class="language-{_encode_html(lang)}"' if lang else ""
out.append(f"<pre><code{cls}>{_encode_html(chr(10).join(body))}</code></pre>")
continue
if line.startswith("> "):
quoted = []
while i < len(lines) and lines[i].startswith("> "):
quoted.append(lines[i][2:])
i += 1
inner = []
_render_block(quoted, inner)
out.append("<blockquote>\n" + "\n".join(inner) + "\n</blockquote>")
continue
if _UL.match(line):
items = []
while i < len(lines) and _UL.match(lines[i]):
items.append(f"<li>{_render_inline(lines[i][2:])}</li>")
i += 1
out.append("<ul>\n" + "\n".join(items) + "\n</ul>")
continue
if _OL.match(line):
items = []
while i < len(lines) and _OL.match(lines[i]):
m = _OL.match(lines[i])
items.append(f"<li>{_render_inline(lines[i][m.end():])}</li>")
i += 1
out.append("<ol>\n" + "\n".join(items) + "\n</ol>")
continue
para = []
while i < len(lines) and not _is_block_start(lines[i]):
para.append(_render_inline(lines[i].strip()))
i += 1
out.append("<p>" + "\n".join(para) + "</p>")
def markdown_to_html(raw):
"""Convert the supported Markdown subset to HTML. Never fails."""
text = re.sub(r"\r\n?", "\n", raw).strip()
if not text: # empty input is NOT an error — the tool shows nothing
return {"output": "", "error": None}
out = []
for block in re.split(r"\n{2,}", text):
_render_block([l for l in block.split("\n") if l.strip() != ""], out)
return {"output": "\n".join(out), "error": None}
# Example:
# markdown_to_html('## Hello *world*')["output"]
# → '<h2>Hello <em>world</em></h2>'
# markdown_to_html('```js\nconst x = 1; // <b>\n```')["output"]
# → '<pre><code class="language-js">const x = 1; // <b></code></pre>'
# markdown_to_html('<script>alert(1)</script>')["output"]
# → '<p><script>alert(1)</script></p>'
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →