cmark-writer 0.8.0

A CommonMark writer implementation in Rust for serializing AST nodes to CommonMark format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! New node processor implementation
//!
//! Processor system rewritten with new trait architecture

use crate::ast::Node;
use crate::error::{WriteError, WriteResult};
use crate::traits::{
    BlockNodeProcessor, ConfigurableProcessor, InlineNodeProcessor, NodeProcessor, Writer,
};

/// Block processor configuration
#[derive(Debug, Clone)]
pub struct BlockProcessorConfig {
    /// Whether to ensure trailing newlines
    pub ensure_trailing_newlines: bool,
    /// Block separator
    pub block_separator: String,
}

impl Default for BlockProcessorConfig {
    fn default() -> Self {
        Self {
            ensure_trailing_newlines: true,
            block_separator: "\n\n".to_string(),
        }
    }
}

/// Inline processor configuration
#[derive(Debug, Clone)]
pub struct InlineProcessorConfig {
    /// Enable strict validation mode
    pub strict_validation: bool,
    /// Allow newlines in inline elements
    pub allow_newlines: bool,
}

impl Default for InlineProcessorConfig {
    fn default() -> Self {
        Self {
            strict_validation: true,
            allow_newlines: false,
        }
    }
}

/// Enhanced block node processor
#[derive(Debug)]
pub struct EnhancedBlockProcessor {
    config: BlockProcessorConfig,
}

impl EnhancedBlockProcessor {
    /// Create a new block processor
    pub fn new() -> Self {
        Self {
            config: BlockProcessorConfig::default(),
        }
    }

    /// Create with custom configuration
    pub fn with_config(config: BlockProcessorConfig) -> Self {
        Self { config }
    }
}

impl Default for EnhancedBlockProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl NodeProcessor for EnhancedBlockProcessor {
    fn can_process(&self, node: &Node) -> bool {
        matches!(
            node,
            Node::Document(_)
                | Node::Heading { .. }
                | Node::Paragraph(_)
                | Node::BlockQuote(_)
                | Node::CodeBlock { .. }
                | Node::UnorderedList(_)
                | Node::OrderedList { .. }
                | Node::ThematicBreak
                | Node::Table { .. }
                | Node::HtmlBlock(_)
                | Node::LinkReferenceDefinition { .. }
        ) || matches!(node, Node::Custom(custom) if custom.is_block())
    }

    fn process_commonmark(
        &self,
        writer: &mut crate::writer::CommonMarkWriter,
        node: &Node,
    ) -> WriteResult<()> {
        match node {
            Node::Document(children) => {
                for (i, child) in children.iter().enumerate() {
                    if i > 0 {
                        writer.write_str("\n\n")?;
                    }
                    writer.write_node(child)?;
                }
                Ok(())
            }
            Node::Heading {
                level,
                content,
                heading_type,
            } => writer.write_heading(*level, content, heading_type),
            Node::Paragraph(content) => writer.write_paragraph(content),
            Node::BlockQuote(content) => writer.write_blockquote(content),
            Node::CodeBlock {
                language,
                content,
                block_type,
            } => writer.write_code_block(language, content, block_type),
            Node::UnorderedList(items) => writer.write_unordered_list(items),
            Node::OrderedList { start, items } => writer.write_ordered_list(items, *start, true),
            Node::ThematicBreak => writer.write_thematic_break(),
            #[cfg(feature = "gfm")]
            Node::Table {
                headers,
                alignments,
                rows,
            } => writer.write_table_with_alignment(headers, alignments, rows),
            #[cfg(not(feature = "gfm"))]
            Node::Table { headers, rows, .. } => writer.write_table(headers, rows),
            Node::HtmlBlock(content) => writer.write_html_block(content),
            Node::LinkReferenceDefinition {
                label,
                destination,
                title,
            } => writer.write_link_reference_definition(label, destination, title),
            Node::Custom(custom_node) if custom_node.is_block() => {
                // CustomNode implements CommonMarkRenderable
                custom_node.render_commonmark(writer)
            }
            _ => Err(WriteError::UnsupportedNodeType),
        }?;

        if self.config.ensure_trailing_newlines {
            // Newline handling is now context-aware and automatic
        }

        Ok(())
    }

    fn process_html(&self, writer: &mut crate::writer::HtmlWriter, node: &Node) -> WriteResult<()> {
        writer.write_node_internal(node).map_err(WriteError::from)
    }

    fn priority(&self) -> u32 {
        100
    }
}

impl BlockNodeProcessor for EnhancedBlockProcessor {
    fn ensure_block_separation(&self, writer: &mut dyn Writer) -> WriteResult<()> {
        writer.write_str(&self.config.block_separator)
    }
}

impl ConfigurableProcessor for EnhancedBlockProcessor {
    type Config = BlockProcessorConfig;

    fn configure(&mut self, config: Self::Config) {
        self.config = config;
    }

    fn config(&self) -> &Self::Config {
        &self.config
    }
}

/// Enhanced inline node processor
#[derive(Debug)]
pub struct EnhancedInlineProcessor {
    config: InlineProcessorConfig,
}

impl EnhancedInlineProcessor {
    /// Create a new inline processor
    pub fn new() -> Self {
        Self {
            config: InlineProcessorConfig::default(),
        }
    }

    /// Create with custom configuration
    pub fn with_config(config: InlineProcessorConfig) -> Self {
        Self { config }
    }
}

impl Default for EnhancedInlineProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl NodeProcessor for EnhancedInlineProcessor {
    fn can_process(&self, node: &Node) -> bool {
        matches!(
            node,
            Node::Text(_)
                | Node::Emphasis(_)
                | Node::Strong(_)
                | Node::InlineCode(_)
                | Node::Link { .. }
                | Node::Image { .. }
                | Node::Autolink { .. }
                | Node::ReferenceLink { .. }
                | Node::HtmlElement(_)
                | Node::SoftBreak
                | Node::HardBreak
        ) || matches!(node, Node::Custom(custom) if !custom.is_block())
            || (cfg!(feature = "gfm")
                && matches!(node, Node::Strikethrough(_) | Node::ExtendedAutolink(_)))
    }

    fn process_commonmark(
        &self,
        writer: &mut crate::writer::CommonMarkWriter,
        node: &Node,
    ) -> WriteResult<()> {
        if self.config.strict_validation {
            self.validate_inline_content(node)?;
        }

        match node {
            Node::Text(content) => writer.write_text_content(content),
            Node::Emphasis(content) => writer.write_emphasis(content),
            Node::Strong(content) => writer.write_strong(content),
            #[cfg(feature = "gfm")]
            Node::Strikethrough(content) => writer.write_strikethrough(content),
            Node::InlineCode(content) => writer.write_code_content(content),
            Node::Link {
                url,
                title,
                content,
            } => writer.write_link(url, title, content),
            Node::Image { url, title, alt } => writer.write_image(url, title, alt),
            Node::Autolink { url, is_email } => writer.write_autolink(url, *is_email),
            #[cfg(feature = "gfm")]
            Node::ExtendedAutolink(url) => writer.write_extended_autolink(url),
            Node::ReferenceLink { label, content } => writer.write_reference_link(label, content),
            Node::HtmlElement(element) => writer.write_html_element(element),
            Node::SoftBreak => writer.write_soft_break(),
            Node::HardBreak => writer.write_hard_break(),
            Node::Custom(custom_node) if !custom_node.is_block() => {
                custom_node.render_commonmark(writer)
            }
            _ => Err(WriteError::UnsupportedNodeType),
        }
    }

    fn process_html(&self, writer: &mut crate::writer::HtmlWriter, node: &Node) -> WriteResult<()> {
        writer.write_node_internal(node).map_err(WriteError::from)
    }

    fn priority(&self) -> u32 {
        50
    }
}

impl InlineNodeProcessor for EnhancedInlineProcessor {
    fn validate_inline_content(&self, node: &Node) -> WriteResult<()> {
        if !self.config.allow_newlines && !matches!(node, Node::SoftBreak | Node::HardBreak) {
            // Recursive function to check for newlines in text content
            fn check_for_newlines(node: &Node) -> Result<(), String> {
                match node {
                    // Direct text content nodes
                    Node::Text(content) => {
                        if content.contains('\n') {
                            return Err(format!("Text node: {}", content));
                        }
                    }
                    Node::InlineCode(content) => {
                        if content.contains('\n') {
                            return Err(format!("Inline code: {}", content));
                        }
                    }
                    Node::Autolink { url, .. } => {
                        if url.contains('\n') {
                            return Err(format!("Autolink URL: {}", url));
                        }
                    }
                    #[cfg(feature = "gfm")]
                    Node::ExtendedAutolink(url) => {
                        if url.contains('\n') {
                            return Err(format!("Extended autolink URL: {}", url));
                        }
                    }

                    // Nodes with child content that needs recursive checking
                    Node::Emphasis(children)
                    | Node::Strong(children)
                    | Node::Strikethrough(children) => {
                        for child in children {
                            check_for_newlines(child)?;
                        }
                    }
                    Node::Link {
                        content,
                        url,
                        title,
                        ..
                    } => {
                        // Check URL and title for newlines
                        if url.contains('\n') {
                            return Err(format!("Link URL: {}", url));
                        }
                        if let Some(title_text) = title {
                            if title_text.contains('\n') {
                                return Err(format!("Link title: {}", title_text));
                            }
                        }
                        // Check content recursively
                        for child in content {
                            check_for_newlines(child)?;
                        }
                    }
                    Node::ReferenceLink { content, label, .. } => {
                        // Check label for newlines
                        if label.contains('\n') {
                            return Err(format!("Reference link label: {}", label));
                        }
                        // Check content recursively
                        for child in content {
                            check_for_newlines(child)?;
                        }
                    }
                    Node::Image {
                        alt, url, title, ..
                    } => {
                        // Check URL and title for newlines
                        if url.contains('\n') {
                            return Err(format!("Image URL: {}", url));
                        }
                        if let Some(title_text) = title {
                            if title_text.contains('\n') {
                                return Err(format!("Image title: {}", title_text));
                            }
                        }
                        // Check alt text recursively
                        for child in alt {
                            check_for_newlines(child)?;
                        }
                    }

                    // HTML elements might contain text, but we allow them for now
                    Node::HtmlElement(_) => {
                        // HTML elements are allowed to contain newlines as they might be formatted
                    }

                    // Custom nodes - delegate validation to the custom node implementation
                    Node::Custom(_) => {
                        // Custom nodes should handle their own validation
                    }

                    // Break nodes are explicitly allowed
                    Node::SoftBreak | Node::HardBreak => {}

                    // Other nodes shouldn't appear in inline context, but we don't error here
                    _ => {}
                }
                Ok(())
            }

            if let Err(error_msg) = check_for_newlines(node) {
                return Err(WriteError::NewlineInInlineElement(error_msg.into()));
            }
        }
        Ok(())
    }
}

impl ConfigurableProcessor for EnhancedInlineProcessor {
    type Config = InlineProcessorConfig;

    fn configure(&mut self, config: Self::Config) {
        self.config = config;
    }

    fn config(&self) -> &Self::Config {
        &self.config
    }
}

/// Custom node processor
#[derive(Debug, Default)]
pub struct CustomNodeProcessor;

impl NodeProcessor for CustomNodeProcessor {
    fn can_process(&self, node: &Node) -> bool {
        matches!(node, Node::Custom(_))
    }

    fn process_commonmark(
        &self,
        writer: &mut crate::writer::CommonMarkWriter,
        node: &Node,
    ) -> WriteResult<()> {
        match node {
            Node::Custom(custom_node) => {
                custom_node.render_commonmark(writer)?;

                if custom_node.is_block() {
                    // Newline handling is now context-aware and automatic
                }

                Ok(())
            }
            _ => Err(WriteError::UnsupportedNodeType),
        }
    }

    fn process_html(&self, writer: &mut crate::writer::HtmlWriter, node: &Node) -> WriteResult<()> {
        match node {
            Node::Custom(custom_node) => {
                // Use the html_render method from CustomNode trait
                custom_node.html_render(writer)
            }
            _ => Err(WriteError::UnsupportedNodeType),
        }
    }

    fn priority(&self) -> u32 {
        200 // High priority for custom node processing
    }
}