Skip to content

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

// markdown-to-html — escape-first CommonMark subset → HTML renderer. Swift 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). Swift standard library only (no Foundation), and the stdlib has
// no regex, so every TS regex became a byte scanner over [UInt8]: 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 traps on any input.

struct MarkdownToHtmlResult {
    let output: String
    let error: String?
}

/// JS `\s` (the ASCII set; URLs may not contain any of these).
private func isSpaceByte(_ b: UInt8) -> Bool {
    b == 0x20 || b == 0x09 || b == 0x0A || b == 0x0B || b == 0x0C || b == 0x0D
}

private func startsWith(_ s: [UInt8], _ p: String) -> Bool {
    s.starts(with: Array(p.utf8))
}

private func appendEscaped(_ out: inout [UInt8], _ s: [UInt8]) {
    for b in s {
        switch b {
        case UInt8(ascii: "&"): out.append(contentsOf: Array("&".utf8))
        case UInt8(ascii: "<"): out.append(contentsOf: Array("&lt;".utf8))
        case UInt8(ascii: ">"): out.append(contentsOf: Array("&gt;".utf8))
        case UInt8(ascii: "'"): out.append(contentsOf: Array("&apos;".utf8))
        case UInt8(ascii: "\""): out.append(contentsOf: Array("&quot;".utf8))
        default: out.append(b)
        }
    }
}

/// Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
/// the entities we emit are never re-escaped.
private func encodeHtml(_ s: [UInt8]) -> [UInt8] {
    var out: [UInt8] = []
    out.reserveCapacity(s.count)
    appendEscaped(&out, s)
    return out
}

/// 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.
private func extractCodeSpans(_ s: [UInt8], codes: inout [[UInt8]]) -> [UInt8] {
    var out: [UInt8] = []
    var i = 0
    while i < s.count {
        if s[i] == UInt8(ascii: "`") {
            var j = i + 1
            while j < s.count && s[j] != UInt8(ascii: "`") { j += 1 }
            if j < s.count && j > i + 1 {
                var code: [UInt8] = Array("<code>".utf8)
                appendEscaped(&code, Array(s[(i + 1)..<j]))
                code.append(contentsOf: Array("</code>".utf8))
                codes.append(code)
                out.append(0)
                out.append(contentsOf: Array(String(codes.count - 1).utf8))
                out.append(0)
                i = j + 1
                continue
            }
        }
        out.append(s[i]) // no closing backtick (or empty span): literal char
        i += 1
    }
    return out
}

/// `!\[([^\]]*)\]\(([^)\s]+)\)` — alt may be empty and contain anything but
/// `]`; the URL must be non-empty and stop at `)` or whitespace.
private func replaceImages(_ s: [UInt8]) -> [UInt8] {
    var out: [UInt8] = []
    var i = 0
    while i < s.count {
        if s[i] == UInt8(ascii: "!") && i + 1 < s.count && s[i + 1] == UInt8(ascii: "[") {
            var j = i + 2
            while j < s.count && s[j] != UInt8(ascii: "]") { j += 1 }
            if j < s.count && j + 1 < s.count && s[j + 1] == UInt8(ascii: "(") {
                var k = j + 2
                while k < s.count && s[k] != UInt8(ascii: ")") && !isSpaceByte(s[k]) { k += 1 }
                if k < s.count && s[k] == UInt8(ascii: ")") && k > j + 2 {
                    out.append(contentsOf: Array("<img src=\"".utf8))
                    out.append(contentsOf: s[(j + 2)..<k])
                    out.append(contentsOf: Array("\" alt=\"".utf8))
                    out.append(contentsOf: s[(i + 2)..<j])
                    out.append(contentsOf: Array("\">".utf8))
                    i = k + 1
                    continue
                }
            }
        }
        out.append(s[i]) // on failure the engine advances one char — emit it
        i += 1
    }
    return out
}

/// `\[([^\]]+)\]\(([^)\s]+)\)` — link text must be non-empty (images ran
/// first, so `![` is already gone).
private func replaceLinks(_ s: [UInt8]) -> [UInt8] {
    var out: [UInt8] = []
    var i = 0
    while i < s.count {
        if s[i] == UInt8(ascii: "[") {
            var j = i + 1
            while j < s.count && s[j] != UInt8(ascii: "]") { j += 1 }
            if j < s.count && j > i + 1 && j + 1 < s.count && s[j + 1] == UInt8(ascii: "(") {
                var k = j + 2
                while k < s.count && s[k] != UInt8(ascii: ")") && !isSpaceByte(s[k]) { k += 1 }
                if k < s.count && s[k] == UInt8(ascii: ")") && k > j + 2 {
                    out.append(contentsOf: Array("<a href=\"".utf8))
                    out.append(contentsOf: s[(j + 2)..<k])
                    out.append(contentsOf: Array("\">".utf8))
                    out.append(contentsOf: s[(i + 1)..<j])
                    out.append(contentsOf: Array("</a>".utf8))
                    i = k + 1
                    continue
                }
            }
        }
        out.append(s[i])
        i += 1
    }
    return 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).
private func replacePairs(_ s: [UInt8], marker: UInt8, width: Int, open: String, close: String) -> [UInt8] {
    let openB = Array(open.utf8)
    let closeB = Array(close.utf8)
    var out: [UInt8] = []
    var i = 0
    while i < s.count {
        let opens = s[i] == marker && (width == 1 || (i + 1 < s.count && s[i + 1] == marker))
        if opens {
            let start = i + width
            var j = start
            while j < s.count && s[j] != marker { j += 1 }
            let closed = j < s.count && (width == 1 || (j + 1 < s.count && s[j + 1] == marker))
            if closed && j > start {
                out.append(contentsOf: openB)
                out.append(contentsOf: s[start..<j])
                out.append(contentsOf: closeB)
                i = j + width
                continue
            }
        }
        out.append(s[i])
        i += 1
    }
    return out
}

/// `\u0000(\d+)\u0000` — placeholders resolve back to their stored spans.
private func restoreCodeSpans(_ s: [UInt8], codes: [[UInt8]]) -> [UInt8] {
    var out: [UInt8] = []
    var i = 0
    while i < s.count {
        if s[i] == 0 {
            var j = i + 1
            while j < s.count && s[j] >= 0x30 && s[j] <= 0x39 { j += 1 }
            if j > i + 1 && j < s.count && s[j] == 0 {
                let n = Int(String(decoding: s[(i + 1)..<j], as: UTF8.self)) ?? Int.max
                if n < codes.count {
                    out.append(contentsOf: codes[n])
                }
                i = j + 1
                continue
            }
        }
        out.append(s[i])
        i += 1
    }
    return out
}

/// Inline pass: code spans first (placeholder-protected), then images, links,
/// bold, italic, strikethrough — non-greedy pairs, in TS precedence order.
private func renderInline(_ s: [UInt8]) -> [UInt8] {
    var codes: [[UInt8]] = []
    var text = extractCodeSpans(s, codes: &codes)
    text = encodeHtml(text)
    text = replaceImages(text)
    text = replaceLinks(text)
    text = replacePairs(text, marker: UInt8(ascii: "*"), width: 2, open: "<strong>", close: "</strong>")
    text = replacePairs(text, marker: UInt8(ascii: "_"), width: 2, open: "<strong>", close: "</strong>")
    text = replacePairs(text, marker: UInt8(ascii: "*"), width: 1, open: "<em>", close: "</em>")
    text = replacePairs(text, marker: UInt8(ascii: "_"), width: 1, open: "<em>", close: "</em>")
    text = replacePairs(text, marker: UInt8(ascii: "~"), width: 2, open: "<del>", close: "</del>")
    return restoreCodeSpans(text, codes: codes)
}

/// `^(#{1,6}) (.*)$` — returns the heading level (1-6) or nil.
private func headingLevel(_ s: [UInt8]) -> Int? {
    var n = 0
    while n < s.count && s[n] == UInt8(ascii: "#") { n += 1 }
    if n >= 1 && n <= 6 && n < s.count && s[n] == UInt8(ascii: " ") { return n }
    return nil
}

/// `^(---+|\*\*\*+|___+)\s*$` — the whole run is one marker char (3+), then
/// only whitespace.
private func isHr(_ s: [UInt8]) -> Bool {
    if s.count < 3 { return false }
    let c = s[0]
    if c != UInt8(ascii: "-") && c != UInt8(ascii: "*") && c != UInt8(ascii: "_") { return false }
    var k = 0
    while k < s.count && s[k] == c { k += 1 }
    if k < 3 { return false }
    return s[k...].allSatisfy { isSpaceByte($0) }
}

/// `^[-*+] `
private func isUl(_ s: [UInt8]) -> Bool {
    s.count >= 2
        && (s[0] == UInt8(ascii: "-") || s[0] == UInt8(ascii: "*") || s[0] == UInt8(ascii: "+"))
        && s[1] == UInt8(ascii: " ")
}

/// `^\d+\. ` — returns the full prefix length (digits + ". ").
private func olPrefixLen(_ s: [UInt8]) -> Int? {
    var n = 0
    while n < s.count && s[n] >= 0x30 && s[n] <= 0x39 { n += 1 }
    if n >= 1 && n + 1 < s.count && s[n] == UInt8(ascii: ".") && s[n + 1] == UInt8(ascii: " ") {
        return n + 2
    }
    return nil
}

/// 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 func isBlockStart(_ s: [UInt8]) -> Bool {
    headingLevel(s) != nil || isHr(s) || startsWith(s, "```") || startsWith(s, "> ")
        || isUl(s) || olPrefixLen(s) != nil
}

/// ASCII whitespace trim (the renderer's contract; input was already
/// normalized, so only ' ' \t \v \f appear at line edges).
private func trimBytes(_ s: [UInt8]) -> [UInt8] {
    var a = 0
    var e = s.count
    while a < e && isSpaceByte(s[a]) { a += 1 }
    while e > a && isSpaceByte(s[e - 1]) { e -= 1 }
    return Array(s[a..<e])
}

private func joinB(_ parts: [[UInt8]], sep: String) -> [UInt8] {
    var out: [UInt8] = []
    let sb = Array(sep.utf8)
    for (k, p) in parts.enumerated() {
        if k > 0 { out.append(contentsOf: sb) }
        out.append(contentsOf: p)
    }
    return out
}

/// `\r\n?` → `\n`
private func normalizeNewlines(_ s: [UInt8]) -> [UInt8] {
    var out: [UInt8] = []
    out.reserveCapacity(s.count)
    var i = 0
    while i < s.count {
        if s[i] == 0x0D {
            out.append(0x0A)
            if i + 1 < s.count && s[i + 1] == 0x0A { i += 1 }
        } else {
            out.append(s[i])
        }
        i += 1
    }
    return out
}

/// Split on runs of 2+ newlines (JS `text.split(/\n{2,}/)`).
private func splitBlocks(_ s: [UInt8]) -> [[UInt8]] {
    var blocks: [[UInt8]] = []
    var start = 0
    var i = 0
    while i < s.count {
        if s[i] == 0x0A {
            var j = i
            while j < s.count && s[j] == 0x0A { j += 1 }
            if j - i >= 2 {
                blocks.append(Array(s[start..<i]))
                start = j
            }
            i = j
        } else {
            i += 1
        }
    }
    blocks.append(Array(s[start...]))
    return blocks
}

/// Render consecutive lines (one blank-line-separated chunk).
private func renderBlock(lines: [[UInt8]], out: inout [[UInt8]]) {
    var i = 0
    while i < lines.count {
        let line = lines[i]

        if let level = headingLevel(line) {
            var h: [UInt8] = Array("<h\(level)>".utf8)
            h.append(contentsOf: renderInline(trimBytes(Array(line[(level + 1)...]))))
            h.append(contentsOf: Array("</h\(level)>".utf8))
            out.append(h)
            i += 1
            continue
        }

        if isHr(line) {
            out.append(Array("<hr>".utf8))
            i += 1
            continue
        }

        if startsWith(line, "```") {
            let lang = trimBytes(Array(line[3...]))
            var body: [[UInt8]] = []
            i += 1
            while i < lines.count && !startsWith(lines[i], "```") {
                body.append(lines[i])
                i += 1
            }
            i += 1 // past the closing fence (or past the end of an unclosed fence)
            var pre: [UInt8] = Array("<pre><code".utf8)
            if !lang.isEmpty {
                pre.append(contentsOf: Array(" class=\"language-".utf8))
                appendEscaped(&pre, lang)
                pre.append(UInt8(ascii: "\""))
            }
            pre.append(UInt8(ascii: ">"))
            appendEscaped(&pre, joinB(body, sep: "\n"))
            pre.append(contentsOf: Array("</code></pre>".utf8))
            out.append(pre)
            continue
        }

        if startsWith(line, "> ") {
            var quoted: [[UInt8]] = []
            while i < lines.count && startsWith(lines[i], "> ") {
                quoted.append(Array(lines[i][2...]))
                i += 1
            }
            var inner: [[UInt8]] = []
            renderBlock(lines: quoted, out: &inner)
            var bq: [UInt8] = Array("<blockquote>\n".utf8)
            bq.append(contentsOf: joinB(inner, sep: "\n"))
            bq.append(contentsOf: Array("\n</blockquote>".utf8))
            out.append(bq)
            continue
        }

        if isUl(line) {
            var items: [[UInt8]] = []
            while i < lines.count && isUl(lines[i]) {
                var li: [UInt8] = Array("<li>".utf8)
                li.append(contentsOf: renderInline(Array(lines[i][2...])))
                li.append(contentsOf: Array("</li>".utf8))
                items.append(li)
                i += 1
            }
            var ul: [UInt8] = Array("<ul>\n".utf8)
            ul.append(contentsOf: joinB(items, sep: "\n"))
            ul.append(contentsOf: Array("\n</ul>".utf8))
            out.append(ul)
            continue
        }

        if olPrefixLen(line) != nil {
            var items: [[UInt8]] = []
            while i < lines.count, let n = olPrefixLen(lines[i]) {
                var li: [UInt8] = Array("<li>".utf8)
                li.append(contentsOf: renderInline(Array(lines[i][n...])))
                li.append(contentsOf: Array("</li>".utf8))
                items.append(li)
                i += 1
            }
            var ol: [UInt8] = Array("<ol>\n".utf8)
            ol.append(contentsOf: joinB(items, sep: "\n"))
            ol.append(contentsOf: Array("\n</ol>".utf8))
            out.append(ol)
            continue
        }

        var para: [[UInt8]] = []
        while i < lines.count && !isBlockStart(lines[i]) {
            para.append(renderInline(trimBytes(lines[i])))
            i += 1
        }
        var p: [UInt8] = Array("<p>".utf8)
        p.append(contentsOf: joinB(para, sep: "\n"))
        p.append(contentsOf: Array("</p>".utf8))
        out.append(p)
    }
}

/// Convert the supported Markdown subset to HTML. Never fails.
func markdownToHtml(_ raw: String) -> MarkdownToHtmlResult {
    var text = normalizeNewlines(Array(raw.utf8))
    text = trimBytes(text)
    if text.isEmpty {
        return MarkdownToHtmlResult(output: "", error: nil) // NOT an error
    }
    var out: [[UInt8]] = []
    for block in splitBlocks(text) {
        var lines: [[UInt8]] = []
        var pos = 0
        while pos <= block.count {
            var end = pos
            while end < block.count && block[end] != 0x0A { end += 1 }
            let line = Array(block[pos..<end])
            if !trimBytes(line).isEmpty { lines.append(line) }
            pos = end + 1
        }
        renderBlock(lines: lines, out: &out)
    }
    return MarkdownToHtmlResult(output: String(decoding: joinB(out, sep: "\n"), as: UTF8.self), error: nil)
}

// 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 →