Debian Codegraph @

README.md

raw
1 # [Comrak](https://comrak.ee/)
2
3 [![Build status](https://github.com/kivikakk/comrak/actions/workflows/rust.yml/badge.svg)](https://github.com/kivikakk/comrak/actions/workflows/rust.yml)
4 [![CommonMark: 652/652](https://img.shields.io/badge/commonmark-652%2F652-brightgreen.svg)](https://github.com/commonmark/commonmark-spec/blob/9103e341a973013013bb1a80e13567007c5cef6f/spec.txt)
5 [![GFM: 670/670](https://img.shields.io/badge/gfm-670%2F670-brightgreen.svg)](https://github.com/kivikakk/cmark-gfm/blob/2f13eeedfe9906c72a1843b03552550af7bee29a/test/spec.txt)
6 [![crates.io version](https://img.shields.io/crates/v/comrak.svg)](https://crates.io/crates/comrak)
7 [![docs.rs](https://docs.rs/comrak/badge.svg)](https://docs.rs/comrak)
8 [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/11796/badge)](https://www.bestpractices.dev/projects/11796)
9
10 [Comrak](https://comrak.ee/) is a [CommonMark](https://commonmark.org/) and [GitHub Flavored Markdown](https://github.github.com/gfm/) compatible parser and renderer, written in Rust.
11
12 Compliant with [CommonMark 0.31.2](https://spec.commonmark.org/0.31.2/) by default.
13
14 ## Installation
15
16 Specify it as a requirement in `Cargo.toml`:
17
18 ```toml
19 [dependencies]
20 comrak = "0.54"
21 ```
22
23 Comrak's library supports Rust <span class="msrv">1.85</span>+.
24
25 ### CLI
26
27 - Anywhere with a Rust toolchain:
28 - `cargo install comrak`
29 - <code>[cargo binstall](https://github.com/cargo-bins/cargo-binstall) comrak</code>
30 - Many Unix distributions:
31 - `pacman -S comrak`
32 - `brew install comrak`
33 - `dnf install comrak`
34 - `nix run nixpkgs#comrak`
35 - Windows:
36 - <code>[scoop](https://scoop.sh/) install comrak</code>
37
38 You can also find builds I've published in [GitHub Releases](https://github.com/kivikakk/comrak/releases), but they're limited to machines I have access to at the time of making them! [webinstall.dev](https://webinstall.dev/comrak/) offers `curl | shell`-style installation of the latest of these for your OS, including Windows.
39
40 ## Usage
41
42 <details>
43
44 <summary>Click to expand the CLI <code>--help</code> output.
45
46 ```console
47 $ comrak --help
48 ```
49
50 </summary>
51
52 ```
53 A 100% CommonMark-compatible GitHub Flavored Markdown parser and formatter
54
55 Usage: comrak [OPTIONS] [FILE]...
56
57 Arguments:
58 [FILE]...
59 CommonMark file(s) to parse; or standard input if none passed
60
61 Options:
62 -c, --config-file <PATH>
63 Path to config file containing command-line arguments, or 'none'
64
65 [default: /home/runner/.config/comrak/config]
66
67 -i, --inplace
68 Reformat CommonMark files in-place
69
70 --hardbreaks
71 Treat newlines as hard line breaks
72
73 --smart
74 Replace punctuation like "this" with smart punctuation like “this”
75
76 --github-pre-lang
77 Use GitHub-style "<pre lang>" for code blocks
78
79 --full-info-string
80 Include words following the code block info string in a data-meta attribute
81
82 --gfm
83 Enable GitHub-flavored markdown extensions: strikethrough, tagfilter, table, autolink, and
84 tasklist. Also enables --github-pre-lang and --gfm-quirks
85
86 --gfm-quirks
87 Use GFM-style quirks in output HTML, such as not nesting <strong> tags, which otherwise
88 breaks CommonMark compatibility
89
90 --relaxed-tasklist-character
91 Permit any character inside a tasklist item, not just " ", "x" or "X"
92
93 --relaxed-autolinks
94 Relax autolink parsing: allows links to be recognised when in brackets, permits all URL
95 schemes, and permits domains without a TLD (like "http://localhost")
96
97 --tasklist-classes
98 Include "task-list-item" and "task-list-item-checkbox" classes on
99
100 --default-info-string <INFO>
101 Default value for fenced code block's info strings if none is given
102
103 --unsafe
104 Allow inline and block HTML (unless --escape is given), and permit
105
106 --gemoji
107 Translate gemoji like ":thumbsup:" into Unicode emoji like "👍"
108
109 --escape
110 Escape raw HTML, instead of clobbering it; takes precedence over --unsafe
111
112 --escaped-char-spans
113 Wrap escaped Markdown characters in "<span data-escaped-char>" in HTML
114
115 -e, --extension <EXTENSION>
116 Specify extensions to use
117
118 Multiple extensions can be delimited with ",", e.g. '--extension strikethrough,table', or
119 you can pass --extension/-e multiple times
120
121 [possible values: strikethrough, tagfilter, table, autolink, tasklist, superscript,
122 footnotes, inline-footnotes, description-lists, multiline-block-quotes, math-dollars,
123 math-latex, math-code, wikilinks-title-after-pipe, wikilinks-title-before-pipe, underline,
124 subscript, spoiler, greentext, alerts, cjk-friendly-emphasis, subtext, highlight, insert,
125 phoenix-heex, block-directive, header-attributes, fenced-code-attributes,
126 inline-code-attributes, link-attributes]
127
128 -t, --to <FORMAT>
129 Specify output format
130
131 [default: html]
132 [possible values: html, xml, commonmark]
133
134 -o, --output <FILE>
135 Write output to FILE instead of stdout
136
137 --width <WIDTH>
138 Specify wrap width for output CommonMark, or '0' to disable wrapping
139
140 [default: 0]
141
142 --header-id-prefix <PREFIX>
143 Use the Comrak header IDs extension, with the given ID prefix
144
145 --header-id-prefix-in-href
146 Apply the header ID prefix to the href anchor as well
147
148 --front-matter-delimiter <DELIMITER>
149 Detect frontmatter that starts and ends with the given string, and do not include it in
150 the resulting document
151
152 --syntax-highlighting <THEME>
153 Syntax highlighting for fenced code blocks; 'css' for CSS classes (default), a theme name
154 for inline styles, or 'none' to disable
155
156 [default: css]
157
158 --list-style <LIST_STYLE>
159 Specify bullet character for lists ("-", "+", "*") in CommonMark output
160
161 [default: dash]
162 [possible values: dash, plus, star]
163
164 --alert-style <ALERT_STYLE>
165 Specify alert style (<div> vs <aside>) in HTML output
166
167 [default: specific]
168 [possible values: specific, semantic]
169
170 --sourcepos
171 Include source position attributes in HTML and XML output
172
173 --ignore-setext
174 Do not parse setext headers
175
176 --ignore-empty-links
177 Do not parse empty links
178
179 --sourcepos-chars
180 Report column positions in sourcepos as a Unicode character count rather than UTF-8 byte
181 offsets
182
183 --experimental-minimize-commonmark
184 Minimise escapes in CommonMark output using a trial-and-error algorithm
185
186 --compact
187 Suppress pretty-printing newlines between block-level HTML elements
188
189 -h, --help
190 Print help (see a summary with '-h')
191
192 -V, --version
193 Print version
194
195 By default, Comrak will attempt to read command-line options from a config file specified by
196 --config-file. This behaviour can be disabled by passing --config-file none. It is not an error if
197 the file does not exist.
198 ```
199
200 </details>
201
202 And there's a Rust interface. You can use `comrak::markdown_to_html` directly:
203
204 ```rust
205 use comrak::{markdown_to_html, Options};
206 assert_eq!(
207 markdown_to_html("¡Olá, **世界**!", &Options::default()),
208 "<p>¡Olá, <strong>世界</strong>!</p>\n"
209 );
210 ```
211
212 Or you can parse the input into an AST yourself, manipulate it, and then use your desired formatter:
213
214 ```rust
215 use comrak::nodes::NodeValue;
216 use comrak::{format_html, parse_document, Arena, Options};
217
218 fn replace_text(document: &str, orig_string: &str, replacement: &str) -> String {
219 // The returned nodes are created in the supplied Arena, and are bound by its lifetime.
220 let arena = Arena::new();
221
222 // Parse the document into a root `AstNode`
223 let root = parse_document(&arena, document, &Options::default());
224
225 // Iterate over all the descendants of root.
226 for node in root.descendants() {
227 if let NodeValue::Text(ref mut text) = node.data_mut().value {
228 // If the node is a text node, perform the string replacement.
229 *text = text.to_mut().replace(orig_string, replacement).into()
230 }
231 }
232
233 let mut html = String::new();
234 format_html(root, &Options::default(), &mut html).unwrap();
235
236 html
237 }
238
239 fn main() {
240 let doc = "Hello, pretty world!\n\n1. Do you like [pretty](#) paintings?\n2. Or *pretty* music?\n";
241 let orig = "pretty";
242 let repl = "beautiful";
243 let html = replace_text(doc, orig, repl);
244
245 println!("{}", html);
246 // Output:
247 //
248 // <p>Hello, beautiful world!</p>
249 // <ol>
250 // <li>Do you like <a href="#">beautiful</a> paintings?</li>
251 // <li>Or <em>beautiful</em> music?</li>
252 // </ol>
253 }
254 ```
255
256 For a slightly more real-world example, see how I [generate my GitHub user README](https://github.com/kivikakk/kivikakk) from a base document with embedded YAML, which itself has embedded Markdown, or
257 [check out some of Comrak's dependents on crates.io](https://crates.io/crates/comrak/reverse_dependencies) or [on GitHub](https://github.com/kivikakk/comrak/network/dependents).
258
259 ## Security
260
261 As with [`cmark`](https://github.com/commonmark/cmark) and [`cmark-gfm`](https://github.com/github/cmark-gfm#security),
262 Comrak will scrub raw HTML and potentially dangerous links. This change was introduced in Comrak 0.4.0 in support of a
263 safe-by-default posture, and later adopted by our contemporaries. :)
264
265 To allow these, use the `r#unsafe` option (or `--unsafe` with the command line program). If doing so, we recommend the
266 use of a sanitisation library like [`ammonia`](https://github.com/notriddle/ammonia) configured specific to your needs.
267
268 ## Extensions
269
270 Comrak supports the five extensions to CommonMark defined in the [GitHub Flavored Markdown
271 Spec](https://github.github.com/gfm/):
272
273 - [Tables](https://github.github.com/gfm/#tables-extension-)
274 - [Task list items](https://github.github.com/gfm/#task-list-items-extension-)
275 - [Strikethrough](https://github.github.com/gfm/#strikethrough-extension-)
276 - [Autolinks](https://github.github.com/gfm/#autolinks-extension-)
277 - [Disallowed Raw HTML](https://github.github.com/gfm/#disallowed-raw-html-extension-)
278
279 Comrak additionally supports its own extensions, which are yet to be specced out (PRs welcome!):
280
281 - Superscript
282 - Header IDs
283 - Footnotes
284 - Inline footnotes
285 - Description lists
286 - Front matter
287 - Multi-line blockquotes
288 - Math
289 - Emoji shortcodes
290 - Wikilinks
291 - Underline
292 - Spoiler text
293 - "Greentext"
294 - Alerts
295 - [CJK friendly emphasis](https://github.com/tats-u/markdown-cjk-friendly)
296
297 By default none are enabled; they are individually enabled with each parse by setting the appropriate values in the
298 [`options::Extension` struct](https://docs.rs/comrak/latest/comrak/options/struct.Extension.html).
299
300 ## Custom formatting
301
302 The default HTML formatter can be partially specialised, to
303 allow customising the output for certain node types without
304 having to reimplement a whole formatter. See the docs for
305 [`comrak::create_formatter`](https://docs.rs/comrak/latest/comrak/macro.create_formatter.html)
306 for details.
307
308 ## Plugins
309
310 ### Fenced code block syntax highlighting
311
312 You can provide your own syntax highlighting engine.
313
314 Create an implementation of the `SyntaxHighlighterAdapter` trait, and then provide an instance of such adapter to
315 `Plugins.render.codefence_syntax_highlighter`. For formatting a Markdown document with plugins, use the
316 `markdown_to_html_with_plugins` function, which accepts your plugins object as a parameter.
317
318 See the `syntax_highlighter.rs` and `syntect.rs` examples for more details.
319
320 #### Syntect
321
322 [`syntect`](https://github.com/trishume/syntect) is a syntax highlighting library for Rust. By default, `comrak` offers
323 a plugin for it. In order to utilize it, create an instance of `plugins::syntect::SyntectAdapter` and use it in your
324 `Plugins` option.
325
326 ## Related projects
327
328 Comrak's original design goal was to model the upstream
329 [`cmark-gfm`](https://github.com/github/cmark-gfm) as closely as possible in
330 terms of code structure. Many years have passed since its inception, and the codebases
331 have since grown considerably apart. It does remain the case, though, that there
332 are bugs in `cmark-gfm` that are likely in Comrak too, as a result.
333
334 Over the years, we have increasingly opted to fix such bugs, rather than
335 maintain upstream compatibility at all costs. `cmark-gfm` no longer appears to
336 be under active maintenance, but Comrak is a living and growing project.
337
338 This library offers an AST backed by
339 [`typed_arena`](https://github.com/thomcc/rust-typed-arena), with extensive
340 use of `RefCell` in the core node type to provide mutable access with
341 parent/sibling/child pointers. This can produce non-idiomatic-looking code,
342 though in practice it has proven very usable.
343
344 For whatever reason, Comrak may not meet your requirements. Here are some
345 projects and resources to also consider:
346
347 - [Raph Levien](https://github.com/raphlinus)'s [`pulldown-cmark`](https://github.com/google/pulldown-cmark). It's
348 very fast, uses a novel parsing algorithm, and doesn't construct an AST (but you can use it to make one if you
349 want). `cargo doc` uses this, as do many other projects in the ecosystem.
350 - [markdown-rs](https://github.com/wooorm/markdown-rs) looks really promising.
351 - [markdown-it](https://github.com/markdown-it-rust/markdown-it) is a port of JavaScript's [markdown-it.js](https://github.com/markdown-it/markdown-it).
352 - [babelmark](https://babelmark.github.io/) lets you compare many implementations at once, including the above.
353 - Know of another library? Please open a PR to add it!
354
355 ### Bindings
356
357 - [Commonmarker](https://github.com/gjtorikian/commonmarker) — Ruby bindings for this library built with Magnus/rb-sys.
358 Available on RubyGems as [`commonmarker`](https://rubygems.org/gems/commonmarker).
359 - [MDEx](https://github.com/leandrocp/mdex) — Elixir bindings for this library built with Rustler.
360 Available on Hex as [`mdex`](https://hex.pm/packages/mdex).
361 - [comrak](https://github.com/lmmx/comrak) — Python bindings for this library built with PyO3.
362 Available on PyPI as [`comrak`](https://pypi.org/project/comrak), benchmarked at 15-60x faster than pure Python alternatives.
363 - [comrak-ext](https://github.com/Martin005/comrak-ext) — Python bindings; fork of `comrak` with additional APIs exposed, including the AST.
364 Available on PyPI as [`comrak-ext`](https://pypi.org/project/comrak-ext).
365 - [comrak-wasm](https://github.com/nberlette/comrak-wasm) — TypeScript bindings for this library, built with WebAssembly.
366 Available on JSR as [`@nick/comrak`](https://jsr.io/@nick/comrak).
367
368 ### Users
369
370 Comrak is used in a few Rust-y places, and more beyond:
371
372 - [crates.io](https://crates.io), [docs.rs](https://docs.rs) and [lib.rs](https://lib.rs) use Comrak to render README Markdown faithfully.
373 - [GitLab](https://gitlab.com) uses Comrak to render Markdown documents, issues, comments, and more.
374 - [Deno](https://deno.com) uses Comrak to render documentation in [`deno_doc`](https://github.com/denoland/deno_doc).
375 - [Reddit](https://reddit.com)'s new-style site uses a Comrak fork[^reddit].
376 - [Lockbook](https://lockbook.net/) is a Markdown-based secure notebook with native apps. It looks really neat!!
377 - [many](https://github.com/kivikakk/comrak/network/dependents) [more!](https://crates.io/crates/comrak/reverse_dependencies)
378
379 I'd be really happy to add your site or app here, just open a PR or issue. :)
380
381 [^reddit]: And they contributed some really nice changes, years back. Then management went and sold their user base and all their credibility. What can you do.
382
383 ## Benchmarking
384
385 We offer some tools to perform stdin-to-stdout benchmarking of Comrak with its contemporaries. In this respect, Comrak is not and will not be the fastest: some alternatives do not construct an AST in this scenario.
386
387 You'll need to [install hyperfine](https://github.com/sharkdp/hyperfine#installation), and CMake if you want to compare against `cmark-gfm`.
388
389 If you want to just run the benchmark for the `comrak` binary itself, run:
390
391 ```bash
392 make bench-comrak
393 ```
394
395 This will build Comrak in release mode, and run benchmark on it. You will see the time measurements as reported by hyperfine in the console.
396
397 The `Makefile` also provides a way to run benchmarks for `comrak` current state (with your changes), `comrak` main branch, [`cmark-gfm`](https://github.com/github/cmark-gfm), [`pulldown-cmark`](https://github.com/raphlinus/pulldown-cmark) and [`markdown-it.rs`](https://github.com/rlidwka/markdown-it.rs). You'll need CMake, and ensure [submodules are prepared](https://stackoverflow.com/a/10168693/499609).
398
399 ```bash
400 make bench-all
401 ```
402
403 This will build and run benchmarks across all, and report the time taken by each as well as relative time.
404
405 <!-- XXX: The following isn't really true at the moment, due to https://github.com/kivikakk/comrak/issues/339 -->
406
407 <!-- Apart from this, CI is also setup for running benchmarks when a pull request is first opened. It will add a comment with the results on the pull request in a tabular format comparing the 5 versions. After that you can manually trigger this CI by commenting `/run-bench` on the PR, this will update the existing comment with new results. Note benchmarks won't be automatically run on each push. -->
408
409 ## Contributing
410
411 Contributions are **highly encouraged**; if you'd like to assist, consider checking out the [`good first issue` label](https://github.com/kivikakk/comrak/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)! I'm happy to help provide direction and guidance throughout, even if (especially if!) you're new to Rust or open source.
412
413 Where possible I practice [Optimistic Merging](http://hintjens.com/blog:106) as described by Peter Hintjens. Please keep the [code of conduct](CODE_OF_CONDUCT.md) in mind too.
414
415 Thank you to Comrak's many contributors for PRs and issues opened!
416
417 ### Vulnerabilities
418
419 Please report security issues to the author at <<[email protected]>>. If you
420 have a GitHub account, you are welcome to use its interface to [privately report
421 security issues](https://github.com/kivikakk/comrak/security/advisories/new).
422
423 ### Policy on LLM contributions
424
425 This policy is based on and inspired by [Servo's AI contributions policy](https://book.servo.org/contributing/getting-started.html#ai-contributions) ([permalink](https://archive.is/7LLb2#ai-contributions)) and [QEMU's Use of AI-generated content policy](https://github.com/qemu/qemu/blob/667e1fff878326c35c7f5146072e60a63a9a41c8/docs/devel/code-provenance.rst#use-of-ai-generated-content). Please see those links for a more detailed analysis.
426
427 Contributions must not include content generated by large language models or other probabilistic tools, including but not limited to Copilot or ChatGPT. This policy covers code, documentation, pull requests, issues, comments, and any other contributions to Comrak.
428
429 ## Contributors
430
431 [![Small chart showing Comrak contributors.](https://opencollective.com/comrak/contributors.svg?width=890&button=false)](https://github.com/kivikakk/comrak/graphs/contributors)
432
433 ## Contact
434
435 Asherah Connor <<[email protected]>>
436
437 ## Legal
438
439 Copyright (c) 2017–2026, Comrak contributors. Licensed under
440 the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause).
441
442 `cmark` itself is is copyright (c) 2014, John MacFarlane.
443
444 See [COPYING](COPYING) for all the details.