Skip to content

HTML to Markdown Converter — Rust source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

// html-to-markdown — supported HTML subset → Markdown converter. Rust port
// (canonical TS: src/lib/html-to-markdown.ts; Go twin:
// cli/html-to-markdown/html-to-markdown.go).
//
// Language: Rust (2021 edition, standard library only — no regex crate).
// CosmoDev polyglot showcase port of the `html-to-markdown` tool.
//
// A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
// renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with
// the language taken from class="language-*", ul/ol with 2-space (ul) and
// 4-space (ol) nested indent, hr, br as two-spaces-newline; inline marks
// strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
// verbatim titles, images decode alt/src. Unknown tags are transparent,
// stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
// backslash-escape \ ` * _ [ ]. A '<' with no closing '>' is the one error
// ("Unclosed tag").
//
// The Rust stdlib has no regex, so every TS regex became a scanner, and no
// WHATWG entity table, so decode hand-rolls the fallback — numeric (&#NN; /
// &#xHH;) plus the six named entities (amp lt gt quot apos nbsp), single
// pass, no double-decode ("x &amp;lt; y" stays "x &lt; y"; the Go twin uses
// the full stdlib html.UnescapeString table). Text nodes collapse runs of
// JS whitespace (the full \s set — NBSP, U+2000-200A, ...) to one space,
// mirroring the TS /\s+/g pass. All scanning happens at ASCII boundaries, so
// multi-byte UTF-8 content is never split and the port never panics.
//
// display source — part of CosmoDev's polyglot tool pages.

/// Mirrors HtmlToMarkdownResult in the TS lib: on success output is set and
/// error is None; on failure output is empty. Empty or whitespace-only input
/// is NOT an error — the tool shows nothing.
pub struct HtmlToMarkdownResult {
    pub output: String,
    pub error: Option<String>,
}

/// The one error: a '<' whose '>' never comes.
const UNCLOSED_TAG: &str = "Unclosed tag";

/// VOID in the TS lib — tags that never open a scope.
const VOID_TAGS: [&str; 7] = ["br", "hr", "img", "meta", "link", "input", "source"];

/// BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.
const BLOCK_TAGS: [&str; 13] = [
    "p", "div", "blockquote", "pre", "ul", "ol", "hr", "h1", "h2", "h3", "h4", "h5", "h6",
];

/// The six named entities decoded by the hand-rolled scanner (the TS lib
/// uses the full WHATWG shared table).
const NAMED_ENTITIES: [(&str, &str); 6] = [
    ("amp", "&"),
    ("lt", "<"),
    ("gt", ">"),
    ("quot", "\""),
    ("apos", "'"),
    ("nbsp", "\u{00a0}"),
];

/// One forest node: text (is_elem false) or element. Children are arena
/// indices, so the parser can hold a plain stack of indices.
struct Node {
    is_elem: bool,
    tag: String,
    text: String,
    attrs: Vec<(String, String)>,
    children: Vec<usize>,
}

impl Node {
    fn text(v: &str) -> Node {
        Node {
            is_elem: false,
            tag: String::new(),
            text: v.to_string(),
            attrs: Vec::new(),
            children: Vec::new(),
        }
    }

    fn elem(tag: String) -> Node {
        Node {
            is_elem: true,
            tag,
            text: String::new(),
            attrs: Vec::new(),
            children: Vec::new(),
        }
    }
}

/// JS \s — the full set (JS \s matches U+00A0, U+2000-200A, ...; Rust's
/// char::is_whitespace diverges), used for trim and the \s+ collapse.
fn is_js_ws(c: char) -> bool {
    matches!(
        c,
        ' ' | '\t'
            | '\n'
            | '\u{0b}'
            | '\u{0c}'
            | '\r'
            | '\u{a0}'
            | '\u{1680}'
            | '\u{2000}'..='\u{200a}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{202f}'
            | '\u{205f}'
            | '\u{3000}'
            | '\u{feff}'
    )
}

/// JS String.prototype.trim over the JS-\s class.
fn trim_js(s: &str) -> &str {
    s.trim_matches(is_js_ws)
}

/// Collapse any run of JS whitespace to a single space — /\s+/g, ' '.
fn collapse_ws(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut in_run = false;
    for c in s.chars() {
        if is_js_ws(c) {
            in_run = true;
        } else {
            if in_run {
                out.push(' ');
                in_run = false;
            }
            out.push(c);
        }
    }
    if in_run {
        out.push(' ');
    }
    out
}

/// Decode every recognized reference in s. Unknown refs and stray '&' pass
/// through untouched; "x &amp;lt; y" stays "x &lt; y". Byte scanning: '&' and
/// the reference grammar are ASCII, so every other byte (UTF-8 continuation
/// included) passes through verbatim.
fn decode_entities(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < b.len() {
        let amp = match b[i..].iter().position(|&x| x == b'&') {
            Some(off) => i + off,
            None => {
                out.push_str(&s[i..]);
                break;
            }
        };
        out.push_str(&s[i..amp]);
        let p = amp + 1;
        let mut matched = false;
        let mut next = amp + 1;
        if p < b.len() && b[p] == b'#' {
            // &#NN; / &#xHH;
            let hex = p + 1 < b.len() && (b[p + 1] == b'x' || b[p + 1] == b'X');
            let mut d = if hex { p + 2 } else { p + 1 };
            let start = d;
            while d < b.len() && if hex { b[d].is_ascii_hexdigit() } else { b[d].is_ascii_digit() } {
                d += 1;
            }
            if d > start && d < b.len() && b[d] == b';' && d - start <= 7 {
                let mut cp: u32 = 0;
                let radix = if hex { 16 } else { 10 };
                for &c in &b[start..d] {
                    let v = (c as char).to_digit(radix).unwrap_or(0);
                    cp = cp * radix + v;
                }
                // from_u32 rejects lone surrogates and values above U+10FFFF.
                if let Some(ch) = char::from_u32(cp) {
                    out.push(ch);
                    matched = true;
                    next = d + 1;
                }
            }
        } else if p < b.len() && (b[p] as char).is_ascii_alphabetic() {
            // &name; — first char a letter, rest letters/digits.
            let mut d = p + 1;
            while d < b.len() && (b[d] as char).is_ascii_alphanumeric() {
                d += 1;
            }
            if d < b.len() && b[d] == b';' {
                let name = &s[p..d]; // ASCII-only span — slicing is boundary-safe
                for (n, rep) in NAMED_ENTITIES {
                    if n == name {
                        out.push_str(rep);
                        matched = true;
                        next = d + 1;
                        break;
                    }
                }
            }
        }
        if !matched {
            out.push('&');
            next = amp + 1;
        }
        i = next;
    }
    out
}

/// Backslash-escape the Markdown-significant \ ` * _ [ ].
fn escape_markdown(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '\\' | '`' | '*' | '_' | '[' | ']') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// `language-([\w-]+)` — the first occurrence whose capture is non-empty.
fn lang_from_class(class: &str) -> String {
    let b = class.as_bytes();
    let mut from = 0;
    while let Some(off) = b[from..]
        .windows(9)
        .position(|w| w == b"language-")
    {
        let start = from + off + 9;
        let mut e = start;
        while e < b.len() && matches!(b[e], b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') {
            e += 1;
        }
        if e > start {
            return class[start..e].to_string(); // ASCII bounds — safe slice
        }
        from = start;
    }
    String::new()
}

/// The TS attr regex as a scanner, resumed left-to-right like the /g loop:
/// name `[a-zA-Z-]+`, optional `\s*=\s*("..."|'...'|bare)`, resume after the
/// value when one matched, else after the name. Values stay RAW (href/src/
/// alt are entity-decoded at use; titles verbatim); the strip mirrors TS
/// am[2].slice(1, -1): quoted values lose their quotes, bare values lose
/// their first and last bytes (same quirk the Go twin keeps for lock-step).
fn scan_attrs(body: &str, from: usize, elem: &mut Node) {
    let b = body.as_bytes();
    let mut p = from;
    while p < b.len() {
        let c = b[p] as char;
        if c.is_ascii_alphabetic() || c == '-' {
            let mut q = p + 1;
            while q < b.len() && ((b[q] as char).is_ascii_alphabetic() || b[q] == b'-') {
                q += 1;
            }
            let mut r = q;
            while r < b.len() && is_js_ws(b[r] as char) {
                r += 1;
            }
            let mut vend = q;
            let mut raw_val: Option<(usize, usize)> = None;
            if r < b.len() && b[r] == b'=' {
                let mut r2 = r + 1;
                while r2 < b.len() && is_js_ws(b[r2] as char) {
                    r2 += 1;
                }
                if r2 < b.len() {
                    let vc = b[r2] as char;
                    if vc == '"' || vc == '\'' {
                        let mut e = r2 + 1;
                        while e < b.len() && b[e] != vc as u8 {
                            e += 1;
                        }
                        if e < b.len() {
                            raw_val = Some((r2, e + 1)); // value includes the quotes
                            vend = e + 1;
                        }
                    }
                    if raw_val.is_none() {
                        // bare [^\s>]+ — must be non-empty
                        let mut e = r2;
                        while e < b.len() && !is_js_ws(b[e] as char) && b[e] != b'>' {
                            e += 1;
                        }
                        if e > r2 {
                            raw_val = Some((r2, e));
                            vend = e;
                        } else {
                            vend = q; // no value — the group backtracks off
                        }
                    }
                } else {
                    vend = q;
                }
            }
            let value = match raw_val {
                Some((a0, a1)) => {
                    let v = &body[a0..a1]; // bounds at ASCII chars — safe slice
                    if v.len() >= 2 {
                        String::from_utf8_lossy(&v.as_bytes()[1..v.len() - 1]).into_owned()
                    } else {
                        String::new()
                    }
                }
                None => String::new(),
            };
            elem.attrs.push((body[p..q].to_ascii_lowercase(), value));
            p = vend;
        } else {
            p += 1;
        }
    }
}

/// Attach a node to its parent; returns the new arena index.
fn attach(arena: &mut Vec<Node>, parent: usize, nd: Node) -> usize {
    let ix = arena.len();
    arena.push(nd);
    arena[parent].children.push(ix);
    ix
}

/// Parse into a node forest. arena[0] is a synthetic root holding the
/// top-level nodes. Attribute values may be double-quoted, single-quoted or
/// bare; a quoted value may contain '>'. Returns the arena or the one error.
fn parse_html(raw: &str) -> Result<Vec<Node>, String> {
    let b = raw.as_bytes();
    let mut arena = vec![Node::elem(String::new())];
    let mut stack: Vec<usize> = vec![0]; // arena[0] = synthetic root
    let mut i = 0;
    while i < b.len() {
        let lt = match b[i..].iter().position(|&x| x == b'<') {
            Some(off) => i + off,
            None => {
                attach(&mut arena, *stack.last().unwrap(), Node::text(&raw[i..]));
                break;
            }
        };
        if lt > i {
            attach(&mut arena, *stack.last().unwrap(), Node::text(&raw[i..lt]));
        }
        // Find the tag's '>', skipping quoted attribute values.
        let mut j = lt + 1;
        let mut quote: u8 = 0;
        while j < b.len() && (b[j] != b'>' || quote != 0) {
            let c = b[j];
            if quote == 0 && (c == b'"' || c == b'\'') {
                quote = c;
            } else if quote != 0 && c == quote {
                quote = 0;
            }
            j += 1;
        }
        if j >= b.len() {
            return Err(UNCLOSED_TAG.to_string());
        }
        let inner = trim_js(&raw[lt + 1..j]).to_string();
        i = j + 1;

        if inner.starts_with("!--") {
            continue; // comment
        }
        if inner.starts_with('!') {
            continue; // doctype
        }
        let closing = inner.starts_with('/');
        let mut body: &str = if closing { &inner[1..] } else { &inner };
        if !closing && body.ends_with('/') {
            body = &body[..body.len() - 1]; // TS inner.replace(/\/$/, '') — one slash
        }
        // ^[a-zA-Z][a-zA-Z0-9-]* — else drop (browsers would show it as text)
        let bb = body.as_bytes();
        if bb.is_empty() || !(bb[0] as char).is_ascii_alphabetic() {
            continue;
        }
        let mut name_end = 1;
        while name_end < bb.len()
            && ((bb[name_end] as char).is_ascii_alphanumeric() || bb[name_end] == b'-')
        {
            name_end += 1;
        }
        let tag = body[..name_end].to_ascii_lowercase();

        if closing {
            for k in (1..stack.len()).rev() {
                if arena[stack[k]].tag == tag {
                    stack.truncate(k);
                    break;
                }
            }
            continue;
        }

        let mut elem = Node::elem(tag);
        scan_attrs(body, name_end, &mut elem);
        let ix = attach(&mut arena, *stack.last().unwrap(), elem);
        if !VOID_TAGS.contains(&arena[ix].tag.as_str()) && !body.ends_with('/') {
            stack.push(ix);
        }
    }
    Ok(arena)
}

/// Attribute value by (lowercased) name; "" when absent — TS attrs.href ?? ''.
fn attr_of<'a>(arena: &'a [Node], ix: usize, name: &str) -> &'a str {
    arena[ix]
        .attrs
        .iter()
        .find(|(k, _)| k == name)
        .map(|(_, v)| v.as_str())
        .unwrap_or("")
}

/// Inline content of one block: marks, links, images, escaped text.
fn render_inline(arena: &[Node], nodes: &[usize]) -> String {
    let mut out = String::new();
    for &ix in nodes {
        let n = &arena[ix];
        if !n.is_elem {
            // TS order: escape(decode(v)) then the \s+ collapse.
            out.push_str(&collapse_ws(&escape_markdown(&decode_entities(&n.text))));
            continue;
        }
        match n.tag.as_str() {
            "br" => out.push_str("  \n"),
            "strong" | "b" => {
                let rendered = render_inline(arena, &n.children);
                let inner = trim_js(&rendered);
                if !inner.is_empty() {
                    out.push_str(&format!("**{inner}**")); // empty emphasis renders as nothing
                }
            }
            "em" | "i" => {
                let rendered = render_inline(arena, &n.children);
                let inner = trim_js(&rendered);
                if !inner.is_empty() {
                    out.push_str(&format!("*{inner}*"));
                }
            }
            "del" | "s" => {
                let rendered = render_inline(arena, &n.children);
                let inner = trim_js(&rendered);
                if !inner.is_empty() {
                    out.push_str(&format!("~~{inner}~~"));
                }
            }
            "code" => {
                let rendered = render_inline(arena, &n.children);
                let inner = trim_js(&rendered);
                if !inner.is_empty() {
                    out.push_str(&format!("`{inner}`"));
                }
            }
            "a" => {
                let href = decode_entities(attr_of(arena, ix, "href"));
                let title = attr_of(arena, ix, "title"); // stays verbatim
                let rendered = render_inline(arena, &n.children);
                let trimmed = trim_js(&rendered);
                let label = if trimmed.is_empty() { href.as_str() } else { trimmed };
                out.push('[');
                out.push_str(label);
                out.push_str("](");
                out.push_str(&href);
                if !title.is_empty() {
                    out.push_str(&format!(" \"{title}\""));
                }
                out.push(')');
            }
            "img" => {
                let decoded = decode_entities(attr_of(arena, ix, "alt"));
                let escaped = escape_markdown(&decoded);
                let alt = trim_js(&escaped);
                out.push_str(&format!(
                    "![{alt}]({})",
                    decode_entities(attr_of(arena, ix, "src"))
                ));
            }
            _ => out.push_str(&render_inline(arena, &n.children)), // span/unknown: transparent
        }
    }
    out
}

/// Concatenate the entity-decoded text under nodes (pre content only).
fn text_of(arena: &[Node], nodes: &[usize]) -> String {
    let mut out = String::new();
    for &ix in nodes {
        let n = &arena[ix];
        if n.is_elem {
            out.push_str(&text_of(arena, &n.children));
        } else {
            out.push_str(&decode_entities(&n.text));
        }
    }
    out
}

/// Render a sequence of nodes as Markdown blocks.
fn render_blocks(arena: &[Node], nodes: &[usize]) -> Vec<String> {
    fn flush(arena: &[Node], out: &mut Vec<String>, para: &mut Vec<usize>) {
        if !para.is_empty() {
            let rendered = render_inline(arena, para);
            let text = trim_js(&rendered);
            if !text.is_empty() {
                out.push(text.to_string());
            }
            para.clear();
        }
    }
    let mut out: Vec<String> = Vec::new();
    let mut para: Vec<usize> = Vec::new();
    for &ix in nodes {
        let n = &arena[ix];
        if !(n.is_elem && BLOCK_TAGS.contains(&n.tag.as_str())) {
            para.push(ix);
            continue;
        }
        flush(arena, &mut out, &mut para);
        match n.tag.as_str() {
            "hr" => out.push("---".to_string()),
            "p" => {
                let rendered = render_inline(arena, &n.children);
                let text = trim_js(&rendered);
                if !text.is_empty() {
                    out.push(text.to_string());
                }
            }
            "div" => out.extend(render_blocks(arena, &n.children)),
            "blockquote" => {
                let inner = render_blocks(arena, &n.children).join("\n\n");
                let quoted: Vec<String> = inner
                    .split('\n')
                    .map(|l| if l.is_empty() { ">".to_string() } else { format!("> {l}") })
                    .collect();
                out.push(quoted.join("\n"));
            }
            "pre" => {
                let code_ix = n
                    .children
                    .iter()
                    .copied()
                    .find(|&c| arena[c].is_elem && arena[c].tag == "code");
                let lang = match code_ix {
                    Some(c) => lang_from_class(attr_of(arena, c, "class")),
                    None => String::new(),
                };
                let src = code_ix.unwrap_or(ix);
                let mut body = text_of(arena, &arena[src].children);
                while body.ends_with('\n') {
                    body.pop();
                } // TS replace(/\n+$/, '')
                out.push(format!("```{lang}\n{body}\n```"));
            }
            "ul" | "ol" => out.push(render_list(arena, ix, 0)),
            _ => {
                // h1-h6 (the remaining BLOCK_TAGS)
                let level = n
                    .tag
                    .as_bytes()
                    .get(1)
                    .filter(|c| c.is_ascii_digit())
                    .map(|c| c - b'0')
                    .unwrap_or(0);
                let rendered = render_inline(arena, &n.children);
                out.push(format!(
                    "{} {}",
                    "#".repeat(level as usize),
                    trim_js(&rendered)
                ));
            }
        }
    }
    flush(arena, &mut out, &mut para);
    out
}

/// ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
/// numbering restarted per list.
fn render_list(arena: &[Node], list_ix: usize, depth: usize) -> String {
    let list = &arena[list_ix];
    let ordered = list.tag == "ol";
    let items: Vec<usize> = list
        .children
        .iter()
        .copied()
        .filter(|&c| arena[c].is_elem && arena[c].tag == "li")
        .collect();
    let mut lines: Vec<String> = Vec::new();
    for (idx, &li_ix) in items.iter().enumerate() {
        let li = &arena[li_ix];
        let marker = if ordered { format!("{}.", idx + 1) } else { "-".to_string() };
        let indent = " ".repeat(if depth == 0 { 0 } else if ordered { 4 } else { 2 });
        // Split li children into inline content + nested lists.
        let mut inline: Vec<usize> = Vec::new();
        let mut nested: Vec<String> = Vec::new();
        for &c in &li.children {
            if arena[c].is_elem && (arena[c].tag == "ul" || arena[c].tag == "ol") {
                nested.push(render_list(arena, c, depth + 1));
            } else {
                inline.push(c);
            }
        }
        let rendered = render_inline(arena, &inline);
        let text = trim_js(&rendered);
        lines.push(if text.is_empty() {
            format!("{indent}{marker}")
        } else {
            format!("{indent}{marker} {text}")
        });
        lines.extend(nested);
    }
    lines.join("\n")
}

/// Convert the supported HTML subset to Markdown. Never panics — the result
/// carries output/error, mirroring HtmlToMarkdownResult.
pub fn html_to_markdown(raw: &str) -> HtmlToMarkdownResult {
    if trim_js(raw).is_empty() {
        // empty input is NOT an error — the tool shows nothing
        return HtmlToMarkdownResult { output: String::new(), error: None };
    }
    let arena = match parse_html(raw) {
        Ok(a) => a,
        Err(e) => return HtmlToMarkdownResult { output: String::new(), error: Some(e) },
    };
    HtmlToMarkdownResult {
        output: render_blocks(&arena, &arena[0].children).join("\n\n"),
        error: None,
    }
}

// Example:
// let r = html_to_markdown("<h1>Title</h1><p>a &amp; <b>b</b></p>");
// assert_eq!(r.output, "# Title\n\na & **b**");
// html_to_markdown("<p x=\"").error → Some("Unclosed tag")

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 →