Skip to content

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

# =============================================================================
#  html-to-markdown.rb — supported HTML subset → Markdown converter
# -----------------------------------------------------------------------------
#  Language : Ruby (3.x, standard library only)
#  Source:   CosmoDev polyglot showcase port of the `html-to-markdown` tool,
#            ported from src/lib/html-to-markdown.ts (the canonical TypeScript
#            lib); Go CLI twin: cli/html-to-markdown/html-to-markdown.go
#  License  : display source — part of CosmoDev's polyglot tool pages
# -----------------------------------------------------------------------------
#  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 ("Unclosed tag").
#
#  Entity decode: Ruby's stdlib CGI.unescapeHTML only knows five named
#  entities (no &nbsp;/&copy;), so it is NOT the shared WHATWG-table
#  equivalent and this port hand-rolls the fallback instead: 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").
# =============================================================================

module HtmlToMarkdown
  VOID = %w[br hr img meta link input source].freeze
  BLOCK_TAGS = %w[p div blockquote pre ul ol hr h1 h2 h3 h4 h5 h6].freeze

  # Six named entities + numeric references; unknown names pass through whole.
  NAMED = { 'amp' => '&', 'lt' => '<', 'gt' => '>', 'quot' => '"',
            'apos' => "'", 'nbsp' => " " }.freeze
  ENTITY_RE = /&(#[xX][0-9a-fA-F]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/.freeze
  TAG_NAME_RE = /\A([a-zA-Z][a-zA-Z0-9-]*)/.freeze
  ATTR_RE = /([a-zA-Z-]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?/.freeze
  LANG_CLASS_RE = /language-([\w-]+)/.freeze
  MD_ESCAPE_RE = /[\\`*_\[\]]/.freeze
  # JS \s covers more than Ruby's ASCII \s — NBSP etc. named explicitly.
  WS_RUN_RE = /[\s   - 

   ]+/.freeze

  # One forest node: text (tag nil) or element.
  Node = Struct.new(:tag, :attrs, :children, :text, keyword_init: true)

  module_function

  def decode_entities(s)
    s.gsub(ENTITY_RE) do |whole|
      body = Regexp.last_match(1)
      if body.start_with?('#')
        hex = body[1] == 'x' || body[1] == 'X'
        num = hex ? body[2..].to_i(16) : body[1..].to_i
        if (num >= 0xD800 && num <= 0xDFFF) || num > 0x10FFFF || num.negative?
          whole # lone surrogate / out of range — keep the reference
        else
          [num].pack('U')
        end
      else
        NAMED.fetch(body, whole)
      end
    end
  end

  def escape_markdown(s)
    s.gsub(MD_ESCAPE_RE) { |m| "\\#{m}" }
  end

  # Parse into a node forest. Attribute values may be double-quoted,
  # single-quoted or bare; a quoted value may contain '>'. Returns
  # [nodes, nil] or [nil, 'Unclosed tag'].
  def parse_html(raw)
    roots = []
    stack = []
    top = -> { stack.empty? ? roots : stack.last.children }
    i = 0
    while i < raw.length
      lt = raw.index('<', i)
      if lt.nil?
        top.call << Node.new(tag: nil, text: raw[i..])
        break
      end
      top.call << Node.new(tag: nil, text: raw[i...lt]) if lt > i
      # Find the tag's '>', skipping quoted attribute values.
      j = lt + 1
      quote = nil
      while j < raw.length && (raw[j] != '>' || !quote.nil?)
        if quote.nil? && (raw[j] == '"' || raw[j] == "'")
          quote = raw[j]
        elsif !quote.nil? && raw[j] == quote
          quote = nil
        end
        j += 1
      end
      return [nil, 'Unclosed tag'] if j >= raw.length

      inner = raw[(lt + 1)...j].strip
      i = j + 1

      next if inner.start_with?('!--') # comment
      next if inner.start_with?('!')   # doctype
      closing = inner.start_with?('/')
      body = closing ? inner[1..] : inner.sub(/\/\z/, '')
      name = TAG_NAME_RE.match(body)
      next unless name # not a real tag — browsers would show it as text; we drop it
      tag = name[1].downcase

      if closing
        (stack.length - 1).downto(0) do |k|
          if stack[k].tag == tag
            stack.slice!(k..)
            break
          end
        end
        next
      end

      attrs = {}
      body.scan(ATTR_RE) do |aname, val|
        # 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).
        attrs[aname.downcase] = val ? (val.length >= 2 ? val[1..-2] : '') : ''
      end
      elem = Node.new(tag: tag, attrs: attrs, children: [])
      top.call << elem
      stack << elem unless VOID.include?(tag) || body.end_with?('/')
    end
    [roots, nil]
  end

  def block_tag?(n)
    !n.tag.nil? && BLOCK_TAGS.include?(n.tag)
  end

  # Inline content of one block: marks, links, images, escaped text.
  def render_inline(nodes)
    nodes.filter_map do |n|
      if n.tag.nil?
        WS_RUN_RE.gsub(' ', escape_markdown(decode_entities(n.text)))
      else
        case n.tag
        when 'br'
          "  \n"
        when 'strong', 'b'
          inner = render_inline(n.children).strip
          inner.empty? ? nil : "**#{inner}**" # empty emphasis renders as nothing
        when 'em', 'i'
          inner = render_inline(n.children).strip
          inner.empty? ? nil : "*#{inner}*"
        when 'del', 's'
          inner = render_inline(n.children).strip
          inner.empty? ? nil : "~~#{inner}~~"
        when 'code'
          inner = render_inline(n.children).strip
          inner.empty? ? nil : "`#{inner}`"
        when 'a'
          href = decode_entities(n.attrs['href'].to_s)
          t = n.attrs['title'].to_s
          title = t.empty? ? '' : " \"#{t}\""
          label = render_inline(n.children).strip
          label = href if label.empty?
          "[#{label}](#{href}#{title})"
        when 'img'
          alt = escape_markdown(decode_entities(n.attrs['alt'].to_s)).strip
          "![#{alt}](#{decode_entities(n.attrs['src'].to_s)})"
        else
          render_inline(n.children) # span and unknown tags are transparent
        end
      end
    end.join
  end

  # Concatenate the entity-decoded text under nodes (pre content only).
  def text_of(nodes)
    nodes.map { |c| c.tag.nil? ? decode_entities(c.text) : text_of(c.children) }.join
  end

  # Render a sequence of nodes as Markdown blocks.
  def render_blocks(nodes)
    out = []
    para = []
    flush = lambda do
      unless para.empty?
        text = render_inline(para).strip
        out << text unless text.empty?
        para = []
      end
    end
    nodes.each do |n|
      unless block_tag?(n)
        para << n
        next
      end
      flush.call
      case n.tag
      when 'hr'
        out << '---'
      when 'p'
        text = render_inline(n.children).strip
        out << text unless text.empty?
      when 'div'
        out.concat(render_blocks(n.children))
      when 'blockquote'
        inner = render_blocks(n.children).join("\n\n")
        out << inner.split("\n", -1).map { |l| l.empty? ? '>' : "> #{l}" }.join("\n")
      when 'pre'
        code_elem = n.children.find { |c| c.tag == 'code' }
        lang = code_elem ? LANG_CLASS_RE.match(code_elem.attrs['class'].to_s)&.[](1).to_s : ''
        body = text_of((code_elem || n).children).sub(/\n+\z/, '')
        out << "```#{lang}\n#{body}\n```"
      when 'ul', 'ol'
        out << render_list(n, 0)
      else # h1-h6
        level = n.tag[1] && n.tag[1] >= '1' && n.tag[1] <= '6' ? n.tag[1].to_i : 0
        out << ('#' * level) + ' ' + render_inline(n.children).strip
      end
    end
    flush.call
    out
  end

  # ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
  # numbering restarted per list.
  def render_list(list, depth)
    items = list.children.select { |c| c.tag == 'li' }
    ordered = list.tag == 'ol'
    lines = []
    items.each_with_index do |li, idx|
      marker = ordered ? "#{idx + 1}." : '-'
      indent = ' ' * (depth.zero? ? 0 : (ordered ? 4 : 2))
      # Split li children into inline content + nested lists.
      inline = []
      nested = []
      li.children.each do |c|
        if c.tag == 'ul' || c.tag == 'ol'
          nested << render_list(c, depth + 1)
        else
          inline << c
        end
      end
      text = render_inline(inline).strip
      lines << (text.empty? ? "#{indent}#{marker}" : "#{indent}#{marker} #{text}")
      lines.concat(nested)
    end
    lines.join("\n")
  end

  # Convert the supported HTML subset to Markdown. Never raises — the result
  # hash carries output/error, mirroring HtmlToMarkdownResult. Empty or
  # whitespace-only input is NOT an error — the tool shows nothing.
  def convert(raw)
    return { output: '', error: nil } if raw.strip.empty?

    nodes, err = parse_html(raw)
    return { output: '', error: err } if err

    { output: render_blocks(nodes).join("\n\n"), error: nil }
  end
end

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