commonmarker 2.10.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/UPGRADING.md ADDED
@@ -0,0 +1,102 @@
1
+ # Upgrading Commonmarker
2
+
3
+ ## Upgrading from 2.x
4
+
5
+ Commonmarker 3.0 changes what a bare `Commonmarker.to_html(text)` produces and turns `Commonmarker` into a class. Each change is described below along with what to do about it.
6
+
7
+ ### The defaults are now comrak's
8
+
9
+ Previously, Commonmarker enabled a handful of options and the syntax highlighter by default, so `Commonmarker.to_html(text)` with no options produced GitHub-comment-style HTML.
10
+
11
+ 3.0 uses comrak's own defaults instead: plain CommonMark, with no extensions and no plugins. Comrak documents these defaults as compliant with [CommonMark 0.31.2](https://spec.commonmark.org/0.31.2/). Everything in this table is now off unless you turn it on:
12
+
13
+ | Option | 2.x default | 3.0 default |
14
+ | ------------------------------------------------------------- | -------------------------------- | ----------------- |
15
+ | `extension: { strikethrough:, table:, autolink:, tasklist: }` | `true` | `false` |
16
+ | `extension: { shortcodes: }` | `true` | `false` |
17
+ | `extension: { header_ids: }` | `""` (on, with no prefix) | `nil` (off) |
18
+ | `render: { hardbreaks: }` | `true` | `false` |
19
+ | `render: { github_pre_lang: }` | `true` | `false` |
20
+ | `render: { escaped_char_spans: }` | `true` | `false` |
21
+ | `render: { width: }` | `80` | `0` (no wrapping) |
22
+ | `plugins: { syntax_highlighter: }` | `{ theme: "base16-ocean.dark" }` | `nil` (off) |
23
+
24
+ The visible effects are:
25
+
26
+ - Soft line breaks stay soft. A newline inside a paragraph no longer becomes `<br />`.
27
+ - Headings have no `id` attribute and no anchor link.
28
+ - Fenced code blocks render as `<pre><code class="language-ruby">` instead of `<pre lang="ruby">`, and are not syntax highlighted.
29
+ - `~~strikethrough~~`, tables, bare URLs, `- [ ]` task lists, and `:emoji:` shortcodes render as literal text.
30
+ - `to_commonmark` no longer wraps lines at 80 columns.
31
+
32
+ **To get the 2.x output back**, pass the old defaults explicitly. If you convert many documents, build one `Commonmarker` instance with them (see the next section) rather than passing them on every call:
33
+
34
+ ```ruby
35
+ OPTIONS = {
36
+ render: { hardbreaks: true, github_pre_lang: true, width: 80, escaped_char_spans: true },
37
+ extension: { strikethrough: true, table: true, autolink: true, tasklist: true, shortcodes: true, header_ids: "" },
38
+ }.freeze
39
+ PLUGINS = { syntax_highlighter: { theme: "base16-ocean.dark" } }.freeze
40
+
41
+ Commonmarker.to_html(text, options: OPTIONS, plugins: PLUGINS)
42
+ ```
43
+
44
+ **For GitHub Flavored Markdown**, enable what comrak's own `--gfm` flag enables:
45
+
46
+ ```ruby
47
+ Commonmarker.to_html(text, options: {
48
+ extension: { strikethrough: true, table: true, autolink: true, tasklist: true },
49
+ render: { github_pre_lang: true, gfm_quirks: true },
50
+ })
51
+ ```
52
+
53
+ Two smaller consequences of the new defaults:
54
+
55
+ - `nil` now always means "the default". In 2.x, `render: { hardbreaks: nil }` gave comrak's default (`false`) while leaving the key out gave Commonmarker's (`true`). Those are now the same thing, for every option.
56
+ - `Commonmarker::Config::OPTIONS` reports the new defaults, with `nil` for the string options that are off (`default_info_string`, `header_ids`, `front_matter_delimiter`), and `Commonmarker::Config::PLUGINS` is `{ syntax_highlighter: nil }`. Both are snapshots for introspection; passing them back in changes nothing.
57
+
58
+ ### `Commonmarker` is a class
59
+
60
+ `Commonmarker` was a module. It is now a class, so that `Commonmarker.new(options:, plugins:)` can validate a configuration once and reuse it across calls and threads:
61
+
62
+ ```ruby
63
+ MARKDOWN = Commonmarker.new(options: { parse: { smart: true } }, plugins: { syntax_highlighter: {} })
64
+
65
+ MARKDOWN.to_html(text)
66
+ MARKDOWN.to_commonmark(text)
67
+ MARKDOWN.parse(text)
68
+ ```
69
+
70
+ `Commonmarker.to_html`, `Commonmarker.parse`, and `Node#to_html` keep working as before. What breaks:
71
+
72
+ - `module Commonmarker ... end` raises `TypeError` when the file loads. Reopen it with `class Commonmarker` instead.
73
+ - `include Commonmarker` and `extend Commonmarker` no longer work. Call `Commonmarker.to_html` directly.
74
+
75
+ ### `alert_style` and `list_style` take Symbols
76
+
77
+ Both pick from a fixed set of names, and now take a Symbol like option keys, node types, and list types do everywhere else in the API:
78
+
79
+ ```ruby
80
+ Commonmarker.to_html(md, options: { render: { alert_style: :semantic } }) # was "semantic"
81
+ doc.to_commonmark(options: { render: { list_style: :plus } }) # was "plus"
82
+ ```
83
+
84
+ - A String raises `TypeError`: ``render option `:list_style` must be Symbol; got String``.
85
+ - An unknown name raises `ArgumentError` instead of silently falling back to the default: ``render option `:list_style` must be one of :dash, :plus, :star; got :bullet``.
86
+ - `Commonmarker::Config::OPTIONS` reports these defaults as `:specific` and `:dash`.
87
+
88
+ Free-form string options (`header_ids`, `front_matter_delimiter`, `default_info_string`, and the highlighter `theme`) still take Strings.
89
+
90
+ ### Options are processed in Rust
91
+
92
+ Option and plugin handling moved out of Ruby, which removed some Ruby-side internals:
93
+
94
+ - `Commonmarker::Config.process_options` and `Commonmarker::Config.process_plugins` are gone. Pass your Hash to `Commonmarker.new`, which validates it up front.
95
+ - `Commonmarker::Utils` and `Commonmarker::Constants` are gone.
96
+ - `Commonmarker::Config::OPTIONS` no longer has a `:format` key.
97
+
98
+ Validation still raises `TypeError` for a value of the wrong type. A value of the right type that is not allowed (an unknown theme, a negative width, an unknown `list_style`) raises `ArgumentError`.
99
+
100
+ ### comrak 1.x output changes
101
+
102
+ 3.0 is built on comrak 1.2, where 2.x used 0.56. Comrak 1.0 formally specified footnotes, math, superscript and subscript, description lists, header IDs, wikilinks, alerts, tables, autolinks, and task lists, and each spec changed output in edge cases. Among them: duplicate footnote definitions follow first-wins, empty headings get a `-1` id, and lists, footnote definitions, and fenced containers stop nesting at 100 levels. If you snapshot-test HTML output, expect some diffs. [Comrak's changelog](https://github.com/kivikakk/comrak/blob/main/CHANGELOG.md) has the full list.
@@ -2,7 +2,7 @@
2
2
  name = "commonmarker"
3
3
  version = "1.0.0"
4
4
  edition = "2021"
5
- rust-version = "1.75.0"
5
+ rust-version = "1.89.0"
6
6
  publish = false
7
7
 
8
8
  [dependencies]
@@ -20,7 +20,8 @@ syntect = { version = "5.3", default-features = false, features = [
20
20
 
21
21
  # Everywhere except Windows: Oniguruma, the faster engine.
22
22
  [target.'cfg(not(windows))'.dependencies]
23
- comrak = { version = "0.56", default-features = false, features = [
23
+ comrak = { version = "1.2", default-features = false, features = [
24
+ "attributes",
24
25
  "shortcodes",
25
26
  "syntect-onig",
26
27
  ] }
@@ -29,7 +30,8 @@ comrak = { version = "0.56", default-features = false, features = [
29
30
  # linking a second copy (onig_sys) collides at link time and segfaults (xref #467).
30
31
  # syntect-fancy swaps in the pure-Rust fancy-regex backend instead.
31
32
  [target.'cfg(windows)'.dependencies]
32
- comrak = { version = "0.56", default-features = false, features = [
33
+ comrak = { version = "1.2", default-features = false, features = [
34
+ "attributes",
33
35
  "shortcodes",
34
36
  "syntect-fancy",
35
37
  ] }
@@ -1,178 +1,270 @@
1
1
  extern crate core;
2
2
 
3
- use std::fmt::{self, Write};
3
+ use std::fmt;
4
+ use std::sync::{Arc, OnceLock};
4
5
 
6
+ use comrak::html::{self, ChildRendering, Context};
5
7
  use comrak::parse_document;
6
- use magnus::{function, scan_args, RHash, RString, Ruby, Value};
8
+ use comrak::plugins::syntect::SyntectAdapter;
9
+ use comrak::Node;
10
+ use magnus::{method, Class, Module, RString, Ruby, Value};
7
11
  use node::CommonmarkerNode;
8
12
  use plugins::syntax_highlighting::construct_syntax_highlighter_from_plugin;
13
+ use plugins::{comrak_plugins, format_plugins};
9
14
 
15
+ mod nesting;
10
16
  mod options;
11
-
12
17
  mod plugins;
18
+ mod rctree;
19
+ mod utils;
13
20
 
14
21
  use rb_allocator::ruby_global_allocator;
15
22
  use typed_arena::Arena;
16
23
 
17
- use crate::options::{iterate_extension_options, iterate_parse_options, iterate_render_options};
24
+ use crate::options::{default_options_to_hash, format_options, Options};
25
+ use crate::plugins::default_plugins_to_hash;
18
26
 
19
- mod nesting;
20
27
  mod node;
21
- mod rctree;
22
- mod utils;
23
28
 
24
29
  pub const EMPTY_STR: &str = "";
25
30
 
26
31
  // Inform Ruby's GC about memory allocations.
27
32
  ruby_global_allocator!();
28
33
 
29
- /// A writer that writes directly to a Ruby String, avoiding intermediate Rust allocations.
30
- struct RStringWriter(RString);
31
-
32
- impl Write for RStringWriter {
33
- fn write_str(&mut self, s: &str) -> fmt::Result {
34
- self.0.cat(s);
35
- Ok(())
36
- }
37
- }
38
-
39
- fn commonmark_parse(ruby: &Ruby, args: &[Value]) -> Result<CommonmarkerNode, magnus::Error> {
40
- let args = scan_args::scan_args::<_, (), (), (), _, ()>(args)?;
41
- let (rb_commonmark,): (RString,) = args.required;
42
-
34
+ /// Borrows the CommonMark text as `&str`, rejecting invalid UTF-8.
35
+ fn commonmark_str<'a>(ruby: &Ruby, rb_commonmark: &'a RString) -> Result<&'a str, magnus::Error> {
43
36
  // SAFETY: We hold the GVL and rb_commonmark won't be modified until we return
44
- let commonmark_str = unsafe {
37
+ unsafe {
45
38
  rb_commonmark.as_str().map_err(|e| {
46
39
  magnus::Error::new(
47
40
  ruby.exception_encoding_error(),
48
- format!("invalid UTF-8: {}", e),
41
+ format!("invalid UTF-8: {e}"),
49
42
  )
50
- })?
51
- };
52
-
53
- let kwargs = scan_args::get_kwargs::<_, (), (Option<RHash>, Option<RHash>, Option<RHash>), ()>(
54
- args.keywords,
55
- &[],
56
- &["parse", "render", "extension"],
57
- )?;
58
- let (rb_parse, rb_render, rb_extension) = kwargs.optional;
59
-
60
- let max_nesting_depth = nesting::max_nesting_depth(ruby, rb_parse)?;
43
+ })
44
+ }
45
+ }
61
46
 
62
- let mut comrak_parse_options = comrak::options::Parse::default();
63
- let mut comrak_render_options = comrak::options::Render::default();
64
- let mut comrak_extension_options = comrak::options::Extension::default();
47
+ /// Tracks the maximum nesting depth during rendering, replacing a separate
48
+ /// O(N) tree traversal with depth tracking inside the formatter. If `exceeded`
49
+ /// is set, the document is too deeply nested and the partial output is discarded.
50
+ struct DepthState {
51
+ depth: usize,
52
+ max_depth: usize,
53
+ exceeded: bool,
54
+ }
65
55
 
66
- if let Some(rb_parse) = rb_parse {
67
- iterate_parse_options(&mut comrak_parse_options, rb_parse);
68
- }
69
- if let Some(rb_render) = rb_render {
70
- iterate_render_options(&mut comrak_render_options, rb_render);
71
- }
72
- if let Some(rb_extension) = rb_extension {
73
- iterate_extension_options(&mut comrak_extension_options, rb_extension);
56
+ /// Formatter that tracks nesting depth and delegates to comrak's default
57
+ /// formatter. Combines the nesting check with the render, eliminating a
58
+ /// separate tree traversal. Checks before incrementing (matching nesting::check).
59
+ fn format_node_with_depth_check(
60
+ context: &mut Context<DepthState>,
61
+ node: Node<'_>,
62
+ entering: bool,
63
+ ) -> Result<ChildRendering, fmt::Error> {
64
+ if entering {
65
+ if context.user.depth > context.user.max_depth {
66
+ context.user.exceeded = true;
67
+ }
68
+ context.user.depth += 1;
69
+ } else {
70
+ context.user.depth -= 1;
74
71
  }
72
+ html::format_node_default(context, node, entering)
73
+ }
75
74
 
76
- let comrak_options = comrak::Options {
77
- parse: comrak_parse_options,
78
- render: comrak_render_options,
79
- extension: comrak_extension_options,
80
- };
75
+ /// Everything a `Commonmarker` instance needs to parse and render, processed
76
+ /// once from the Ruby `options` and `plugins` hashes.
77
+ struct Config {
78
+ options: Options,
79
+ syntax_highlighter: Option<Arc<SyntectAdapter>>,
80
+ }
81
81
 
82
- let arena = Arena::new();
83
- let root = parse_document(&arena, commonmark_str, &comrak_options);
82
+ impl Config {
83
+ fn plugins(&self) -> comrak::options::Plugins<'_> {
84
+ comrak_plugins(self.syntax_highlighter.as_deref())
85
+ }
86
+ }
84
87
 
85
- CommonmarkerNode::new_from_comrak_node(ruby, root, max_nesting_depth)
88
+ /// The Rust side of a `Commonmarker` instance.
89
+ ///
90
+ /// Ruby allocates it empty and `initialize` fills it through `commonmark_init`,
91
+ /// so the configuration is validated once and every later `parse`/`to_html`
92
+ /// call reuses it. It holds no Ruby objects, so there is nothing to mark.
93
+ #[derive(Default)]
94
+ #[magnus::wrap(class = "Commonmarker", free_immediately, size)]
95
+ struct Commonmarker {
96
+ config: OnceLock<Config>,
86
97
  }
87
98
 
88
- fn commonmark_to_html(ruby: &Ruby, args: &[Value]) -> Result<RString, magnus::Error> {
89
- let args = scan_args::scan_args::<_, (), (), (), _, ()>(args)?;
90
- let (rb_commonmark,): (RString,) = args.required;
99
+ impl Commonmarker {
100
+ /// `Commonmarker#commonmark_init(options, plugins)`, called from `initialize`.
101
+ fn init(
102
+ ruby: &Ruby,
103
+ rb_self: &Self,
104
+ rb_options: Value,
105
+ rb_plugins: Value,
106
+ ) -> Result<(), magnus::Error> {
107
+ let options = format_options(ruby, Some(rb_options))?;
108
+ let formatted_plugins = format_plugins(ruby, Some(rb_plugins))?;
109
+ let syntax_highlighter = construct_syntax_highlighter_from_plugin(ruby, formatted_plugins)?;
110
+
111
+ rb_self
112
+ .config
113
+ .set(Config {
114
+ options,
115
+ syntax_highlighter,
116
+ })
117
+ .map_err(|_| {
118
+ magnus::Error::new(
119
+ ruby.exception_runtime_error(),
120
+ "Commonmarker instance is already initialized",
121
+ )
122
+ })
123
+ }
91
124
 
92
- // SAFETY: We hold the GVL and rb_commonmark won't be modified until we return
93
- let commonmark_str = unsafe {
94
- rb_commonmark.as_str().map_err(|e| {
125
+ fn config(&self, ruby: &Ruby) -> Result<&Config, magnus::Error> {
126
+ self.config.get().ok_or_else(|| {
95
127
  magnus::Error::new(
96
- ruby.exception_encoding_error(),
97
- format!("invalid UTF-8: {}", e),
128
+ ruby.exception_runtime_error(),
129
+ "Commonmarker instance was not initialized; create it with Commonmarker.new",
98
130
  )
99
- })?
100
- };
101
-
102
- let kwargs = scan_args::get_kwargs::<
103
- _,
104
- (),
105
- (Option<RHash>, Option<RHash>, Option<RHash>, Option<RHash>),
106
- (),
107
- >(
108
- args.keywords,
109
- &[],
110
- &["render", "parse", "extension", "plugins"],
111
- )?;
112
- let (rb_render, rb_parse, rb_extension, rb_plugins) = kwargs.optional;
131
+ })
132
+ }
113
133
 
114
- let max_nesting_depth = nesting::max_nesting_depth(ruby, rb_parse)?;
134
+ /// `Commonmarker#commonmark_parse(text)`.
135
+ fn parse(
136
+ ruby: &Ruby,
137
+ rb_self: &Self,
138
+ rb_commonmark: RString,
139
+ ) -> Result<CommonmarkerNode, magnus::Error> {
140
+ let config = rb_self.config(ruby)?;
141
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
115
142
 
116
- let mut comrak_parse_options = comrak::options::Parse::default();
117
- let mut comrak_render_options = comrak::options::Render::default();
118
- let mut comrak_extension_options = comrak::options::Extension::default();
143
+ let arena = Arena::new();
144
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
119
145
 
120
- if let Some(rb_parse) = rb_parse {
121
- iterate_parse_options(&mut comrak_parse_options, rb_parse);
122
- }
123
- if let Some(rb_render) = rb_render {
124
- iterate_render_options(&mut comrak_render_options, rb_render);
125
- }
126
- if let Some(rb_extension) = rb_extension {
127
- iterate_extension_options(&mut comrak_extension_options, rb_extension);
146
+ CommonmarkerNode::new_from_comrak_node(ruby, root, config.options.max_nesting_depth)
128
147
  }
129
148
 
130
- let mut comrak_plugins = comrak::options::Plugins::default();
131
-
132
- let syntect_adapter = match construct_syntax_highlighter_from_plugin(ruby, rb_plugins) {
133
- Ok(Some(adapter)) => Some(adapter),
134
- Ok(None) => None,
135
- Err(err) => return Err(err),
136
- };
149
+ /// `Commonmarker#commonmark_to_html(text)`.
150
+ fn to_html(
151
+ ruby: &Ruby,
152
+ rb_self: &Self,
153
+ rb_commonmark: RString,
154
+ ) -> Result<RString, magnus::Error> {
155
+ let config = rb_self.config(ruby)?;
156
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
157
+
158
+ let arena = Arena::new();
159
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
160
+
161
+ // Render and track nesting depth in one pass, eliminating a separate
162
+ // O(N) tree traversal for the nesting check.
163
+ let mut buffer = String::with_capacity(commonmark_str.len() * 2);
164
+ let depth_state = html::format_document_with_formatter(
165
+ root,
166
+ &config.options.comrak,
167
+ &mut buffer,
168
+ &config.plugins(),
169
+ format_node_with_depth_check,
170
+ DepthState {
171
+ depth: 0,
172
+ max_depth: config.options.max_nesting_depth,
173
+ exceeded: false,
174
+ },
175
+ )
176
+ .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
137
177
 
138
- match syntect_adapter {
139
- Some(ref adapter) => {
140
- comrak_plugins.render.codefence_syntax_highlighter = Some(adapter.as_ref())
178
+ if depth_state.exceeded {
179
+ return Err(nesting::exceeded_error(
180
+ ruby,
181
+ config.options.max_nesting_depth,
182
+ ));
141
183
  }
142
- None => comrak_plugins.render.codefence_syntax_highlighter = None,
184
+
185
+ Ok(ruby.str_new(&buffer))
143
186
  }
144
187
 
145
- let comrak_options = comrak::Options {
146
- parse: comrak_parse_options,
147
- render: comrak_render_options,
148
- extension: comrak_extension_options,
149
- };
188
+ /// `Commonmarker#commonmark_to_commonmark(text)`: parses the text and
189
+ /// writes it back out as CommonMark.
190
+ fn to_commonmark(
191
+ ruby: &Ruby,
192
+ rb_self: &Self,
193
+ rb_commonmark: RString,
194
+ ) -> Result<RString, magnus::Error> {
195
+ let config = rb_self.config(ruby)?;
196
+ let commonmark_str = commonmark_str(ruby, &rb_commonmark)?;
197
+
198
+ let arena = Arena::new();
199
+ let root = parse_document(&arena, commonmark_str, &config.options.comrak);
200
+
201
+ nesting::check(ruby, root, config.options.max_nesting_depth)?;
202
+
203
+ let mut buffer = String::with_capacity(commonmark_str.len());
204
+ comrak::format_commonmark_with_plugins(
205
+ root,
206
+ &config.options.comrak,
207
+ &mut buffer,
208
+ &config.plugins(),
209
+ )
210
+ .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
150
211
 
151
- // Pre-allocate Ruby string with estimated capacity (assume HTML is typically 2x commonmark size)
152
- let output = ruby.str_with_capacity(commonmark_str.len() * 2);
153
- let mut writer = RStringWriter(output);
212
+ Ok(ruby.str_new(&buffer))
213
+ }
154
214
 
155
- // Parse and render directly to Ruby string, avoiding intermediate Rust String allocation
156
- let arena = Arena::new();
157
- let root = parse_document(&arena, commonmark_str, &comrak_options);
215
+ /// `Commonmarker#commonmark_render_html(node)`.
216
+ fn render_html(
217
+ ruby: &Ruby,
218
+ rb_self: &Self,
219
+ node: &CommonmarkerNode,
220
+ ) -> Result<String, magnus::Error> {
221
+ let config = rb_self.config(ruby)?;
158
222
 
159
- nesting::check(ruby, root, max_nesting_depth)?;
223
+ node.render_html(ruby, &config.options, &config.plugins())
224
+ }
160
225
 
161
- comrak::html::format_document_with_plugins(root, &comrak_options, &mut writer, &comrak_plugins)
162
- .map_err(|e| magnus::Error::new(ruby.exception_runtime_error(), e.to_string()))?;
226
+ /// `Commonmarker#commonmark_render_commonmark(node)`.
227
+ fn render_commonmark(
228
+ ruby: &Ruby,
229
+ rb_self: &Self,
230
+ node: &CommonmarkerNode,
231
+ ) -> Result<String, magnus::Error> {
232
+ let config = rb_self.config(ruby)?;
163
233
 
164
- Ok(output)
234
+ node.render_commonmark(ruby, &config.options, &config.plugins())
235
+ }
165
236
  }
166
237
 
167
238
  #[magnus::init]
168
239
  fn init(ruby: &Ruby) -> Result<(), magnus::Error> {
169
- let m_commonmarker = ruby.define_module("Commonmarker")?;
240
+ let c_commonmarker = ruby.define_class("Commonmarker", ruby.class_object())?;
241
+
242
+ // Instances are allocated empty and configured by `initialize` (in Ruby),
243
+ // which hands the options and plugins to `commonmark_init`.
244
+ c_commonmarker.define_alloc_func::<Commonmarker>();
245
+ c_commonmarker.define_private_method("commonmark_init", method!(Commonmarker::init, 2))?;
246
+ c_commonmarker.define_private_method("commonmark_parse", method!(Commonmarker::parse, 1))?;
247
+ c_commonmarker
248
+ .define_private_method("commonmark_to_html", method!(Commonmarker::to_html, 1))?;
249
+ c_commonmarker.define_private_method(
250
+ "commonmark_to_commonmark",
251
+ method!(Commonmarker::to_commonmark, 1),
252
+ )?;
253
+ c_commonmarker.define_private_method(
254
+ "commonmark_render_html",
255
+ method!(Commonmarker::render_html, 1),
256
+ )?;
257
+ c_commonmarker.define_private_method(
258
+ "commonmark_render_commonmark",
259
+ method!(Commonmarker::render_commonmark, 1),
260
+ )?;
170
261
 
171
- m_commonmarker.define_module_function("commonmark_parse", function!(commonmark_parse, -1))?;
172
- m_commonmarker
173
- .define_module_function("commonmark_to_html", function!(commonmark_to_html, -1))?;
262
+ // Define Config module to hold constants
263
+ let m_config = c_commonmarker.define_module("Config")?;
264
+ m_config.const_set("OPTIONS", default_options_to_hash(ruby)?)?;
265
+ m_config.const_set("PLUGINS", default_plugins_to_hash(ruby)?)?;
174
266
 
175
- node::init(ruby, m_commonmarker).expect("cannot define Commonmarker::Node class");
267
+ node::init(ruby, c_commonmarker).expect("cannot define Commonmarker::Node class");
176
268
 
177
269
  Ok(())
178
270
  }
@@ -1,38 +1,19 @@
1
1
  use comrak::arena_tree::NodeEdge;
2
2
  use comrak::nodes::AstNode;
3
- use magnus::value::ReprValue;
4
- use magnus::{ExceptionClass, Module, RHash, Ruby, TryConvert};
3
+ use magnus::{ExceptionClass, Module, RClass, Ruby};
5
4
 
6
- /// Default for the `max_nesting_depth` parse option. Mirrors
5
+ /// Default for the `max_nesting_depth` parse option. Exposed to Ruby as
7
6
  /// `Commonmarker::Config::OPTIONS[:parse][:max_nesting_depth]`, and also applies
8
- /// when the option is passed as `nil`, which `Commonmarker::Config` strips.
7
+ /// when the option is passed as `nil`. The option is read alongside comrak's
8
+ /// in `crate::options::format_options`.
9
9
  pub const DEFAULT_MAX_NESTING_DEPTH: usize = 1000;
10
10
 
11
- const PARSE_MAX_NESTING_DEPTH: &str = "max_nesting_depth";
12
-
13
- /// Reads the `max_nesting_depth` parse option, falling back to the default.
14
- pub fn max_nesting_depth(ruby: &Ruby, rb_parse: Option<RHash>) -> Result<usize, magnus::Error> {
15
- let value = rb_parse.and_then(|options| options.get(ruby.to_symbol(PARSE_MAX_NESTING_DEPTH)));
16
-
17
- match value {
18
- Some(value) if !value.is_nil() => {
19
- let depth: i64 = TryConvert::try_convert(value)?;
20
- usize::try_from(depth).map_err(|_| {
21
- magnus::Error::new(
22
- ruby.exception_arg_error(),
23
- format!("parse option `:max_nesting_depth` must be a non-negative Integer; got {depth}"),
24
- )
25
- })
26
- }
27
- _ => Ok(DEFAULT_MAX_NESTING_DEPTH),
28
- }
29
- }
30
-
31
11
  /// The error raised when a document nests deeper than `max_nesting_depth`.
32
12
  pub fn exceeded_error(ruby: &Ruby, max_nesting_depth: usize) -> magnus::Error {
33
13
  let class = ruby
34
- .define_module("Commonmarker")
35
- .and_then(|module| module.const_get::<_, ExceptionClass>("NestingDepthExceededError"));
14
+ .class_object()
15
+ .const_get::<_, RClass>("Commonmarker")
16
+ .and_then(|class| class.const_get::<_, ExceptionClass>("NestingDepthExceededError"));
36
17
 
37
18
  match class {
38
19
  Ok(class) => magnus::Error::new(