Skip to content

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

// markdown-to-html — escape-first CommonMark subset → HTML renderer. Kotlin 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 throws.

data class MarkdownToHtmlResult(val output: String, val error: String?)

private val HEADING = Regex("^(#{1,6}) (.*)$")
private val HR = Regex("^(---+|\\*\\*\\*+|___+)\\s*$")
private val UL = Regex("^[-*+] ")
private val OL = Regex("^\\d+\\. ")
private val CODE_SPAN = Regex("`([^`]+)`")
private val IMAGE = Regex("!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)")
private val LINK = Regex("\\[([^\\]]+)\\]\\(([^)\\s]+)\\)")

/** JS-style global replace: each match becomes a computed string (no
 *  replacement-template escapes, captured text is emitted verbatim). */
private fun replaceAll(s: String, re: Regex, f: (MatchResult) -> String): String {
    val out = StringBuilder()
    var last = 0
    for (m in re.findAll(s)) {
        out.append(s, last, m.range.first).append(f(m))
        last = m.range.last + 1
    }
    return out.append(s.substring(last)).toString()
}

/** Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
 *  the entities we emit are never re-escaped. */
fun encodeHtml(text: String): String = text
    .replace("&", "&")
    .replace("<", "&lt;")
    .replace(">", "&gt;")
    .replace("'", "&apos;")
    .replace("\"", "&quot;")

/** Inline pass: code spans first (placeholder-protected), then images, links,
 *  bold, italic, strikethrough — non-greedy pairs. */
fun renderInline(s: String): String {
    val codes = mutableListOf<String>()
    var text = replaceAll(s, CODE_SPAN) { m ->
        codes.add("<code>" + encodeHtml(m.groupValues[1]) + "</code>")
        "\u0000${codes.size - 1}\u0000"
    }
    text = encodeHtml(text)
    text = replaceAll(text, IMAGE) { "<img src=\"${it.groupValues[2]}\" alt=\"${it.groupValues[1]}\">" }
    text = replaceAll(text, LINK) { "<a href=\"${it.groupValues[2]}\">${it.groupValues[1]}</a>" }
    text = replaceAll(text, Regex("\\*\\*([^*]+)\\*\\*")) { "<strong>${it.groupValues[1]}</strong>" }
    text = replaceAll(text, Regex("__([^_]+)__")) { "<strong>${it.groupValues[1]}</strong>" }
    text = replaceAll(text, Regex("\\*([^*]+)\\*")) { "<em>${it.groupValues[1]}</em>" }
    text = replaceAll(text, Regex("_([^_]+)_")) { "<em>${it.groupValues[1]}</em>" }
    text = replaceAll(text, Regex("~~([^~]+)~~")) { "<del>${it.groupValues[1]}</del>" }
    return replaceAll(text, Regex("\u0000(\\d+)\u0000")) { codes[it.groupValues[1].toInt()] }
}

/** True when a line STARTS a new block — the paragraph terminator. Any new
 *  block type must register here and in the renderBlock dispatch below. */
private fun isBlockStart(line: String): Boolean = HEADING.containsMatchIn(line) ||
    HR.containsMatchIn(line) ||
    line.startsWith("```") ||
    line.startsWith("> ") ||
    UL.containsMatchIn(line) ||
    OL.containsMatchIn(line)

/** Render consecutive lines (one blank-line-separated chunk). */
private fun renderBlock(lines: List<String>, out: MutableList<String>) {
    var i = 0
    while (i < lines.size) {
        val line = lines[i]

        val heading = HEADING.find(line)
        if (heading != null) {
            val level = heading.groupValues[1].length
            out.add("<h$level>${renderInline(heading.groupValues[2].trim())}</h$level>")
            i++
            continue
        }

        if (HR.containsMatchIn(line)) {
            out.add("<hr>")
            i++
            continue
        }

        if (line.startsWith("```")) {
            val lang = line.substring(3).trim()
            val body = mutableListOf<String>()
            i++
            while (i < lines.size && !lines[i].startsWith("```")) {
                body.add(lines[i])
                i++
            }
            i++ // past the closing fence (or past the end of an unclosed fence)
            val cls = if (lang.isEmpty()) "" else " class=\"language-" + encodeHtml(lang) + "\""
            out.add("<pre><code$cls>" + encodeHtml(body.joinToString("\n")) + "</code></pre>")
            continue
        }

        if (line.startsWith("> ")) {
            val quoted = mutableListOf<String>()
            while (i < lines.size && lines[i].startsWith("> ")) {
                quoted.add(lines[i].substring(2))
                i++
            }
            val inner = mutableListOf<String>()
            renderBlock(quoted, inner)
            out.add("<blockquote>\n" + inner.joinToString("\n") + "\n</blockquote>")
            continue
        }

        if (UL.containsMatchIn(line)) {
            val items = mutableListOf<String>()
            while (i < lines.size && UL.containsMatchIn(lines[i])) {
                items.add("<li>" + renderInline(lines[i].replaceFirst(UL, "")) + "</li>")
                i++
            }
            out.add("<ul>\n" + items.joinToString("\n") + "\n</ul>")
            continue
        }

        if (OL.containsMatchIn(line)) {
            val items = mutableListOf<String>()
            while (i < lines.size && OL.containsMatchIn(lines[i])) {
                val m = OL.find(lines[i])!!
                items.add("<li>" + renderInline(lines[i].substring(m.value.length)) + "</li>")
                i++
            }
            out.add("<ol>\n" + items.joinToString("\n") + "\n</ol>")
            continue
        }

        val para = mutableListOf<String>()
        while (i < lines.size && !isBlockStart(lines[i])) {
            para.add(renderInline(lines[i].trim()))
            i++
        }
        out.add("<p>" + para.joinToString("\n") + "</p>")
    }
}

/** Convert the supported Markdown subset to HTML. Never fails. */
fun markdownToHtml(raw: String): MarkdownToHtmlResult {
    val text = raw.replace(Regex("\r\n?"), "\n").trim()
    if (text.isEmpty()) return MarkdownToHtmlResult("", null) // NOT an error
    val out = mutableListOf<String>()
    for (block in text.split(Regex("\n{2,}"))) {
        renderBlock(block.split("\n").filter { it.trim().isNotEmpty() }, out)
    }
    return MarkdownToHtmlResult(out.joinToString("\n"), null)
}

// Example:
// markdownToHtml("## Hello *world*").output
// → "<h2>Hello <em>world</em></h2>"
// markdownToHtml("```js\nconst x = 1; // <b>\n```").output
// → "<pre><code class=\"language-js\">const x = 1; // &lt;b&gt;</code></pre>"
// markdownToHtml("<script>alert(1)</script>").output
// → "<p>&lt;script&gt;alert(1)&lt;/script&gt;</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 →