Skip to content

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

# frozen_string_literal: true

# markdown-to-html — escape-first CommonMark subset → HTML renderer. Ruby 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 raises — errors travel
# in the result hash.

module MarkdownToHtml
  module_function

  HEADING = /\A(\#{1,6}) (.*)\z/
  HR = /\A(---+|\*\*\*+|___+)\s*\z/
  UL = /\A[-*+] /
  OL = /\A\d+\. /
  CODE_SPAN = /`([^`]+)`/
  IMAGE = /!\[([^\]]*)\]\(([^)\s]+)\)/
  LINK = /\[([^\]]+)\]\(([^)\s]+)\)/

  # Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
  # the entities we emit are never re-escaped.
  def encode_html(text)
    text.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')
        .gsub("'", '&apos;').gsub('"', '&quot;')
  end

  # Inline pass: code spans first (placeholder-protected), then images, links,
  # bold, italic, strikethrough — non-greedy pairs.
  def render_inline(s)
    codes = []
    text = s.gsub(CODE_SPAN) do
      codes << "<code>#{encode_html($1)}</code>"
      "\x00#{codes.length - 1}\x00"
    end
    text = encode_html(text)
    text = text.gsub(IMAGE) { "<img src=\"#{$2}\" alt=\"#{$1}\">" }
    text = text.gsub(LINK) { "<a href=\"#{$2}\">#{$1}</a>" }
    text = text.gsub(/\*\*([^*]+)\*\*/) { "<strong>#{$1}</strong>" }
    text = text.gsub(/__([^_]+)__/) { "<strong>#{$1}</strong>" }
    text = text.gsub(/\*([^*]+)\*/) { "<em>#{$1}</em>" }
    text = text.gsub(/_([^_]+)_/) { "<em>#{$1}</em>" }
    text = text.gsub(/~~([^~]+)~~/) { "<del>#{$1}</del>" }
    text.gsub(/\x00(\d+)\x00/) { codes[$1.to_i] }
  end

  # True when a line STARTS a new block — the paragraph terminator. Any new
  # block type must register here and in the render_block dispatch below.
  def block_start?(line)
    HEADING.match?(line) || HR.match?(line) || line.start_with?('```') ||
      line.start_with?('> ') || UL.match?(line) || OL.match?(line)
  end

  # Render consecutive lines (one blank-line-separated chunk).
  def render_block(lines, out)
    i = 0
    while i < lines.length
      line = lines[i]

      heading = HEADING.match(line)
      if heading
        level = heading[1].length
        out << "<h#{level}>#{render_inline(heading[2].strip)}</h#{level}>"
        i += 1
        next
      end

      if HR.match?(line)
        out << '<hr>'
        i += 1
        next
      end

      if line.start_with?('```')
        lang = line[3..].strip
        body = []
        i += 1
        while i < lines.length && !lines[i].start_with?('```')
          body << lines[i]
          i += 1
        end
        i += 1 # past the closing fence (or past the end of an unclosed fence)
        cls = lang.empty? ? '' : " class=\"language-#{encode_html(lang)}\""
        out << "<pre><code#{cls}>#{encode_html(body.join("\n"))}</code></pre>"
        next
      end

      if line.start_with?('> ')
        quoted = []
        while i < lines.length && lines[i].start_with?('> ')
          quoted << lines[i][2..]
          i += 1
        end
        inner = []
        render_block(quoted, inner)
        out << "<blockquote>\n#{inner.join("\n")}\n</blockquote>"
        next
      end

      if UL.match?(line)
        items = []
        while i < lines.length && UL.match?(lines[i])
          items << "<li>#{render_inline(lines[i][2..])}</li>"
          i += 1
        end
        out << "<ul>\n#{items.join("\n")}\n</ul>"
        next
      end

      if OL.match?(line)
        items = []
        while i < lines.length && OL.match?(lines[i])
          m = OL.match(lines[i])
          items << "<li>#{render_inline(lines[i][m[0].length..])}</li>"
          i += 1
        end
        out << "<ol>\n#{items.join("\n")}\n</ol>"
        next
      end

      para = []
      while i < lines.length && !block_start?(lines[i])
        para << render_inline(lines[i].strip)
        i += 1
      end
      out << "<p>#{para.join("\n")}</p>"
    end
  end

  # Convert the supported Markdown subset to HTML. Never fails.
  def markdown_to_html(raw)
    text = raw.gsub(/\r\n?/, "\n").strip
    return { output: '', error: nil } if text.empty? # NOT an error

    out = []
    text.split(/\n{2,}/).each do |block|
      render_block(block.split("\n").reject { |l| l.strip.empty? }, out)
    end
    { output: out.join("\n"), error: nil }
  end
end

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