Skip to content

HTML to Markdown Converter — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// html-to-markdown — supported HTML subset → Markdown converter.
//
// Language: Kotlin (JVM, standard library only).
// CosmoDev polyglot showcase port of the `html-to-markdown` tool.
// Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
// the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
//
// 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.
//
// Entity decode: the JVM has no WHATWG table, so this port 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).
//
// display source — part of CosmoDev's polyglot tool pages.

object HtmlToMarkdown {
    /** Result mirrors HtmlToMarkdownResult in the TS lib: on success output
     * is set and error is null; on failure output is empty. Empty or
     * whitespace-only input is NOT an error — the tool shows nothing. */
    data class Result(val output: String, val error: String?)

    private const val UNCLOSED_TAG = "Unclosed tag"

    /** VOID in the TS lib — tags that never open a scope. */
    private val VOID = setOf("br", "hr", "img", "meta", "link", "input", "source")

    /** BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks. */
    private val BLOCK_TAGS = setOf(
        "p", "div", "blockquote", "pre", "ul", "ol", "hr",
        "h1", "h2", "h3", "h4", "h5", "h6",
    )

    /** The six named entities decoded by the hand-rolled scanner. */
    private val NAMED = mapOf(
        "amp" to "&", "lt" to "<", "gt" to ">",
        "quot" to "\"", "apos" to "'", "nbsp" to " ",
    )

    private val TAG_NAME = Regex("^([a-zA-Z][a-zA-Z0-9-]*)")
    private val ATTR = Regex("([a-zA-Z-]+)(?:\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+))?")
    private val LANG_CLASS = Regex("language-([\\w-]+)")
    private val MD_ESCAPE = Regex("[\\\\`*_\\[\\]]")
    private val WS_RUN = Regex("\\s+")

    /** One forest node: text (isElem false) or element. */
    private class Node(val isElem: Boolean, val tag: String = "", val text: String = "") {
        val attrs = mutableMapOf<String, String>()
        val children = mutableListOf<Node>()

        companion object {
            fun text(v: String) = Node(isElem = false, text = v)
            fun elem(tag: String) = Node(isElem = true, tag = tag)
        }
    }

    /** Append sink: the current open element's children, else the roots. */
    private fun top(roots: MutableList<Node>, stack: List<Node>): MutableList<Node> =
        if (stack.isEmpty()) roots else stack.last().children

    private fun isAsciiLetter(c: Char): Boolean =
        (c in 'A'..'Z') || (c in 'a'..'z')

    private fun isAsciiDigit(c: Char): Boolean = c in '0'..'9'

    /** Decode one character reference starting at s[i] == '&'. Returns the
     * replacement and the index after ';' via [end], or null when the '&' is
     * not a recognized reference (emit it literally — decode never fails). */
    private fun decodeReference(s: String, i: Int, end: IntArray): String? {
        val p = i + 1
        if (p < s.length && s[p] == '#') { // &#NN; / &#xHH;
            val hex = p + 1 < s.length && (s[p + 1] == 'x' || s[p + 1] == 'X')
            var d = if (hex) p + 2 else p + 1
            val start = d
            while (d < s.length && (isAsciiDigit(s[d]) ||
                        (hex && (s[d] in 'a'..'f' || s[d] in 'A'..'F')))
            ) d++
            if (d > start && d < s.length && s[d] == ';') {
                val num = s.substring(start, d).toIntOrNull(if (hex) 16 else 10) ?: return null
                if ((num in 0xD800..0xDFFF) || num > 0x10FFFF) return null
                end[0] = d + 1
                return String(Character.toChars(num))
            }
            return null
        }
        // &name; — first char a letter, rest letters/digits (TS [A-Za-z][A-Za-z0-9]*).
        if (p < s.length && isAsciiLetter(s[p])) {
            var d = p + 1
            while (d < s.length && (isAsciiLetter(s[d]) || isAsciiDigit(s[d]))) d++
            if (d < s.length && s[d] == ';') return NAMED[s.substring(p, d)]?.also { end[0] = d + 1 }
        }
        return null
    }

    /** Resolve character references in one pass — no double-decode:
     * "x &amp;lt; y" stays "x &lt; y". Unknown refs pass through. */
    private fun decodeEntities(s: String): String {
        val b = StringBuilder(s.length)
        var i = 0
        val end = IntArray(1)
        while (i < s.length) {
            val c = s[i]
            if (c == '&') {
                val rep = decodeReference(s, i, end)
                if (rep != null) {
                    b.append(rep)
                    i = end[0]
                    continue
                }
            }
            b.append(c)
            i++
        }
        return b.toString()
    }

    /** Backslash-escape the Markdown-significant \ ` * _ [ ]. */
    private fun escapeMarkdown(s: String): String = MD_ESCAPE.replace(s) { m -> "\\" + m.value }

    /** Collapse any run of whitespace to a single space (TS \s+ pass; NBSP
     * is JS \s but not Kotlin \s, so normalize it explicitly first). */
    private fun collapseWhitespace(s: String): String = WS_RUN.replace(s.replace("\u00A0", " "), " ")

    /** Parse into a node forest. Attribute values may be double-quoted,
     * single-quoted or bare; a quoted value may contain '>'. Returns
     * (roots, null) or (null, "Unclosed tag"). */
    private fun parseHtml(raw: String): Pair<List<Node>?, String?> {
        val roots = mutableListOf<Node>()
        val stack = mutableListOf<Node>()
        var i = 0
        while (i < raw.length) {
            val lt = raw.indexOf('<', i)
            if (lt == -1) {
                top(roots, stack).add(Node.text(raw.substring(i)))
                break
            }
            if (lt > i) top(roots, stack).add(Node.text(raw.substring(i, lt)))
            // Find the tag's '>', skipping quoted attribute values.
            var j = lt + 1
            var quote = ' '
            var inQuote = false
            while (j < raw.length && (raw[j] != '>' || inQuote)) {
                val c = raw[j]
                if (!inQuote && (c == '"' || c == '\'')) {
                    quote = c
                    inQuote = true
                } else if (inQuote && c == quote) {
                    inQuote = false
                }
                j++
            }
            if (j >= raw.length) return null to UNCLOSED_TAG
            val inner = raw.substring(lt + 1, j).trim()
            i = j + 1

            if (inner.startsWith("!--")) continue // comment
            if (inner.startsWith("!")) continue // doctype
            val closing = inner.startsWith("/")
            val body = if (closing) inner.substring(1) else inner.replace(Regex("/$"), "")
            val name = TAG_NAME.find(body) ?: continue // not a real tag — drop it
            val tag = name.groupValues[1].lowercase()

            if (closing) {
                for (k in stack.indices.reversed()) {
                    if (stack[k].tag == tag) {
                        stack.subList(k, stack.size).clear()
                        break
                    }
                }
                continue
            }

            val elem = Node.elem(tag)
            for (am in ATTR.findAll(body)) {
                // Values stay RAW here; href/src/alt are entity-decoded at
                // use, titles stay verbatim. The strip mirrors TS
                // am[2].slice(1, -1): quoted values lose their quotes, bare
                // values lose their first and last characters (same quirk
                // the Go twin keeps for lock-step).
                val v = am.groupValues[2]
                elem.attrs[am.groupValues[1].lowercase()] =
                    if (v.length >= 2) v.substring(1, v.length - 1) else ""
            }
            top(roots, stack).add(elem)
            if (tag !in VOID && !body.endsWith("/")) stack.add(elem)
        }
        return roots to null
    }

    private fun isBlock(n: Node): Boolean = n.isElem && n.tag in BLOCK_TAGS

    /** Inline content of one block: marks, links, images, escaped text. */
    private fun renderInline(nodes: List<Node>): String = buildString {
        for (n in nodes) {
            if (!n.isElem) {
                append(collapseWhitespace(escapeMarkdown(decodeEntities(n.text))))
            } else {
                when (n.tag) {
                    "br" -> append("  \n")
                    "strong", "b" -> {
                        val inner = renderInline(n.children).trim()
                        if (inner.isNotEmpty()) append("**$inner**") // empty emphasis renders as nothing
                    }
                    "em", "i" -> {
                        val inner = renderInline(n.children).trim()
                        if (inner.isNotEmpty()) append("*$inner*")
                    }
                    "del", "s" -> {
                        val inner = renderInline(n.children).trim()
                        if (inner.isNotEmpty()) append("~~$inner~~")
                    }
                    "code" -> {
                        val inner = renderInline(n.children).trim()
                        if (inner.isNotEmpty()) append("`$inner`")
                    }
                    "a" -> {
                        val href = decodeEntities(n.attrs["href"] ?: "")
                        val t = n.attrs["title"] ?: ""
                        val title = if (t.isEmpty()) "" else " \"$t\""
                        val label = renderInline(n.children).trim().ifEmpty { href }
                        append("[$label]($href$title)")
                    }
                    "img" -> {
                        val alt = escapeMarkdown(decodeEntities(n.attrs["alt"] ?: "")).trim()
                        append("![${alt}](${decodeEntities(n.attrs["src"] ?: "")})")
                    }
                    else -> append(renderInline(n.children)) // span and unknown tags are transparent
                }
            }
        }
    }

    /** Concatenate the entity-decoded text under nodes (pre content only). */
    private fun textOf(nodes: List<Node>): String = buildString {
        for (c in nodes) {
            if (c.isElem) append(textOf(c.children)) else append(decodeEntities(c.text))
        }
    }

    /** Render a sequence of nodes as Markdown blocks. */
    private fun renderBlocks(nodes: List<Node>): List<String> {
        val out = mutableListOf<String>()
        val para = mutableListOf<Node>()
        fun flush() {
            if (para.isNotEmpty()) {
                val text = renderInline(para).trim()
                if (text.isNotEmpty()) out.add(text)
                para.clear()
            }
        }
        for (n in nodes) {
            if (!isBlock(n)) {
                para.add(n)
                continue
            }
            flush()
            when (n.tag) {
                "hr" -> out.add("---")
                "p" -> {
                    val text = renderInline(n.children).trim()
                    if (text.isNotEmpty()) out.add(text)
                }
                "div" -> out.addAll(renderBlocks(n.children))
                "blockquote" -> {
                    val inner = renderBlocks(n.children).joinToString("\n\n")
                    out.add(inner.split("\n").joinToString("\n") { l -> if (l.isEmpty()) ">" else "> $l" })
                }
                "pre" -> {
                    val codeElem = n.children.firstOrNull { it.isElem && it.tag == "code" }
                    val lang = codeElem?.let { LANG_CLASS.find(it.attrs["class"] ?: "")?.groupValues?.get(1) } ?: ""
                    val body = textOf((codeElem ?: n).children).replace(Regex("\n+$"), "")
                    out.add("```$lang\n$body\n```")
                }
                "ul", "ol" -> out.add(renderList(n, 0))
                else -> { // h1-h6
                    val level = if (n.tag.length >= 2 && n.tag[1] in '1'..'6') n.tag[1] - '0' else 0
                    out.add("#".repeat(level) + " " + renderInline(n.children).trim())
                }
            }
        }
        flush()
        return out
    }

    /** ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
     * numbering restarted per list. */
    private fun renderList(list: Node, depth: Int): String {
        val items = list.children.filter { it.isElem && it.tag == "li" }
        val ordered = list.tag == "ol"
        val lines = mutableListOf<String>()
        items.forEachIndexed { idx, li ->
            val marker = if (ordered) "${idx + 1}." else "-"
            val indent = " ".repeat(if (depth == 0) 0 else if (ordered) 4 else 2)
            // Split li children into inline content + nested lists.
            val inline = mutableListOf<Node>()
            val nested = mutableListOf<String>()
            for (c in li.children) {
                if (c.isElem && (c.tag == "ul" || c.tag == "ol")) nested.add(renderList(c, depth + 1))
                else inline.add(c)
            }
            val text = renderInline(inline).trim()
            lines.add(if (text.isEmpty()) "$indent$marker" else "$indent$marker $text")
            lines.addAll(nested)
        }
        return lines.joinToString("\n")
    }

    /** Convert the supported HTML subset to Markdown. Never throws — the
     * result carries output/error, mirroring HtmlToMarkdownResult. */
    fun convert(raw: String): Result {
        if (raw.isBlank()) return Result(output = "", error = null)
        val (roots, err) = parseHtml(raw)
        if (err != null || roots == null) return Result(output = "", error = err)
        return Result(output = renderBlocks(roots).joinToString("\n\n"), error = null)
    }
}

// Example:
// HtmlToMarkdown.convert("<h1>Title</h1><p>a &amp; <b>b</b></p>").output
// → "# Title\n\na & **b**"

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 →