gjtorikian/commonmarker
حول
Ruby wrapper for the comrak (CommonMark parser) Rust crate
أدوات التطويرالنمو المقاس للنجوم
- خلال 24 ساعة
- -١
- خلال 7 أيام
- ٠
- خلال 15 يومًا
- +١
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلCommonmarker
Ruby wrapper for Rust's comrak crate.
It uses comrak's defaults out of the box, which comrak documents as compliant with CommonMark. It also offers comrak's extensions to the spec, including the ones in the GitHub Flavored Markdown spec, such as tables, strikethrough, and autolinking.
[!NOTE] Commonmarker's defaults are comrak's: plain CommonMark, with no extensions and no plugins enabled. For GitHub-style output, turn on the GFM extensions and rendering quirks:
Commonmarker.to_html(text, options: { extension: { strikethrough: true, table: true, autolink: true, tasklist: true }, render: { github_pre_lang: true, gfm_quirks: true }, })For more information on the available options and extensions, see the documentation below.
Installation
Add this line to your application's Gemfile:
gem 'commonmarker'
And then execute:
$ bundle
Or install it yourself as:
$ gem install commonmarker
Usage
This gem expects to receive UTF-8 strings. Ensure your strings are the right encoding before passing them into Commonmarker.
Converting to HTML
Call to_html on a string to convert it to HTML:
require 'commonmarker'
Commonmarker.to_html('"Hi *there*"', options: {
parse: { smart: true }
})
# => <p>“Hi <em>there</em>”</p>\n
(The second argument is optional--see below for more information.)
Reusing a configuration
Commonmarker.to_html and Commonmarker.parse process their options and plugins on every call. When you convert many documents with the same settings, build a Commonmarker instance once and call to_html or parse on it instead:
require 'commonmarker'
markdown = Commonmarker.new(options: { parse: { smart: true } }, plugins: { syntax_highlighter: { theme: "InspiredGitHub" } })
markdown.to_html('"Hi *there*"')
# => <p>“Hi <em>there</em>”</p>\n
doc = markdown.parse("*Hello* world")
doc.to_html
# => <p><em>Hello</em> world</p>\n
The options and plugins are validated and processed when the instance is created, so invalid values raise from Commonmarker.new rather than from the first conversion, and changing the hashes afterwards has no effect on the instance. Instances hold no mutable state, so one can live in a constant and be shared across threads. Commonmarker.to_html(text, options: o, plugins: p) is the same as Commonmarker.new(options: o, plugins: p).to_html(text).
to_html and to_commonmark also accept a Commonmarker::Node, so a document you parsed and then modified renders with the same settings without passing them again:
doc = markdown.parse("*Hello* [GitHub](https://www.github.com)")
# Transform links to regular text
doc.walk do |node|
node.replace(node.first_child) if node.type == :link
end
markdown.to_html(doc)
# => <p><em>Hello</em> GitHub</p>\n
markdown.to_commonmark(doc)
# => *Hello* GitHub\n
Node#to_html and Node#to_commonmark keep their own options: and plugins: arguments for one-off renders.
Generating a document
You can also parse a string to receive a :document node. You can then print that node to HTML, iterate over the children, and do other fun node stuff. For example:
require 'commonmarker'
doc = Commonmarker.parse("*Hello* world", options: {
parse: { smart: true }
})
puts(doc.to_html) # => <p><em>Hello</em> world</p>\n
doc.walk do |node|
puts node.type # => [:document, :paragraph, :emph, :text, :text]
end
(The second argument is optional--see below for more information.)
When it comes to modifying the document, you can perform the following operations:
insert_beforeinsert_afterprepend_childappend_childdelete
You can also get the source position of a node by calling source_position:
doc = Commonmarker.parse("*Hello* world")
puts doc.first_child.first_child.source_position
# => {:start_line=>1, :start_column=>1, :end_line=>1, :end_column=>7}
You can also modify the following attributes:
urltitleheader_levellist_typelist_startlist_tightfence_infoalert_type
Example: Walking the AST
You can use walk or each to iterate over nodes:
walkwill iterate on a node and recursively iterate on a node's children.eachwill iterate on a node's direct children, but no further.
require 'commonmarker'
# parse some string
doc = Commonmarker.parse("# The site\n\n [GitHub](https://www.github.com)")
# Walk tree and print out URLs for links
doc.walk do |node|
if node.type == :link
printf("URL = %s\n", node.url)
end
end
# => URL = https://www.github.com
# Transform links to regular text
doc.walk do |node|
if node.type == :link
node.insert_before(node.first_child)
node.delete
end
end
# => <h1>The site</h1>\n<p>GitHub</p>\n
Example: Converting a document back into raw CommonMark
You can use to_commonmark on a node to render it as raw text:
require 'commonmarker'
# parse some string
doc = Commonmarker.parse("# The site\n\n [GitHub](https://www.github.com)")
# Transform links to regular text
doc.walk do |node|
if node.type == :link
node.insert_before(node.first_child)
node.delete
end
end
doc.to_commonmark
# => # The site\n\nGitHub\n
Reading and writing node content
string_content reads and writes the text of nodes whose content is plain text (like :text, :code, and :code_block).
literal reads and writes the raw string a node carries, for every node type that has one (like :text, :code, :code_block, :html_block, :html_inline, :raw, :math, and :frontmatter).
The two exist separately because they mean different things. Rewriting string_content only ever swaps text for text. Rewriting literal on an :html_block, :html_inline, or :raw node writes markup that is emitted unescaped:
doc = Commonmarker.parse("A <b>bold</b> claim")
doc.walk do |node|
node.literal = "<i>" if node.type == :html_inline && node.literal == "<b>"
end
Note that a :frontmatter node's literal includes its delimiters and trailing newlines, so anything you assign must include them too.
Node attributes
With any of the *_attributes extensions enabled, comrak parses Pandoc-style attribute blocks such as {#intro .big data-x=1} off the end of headings, fenced code blocks, inline code, links and images. attributes reads them as a Hash of id, classes and pairs, or nil when a node has none; attributes= replaces them, and accepts nil to clear them:
doc = Commonmarker.parse("## Intro {#intro .big data-x=1}", options: { extension: { header_attributes: true } })
doc.first_child.attributes
# => {id: "intro", classes: ["big"], pairs: {"data-x" => "1"}}
doc.first_child.attributes = { classes: ["lede"], pairs: { "data-x" => "2" } }
Attributes only reach the HTML when the attributes render option is on and unsafe is on, because an attribute block can smuggle in event handlers and the like. If you render untrusted Markdown, leave attributes off and apply an allowlist of the parsed values yourself:
Commonmarker.to_html("## Intro {#intro .big}", options: {
extension: { header_attributes: true, header_ids: nil },
render: { attributes: true, unsafe: true },
})
# => <h2 id="intro" class="big">Intro</h2>
Options and plugins
Options
Commonmarker accepts the same parse, render, and extensions options that comrak does, as a hash dictionary with symbol keys:
Commonmarker.to_html('"Hi *there*"', options: {
parse: { smart: true },
render: { hardbreaks: true }
})
Note that there is a distinction in comrak for "parse" options and "render" options, which are represented in the tables below. The defaults are comrak's. Passing nil for any option means "use the default", which for the string-valued options (default_info_string, header_ids, and front_matter_delimiter) means leaving that feature off.
Parse options
| Name | Description | Default |
|---|---|---|
smart |
Punctuation (quotes, full-stops and hyphens) are converted into 'smart' punctuation. | false |
default_info_string |
The default info string for fenced code blocks. | nil |
relaxed_tasklist_matching |
Enables relaxing of the tasklist extension matching, allowing any non-space to be used for the "checked" state instead of only x and X. |
false |
relaxed_autolinks |
Enable relaxing of the autolink extension parsing, allowing links to be recognized when in brackets, as well as permitting any url scheme. | false |
leave_footnote_definitions |
Allow footnote definitions to remain in their original positions instead of being moved to the document's end (only affects AST) | false |
ignore_setext |
Ignores setext-style headings. | false |
sourcepos_chars |
Use character-based column tracking in source positions instead of byte-based. Relevant for multi-byte UTF-8 documents with sourcepos. |
false |
max_nesting_depth |
The deepest a node may nest below the document. Deeper documents raise Commonmarker::NestingDepthExceededError instead of being parsed. |
1000 |
tasklist_in_table |
Allows a task list item to be the sole content of a table cell. Needs the table and tasklist extensions. |
false |
escaped_char_spans |
Keeps escaped characters as escaped nodes in the AST. Implied by the render option of the same name. |
false |
Render options
| Name | Description | Default |
|---|---|---|
hardbreaks |
Soft line breaks translate into hard line breaks. | false |
github_pre_lang |
GitHub-style <pre lang="xyz"> is used for fenced code blocks with info tags. |
false |
full_info_string |
Gives info string data after a space in a data-meta attribute on code blocks. |
false |
width |
The wrap column when outputting CommonMark. 0 means no wrapping. |
0 |
unsafe |
Allow rendering of raw HTML and potentially dangerous links. | false |
escape |
Escape raw HTML instead of clobbering it. | false |
sourcepos |
Include source position attribute in HTML and XML output. | false |
escaped_char_spans |
Wrap escaped characters in span tags. | false |
ignore_empty_links |
Ignores empty links, leaving the Markdown text in place. | false |
gfm_quirks |
Outputs HTML with GFM-style quirks; namely, not nesting <strong> inlines. |
false |
prefer_fenced |
Always output fenced code blocks, even where an indented one could be used. | false |
tasklist_classes |
Add CSS classes to the HTML output of the tasklist extension | false |
compact_html |
Suppress newlines in pretty-printed HTML output. | false |
alert_style |
The style of alert output: :specific (<div class="markdown-alert">) or :semantic (<aside class="admonition">). |
:specific |
list_style |
The bullet list marker used when outputting CommonMark: :dash (-), :plus (+) or :star (*). |
:dash |
figure_with_caption |
Renders an image that has a title as a <figure>, with the title as its <figcaption>. |
false |
ol_width |
The minimum ordered list marker width when outputting CommonMark. Values below 3 have no effect. | 0 |
experimental_minimize_commonmark |
Drops escapes from CommonMark output when the document still roundtrips without them. Expensive. | false |
attributes |
Writes parsed or assigned node attributes into the HTML. Does nothing without unsafe, since attributes can carry scripts. |
false |
As well, there are several extensions which you can toggle in the same manner:
Commonmarker.to_html('"Hi *there*"', options: {
extension: { footnotes: true, description_lists: true }
})
Extension options
| Name | Description | Default |
|---|---|---|
strikethrough |
Enables the strikethrough extension from the GFM spec. | false |
table |
Enables the table extension from the GFM spec. | false |
autolink |
Enables the autolink extension from the GFM spec. | false |
tasklist |
Enables the task list extension from the GFM spec. | false |
superscript |
Enables the superscript Comrak extension. | false |
header_ids |
Enables the header IDs Comrak extension; the value is prefixed to every generated ID. Pass "" for no prefix. |
nil |
header_id_prefix_in_href |
Also add the prefix to generated href attributes pointing to headers. |
false |
footnotes |
Enables the footnotes extension per cmark-gfm. |
false |
inline_footnotes |
Enables the inline footnotes extension. | false |
description_lists |
Enables the description lists extension. | false |
front_matter_delimiter |
Enables the front matter extension; the value is the delimiter line, such as "---". |
nil |
multiline_block_quotes |
Enables the multiline block quotes extension. | false |
math_dollars, math_code |
Enables the math extension. | false |
math_latex |
Enables the math extension with LaTeX-style delimiters (\(inline\), \[display\]). |
false |
shortcodes |
Enables the shortcodes extension, which turns :smile: and friends into emoji. |
false |
wikilinks_title_before_pipe |
Enables the wikilinks extension, placing the title before the dividing pipe. | false |
wikilinks_title_after_pipe |
Enables the wikilinks extension, placing the title after the dividing pipe. | false |
underline |
Enables the underline extension. | false |
spoiler |
Enables the spoiler extension. | false |
greentext |
Enables the greentext extension. | false |
subtext |
Enables the subtext extension. | false |
subscript |
Enables the subscript extension. | false |
alerts |
Enables the alerts extension. | false |
cjk_friendly_emphasis |
Enables the CJK friendly emphasis extension. | false |
highlight |
Enables highlighting via == |
false |
insert |
Enables the insert extension, rendering ++text++ as <ins>text</ins>. |
false |
block_directive |
Enables the block directive extension. | false |
math_dollars_block |
Enables multiline display math blocks delimited by $$ lines. Requires math_dollars. |
false |
wikilinks_ignore_embeds |
Ignores wikilink-style embeds (![[url]]) when a wikilinks extension is enabled. |
false |
ofm_callouts |
Enables Obsidian-style callouts, such as > [!tip]. |
false |
ofm_comments |
Enables Obsidian-style %%comment%% comments, which are dropped from the output. |
false |
ofm_block_ids |
Enables Obsidian-style block identifiers (^abc123 at the end of a block). |
false |
header_attributes |
Parses {#id .class key=value} attribute blocks at the end of ATX and setext headings. |
false |
fenced_code_attributes |
Parses attribute blocks in the info string of fenced code blocks. | false |
inline_code_attributes |
Parses attribute blocks directly after inline code spans. | false |
link_attributes |
Parses attribute blocks directly after links and images. | false |
For more information on these options, see the comrak documentation.
Plugins
In addition to the possibilities provided by generic CommonMark rendering, Commonmarker also supports plugins as a means of providing further niceties.
Syntax Highlighter Plugin
The syntax highlighter plugin applies syntax highlighting to fenced code blocks that specify a language. Like every plugin, it is disabled by default. Pass an empty Hash to enable it with the default "base16-ocean.dark" theme, or name a theme:
code = <<~CODE
```ruby
def hello
puts "hello"
end
```
CODE
# the default theme
puts Commonmarker.to_html(code, plugins: { syntax_highlighter: {} })
# a theme name from the pre-existing set
puts Commonmarker.to_html(code, plugins: { syntax_highlighter: { theme: "InspiredGitHub" } })
# <pre style="background-color:#ffffff;"><code class="language-ruby"><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">hello
# </span><span style="color:#323232;"> </span><span style="color:#62a35c;">puts </span><span style="color:#183691;">"hello"
# </span><span style="font-weight:bold;color:#a71d5d;">end
# </span></code></pre>
The library comes with a set of pre-existing themes for highlighting code:
"base16-ocean.dark""base16-eighties.dark""base16-mocha.dark""base16-ocean.light""InspiredGitHub""Solarized (dark)""Solarized (light)"
Without the plugin, a fenced code block renders as plain CommonMark HTML. Passing syntax_highlighter: nil has the same effect, which is handy when the plugins Hash is built elsewhere:
Commonmarker.to_html(code)
Commonmarker.to_html(code, plugins: { syntax_highlighter: nil })
# <pre><code class="language-ruby">def hello
# puts "hello"
# end
# </code></pre>
To output CSS classes instead of style attributes, set the theme key to "":
Commonmarker.to_html(code, plugins: { syntax_highlighter: { theme: "" } })
# <pre class="syntax-highlighting"><code class="language-ruby"><span class="source ruby"><span class="meta function ruby"><span class="keyword control def ruby">def</span></span><span class="meta function ruby"> # <span class="entity name function ruby">hello</span></span>
# <span class="support function builtin ruby">puts</span> <span class="string quoted double ruby"><span class="punctuation definition string begin ruby">"</span>hello<span class="punctuation definition string end ruby">"</span></span>
# <span class="keyword control ruby">end</span>\n</span></code></pre>
To use a custom theme, you can provide a path to a directory containing .tmtheme files to load:
Commonmarker.to_html(code, plugins: { syntax_highlighter: { theme: "Monokai", path: "./themes" } })
Syntax highlighters are expensive to build, so Commonmarker builds one per theme/path combination and keeps it for the life of the process. Theme files in a custom path are read the first time that path is used; restart the process to pick up changes to them.
Output formats
Commonmarker can currently only generate output in one format: HTML.
HTML
puts Commonmarker.to_html('*Hello* world!')
# <p><em>Hello</em> world!</p>
Developing locally
After cloning the repo:
script/bootstrap
bundle exec rake compile
If there were no errors, you're done! Otherwise, make sure to follow the comrak dependency instructions.
Benchmarks
❯ bundle exec rake benchmark
input size = 3789 bytes
ruby 3.4.0dev (2024-12-25 master f450108330) +PRISM [arm64-darwin24]
Warming up --------------------------------------
Markly.render_html 11.057k i/100ms
Markly::Node#to_html 10.873k i/100ms
Commonmarker.to_html 24.813k i/100ms
Commonmarker.to_html (no syntax highlighting)
24.243k i/100ms
Commonmarker#to_html 27.063k i/100ms
Commonmarker::Node.to_html
14.214k i/100ms
Kramdown::Document#to_html
3.854k i/100ms
Calculating -------------------------------------
Markly.render_html 109.848k (± 2.8%) i/s (9.10 μs/i) - 552.850k in 5.036926s
Markly::Node#to_html 112.683k (± 3.0%) i/s (8.87 μs/i) - 565.396k in 5.022126s
Commonmarker.to_html 251.737k (± 3.6%) i/s (3.97 μs/i) - 1.265M in 5.033668s
Commonmarker.to_html (no syntax highlighting)
240.071k (± 2.3%) i/s (4.17 μs/i) - 1.212M in 5.051940s
Commonmarker#to_html 273.099k (± 1.1%) i/s (3.66 μs/i) - 1.380M in 5.054553s
Commonmarker::Node.to_html
142.769k (± 2.1%) i/s (7.00 μs/i) - 724.914k in 5.079875s
Kramdown::Document#to_html
37.737k (± 1.4%) i/s (26.50 μs/i) - 188.846k in 5.005327s
Comparison:
Commonmarker#to_html: 273099.4 i/s
Commonmarker.to_html: 251736.9 i/s - 1.08x slower
Commonmarker.to_html (no syntax highlighting): 240070.7 i/s - 1.14x slower
Commonmarker::Node.to_html: 142769.5 i/s - 1.91x slower
Markly::Node#to_html: 112683.0 i/s - 2.42x slower
Markly.render_html: 109848.3 i/s - 2.49x slower
Kramdown::Document#to_html: 37736.6 i/s - 7.24x slower
input size = 3051 bytes
ruby 3.4.0dev (2024-12-25 master f450108330) +PRISM [arm64-darwin24]
Warming up --------------------------------------
Markly.render_html 3.117k i/100ms
Markly::Node#to_html 3.122k i/100ms
Commonmarker.to_html 3.461k i/100ms
Commonmarker.to_html (no syntax highlighting)
3.453k i/100ms
Commonmarker#to_html 3.524k i/100ms
Commonmarker::Node.to_html
1.865k i/100ms
Kramdown::Document#to_html
518.000 i/100ms
Calculating -------------------------------------
Markly.render_html 31.758k (± 4.5%) i/s (31.49 μs/i) - 158.967k in 5.015343s
Markly::Node#to_html 31.760k (± 4.9%) i/s (31.49 μs/i) - 159.222k in 5.024779s
Commonmarker.to_html 35.033k (± 0.9%) i/s (28.54 μs/i) - 176.511k in 5.038807s
Commonmarker.to_html (no syntax highlighting)
34.754k (± 1.0%) i/s (28.77 μs/i) - 176.103k in 5.067574s
Commonmarker#to_html 35.240k (± 1.5%) i/s (28.38 μs/i) - 176.200k in 5.001097s
Commonmarker::Node.to_html
19.716k (± 2.3%) i/s (50.72 μs/i) - 98.845k in 5.016154s
Kramdown::Document#to_html
5.314k (± 0.8%) i/s (188.19 μs/i) - 26.936k in 5.069493s
Comparison:
Commonmarker#to_html: 35240.0 i/s
Commonmarker.to_html: 35033.0 i/s - same-ish: difference falls within error
Commonmarker.to_html (no syntax highlighting): 34754.3 i/s - same-ish: difference falls within error
Markly::Node#to_html: 31759.8 i/s - 1.11x slower
Markly.render_html: 31757.6 i/s - 1.11x slower
Commonmarker::Node.to_html: 19716.0 i/s - 1.79x slower
Kramdown::Document#to_html: 5313.7 i/s - 6.63x slower
input size = 11064832 bytes
ruby 3.4.0dev (2024-12-25 master f450108330) +PRISM [arm64-darwin24]
Warming up --------------------------------------
Markly.render_html 2.000 i/100ms
Markly::Node#to_html 2.000 i/100ms
Commonmarker.to_html 3.000 i/100ms
Commonmarker.to_html (no syntax highlighting)
3.000 i/100ms
Commonmarker#to_html 3.000 i/100ms
Commonmarker::Node.to_html
2.000 i/100ms
Kramdown::Document#to_html
1.000 i/100ms
Calculating -------------------------------------
Markly.render_html 26.830 (± 7.5%) i/s (37.27 ms/i) - 134.000 in 5.035141s
Markly::Node#to_html 25.772 (±11.6%) i/s (38.80 ms/i) - 128.000 in 5.014892s
Commonmarker.to_html 34.650 (± 2.9%) i/s (28.86 ms/i) - 174.000 in 5.024235s
Commonmarker.to_html (no syntax highlighting)
34.140 (± 2.9%) i/s (29.29 ms/i) - 171.000 in 5.013207s
Commonmarker#to_html 34.108 (± 2.9%) i/s (29.32 ms/i) - 171.000 in 5.016186s
Commonmarker::Node.to_html
18.842 (± 5.3%) i/s (53.07 ms/i) - 96.000 in 5.106005s
Kramdown::Document#to_html
6.290 (± 0.0%) i/s (158.97 ms/i) - 32.000 in 5.112588s
Comparison:
Commonmarker.to_html: 34.6 i/s
Commonmarker.to_html (no syntax highlighting): 34.1 i/s - same-ish: difference falls within error
Commonmarker#to_html: 34.1 i/s - same-ish: difference falls within error
Markly.render_html: 26.8 i/s - 1.29x slower
Markly::Node#to_html: 25.8 i/s - 1.34x slower
Commonmarker::Node.to_html: 18.8 i/s - 1.84x slower
Kramdown::Document#to_html: 6.3 i/s - 5.51x slower
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…