HTML to Markdown Converter — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package htmltomarkdown is the Go twin of CosmoDev's src/lib/html-to-markdown.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// html-to-markdown_test.go share vectors with src/lib/html-to-markdown.test.ts
// so the two implementations are held to the same contract.
//
// Pipeline mirrors the TS lib exactly: a hand-rolled single-scan parser (no DOM)
// turns the supported HTML subset into a node forest — tags, quoted strings and
// comments are told apart in one pass, quoted attribute values may contain '>',
// void tags never open, stray closers are ignored, unclosed tags at EOF
// auto-close, and tag names that do not start with a letter are dropped — then
// a renderer emits Markdown blocks: h1-h6, strong/em/del/code with empty
// emphasis as nothing, links with verbatim titles and entity-decoded hrefs,
// images with entity-decoded alt/src, ul/ol with 2-space (ul) and 4-space (ol)
// nested indent and numbering restarted per list, blockquote line prefixing
// ("> " on text lines, ">" on blank ones), fenced pre with the language taken
// from class="language-*", hr, and br as two-spaces-newline. Text nodes are
// entity-decoded via the stdlib WHATWG table (full coverage, single pass, no
// double-decode; U+00A0 normalized to a plain space) and backslash-escape
// \ ` * _ [ ] so literal characters cannot masquerade as Markdown. The one
// error is an unclosed tag literal (a '<' with no closing '>').
package htmltomarkdown
import (
"errors"
"html"
"regexp"
"strconv"
"strings"
)
// Result mirrors HtmlToMarkdownResult in the TS lib. On success Output is set
// and Error is empty (TS: error: null); on failure Output is empty and Error
// holds the message. Empty or whitespace-only input is NOT an error — the tool
// shows nothing.
type Result struct {
Output string
Error string
}
// errUnclosedTag is the one error the converter can produce, matching the TS
// literal 'Unclosed tag'.
var errUnclosedTag = errors.New("Unclosed tag")
// node is one node of the parsed forest: a text node (isElem false, text set)
// or an element (isElem true, tag/attrs/children set).
type node struct {
text string
tag string
attrs map[string]string
children []*node
isElem bool
}
// VOID in the TS lib — tags that never open a scope.
var voidTags = map[string]bool{
"br": true, "hr": true, "img": true, "meta": true,
"link": true, "input": true, "source": true,
}
// BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.
var blockTags = map[string]bool{
"p": true, "div": true, "blockquote": true, "pre": true,
"ul": true, "ol": true, "hr": true,
"h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true,
}
var (
tagNameRe = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9-]*)`)
attrRe = regexp.MustCompile(`([a-zA-Z-]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?`)
langClassRe = regexp.MustCompile(`language-([\w-]+)`)
mdEscapeRe = regexp.MustCompile("[\\\\`*_\\[\\]]")
// JS \s + \v + the unicode spaces JS \s covers (\s in Go is [\t\n\f\r ]).
wsRunRe = regexp.MustCompile(`[\s\v\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}]+`)
)
// decodeEntities resolves character references in one pass via the stdlib
// WHATWG table (html.UnescapeString) — the Go counterpart of the TS lib's
// decodeHtml (./htmlEntities): full named coverage plus numeric decimal/hex,
// single pass, no double-decode ("x &lt; y" stays "x < y"). Unknown or
// malformed references pass through untouched; decoding never panics.
func decodeEntities(s string) string {
return html.UnescapeString(s)
}
// escapeMarkdown backslash-escapes the Markdown-significant characters
// \ ` * _ [ ] — mirrors /[\\`*_[\]]/g in the TS lib.
func escapeMarkdown(s string) string {
return mdEscapeRe.ReplaceAllStringFunc(s, func(m string) string {
return "\\" + m
})
}
// collapseWhitespace collapses any run of whitespace to a single space —
// mirrors .replace(/\s+/g, ' ') in the TS lib.
func collapseWhitespace(s string) string {
return wsRunRe.ReplaceAllString(s, " ")
}
// parseHtml parses raw into a node forest. Attribute values may be
// double-quoted, single-quoted or bare; a quoted value may contain '>'.
// The error return is errUnclosedTag when a '<' has no closing '>'.
func parseHtml(raw string) ([]*node, error) {
roots := []*node{}
var stack []*node
appendTop := func(n *node) {
if len(stack) > 0 {
top := stack[len(stack)-1]
top.children = append(top.children, n)
} else {
roots = append(roots, n)
}
}
i := 0
for i < len(raw) {
lt := strings.IndexByte(raw[i:], '<')
if lt == -1 {
appendTop(&node{text: raw[i:]})
break
}
lt += i
if lt > i {
appendTop(&node{text: raw[i:lt]})
}
// Find the tag's '>', skipping quoted attribute values.
j := lt + 1
var quote byte
for j < len(raw) && (raw[j] != '>' || quote != 0) {
if quote == 0 && (raw[j] == '"' || raw[j] == '\'') {
quote = raw[j]
} else if quote != 0 && raw[j] == quote {
quote = 0
}
j++
}
if j >= len(raw) {
return nil, errUnclosedTag
}
inner := strings.TrimSpace(raw[lt+1 : j])
i = j + 1
if strings.HasPrefix(inner, "!--") {
continue // comment
}
if strings.HasPrefix(inner, "!") {
continue // doctype
}
closing := strings.HasPrefix(inner, "/")
body := inner
if closing {
body = inner[1:]
} else {
body = strings.TrimSuffix(body, "/")
}
nameMatch := tagNameRe.FindStringSubmatch(body)
if nameMatch == nil {
continue // not a real tag — browsers would show it as text; we drop it
}
tag := strings.ToLower(nameMatch[1])
if closing {
for k := len(stack) - 1; k >= 0; k-- {
if stack[k].tag == tag {
stack = stack[:k]
break
}
}
continue
}
attrs := map[string]string{}
for _, am := range attrRe.FindAllStringSubmatch(body, -1) {
// Values stay RAW here; href/src/alt are entity-decoded at use,
// titles stay verbatim so a '"' inside a title cannot break the
// Markdown link. The quote-strip mirrors am[2].slice(1, -1) in the
// TS lib: quoted values lose their quotes, bare values lose their
// first and last characters (same quirk, kept for lock-step).
val := ""
if len(am[2]) >= 2 {
val = am[2][1 : len(am[2])-1]
}
attrs[strings.ToLower(am[1])] = val
}
elem := &node{tag: tag, attrs: attrs, isElem: true}
appendTop(elem)
if !voidTags[tag] && !strings.HasSuffix(body, "/") {
stack = append(stack, elem)
}
}
return roots, nil
}
// renderInline renders the inline content of one block: marks, links, images,
// escaped text.
func renderInline(nodes []*node) string {
var b strings.Builder
for _, n := range nodes {
if !n.isElem {
// Normalization for TS parity: the TS twin's \s+ whitespace pass
// also collapses U+00A0 (JS \s matches it), while Go's \s does
// not — so replace it explicitly right after unescaping, before
// the existing whitespace collapse.
text := strings.ReplaceAll(decodeEntities(n.text), " ", " ")
b.WriteString(collapseWhitespace(escapeMarkdown(text)))
continue
}
switch n.tag {
case "br":
b.WriteString(" \n")
case "strong", "b":
if inner := strings.TrimSpace(renderInline(n.children)); inner != "" {
b.WriteString("**" + inner + "**") // empty emphasis renders as nothing
}
case "em", "i":
if inner := strings.TrimSpace(renderInline(n.children)); inner != "" {
b.WriteString("*" + inner + "*")
}
case "del", "s":
if inner := strings.TrimSpace(renderInline(n.children)); inner != "" {
b.WriteString("~~" + inner + "~~")
}
case "code":
if inner := strings.TrimSpace(renderInline(n.children)); inner != "" {
b.WriteString("`" + inner + "`")
}
case "a":
href := decodeEntities(n.attrs["href"])
title := ""
if n.attrs["title"] != "" {
title = " \"" + n.attrs["title"] + "\""
}
label := strings.TrimSpace(renderInline(n.children))
if label == "" {
label = href
}
b.WriteString("[" + label + "](" + href + title + ")")
case "img":
alt := strings.TrimSpace(escapeMarkdown(decodeEntities(n.attrs["alt"])))
b.WriteString(" + ")")
default:
b.WriteString(renderInline(n.children)) // span and unknown tags are transparent
}
}
return b.String()
}
// isBlock reports whether n is a block-level element.
func isBlock(n *node) bool {
return n.isElem && blockTags[n.tag]
}
// textOf concatenates the entity-decoded text under nodes (pre content only).
func textOf(nodes []*node) string {
var b strings.Builder
for _, c := range nodes {
if c.isElem {
b.WriteString(textOf(c.children))
} else {
b.WriteString(decodeEntities(c.text))
}
}
return b.String()
}
// renderBlocks renders a sequence of nodes as Markdown blocks.
func renderBlocks(nodes []*node) []string {
var out []string
var para []*node
flush := func() {
if len(para) > 0 {
if text := strings.TrimSpace(renderInline(para)); text != "" {
out = append(out, text)
}
para = nil
}
}
for _, n := range nodes {
if !isBlock(n) {
para = append(para, n)
continue
}
flush()
switch n.tag {
case "hr":
out = append(out, "---")
case "p":
if text := strings.TrimSpace(renderInline(n.children)); text != "" {
out = append(out, text)
}
case "div":
out = append(out, renderBlocks(n.children)...)
case "blockquote":
inner := strings.Join(renderBlocks(n.children), "\n\n")
var lines []string
for _, l := range strings.Split(inner, "\n") {
if l != "" {
lines = append(lines, "> "+l)
} else {
lines = append(lines, ">")
}
}
out = append(out, strings.Join(lines, "\n"))
case "pre":
var codeElem *node
for _, c := range n.children {
if c.isElem && c.tag == "code" {
codeElem = c
break
}
}
lang := ""
if codeElem != nil {
if lm := langClassRe.FindStringSubmatch(codeElem.attrs["class"]); lm != nil {
lang = lm[1]
}
}
children := n.children
if codeElem != nil {
children = codeElem.children
}
body := strings.TrimRight(textOf(children), "\n")
out = append(out, "```"+lang+"\n"+body+"\n```")
case "ul", "ol":
out = append(out, renderList(n, 0))
default:
level := 0
if len(n.tag) >= 2 && n.tag[1] >= '1' && n.tag[1] <= '6' {
level = int(n.tag[1] - '0')
}
out = append(out, strings.Repeat("#", level)+" "+strings.TrimSpace(renderInline(n.children)))
}
}
flush()
return out
}
// renderList renders a ul/ol at the given nesting depth: 2-space indent under
// ul, 4-space under ol, numbering restarted per list.
func renderList(list *node, depth int) string {
var items []*node
for _, c := range list.children {
if c.isElem && c.tag == "li" {
items = append(items, c)
}
}
ordered := list.tag == "ol"
var lines []string
for idx, li := range items {
marker := "-"
if ordered {
marker = strconv.Itoa(idx+1) + "."
}
indentLen := 0
if depth != 0 {
if ordered {
indentLen = 4
} else {
indentLen = 2
}
}
indent := strings.Repeat(" ", indentLen)
// Split li children into inline content + nested lists.
var inline []*node
var nested []string
for _, c := range li.children {
if c.isElem && (c.tag == "ul" || c.tag == "ol") {
nested = append(nested, renderList(c, depth+1))
} else {
inline = append(inline, c)
}
}
if text := strings.TrimSpace(renderInline(inline)); text != "" {
lines = append(lines, indent+marker+" "+text)
} else {
lines = append(lines, indent+marker)
}
lines = append(lines, nested...)
}
return strings.Join(lines, "\n")
}
// HtmlToMarkdown converts the supported HTML subset to Markdown. It is the Go
// twin of htmlToMarkdown() in src/lib/html-to-markdown.ts and must agree with
// it on every shared vector.
func HtmlToMarkdown(raw string) Result {
if strings.TrimSpace(raw) == "" {
return Result{}
}
roots, err := parseHtml(raw)
if err != nil {
return Result{Error: err.Error()}
}
return Result{Output: strings.Join(renderBlocks(roots), "\n\n")}
}
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 →