Skip to content

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

// html-to-markdown — supported HTML subset → Markdown converter.
//
// Language: Swift (5.x, standard library only — no Foundation, no Regex).
// 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 Swift standard library has no WHATWG table, so this
// port hand-rolls character-array scanning plus the fallback decoder —
// numeric (&#NN; / &#xHH;) and 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.

enum HtmlToMarkdown {
    /// Mirrors HtmlToMarkdownResult in the TS lib: on success output is set
    /// and error is nil; on failure output is empty. Empty or whitespace-only
    /// input is NOT an error — the tool shows nothing.
    struct Result {
        let output: String
        let error: String?
    }

    private static let unclosedTag = "Unclosed tag"

    /// VOID in the TS lib — tags that never open a scope.
    private static let voidTags: Set<String> = ["br", "hr", "img", "meta", "link", "input", "source"]

    /// BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.
    private static let blockTags: Set<String> = [
        "p", "div", "blockquote", "pre", "ul", "ol", "hr",
        "h1", "h2", "h3", "h4", "h5", "h6",
    ]

    /// The six named entities decoded by the hand-rolled scanner.
    private static let named: [String: String] = [
        "amp": "&", "lt": "<", "gt": ">", "quot": "\"", "apos": "'", "nbsp": "\u{00A0}",
    ]

    /// One forest node: text (isElem false) or element.
    private final class Node {
        let isElem: Bool
        var text = ""
        var tag = ""
        var attrs: [String: String] = [:]
        var children: [Node] = []

        init(text: String) {
            self.isElem = false
            self.text = text
        }

        init(tag: String) {
            self.isElem = true
            self.tag = tag
        }
    }

    // MARK: character helpers (no Foundation/Regex — everything scans chars)

    private static func isAsciiLetter(_ c: Character) -> Bool {
        c == "a" || c == "b" || c == "c" || c == "d" || c == "e" || c == "f" || c == "g"
            || c == "h" || c == "i" || c == "j" || c == "k" || c == "l" || c == "m" || c == "n"
            || c == "o" || c == "p" || c == "q" || c == "r" || c == "s" || c == "t" || c == "u"
            || c == "v" || c == "w" || c == "x" || c == "y" || c == "z"
            || c == "A" || c == "B" || c == "C" || c == "D" || c == "E" || c == "F" || c == "G"
            || c == "H" || c == "I" || c == "J" || c == "K" || c == "L" || c == "M" || c == "N"
            || c == "O" || c == "P" || c == "Q" || c == "R" || c == "S" || c == "T" || c == "U"
            || c == "V" || c == "W" || c == "X" || c == "Y" || c == "Z"
    }

    private static func isAsciiDigit(_ c: Character) -> Bool {
        c >= "0" && c <= "9"
    }

    /// JS \s (the TS twin's whitespace class): ASCII spaces plus the Unicode
    /// spaces JS \s covers, including U+00A0 and U+FEFF.
    private static func isJsSpace(_ c: Character) -> Bool {
        if " \t\n\r\u{0B}\u{0C}".contains(c) { return true }
        guard let scalar = c.unicodeScalars.first, c.unicodeScalars.count == 1 else { return false }
        switch scalar.value {
        case 0xA0, 0x1680, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF, 0x2000...0x200A:
            return true
        default:
            return false
        }
    }

    /// JS String.prototype.trim over the same class as isJsSpace.
    private static func trimJsSpace(_ s: String) -> String {
        var start = s.startIndex
        var end = s.endIndex
        while start < end, isJsSpace(s[start]) { start = s.index(after: start) }
        while end > start, isJsSpace(s[s.index(before: end)]) { end = s.index(before: end) }
        return String(s[start..<end])
    }

    // MARK: entity decode (single pass, never fails)

    /// Decode one reference starting at chars[i] == "&"; returns the decoded
    /// string and the index just past ';' — or nil (emit '&' literally).
    private static func decodeReference(_ chars: [Character], _ i: Int) -> (String, Int)? {
        let p = i + 1
        guard p < chars.count else { return nil }
        if chars[p] == "#" { // &#NN; / &#xHH;
            let hex = p + 1 < chars.count && (chars[p + 1] == "x" || chars[p + 1] == "X")
            var d = hex ? p + 2 : p + 1
            let start = d
            while d < chars.count, isAsciiDigit(chars[d])
                || (hex && ((chars[d] >= "a" && chars[d] <= "f") || (chars[d] >= "A" && chars[d] <= "F"))) {
                d += 1
            }
            if d > start, d < chars.count, chars[d] == ";" {
                let body = String(chars[start..<d])
                if let num = Int(body, radix: hex ? 16 : 10) {
                    // Lone surrogates are not valid standalone scalars; keep the ref.
                    if !(0xD800...0xDFFF).contains(num), num <= 0x10FFFF,
                       let scalar = Unicode.Scalar(num) {
                        return (String(scalar), d + 1)
                    }
                }
            }
            return nil
        }
        // &name; — first char a letter, rest letters/digits (TS [A-Za-z][A-Za-z0-9]*).
        if isAsciiLetter(chars[p]) {
            var d = p + 1
            while d < chars.count, isAsciiLetter(chars[d]) || isAsciiDigit(chars[d]) { d += 1 }
            if d < chars.count, chars[d] == ";" {
                if let rep = named[String(chars[p..<d])] { return (rep, d + 1) }
            }
        }
        return nil
    }

    /// Resolve character references in one pass — no double-decode:
    /// "x &amp;lt; y" stays "x &lt; y". Unknown refs pass through.
    private static func decodeEntities(_ s: String) -> String {
        var out = ""
        let chars = Array(s)
        var i = 0
        while i < chars.count {
            let c = chars[i]
            if c == "&", let (rep, next) = decodeReference(chars, i) {
                out += rep
                i = next
                continue
            }
            out.append(c)
            i += 1
        }
        return out
    }

    // MARK: markdown helpers

    private static let mdEscapes: Set<Character> = ["\\", "`", "*", "_", "[", "]"]

    /// Backslash-escape the Markdown-significant \ ` * _ [ ].
    private static func escapeMarkdown(_ s: String) -> String {
        var out = ""
        for c in s {
            if mdEscapes.contains(c) {
                out.append("\\")
            }
            out.append(c)
        }
        return out
    }

    /// Collapse any run of JS whitespace to a single space — the TS
    /// .replace(/\s+/g, ' ') pass (leading/trailing runs become one space).
    private static func collapseWhitespace(_ s: String) -> String {
        var out = ""
        var pendingSpace = false
        for c in s {
            if isJsSpace(c) {
                pendingSpace = true
            } else {
                if pendingSpace {
                    out.append(" ")
                    pendingSpace = false
                }
                out.append(c)
            }
        }
        if pendingSpace {
            out.append(" ")
        }
        return out
    }

    /// Text-node normalization, TS order: escapeMarkdown(decodeHtml(v))
    /// .replace(/\s+/g, ' ').
    private static func normalizeText(_ s: String) -> String {
        collapseWhitespace(escapeMarkdown(s))
    }

    // MARK: parser

    /// Parse into a node forest. Attribute values may be double-quoted,
    /// single-quoted or bare; a quoted value may contain '>'.
    /// Returns (roots, nil) or (nil, "Unclosed tag").
    private static func parseHtml(_ raw: String) -> ([Node]?, String?) {
        var roots: [Node] = []
        var stack: [Node] = []
        let chars = Array(raw)
        // Append sink: the current open element's children, else the roots.
        func sink(_ node: Node) {
            if let last = stack.last {
                last.children.append(node)
            } else {
                roots.append(node)
            }
        }
        var i = 0
        while i < chars.count {
            guard let lt = chars[i...].firstIndex(of: "<") else {
                sink(Node(text: String(chars[i...])))
                break
            }
            if lt > i {
                sink(Node(text: String(chars[i..<lt])))
            }
            // Find the tag's '>', skipping quoted attribute values.
            var j = lt + 1
            var quote: Character?
            while j < chars.count, chars[j] != ">" || quote != nil {
                let c = chars[j]
                if quote == nil, c == "\"" || c == "'" {
                    quote = c
                } else if quote != nil, c == quote {
                    quote = nil
                }
                j += 1
            }
            if j >= chars.count {
                return (nil, unclosedTag)
            }
            let inner = trimJsSpace(String(chars[(lt + 1)..<j]))
            i = j + 1

            if inner.hasPrefix("!--") { continue } // comment
            if inner.hasPrefix("!") { continue } // doctype
            let closing = inner.hasPrefix("/")
            var body = closing ? String(inner.dropFirst()) : inner
            if !closing, body.hasSuffix("/") { body = String(body.dropLast()) }
            // Tag name: ^[a-zA-Z][a-zA-Z0-9-]* (hand-rolled, no regex).
            let bc = Array(body)
            guard let first = bc.first, isAsciiLetter(first) else {
                continue // not a real tag — browsers would show it as text; we drop it
            }
            var nameEnd = 1
            while nameEnd < bc.count,
                  isAsciiLetter(bc[nameEnd]) || isAsciiDigit(bc[nameEnd]) || bc[nameEnd] == "-" {
                nameEnd += 1
            }
            let tag = String(bc[0..<nameEnd]).lowercased()

            if closing {
                if let k = stack.lastIndex(where: { $0.tag == tag }) {
                    stack.removeSubrange(k..<stack.count)
                }
                continue
            }

            let elem = Node(tag: tag)
            // Attributes: ([a-zA-Z-]+)( = (double | single | bare))? — hand-rolled
            // with the same left-to-right resumption as the TS /g regex: the
            // scan continues after the VALUE when one matched, else after the
            // name. 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).
            var p = nameEnd
            while p < bc.count {
                let c = bc[p]
                if isAsciiLetter(c) || c == "-" {
                    var q = p + 1
                    while q < bc.count, isAsciiLetter(bc[q]) || bc[q] == "-" { q += 1 }
                    let attrName = String(bc[p..<q]).lowercased()
                    var r = q
                    while r < bc.count, isJsSpace(bc[r]) { r += 1 }
                    var value: String?
                    if r < bc.count, bc[r] == "=" {
                        r += 1
                        while r < bc.count, isJsSpace(bc[r]) { r += 1 }
                        if r < bc.count {
                            let vc = bc[r]
                            if vc == "\"" || vc == "'" {
                                var e = r + 1
                                while e < bc.count, bc[e] != vc { e += 1 }
                                if e < bc.count { // closing quote — quoted value, quotes included
                                    value = String(bc[r...e])
                                    r = e + 1
                                }
                            }
                            if value == nil { // bare value ([^\s>]+ — '>' is already consumed)
                                var e = r
                                while e < bc.count, !isJsSpace(bc[e]) { e += 1 }
                                value = String(bc[r..<e])
                                r = e
                            }
                        }
                    }
                    if let v = value {
                        elem.attrs[attrName] = v.count >= 2 ? String(v.dropFirst().dropLast()) : ""
                        p = r
                    } else {
                        elem.attrs[attrName] = ""
                        p = q
                    }
                } else {
                    p += 1
                }
            }
            sink(elem)
            if !voidTags.contains(tag), !body.hasSuffix("/") {
                stack.append(elem)
            }
        }
        return (roots, nil)
    }

    private static func isBlock(_ n: Node) -> Bool {
        n.isElem && blockTags.contains(n.tag)
    }

    /// Inline content of one block: marks, links, images, escaped text.
    private static func renderInline(_ nodes: [Node]) -> String {
        var out = ""
        for n in nodes {
            if !n.isElem {
                out += normalizeText(decodeEntities(n.text))
            } else {
                switch n.tag {
                case "br":
                    out += "  \n"
                case "strong", "b":
                    let inner = trimJsSpace(renderInline(n.children))
                    if !inner.isEmpty { out += "**\(inner)**" } // empty emphasis renders as nothing
                case "em", "i":
                    let inner = trimJsSpace(renderInline(n.children))
                    if !inner.isEmpty { out += "*\(inner)*" }
                case "del", "s":
                    let inner = trimJsSpace(renderInline(n.children))
                    if !inner.isEmpty { out += "~~\(inner)~~" }
                case "code":
                    let inner = trimJsSpace(renderInline(n.children))
                    if !inner.isEmpty { out += "`\(inner)`" }
                case "a":
                    let href = decodeEntities(n.attrs["href"] ?? "")
                    let t = n.attrs["title"] ?? ""
                    let title = t.isEmpty ? "" : " \"\(t)\""
                    var label = trimJsSpace(renderInline(n.children))
                    if label.isEmpty { label = href }
                    out += "[\(label)](\(href)\(title))"
                case "img":
                    let alt = trimJsSpace(escapeMarkdown(decodeEntities(n.attrs["alt"] ?? "")))
                    out += "![\(alt)](\(decodeEntities(n.attrs["src"] ?? "")))"
                default:
                    out += renderInline(n.children) // span and unknown tags are transparent
                }
            }
        }
        return out
    }

    /// Concatenate the entity-decoded text under nodes (pre content only).
    private static func textOf(_ nodes: [Node]) -> String {
        var out = ""
        for c in nodes {
            out += c.isElem ? textOf(c.children) : decodeEntities(c.text)
        }
        return out
    }

    /// The language token from a class="language-*" attribute ([\w-]+ run),
    /// hand-rolled first-occurrence scan like the TS regex exec.
    private static func langFromClass(_ cls: String) -> String {
        let marker = Array("language-")
        let cs = Array(cls)
        var start: Int?
        if cs.count >= marker.count {
            scan: for i in 0...(cs.count - marker.count) {
                for k in 0..<marker.count where cs[i + k] != marker[k] {
                    continue scan
                }
                start = i + marker.count
                break
            }
        }
        guard var d = start else { return "" }
        var out = ""
        while d < cs.count, isAsciiLetter(cs[d]) || isAsciiDigit(cs[d]) || cs[d] == "_" || cs[d] == "-" {
            out.append(cs[d])
            d += 1
        }
        return out
    }

    /// Render a sequence of nodes as Markdown blocks.
    private static func renderBlocks(_ nodes: [Node]) -> [String] {
        var out: [String] = []
        var para: [Node] = []
        func flush() {
            if !para.isEmpty {
                let text = trimJsSpace(renderInline(para))
                if !text.isEmpty { out.append(text) }
                para.removeAll()
            }
        }
        for n in nodes {
            if !isBlock(n) {
                para.append(n)
                continue
            }
            flush()
            switch n.tag {
            case "hr":
                out.append("---")
            case "p":
                let text = trimJsSpace(renderInline(n.children))
                if !text.isEmpty { out.append(text) }
            case "div":
                out += renderBlocks(n.children)
            case "blockquote":
                let inner = renderBlocks(n.children).joined(separator: "\n\n")
                out.append(inner.split(separator: "\n", omittingEmptySubsequences: false)
                    .map { $0.isEmpty ? ">" : "> \($0)" }
                    .joined(separator: "\n"))
            case "pre":
                let codeElem = n.children.first { $0.isElem && $0.tag == "code" }
                let lang = codeElem.map { langFromClass($0.attrs["class"] ?? "") } ?? ""
                var body = textOf((codeElem ?? n).children)
                while body.hasSuffix("\n") { body = String(body.dropLast()) }
                out.append("```" + lang + "\n" + body + "\n```")
            case "ul", "ol":
                out.append(renderList(n, 0))
            default: // h1-h6
                let cs = Array(n.tag)
                var level = 0
                if cs.count >= 2, let d = cs[1].wholeNumberValue, cs[1] >= "1", cs[1] <= "6" {
                    level = d
                }
                out.append(String(repeating: "#", count: level) + " "
                    + trimJsSpace(renderInline(n.children)))
            }
        }
        flush()
        return out
    }

    /// ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
    /// numbering restarted per list.
    private static func renderList(_ list: Node, _ depth: Int) -> String {
        let items = list.children.filter { $0.isElem && $0.tag == "li" }
        let ordered = list.tag == "ol"
        var lines: [String] = []
        for (idx, li) in items.enumerated() {
            let marker = ordered ? "\(idx + 1)." : "-"
            let indent = String(repeating: " ", count: depth == 0 ? 0 : (ordered ? 4 : 2))
            // Split li children into inline content + nested lists.
            var inline: [Node] = []
            var nested: [String] = []
            for c in li.children {
                if c.isElem && (c.tag == "ul" || c.tag == "ol") {
                    nested.append(renderList(c, depth + 1))
                } else {
                    inline.append(c)
                }
            }
            let text = trimJsSpace(renderInline(inline))
            lines.append(text.isEmpty ? "\(indent)\(marker)" : "\(indent)\(marker) \(text)")
            lines += nested
        }
        return lines.joined(separator: "\n")
    }

    /// Convert the supported HTML subset to Markdown. Never traps — the
    /// result carries output/error, mirroring HtmlToMarkdownResult.
    static func convert(_ raw: String) -> Result {
        if trimJsSpace(raw).isEmpty { return Result(output: "", error: nil) }
        let (roots, err) = parseHtml(raw)
        if roots == nil {
            return Result(output: "", error: err)
        }
        return Result(output: renderBlocks(roots ?? []).joined(separator: "\n\n"), error: nil)
    }
}

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