All formats

commonmarker

LanguageRuby (native extension in Rust; precompiled gems for common platforms)
LicenseMIT
Repositorygithub.com/gjtorikian/commonmarker
DocumentationREADME
Depends oncomrak (bundled); a Rust toolchain only if no precompiled gem fits your platform
Read / writeparses CommonMark + GFM + comrak extensions; renders HTML and CommonMark

Since version 1.0, commonmarker is a Ruby wrapper of comrak, a Rust implementation of cmark-gfm. It passes the CommonMark spec tests and implements GFM. By default it enables the GFM extensions strikethrough, table, autolink and tasklist, plus emoji shortcodes, and highlights fenced code with the syntax_highlighter plugin (theme base16-ocean.dark).

Options are a hash with parse:, render: and extension: keys, mirroring comrak. Raw HTML is suppressed unless render: { unsafe: true }. Versions 0.x wrapped the C cmark-gfm and had a different API (CommonMarker.render_html); code written for them needs changes.

Installation#

Shell
gem install commonmarker

Or in a Gemfile: gem "commonmarker".

Basic usage: convert Markdown to HTML#

Ruby
require "commonmarker"

markdown = File.read("README.md", encoding: "UTF-8")
html = Commonmarker.to_html(markdown)
File.write("README.html", html)

How to set options and extensions#

Ruby
html = Commonmarker.to_html(markdown, options: {
  parse: { smart: true },                       # curly quotes, dashes
  render: { unsafe: true, hardbreaks: false },  # allow raw HTML (trusted input only)
  extension: { footnotes: true, header_ids: "", front_matter_delimiter: "---" },
})

header_ids: "" adds id attributes to headings with an empty prefix; front_matter_delimiter makes the parser skip YAML front matter.

How to disable syntax highlighting#

Ruby
html = Commonmarker.to_html(markdown, plugins: { syntax_highlighter: nil })
# or pick a theme
html = Commonmarker.to_html(markdown, plugins: { syntax_highlighter: { theme: "InspiredGitHub" } })
Ruby
doc = Commonmarker.parse(markdown)
doc.walk do |node|
  case node.type
  when :heading
    text = +""
    node.walk { |c| text << c.string_content if c.type == :text }
    puts "h#{node.header_level}: #{text}"
  when :link
    puts "link: #{node.url}"
  end
end

How to change the document and render Markdown again#

Ruby
doc = Commonmarker.parse("# Docs\n\nSee [the site](http://example.com).\n")
doc.walk do |node|
  node.url = node.url.sub("http://", "https://") if node.type == :link
end
puts doc.to_commonmark   # Markdown
puts doc.to_html         # HTML

Tips#