markdown-ppp 2.9.2

Feature-rich Markdown Parsing and Pretty-Printing library
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
//! Tests for expandable transformations (1-to-many AST transformations)

use crate::ast::*;
use crate::ast_transform::{ExpandWith, Transformer};

/// Test transformer that splits paragraphs containing "SPLIT" into two paragraphs
struct ParagraphSplitter;

impl Transformer for ParagraphSplitter {
    fn walk_expand_block(&mut self, block: Block) -> Vec<Block> {
        match block {
            Block::Paragraph(inlines) => {
                // Look for "SPLIT" text in the paragraph
                let mut split_indices = Vec::new();
                for (i, inline) in inlines.iter().enumerate() {
                    if let Inline::Text(text) = inline {
                        if text.contains("SPLIT") {
                            split_indices.push(i);
                        }
                    }
                }

                if split_indices.is_empty() {
                    // No split needed, use default behavior - apply to children
                    let expanded_inlines: Vec<Inline> = inlines
                        .into_iter()
                        .flat_map(|inline| self.walk_expand_inline(inline))
                        .collect();
                    vec![Block::Paragraph(expanded_inlines)]
                } else {
                    // Split at the first SPLIT marker
                    let split_at = split_indices[0];
                    let (first_half, second_half) = inlines.split_at(split_at);

                    // Skip the SPLIT marker in the second half
                    let second_half = if second_half.len() > 1 {
                        second_half[1..].to_vec()
                    } else {
                        vec![]
                    };

                    let mut result = Vec::new();

                    // Add first paragraph if not empty
                    if !first_half.is_empty() {
                        result.push(Block::Paragraph(first_half.to_vec()));
                    }

                    // Add second paragraph if not empty
                    if !second_half.is_empty() {
                        result.push(Block::Paragraph(second_half));
                    }

                    result
                }
            }
            other => {
                // For other types, use default behavior
                vec![self.transform_block(other)]
            }
        }
    }
}

#[test]
fn test_paragraph_splitter() {
    let doc = Document {
        blocks: vec![Block::Paragraph(vec![
            Inline::Text("Before ".to_string()),
            Inline::Text("SPLIT".to_string()),
            Inline::Text(" After".to_string()),
        ])],
    };

    let mut transformer = ParagraphSplitter;
    let result = transformer.walk_expand_document(doc);

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].blocks.len(), 2);

    // Check first paragraph
    if let Block::Paragraph(inlines) = &result[0].blocks[0] {
        assert_eq!(inlines.len(), 1);
        assert_eq!(inlines[0], Inline::Text("Before ".to_string()));
    } else {
        panic!("Expected first block to be a paragraph");
    }

    // Check second paragraph
    if let Block::Paragraph(inlines) = &result[0].blocks[1] {
        assert_eq!(inlines.len(), 1);
        assert_eq!(inlines[0], Inline::Text(" After".to_string()));
    } else {
        panic!("Expected second block to be a paragraph");
    }
}

/// Test transformer that expands text containing "EXPAND" into multiple text nodes
struct TextExpander;

impl Transformer for TextExpander {
    // Override the walk method to implement the actual expansion logic
    fn walk_expand_inline(&mut self, inline: Inline) -> Vec<Inline> {
        match inline {
            Inline::Text(text) if text.contains("EXPAND") => {
                // Split on "EXPAND" and create multiple text nodes
                let parts: Vec<&str> = text.split("EXPAND").collect();
                let mut result = Vec::new();

                for (i, part) in parts.iter().enumerate() {
                    if !part.is_empty() {
                        result.push(Inline::Text(part.to_string()));
                    }
                    // Add emphasis between parts (except after the last part)
                    if i < parts.len() - 1 {
                        result.push(Inline::Emphasis(vec![Inline::Text("EXPANDED".to_string())]));
                    }
                }

                result
            }
            other => {
                // For other types, use default behavior
                vec![self.transform_inline(other)]
            }
        }
    }
}

#[test]
fn test_text_expander() {
    let doc = Document {
        blocks: vec![Block::Paragraph(vec![Inline::Text(
            "Hello EXPAND World EXPAND !".to_string(),
        )])],
    };

    let mut transformer = TextExpander;
    let result = transformer.walk_expand_document(doc);

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].blocks.len(), 1);

    if let Block::Paragraph(inlines) = &result[0].blocks[0] {
        assert_eq!(inlines.len(), 5); // "Hello ", EXPANDED, " World ", EXPANDED, " !"

        assert_eq!(inlines[0], Inline::Text("Hello ".to_string()));
        assert_eq!(
            inlines[1],
            Inline::Emphasis(vec![Inline::Text("EXPANDED".to_string())])
        );
        assert_eq!(inlines[2], Inline::Text(" World ".to_string()));
        assert_eq!(
            inlines[3],
            Inline::Emphasis(vec![Inline::Text("EXPANDED".to_string())])
        );
        assert_eq!(inlines[4], Inline::Text(" !".to_string()));
    } else {
        panic!("Expected paragraph");
    }
}

/// Test transformer that converts headings into heading + paragraph pairs
struct HeadingExpander;

impl Transformer for HeadingExpander {
    fn walk_expand_block(&mut self, block: Block) -> Vec<Block> {
        match block {
            Block::Heading(heading) => {
                // Create the original heading with expanded children
                let mut transformed_heading = heading.clone();
                transformed_heading.content = transformed_heading
                    .content
                    .into_iter()
                    .flat_map(|inline| self.walk_expand_inline(inline))
                    .collect();

                // Create an additional paragraph with metadata
                let meta_paragraph =
                    Block::Paragraph(vec![Inline::Emphasis(vec![Inline::Text(format!(
                        "This is a {} heading",
                        match &heading.kind {
                            HeadingKind::Atx(level) => format!("level {level}"),
                            HeadingKind::Setext(setext) => match setext {
                                SetextHeading::Level1 => "level 1".to_string(),
                                SetextHeading::Level2 => "level 2".to_string(),
                            },
                        }
                    ))])]);

                vec![Block::Heading(transformed_heading), meta_paragraph]
            }
            other => {
                // For other types, use default behavior
                vec![self.transform_block(other)]
            }
        }
    }
}

#[test]
fn test_heading_expander() {
    let doc = Document {
        blocks: vec![Block::Heading(Heading {
            kind: HeadingKind::Atx(2),
            content: vec![Inline::Text("Test Heading".to_string())],
        })],
    };

    let mut transformer = HeadingExpander;
    let result = transformer.walk_expand_document(doc);

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].blocks.len(), 2);

    // Check heading is preserved
    if let Block::Heading(heading) = &result[0].blocks[0] {
        assert_eq!(heading.kind, HeadingKind::Atx(2));
        assert_eq!(heading.content[0], Inline::Text("Test Heading".to_string()));
    } else {
        panic!("Expected first block to be a heading");
    }

    // Check metadata paragraph is added
    if let Block::Paragraph(inlines) = &result[0].blocks[1] {
        assert_eq!(inlines.len(), 1);
        if let Inline::Emphasis(content) = &inlines[0] {
            assert_eq!(
                content[0],
                Inline::Text("This is a level 2 heading".to_string())
            );
        } else {
            panic!("Expected emphasis in metadata paragraph");
        }
    } else {
        panic!("Expected second block to be a paragraph");
    }
}

/// Test using the ExpandWith trait for convenient API
#[test]
fn test_expand_with_trait() {
    let block = Block::Paragraph(vec![
        Inline::Text("Before ".to_string()),
        Inline::Text("SPLIT".to_string()),
        Inline::Text(" After".to_string()),
    ]);

    let mut transformer = ParagraphSplitter;
    let result = block.expand_with(&mut transformer);

    assert_eq!(result.len(), 2);

    if let Block::Paragraph(inlines) = &result[0] {
        assert_eq!(inlines[0], Inline::Text("Before ".to_string()));
    } else {
        panic!("Expected first result to be a paragraph");
    }

    if let Block::Paragraph(inlines) = &result[1] {
        assert_eq!(inlines[0], Inline::Text(" After".to_string()));
    } else {
        panic!("Expected second result to be a paragraph");
    }
}

/// Test transformer that doesn't expand (returns single element)
struct NoOpExpander;

impl Transformer for NoOpExpander {
    fn expand_block(&mut self, block: Block) -> Vec<Block> {
        // Use default implementation (no expansion)
        vec![self.transform_block(block)]
    }
}

#[test]
fn test_no_expansion() {
    let doc = Document {
        blocks: vec![Block::Paragraph(vec![Inline::Text(
            "Regular paragraph".to_string(),
        )])],
    };

    let mut transformer = NoOpExpander;
    let result = transformer.walk_expand_document(doc);

    // Should return exactly one document with one block
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].blocks.len(), 1);

    if let Block::Paragraph(inlines) = &result[0].blocks[0] {
        assert_eq!(inlines[0], Inline::Text("Regular paragraph".to_string()));
    } else {
        panic!("Expected paragraph");
    }
}

/// Test complex transformation that combines multiple expansion strategies
struct ComplexExpander;

impl Transformer for ComplexExpander {
    fn walk_expand_block(&mut self, block: Block) -> Vec<Block> {
        match block {
            // Split paragraphs on "SPLIT"
            Block::Paragraph(inlines) => {
                for (i, inline) in inlines.iter().enumerate() {
                    if let Inline::Text(text) = inline {
                        if text.contains("SPLIT") {
                            let (first_half, second_half) = inlines.split_at(i);
                            let second_half = if second_half.len() > 1 {
                                second_half[1..].to_vec()
                            } else {
                                vec![]
                            };

                            let mut result = Vec::new();
                            if !first_half.is_empty() {
                                // Apply inline expansion to first half
                                let expanded_first: Vec<Inline> = first_half
                                    .iter()
                                    .flat_map(|inline| self.walk_expand_inline(inline.clone()))
                                    .collect();
                                result.push(Block::Paragraph(expanded_first));
                            }
                            if !second_half.is_empty() {
                                // Apply inline expansion to second half
                                let expanded_second: Vec<Inline> = second_half
                                    .iter()
                                    .flat_map(|inline| self.walk_expand_inline(inline.clone()))
                                    .collect();
                                result.push(Block::Paragraph(expanded_second));
                            }
                            return result;
                        }
                    }
                }
                // Apply expand_inline to children
                let expanded_inlines: Vec<Inline> = inlines
                    .into_iter()
                    .flat_map(|inline| self.walk_expand_inline(inline))
                    .collect();
                vec![Block::Paragraph(expanded_inlines)]
            }
            // Expand headings
            Block::Heading(heading) => {
                let mut result = Vec::new();

                // Transform heading with expanded children
                let mut transformed_heading = heading.clone();
                transformed_heading.content = transformed_heading
                    .content
                    .into_iter()
                    .flat_map(|inline| self.walk_expand_inline(inline))
                    .collect();

                result.push(Block::Heading(transformed_heading));

                let meta_paragraph =
                    Block::Paragraph(vec![Inline::Text("(Generated metadata)".to_string())]);
                result.push(meta_paragraph);
                result
            }
            other => {
                // For other types, use default behavior
                vec![self.transform_block(other)]
            }
        }
    }

    fn walk_expand_inline(&mut self, inline: Inline) -> Vec<Inline> {
        match inline {
            Inline::Text(text) if text.contains("EXPAND") => {
                vec![
                    Inline::Text(text.replace("EXPAND", "")),
                    Inline::Strong(vec![Inline::Text("EXPANDED".to_string())]),
                ]
            }
            other => self.walk_expand_inline(other),
        }
    }
}

#[test]
fn test_complex_expansion() {
    let doc = Document {
        blocks: vec![
            Block::Heading(Heading {
                kind: HeadingKind::Atx(1),
                content: vec![Inline::Text("Main EXPAND Title".to_string())],
            }),
            Block::Paragraph(vec![
                Inline::Text("First EXPAND part".to_string()),
                Inline::Text("SPLIT".to_string()),
                Inline::Text("Second EXPAND part".to_string()),
            ]),
        ],
    };

    let mut transformer = ComplexExpander;
    let result = transformer.walk_expand_document(doc);

    assert_eq!(result.len(), 1);
    // Should have: heading + meta paragraph + first paragraph + second paragraph = 4 blocks
    assert_eq!(result[0].blocks.len(), 4);

    // Check heading expansion
    if let Block::Heading(heading) = &result[0].blocks[0] {
        assert_eq!(heading.content.len(), 2); // Text + Strong
        if let Inline::Text(text) = &heading.content[0] {
            assert_eq!(text, "Main  Title"); // "EXPAND" removed
        }
        if let Inline::Strong(content) = &heading.content[1] {
            if let Inline::Text(text) = &content[0] {
                assert_eq!(text, "EXPANDED");
            }
        }
    } else {
        panic!("Expected first block to be heading");
    }

    // Check metadata paragraph
    if let Block::Paragraph(inlines) = &result[0].blocks[1] {
        assert_eq!(inlines[0], Inline::Text("(Generated metadata)".to_string()));
    } else {
        panic!("Expected second block to be metadata paragraph");
    }

    // Check split paragraphs with inline expansion
    if let Block::Paragraph(inlines) = &result[0].blocks[2] {
        assert_eq!(inlines.len(), 2); // Text + Strong from "EXPAND"
    } else {
        panic!("Expected third block to be paragraph");
    }

    if let Block::Paragraph(inlines) = &result[0].blocks[3] {
        assert_eq!(inlines.len(), 2); // Text + Strong from "EXPAND"
    } else {
        panic!("Expected fourth block to be paragraph");
    }
}