Markdown to HTML Converter — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! markdown-to-html — escape-first CommonMark subset → HTML renderer. Rust 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). Rust's stdlib has no regex, so every TS regex became a byte
//! scanner: markers are ASCII and each slice boundary sits on an ASCII char,
//! so multi-byte UTF-8 content passes through untouched and is never split.
//! 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, in TS precedence order; on a failed attempt the engine advances one
//! char (the scanners emit that char and retry — same outcomes). 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 panics on any input.
/// Result union mirror: output + error (None when ok — the renderer never fails).
pub struct MarkdownToHtmlResult {
pub output: String,
pub error: Option<String>,
}
/// JS `\s` (the ASCII set; URLs may not contain any of these).
fn is_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')
}
fn has_prefix(s: &[u8], p: &str) -> bool {
s.starts_with(p.as_bytes())
}
/// Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
/// the entities we emit are never re-escaped.
fn encode_html_bytes(s: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
for &b in s {
match b {
b'&' => out.extend_from_slice(b"&"),
b'<' => out.extend_from_slice(b"<"),
b'>' => out.extend_from_slice(b">"),
b'\'' => out.extend_from_slice(b"'"),
b'"' => out.extend_from_slice(b"""),
b => out.push(b),
}
}
out
}
fn encode_html(text: &str) -> String {
String::from_utf8_lossy(&encode_html_bytes(text.as_bytes())).into_owned()
}
/// Pass 1 of the inline rules: code spans (`([^`]+)`, non-empty content up to
/// the next backtick) become \0<index>\0 placeholders so nothing inside them
/// is ever reprocessed.
fn extract_code_spans(s: &[u8], codes: &mut Vec<String>) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
if s[i] == b'`' {
let mut j = i + 1;
while j < s.len() && s[j] != b'`' {
j += 1;
}
if j < s.len() && j > i + 1 {
// both bounds sit on ASCII chars, so the slice is valid UTF-8
let content = std::str::from_utf8(&s[i + 1..j]).unwrap_or("");
codes.push(format!("<code>{}</code>", encode_html(content)));
out.push(0);
out.extend_from_slice((codes.len() - 1).to_string().as_bytes());
out.push(0);
i = j + 1;
continue;
}
}
out.push(s[i]);
i += 1;
}
out
}
/// `!\[([^\]]*)\]\(([^)\s]+)\)` — alt may be empty and contain anything but
/// `]`; the URL must be non-empty and stop at `)` or whitespace.
fn replace_images(s: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
if s[i] == b'!' && i + 1 < s.len() && s[i + 1] == b'[' {
let mut j = i + 2;
while j < s.len() && s[j] != b']' {
j += 1;
}
if j < s.len() && j + 1 < s.len() && s[j + 1] == b'(' {
let mut k = j + 2;
while k < s.len() && s[k] != b')' && !is_space(s[k]) {
k += 1;
}
if k < s.len() && s[k] == b')' && k > j + 2 {
out.extend_from_slice(b"<img src=\"");
out.extend_from_slice(&s[j + 2..k]);
out.extend_from_slice(b"\" alt=\"");
out.extend_from_slice(&s[i + 2..j]);
out.extend_from_slice(b"\">");
i = k + 1;
continue;
}
}
}
out.push(s[i]); // on failure the engine advances one char — emit it
i += 1;
}
out
}
/// `\[([^\]]+)\]\(([^)\s]+)\)` — link text must be non-empty (images ran
/// first, so `![` is already gone).
fn replace_links(s: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
if s[i] == b'[' {
let mut j = i + 1;
while j < s.len() && s[j] != b']' {
j += 1;
}
if j < s.len() && j > i + 1 && j + 1 < s.len() && s[j + 1] == b'(' {
let mut k = j + 2;
while k < s.len() && s[k] != b')' && !is_space(s[k]) {
k += 1;
}
if k < s.len() && s[k] == b')' && k > j + 2 {
out.extend_from_slice(b"<a href=\"");
out.extend_from_slice(&s[j + 2..k]);
out.extend_from_slice(b"\">");
out.extend_from_slice(&s[i + 1..j]);
out.extend_from_slice(b"</a>");
i = k + 1;
continue;
}
}
}
out.push(s[i]);
i += 1;
}
out
}
/// Emphasis pairs (`**`/`__` strong, `*`/`_` em, `~~` del): the content may
/// not contain the marker char, and the closing marker must follow it
/// immediately (backtracking can never help — the skipped chars are non-markers).
fn replace_pair(s: &[u8], marker: u8, width: usize, open: &str, close: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
let opens = s[i] == marker && (width == 1 || (i + 1 < s.len() && s[i + 1] == marker));
if opens {
let start = i + width;
let mut j = start;
while j < s.len() && s[j] != marker {
j += 1;
}
let closed = j < s.len() && (width == 1 || (j + 1 < s.len() && s[j + 1] == marker));
if closed && j > start {
out.extend_from_slice(open.as_bytes());
out.extend_from_slice(&s[start..j]);
out.extend_from_slice(close.as_bytes());
i = j + width;
continue;
}
}
out.push(s[i]);
i += 1;
}
out
}
/// `\u0000(\d+)\u0000` — placeholders resolve back to their stored spans.
fn restore_code_spans(s: &[u8], codes: &[String]) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
if s[i] == 0 {
let mut j = i + 1;
while j < s.len() && s[j].is_ascii_digit() {
j += 1;
}
if j > i + 1 && j < s.len() && s[j] == 0 {
let n: usize = std::str::from_utf8(&s[i + 1..j])
.ok()
.and_then(|t| t.parse().ok())
.unwrap_or(usize::MAX);
if n < codes.len() {
out.extend_from_slice(codes[n].as_bytes());
}
i = j + 1;
continue;
}
}
out.push(s[i]);
i += 1;
}
out
}
/// Inline pass: code spans first (placeholder-protected), then images, links,
/// bold, italic, strikethrough — non-greedy pairs, in TS precedence order.
fn render_inline(s: &str) -> String {
let mut codes: Vec<String> = Vec::new();
let mut text = extract_code_spans(s.as_bytes(), &mut codes);
text = encode_html_bytes(&text);
text = replace_images(&text);
text = replace_links(&text);
text = replace_pair(&text, b'*', 2, "<strong>", "</strong>");
text = replace_pair(&text, b'_', 2, "<strong>", "</strong>");
text = replace_pair(&text, b'*', 1, "<em>", "</em>");
text = replace_pair(&text, b'_', 1, "<em>", "</em>");
text = replace_pair(&text, b'~', 2, "<del>", "</del>");
String::from_utf8_lossy(&restore_code_spans(&text, &codes)).into_owned()
}
/// `^(#{1,6}) (.*)$` — returns the heading level (1-6) or None.
fn heading_level(line: &str) -> Option<usize> {
let b = line.as_bytes();
let mut n = 0;
while n < b.len() && b[n] == b'#' {
n += 1;
}
if (1..=6).contains(&n) && n < b.len() && b[n] == b' ' {
Some(n)
} else {
None
}
}
/// `^(---+|\*\*\*+|___+)\s*$` — the whole run is one marker char (3+), then
/// only whitespace.
fn is_hr(line: &str) -> bool {
let b = line.as_bytes();
if b.len() < 3 {
return false;
}
let c = b[0];
if c != b'-' && c != b'*' && c != b'_' {
return false;
}
let mut k = 0;
while k < b.len() && b[k] == c {
k += 1;
}
k >= 3 && b[k..].iter().all(|&x| is_space(x))
}
/// `^[-*+] `
fn is_ul(line: &str) -> bool {
let b = line.as_bytes();
b.len() >= 2 && matches!(b[0], b'-' | b'*' | b'+') && b[1] == b' '
}
/// `^\d+\. ` — returns the full prefix length (digits + ". ").
fn ol_prefix_len(line: &str) -> Option<usize> {
let b = line.as_bytes();
let mut n = 0;
while n < b.len() && b[n].is_ascii_digit() {
n += 1;
}
if n >= 1 && n + 1 < b.len() && b[n] == b'.' && b[n + 1] == b' ' {
Some(n + 2)
} else {
None
}
}
/// 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.
fn is_block_start(line: &str) -> bool {
heading_level(line).is_some()
|| is_hr(line)
|| line.starts_with("```")
|| line.starts_with("> ")
|| is_ul(line)
|| ol_prefix_len(line).is_some()
}
/// Render consecutive lines (one blank-line-separated chunk).
fn render_block(lines: &[&str], out: &mut Vec<String>) {
let mut i = 0;
while i < lines.len() {
let line = lines[i];
if let Some(level) = heading_level(line) {
out.push(format!(
"<h{}>{}</h{}>",
level,
render_inline(line[level + 1..].trim()),
level
));
i += 1;
continue;
}
if is_hr(line) {
out.push("<hr>".to_string());
i += 1;
continue;
}
if line.starts_with("```") {
let lang = line[3..].trim();
let mut body: Vec<&str> = Vec::new();
i += 1;
while i < lines.len() && !lines[i].starts_with("```") {
body.push(lines[i]);
i += 1;
}
i += 1; // past the closing fence (or past the end of an unclosed fence)
let cls = if lang.is_empty() {
String::new()
} else {
format!(" class=\"language-{}\"", encode_html(lang))
};
out.push(format!(
"<pre><code{}>{}</code></pre>",
cls,
encode_html(&body.join("\n"))
));
continue;
}
if line.starts_with("> ") {
let mut quoted: Vec<&str> = Vec::new();
while i < lines.len() && lines[i].starts_with("> ") {
quoted.push(&lines[i][2..]);
i += 1;
}
let mut inner: Vec<String> = Vec::new();
render_block("ed, &mut inner);
out.push(format!("<blockquote>\n{}\n</blockquote>", inner.join("\n")));
continue;
}
if is_ul(line) {
let mut items: Vec<String> = Vec::new();
while i < lines.len() && is_ul(lines[i]) {
items.push(format!("<li>{}</li>", render_inline(&lines[i][2..])));
i += 1;
}
out.push(format!("<ul>\n{}\n</ul>", items.join("\n")));
continue;
}
if ol_prefix_len(line).is_some() {
let mut items: Vec<String> = Vec::new();
while i < lines.len() {
match ol_prefix_len(lines[i]) {
Some(n) => {
items.push(format!("<li>{}</li>", render_inline(&lines[i][n..])));
i += 1;
}
None => break,
}
}
out.push(format!("<ol>\n{}\n</ol>", items.join("\n")));
continue;
}
let mut para: Vec<String> = Vec::new();
while i < lines.len() && !is_block_start(lines[i]) {
para.push(render_inline(lines[i].trim()));
i += 1;
}
out.push(format!("<p>{}</p>", para.join("\n")));
}
}
/// Split on runs of 2+ newlines (JS `text.split(/\n{2,}/)`).
fn split_blocks(text: &str) -> Vec<&str> {
let b = text.as_bytes();
let mut blocks: Vec<&str> = Vec::new();
let mut start = 0;
let mut i = 0;
while i < b.len() {
if b[i] == b'\n' {
let mut j = i;
while j < b.len() && b[j] == b'\n' {
j += 1;
}
if j - i >= 2 {
blocks.push(&text[start..i]);
start = j;
}
i = j;
} else {
i += 1;
}
}
blocks.push(&text[start..]);
blocks
}
/// Convert the supported Markdown subset to HTML. Never fails.
pub fn markdown_to_html(raw: &str) -> MarkdownToHtmlResult {
let text = raw.replace("\r\n", "\n").replace('\r', "\n");
let text = text.trim();
if text.is_empty() {
// empty input is NOT an error — the tool shows nothing
return MarkdownToHtmlResult { output: String::new(), error: None };
}
let mut out: Vec<String> = Vec::new();
for block in split_blocks(text) {
let lines: Vec<&str> = block.split('\n').filter(|l| !l.trim().is_empty()).collect();
render_block(&lines, &mut out);
}
MarkdownToHtmlResult { output: out.join("\n"), error: None }
}
// Example:
// let r = markdown_to_html("## Hello *world*");
// assert_eq!(r.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 →