All formats

kramdown

LanguageRuby
LicenseMIT
Repositorygithub.com/gettalong/kramdown
Documentationkramdown.gettalong.org, syntax, options
Depends onrexml; GFM input needs kramdown-parser-gfm
Read / writeparses kramdown (a Markdown superset), GFM, HTML; converts to HTML, LaTeX, kramdown, man and more

kramdown parses its own Markdown dialect: the original syntax plus tables, fenced code, footnotes, definition lists, abbreviations, math blocks, header IDs and inline attribute lists ({: .class #id}). It’s not CommonMark-compliant. A document is parsed into an element tree and converted by converter classes: to_html, to_latex, to_kramdown, to_man, and (with extra gems) PDF. It also parses HTML, which makes HTML-to-Markdown conversion possible.

Jekyll uses kramdown by default, with the GFM parser (kramdown-parser-gfm) as its input format. Raw HTML passes through.

Installation#

Shell
gem install kramdown kramdown-parser-gfm

Basic usage: convert Markdown to HTML#

Ruby
require "kramdown"

markdown = File.read("README.md", encoding: "UTF-8")
doc = Kramdown::Document.new(markdown, auto_ids: true)
File.write("README.html", doc.to_html)
doc.warnings.each { |w| warn w }

How to parse GitHub Flavored Markdown#

Ruby
require "kramdown"
require "kramdown-parser-gfm"

html = Kramdown::Document.new(markdown, input: "GFM", hard_wrap: false).to_html

How to add a table of contents#

Put a list with the {:toc} marker where the TOC should go:

Ruby
markdown = <<~MD
  * TOC
  {:toc}

  # Install
  ## Linux
  # Usage
MD
puts Kramdown::Document.new(markdown).to_html

How to convert HTML to Markdown#

Ruby
html = "<h1>Title</h1><p>Some <em>text</em> and <a href='https://example.com'>a link</a>.</p>"
puts Kramdown::Document.new(html, input: "html").to_kramdown

How to convert Markdown to LaTeX#

Ruby
latex = Kramdown::Document.new(markdown).to_latex

How to list headings#

Ruby
doc = Kramdown::Document.new(markdown)
headers = []
walk = ->(el) do
  headers << [el.options[:level], el.options[:raw_text]] if el.type == :header
  el.children.each { |c| walk.(c) }
end
walk.(doc.root)
headers.each { |level, text| puts "h#{level}: #{text}" }

Tips#