cmark-writer 0.6.1

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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# cmark-writer

[![CI Status](https://github.com/hongjr03/cmark-writer/workflows/CI/badge.svg)](https://github.com/hongjr03/cmark-writer/actions)
[![Crates.io](https://img.shields.io/crates/v/cmark-writer.svg)](https://crates.io/crates/cmark-writer)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Downloads](https://img.shields.io/crates/d/cmark-writer.svg)](https://crates.io/crates/cmark-writer)
[![Codecov](https://codecov.io/gh/hongjr03/cmark-writer/branch/master/graph/badge.svg)](https://codecov.io/gh/hongjr03/cmark-writer)

A CommonMark writer implementation in Rust.

## Usage

### Basic Example

```rust
use cmark_writer::ast::{Node, ListItem};
use cmark_writer::writer::CommonMarkWriter;

// Create a document
let document = Node::Document(vec![
    Node::heading(1, vec![Node::Text("Hello CommonMark".to_string())]),
    Node::Paragraph(vec![
        Node::Text("This is a simple ".to_string()),
        Node::Strong(vec![Node::Text("example".to_string())]),
        Node::Text(".".to_string()),
    ]),
]);

// Render to CommonMark
let mut writer = CommonMarkWriter::new();
writer.write(&document).expect("Failed to write document");
let markdown = writer.into_string();

println!("{}", markdown);
```

### Custom Formatting Options

You can customize the formatting behavior using the options builder pattern:

```rust
use cmark_writer::options::WriterOptionsBuilder;
use cmark_writer::writer::CommonMarkWriter;
use cmark_writer::ast::Node;

// Create custom options using the builder pattern
let options = WriterOptionsBuilder::new()
    .strict(true)                // Follow CommonMark spec strictly
    .hard_break_spaces(false)    // Use backslash for line breaks
    .indent_spaces(2)            // Use 2 spaces for indentation
    .build();

// Create writer with custom options
let mut writer = CommonMarkWriter::with_options(options);
writer.write(&Node::Text("Example".to_string())).unwrap();
```

Alternatively, you can use the struct initialization syntax:

```rust
use cmark_writer::options::WriterOptions;
use cmark_writer::writer::CommonMarkWriter;
use cmark_writer::ast::Node;

// Create custom options using struct initialization
let options = WriterOptions {
    strict: true,                // Follow CommonMark spec strictly
    hard_break_spaces: false,    // Use backslash for line breaks
    indent_spaces: 2,            // Use 2 spaces for indentation
    ..Default::default()         // Other options can be set here
};

// Create writer with custom options
let mut writer = CommonMarkWriter::with_options(options);
writer.write(&Node::Text("Example".to_string())).unwrap();
```

### Tables

The library provides a fluent API for creating tables, even without the GFM feature enabled:

```rust
use cmark_writer::ast::{Node, tables::TableBuilder};

// Create a simple table using the builder pattern
let table = TableBuilder::new()
    .headers(vec![
        Node::Text("Name".to_string()), 
        Node::Text("Age".to_string())
    ])
    .add_row(vec![
        Node::Text("Alice".to_string()),
        Node::Text("30".to_string()),
    ])
    .add_row(vec![
        Node::Text("Bob".to_string()),
        Node::Text("25".to_string()),
    ])
    .build();

// Or use the convenience function
let simple_table = cmark_writer::ast::tables::simple_table(
    vec![Node::Text("Header".to_string())],
    vec![vec![Node::Text("Data".to_string())]]
);
```

Alternatively, you can use the direct struct initialization approach:

```rust
use cmark_writer::ast::Node;

// Create a table using struct initialization
let table = Node::Table {
    headers: vec![
        Node::Text("Name".to_string()),
        Node::Text("Age".to_string()),
    ],
    #[cfg(feature = "gfm")]
    alignments: vec![
        cmark_writer::ast::TableAlignment::Left,
        cmark_writer::ast::TableAlignment::Left,
    ],
    rows: vec![
        vec![
            Node::Text("Alice".to_string()),
            Node::Text("30".to_string()),
        ],
        vec![
            Node::Text("Bob".to_string()),
            Node::Text("25".to_string()),
        ],
    ],
};
```

When the GFM feature is enabled, additional table alignment options become available.

### Safe HTML Handling

The library provides utilities for safely handling HTML content:

```rust
use cmark_writer::ast::{HtmlElement, Node};

// Escape HTML special characters in attributes
let script_element = HtmlElement::new("div")
    .with_attribute("data-content", "alert('hello')")
    .with_children(vec![Node::Text("Safe content".to_string())]);

// HTML attributes are automatically escaped
let mut writer = cmark_writer::writer::CommonMarkWriter::new();
writer.write(&Node::HtmlElement(script_element)).unwrap();
let html = writer.into_string();
// This will produce safe HTML with escaped attributes
```

### GitHub Flavored Markdown (GFM)

The library supports GitHub Flavored Markdown extensions as an optional feature. This includes:

- Tables with column alignment (`:---`, `:---:`, `---:`)
- Strikethrough text (`~~text~~`)
- Task lists (`- [ ]` and `- [x]`)
- Extended autolinks (without angle brackets)
- HTML element filtering (blocking potentially unsafe tags)

To use GFM features, first enable the feature in your `Cargo.toml`:

```toml
[dependencies]
cmark-writer = { version = "0.6.0", features = ["gfm"] }
```

#### Basic GFM Usage

```rust
// Note: this example requires the "gfm" feature to be enabled
#[cfg(feature = "gfm")]
mod example {
    use cmark_writer::writer::CommonMarkWriter;
    use cmark_writer::ast::Node;
    use cmark_writer::options::WriterOptionsBuilder;
    
    pub fn demo() {
        // Create writer options with GFM features enabled using the builder pattern
        let options = WriterOptionsBuilder::new()
            .gfm_tasklists(true)
            .gfm_strikethrough(true)
            .build();  // enable_gfm is automatically set when any GFM feature is enabled
        
        let mut writer = CommonMarkWriter::with_options(options);
        
        // Create a task list item (would use gfm::tasks if available)
        let document = Node::Document(vec![
            Node::Paragraph(vec![
                Node::Text("This is a task list example".to_string())
            ])
        ]);
        
        writer.write(&document).expect("Failed to write document");
        let markdown = writer.into_string();
        println!("{}", markdown);
    }
}
```

#### GFM Tables with the Table Builder

```rust
// Note: this example requires the "gfm" feature to be enabled
#[cfg(feature = "gfm")]
mod example {
    use cmark_writer::ast::Node;
    use cmark_writer::ast::tables::TableBuilder;
    
    pub fn demo() {
        // Create a table with standard alignment
        let table = TableBuilder::new()
            .headers(vec![
                Node::Text("Left".to_string()), 
                Node::Text("Center".to_string()), 
                Node::Text("Right".to_string())
            ])
            .add_row(vec![
                Node::Text("Data 1".to_string()),
                Node::Text("Data 2".to_string()),
                Node::Text("Data 3".to_string()),
            ])
            .build();
    
        // With GFM enabled, you could use alignment features
        #[cfg(feature = "gfm")]
        {
            use cmark_writer::ast::TableAlignment;
            
            let _aligned_table = TableBuilder::new()
                .headers(vec![Node::Text("Header".to_string())])
                .add_row(vec![Node::Text("Content".to_string())])
                .build();
        }
    }
}
```

#### Task Lists and Strikethrough

```rust
// Note: this example requires the "gfm" feature to be enabled
#[cfg(feature = "gfm")]
mod example {
    use cmark_writer::ast::Node;
    use cmark_writer::options::WriterOptions;
    use cmark_writer::writer::CommonMarkWriter;
    
    pub fn demo() {
        // Create a task list using GFM options
        let options = WriterOptions {
            enable_gfm: true,
            gfm_tasklists: true,
            gfm_strikethrough: true,
            ..Default::default()
        };
        
        // Create task-like content
        let completed_task = Node::Paragraph(vec![
            Node::Text("Completed task".to_string())
        ]);
        
        // Create strikethrough-like content
        let strike_text = Node::Paragraph(vec![
            Node::Text("This text would be crossed out".to_string())
        ]);
        
        // With GFM enabled, this would render as task lists and strikethrough
        let mut writer = CommonMarkWriter::with_options(options);
        writer.write(&completed_task).expect("Failed to write");
        writer.write(&strike_text).expect("Failed to write");
    }
}
```

#### GFM HTML Safety

GFM provides additional HTML safety features:

```rust
// Note: this example requires the "gfm" feature to be enabled
#[cfg(feature = "gfm")]
mod example {
    use cmark_writer::ast::{Node, HtmlElement};
    use cmark_writer::options::WriterOptions;
    use cmark_writer::writer::CommonMarkWriter;
    
    pub fn demo() {
        // Create a document with potentially unsafe HTML
        let document = Node::Document(vec![
            Node::HtmlElement(HtmlElement::new("script")
                .with_children(vec![Node::Text("alert('unsafe')".to_string())]))
        ]);
        
        // Enable GFM with HTML filtering
        let options = WriterOptions {
            enable_gfm: true,
            gfm_disallowed_html_tags: vec!["script".to_string(), "iframe".to_string()],
            ..Default::default()
        };
        
        // This will automatically filter out unsafe HTML elements
        let mut writer = CommonMarkWriter::with_options(options);
        writer.write(&document).expect("Failed to write");
    }
}
```

#### Customizing GFM Features

```rust
// Note: this example requires the "gfm" feature to be enabled
#[cfg(feature = "gfm")]
mod example {
    use cmark_writer::options::WriterOptionsBuilder;
    use cmark_writer::writer::CommonMarkWriter;
    
    pub fn demo() {
        // Enable specific GFM features using the builder pattern
        let writer = CommonMarkWriter::with_options(
            WriterOptionsBuilder::new()
                .gfm_tables(true)
                .gfm_strikethrough(true)
                .build()  // enable_gfm is automatically set
        );
        
        // You can also customize the list of disallowed HTML tags
        let custom_html_safety = WriterOptionsBuilder::new()
            .gfm_disallowed_html_tags(vec![
                "script".to_string(), 
                "iframe".to_string()
            ])
            .build();  // enable_gfm is automatically set
        
        let _writer = CommonMarkWriter::with_options(custom_html_safety);
    }
}
```

## API Documentation

### Core Types

- `Node` - Represents various CommonMark node types
- `CommonMarkWriter` - Converts nodes to CommonMark text
- `WriterOptions` - Customization options for the writer

### Creating Custom Nodes

You can extend the CommonMark syntax with your own custom nodes:

```rust
use cmark_writer::ast::{CustomNodeWriter, Node};
use cmark_writer::error::WriteResult;
use cmark_writer::custom_node;

// Define a custom highlight node
#[derive(Debug, Clone, PartialEq)]
#[custom_node]
struct HighlightNode {
    content: String,
    color: String,
}

// Implement the required methods
impl HighlightNode {
    // Custom node writing logic
    fn write_custom(&self, writer: &mut dyn CustomNodeWriter) -> WriteResult<()> {
        writer.write_str("<span style=\"background-color: ")?;
        writer.write_str(&self.color)?;
        writer.write_str("\">")?;
        writer.write_str(&self.content)?;
        writer.write_str("</span>")?;
        Ok(())
    }
    
    // Determine if it's a block or inline element
    fn is_block_custom(&self) -> bool {
        false // This is an inline element
    }
}

// Use your custom node
let document = Node::Document(vec![
    Node::Paragraph(vec![
        Node::Text("Here's some text with a ".to_string()),
        Node::Custom(Box::new(HighlightNode {
            content: "highlighted section".to_string(),
            color: "yellow".to_string(),
        })),
        Node::Text(".".to_string()),
    ]),
]);
```

### Creating Custom Errors

You can also define custom error types for your validation logic:

```rust
use cmark_writer::custom_error;
use cmark_writer::coded_error;
use cmark_writer::WriteError;

// Define a structure error with format string
#[custom_error(format = "Table structure error: {}")]
struct TableStructureError(pub &'static str);

// Define a coded error with error code
#[coded_error]
struct ValidationError(pub String, pub String);

// Use in your code
fn validate_table() -> Result<(), WriteError> {
    // Using a structure error
    return Err(TableStructureError("Rows don't match").into());
    
    // Using a coded error
    // return Err(ValidationError("Invalid alignment".to_string(), "INVALID_ALIGNMENT".to_string()).into());
}
```

## Development

### Building

```bash
cargo build
```

### Running Tests

```bash
cargo test
```

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.