commonmarker
| Language | Ruby (native extension in Rust; precompiled gems for common platforms) |
|---|---|
| License | MIT |
| Repository | github.com/gjtorikian/commonmarker |
| Documentation | README |
| Depends on | comrak (bundled); a Rust toolchain only if no precompiled gem fits your platform |
| Read / write | parses 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#
gem install commonmarker
Or in a Gemfile: gem "commonmarker".
Basic usage: convert Markdown to HTML#
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#
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#
html = Commonmarker.to_html(markdown, plugins: { syntax_highlighter: nil })
# or pick a theme
html = Commonmarker.to_html(markdown, plugins: { syntax_highlighter: { theme: "InspiredGitHub" } })
How to list headings and links#
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#
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#
- Input must be UTF-8; convert other encodings with
String#encodefirst. node.source_positionreturns start and end line and column for editors and linters.- Precompiled gems exist for Linux, macOS and Windows; on other platforms installing compiles Rust code.