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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use crate::error::Error;
use pulldown_cmark::{CodeBlockKind, Event, Options as CmarkOptions, Parser as CmarkParser};
use serde_yaml;
use std::collections::HashMap;

/// Options for Markdown parsing
#[derive(Debug, Clone)]
pub struct ParseOptions {
    /// Enable GitHub-flavored markdown
    pub gfm: bool,
    /// Enable smart punctuation
    pub smart_punctuation: bool,
    /// Parse YAML frontmatter
    pub frontmatter: bool,
    /// Enable custom component syntax
    pub custom_components: bool,
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self {
            gfm: true,
            smart_punctuation: true,
            frontmatter: true,
            custom_components: true,
        }
    }
}

/// Represents a parsed Markdown document
#[derive(Debug)]
pub struct ParsedDocument {
    /// The AST (Abstract Syntax Tree) of the markdown document
    pub ast: Vec<Node>,
    /// Frontmatter metadata if present
    pub frontmatter: Option<HashMap<String, serde_yaml::Value>>,
}

/// Represents a node in the Markdown AST
#[derive(Debug, Clone)]
pub enum Node {
    /// A heading with level (1-6) and content
    Heading {
        level: u8,
        content: String,
        id: String,
    },
    /// A paragraph of text
    Paragraph(Vec<InlineNode>),
    /// A blockquote
    BlockQuote(Vec<Node>),
    /// A code block with optional language
    CodeBlock {
        language: Option<String>,
        content: String,
        attributes: HashMap<String, String>,
    },
    /// A list (ordered or unordered)
    List {
        ordered: bool,
        items: Vec<Vec<Node>>,
    },
    /// A thematic break (horizontal rule)
    ThematicBreak,
    /// A custom component
    Component {
        name: String,
        attributes: HashMap<String, String>,
        children: Vec<Node>,
    },
    /// Raw HTML
    Html(String),
    /// Table
    Table {
        headers: Vec<Vec<InlineNode>>,
        rows: Vec<Vec<Vec<InlineNode>>>,
        alignments: Vec<Alignment>,
    },
}

impl Node {
    /// Get the name of a component node
    pub fn name(&self) -> &str {
        match self {
            Node::Component { name, .. } => name,
            _ => "",
        }
    }

    /// Get the attributes of a component node
    pub fn attributes(&self) -> HashMap<String, String> {
        match self {
            Node::Component { attributes, .. } => attributes.clone(),
            _ => HashMap::new(),
        }
    }

    /// Get the children of a component node
    pub fn children(&self) -> Vec<Node> {
        match self {
            Node::Component { children, .. } => children.clone(),
            _ => Vec::new(),
        }
    }
}

/// Represents an inline node in the Markdown AST
#[derive(Debug, Clone)]
pub enum InlineNode {
    /// Plain text
    Text(String),
    /// Emphasized text
    Emphasis(Vec<InlineNode>),
    /// Strongly emphasized text
    Strong(Vec<InlineNode>),
    /// Strikethrough text
    Strikethrough(Vec<InlineNode>),
    /// Link
    Link {
        text: Vec<InlineNode>,
        url: String,
        title: Option<String>,
    },
    /// Image
    Image {
        alt: String,
        url: String,
        title: Option<String>,
    },
    /// Inline code
    Code(String),
    /// Line break
    LineBreak,
    /// HTML entity
    Html(String),
}

/// Table column alignment
#[derive(Debug, Clone, Copy)]
pub enum Alignment {
    /// No specific alignment
    None,
    /// Left aligned
    Left,
    /// Center aligned
    Center,
    /// Right aligned
    Right,
}

/// Parse a Markdown string into an AST
pub fn parse(markdown: &str, options: &ParseOptions) -> Result<ParsedDocument, Error> {
    let mut frontmatter = None;
    let mut content = markdown.to_string();

    // Process frontmatter if enabled
    if options.frontmatter && content.starts_with("---") {
        if let Some((yaml, rest)) = extract_frontmatter(&content) {
            frontmatter = parse_yaml_frontmatter(yaml)?;
            content = rest.to_string();
        }
    }

    // Configure pulldown-cmark parser options
    let mut cmark_options = CmarkOptions::empty();
    if options.gfm {
        cmark_options.insert(CmarkOptions::ENABLE_TABLES);
        cmark_options.insert(CmarkOptions::ENABLE_STRIKETHROUGH);
        cmark_options.insert(CmarkOptions::ENABLE_TASKLISTS);
    }
    if options.smart_punctuation {
        cmark_options.insert(CmarkOptions::ENABLE_SMART_PUNCTUATION);
    }

    // Parse Markdown content
    let parser = CmarkParser::new_ext(&content, cmark_options);
    let ast = process_events(parser, options)?;

    Ok(ParsedDocument { ast, frontmatter })
}

// Extract YAML frontmatter from Markdown content
fn extract_frontmatter(content: &str) -> Option<(&str, &str)> {
    let rest = content.strip_prefix("---")?;
    let end_index = rest.find("\n---")?;
    let yaml = &rest[..end_index];
    let content_start = end_index + 5; // Skip over the ending "---\n"

    if content_start < rest.len() {
        Some((yaml, &rest[content_start..]))
    } else {
        Some((yaml, ""))
    }
}

// Parse YAML frontmatter into a HashMap
fn parse_yaml_frontmatter(yaml: &str) -> Result<Option<HashMap<String, serde_yaml::Value>>, Error> {
    let frontmatter: HashMap<String, serde_yaml::Value> = serde_yaml::from_str(yaml)?;
    if frontmatter.is_empty() {
        Ok(None)
    } else {
        Ok(Some(frontmatter))
    }
}

// Process pulldown-cmark parser events into our AST
fn process_events<'a, I>(events: I, options: &ParseOptions) -> Result<Vec<Node>, Error>
where
    I: Iterator<Item = Event<'a>>,
{
    let mut nodes = Vec::new();
    let mut current_node: Option<Node> = None;
    let mut current_inline_nodes: Vec<InlineNode> = Vec::new();
    let mut list_stack: Vec<(bool, Vec<Vec<Node>>)> = Vec::new();
    let mut block_quote_stack: Vec<Vec<Node>> = Vec::new();
    let mut link_stack: Vec<(String, Option<String>, Vec<InlineNode>)> = Vec::new();
    let mut component_stack: Vec<(String, HashMap<String, String>, Vec<Node>)> = Vec::new();
    let mut table_headers: Vec<Vec<InlineNode>> = Vec::new();
    let mut table_alignments: Vec<Alignment> = Vec::new();
    let mut table_rows: Vec<Vec<Vec<InlineNode>>> = Vec::new();
    let mut in_table_head = false;
    let mut in_table_row = false;
    let mut current_table_row: Vec<Vec<InlineNode>> = Vec::new();
    let mut current_table_cell: Vec<InlineNode> = Vec::new();
    let mut _in_emphasis = false;
    let mut _in_strong = false;
    let mut _in_strikethrough = false;

    use pulldown_cmark::{Event, Tag};

    let mut events = events.peekable();

    while let Some(event) = events.next() {
        match event {
            Event::Start(Tag::Paragraph) => {
                current_inline_nodes = Vec::new();
            }
            Event::End(Tag::Paragraph) => {
                if !current_inline_nodes.is_empty() {
                    let node = Node::Paragraph(current_inline_nodes.clone());
                    current_inline_nodes.clear();

                    if !block_quote_stack.is_empty() {
                        let last_idx = block_quote_stack.len() - 1;
                        block_quote_stack[last_idx].push(node);
                    } else if !list_stack.is_empty() {
                        let last_list_idx = list_stack.len() - 1;
                        if let Some(last_item) = list_stack[last_list_idx].1.last_mut() {
                            last_item.push(node);
                        }
                    } else if !component_stack.is_empty() {
                        let last_idx = component_stack.len() - 1;
                        component_stack[last_idx].2.push(node);
                    } else {
                        nodes.push(node);
                    }
                }
            }
            Event::Start(Tag::Heading(level, _, _)) => {
                current_inline_nodes = Vec::new();
                current_node = Some(Node::Heading {
                    level: level as u8,
                    content: String::new(),
                    id: String::new(),
                });
            }
            Event::End(Tag::Heading(..)) => {
                if let Some(Node::Heading { level, .. }) = current_node {
                    // Convert inline nodes to string for the heading content
                    let mut content = String::new();
                    for node in &current_inline_nodes {
                        match node {
                            InlineNode::Text(text) => content.push_str(text),
                            InlineNode::Code(code) => content.push_str(code),
                            _ => {} // Simplified handling
                        }
                    }

                    // Generate a slug ID from the heading content
                    let id = content
                        .to_lowercase()
                        .replace(|c: char| !c.is_alphanumeric(), "-")
                        .replace("--", "-")
                        .trim_matches('-')
                        .to_string();

                    let heading = Node::Heading { level, content, id };

                    if !block_quote_stack.is_empty() {
                        let last_idx = block_quote_stack.len() - 1;
                        block_quote_stack[last_idx].push(heading);
                    } else if !component_stack.is_empty() {
                        let last_idx = component_stack.len() - 1;
                        component_stack[last_idx].2.push(heading);
                    } else {
                        nodes.push(heading);
                    }

                    current_node = None;
                    current_inline_nodes.clear();
                }
            }
            Event::Start(Tag::BlockQuote) => {
                block_quote_stack.push(Vec::new());
            }
            Event::End(Tag::BlockQuote) => {
                if let Some(quote_nodes) = block_quote_stack.pop() {
                    let node = Node::BlockQuote(quote_nodes);

                    if !block_quote_stack.is_empty() {
                        let last_idx = block_quote_stack.len() - 1;
                        block_quote_stack[last_idx].push(node);
                    } else if !component_stack.is_empty() {
                        let last_idx = component_stack.len() - 1;
                        component_stack[last_idx].2.push(node);
                    } else {
                        nodes.push(node);
                    }
                }
            }
            Event::Start(Tag::CodeBlock(kind)) => {
                let mut language = None;
                let attributes = HashMap::new();

                if let CodeBlockKind::Fenced(lang) = kind {
                    let lang_str = lang.to_string();
                    if !lang_str.is_empty() {
                        language = Some(lang_str);
                    }
                }

                current_node = Some(Node::CodeBlock {
                    language,
                    content: String::new(),
                    attributes,
                });
            }
            Event::End(Tag::CodeBlock(_)) => {
                if let Some(node) = current_node.take() {
                    if !block_quote_stack.is_empty() {
                        let last_idx = block_quote_stack.len() - 1;
                        block_quote_stack[last_idx].push(node);
                    } else if !component_stack.is_empty() {
                        let last_idx = component_stack.len() - 1;
                        component_stack[last_idx].2.push(node);
                    } else {
                        nodes.push(node);
                    }
                }
            }
            Event::Start(Tag::List(first_item_number)) => {
                list_stack.push((first_item_number.is_some(), Vec::new()));
            }
            Event::End(Tag::List(_)) => {
                if let Some((ordered, items)) = list_stack.pop() {
                    let node = Node::List { ordered, items };

                    if !block_quote_stack.is_empty() {
                        let last_idx = block_quote_stack.len() - 1;
                        block_quote_stack[last_idx].push(node);
                    } else if !list_stack.is_empty() {
                        let last_list_idx = list_stack.len() - 1;
                        if let Some(last_item) = list_stack[last_list_idx].1.last_mut() {
                            last_item.push(node);
                        }
                    } else if !component_stack.is_empty() {
                        let last_idx = component_stack.len() - 1;
                        component_stack[last_idx].2.push(node);
                    } else {
                        nodes.push(node);
                    }
                }
            }
            Event::Start(Tag::Item) => {
                if !list_stack.is_empty() {
                    let last_idx = list_stack.len() - 1;
                    list_stack[last_idx].1.push(Vec::new());
                }
            }
            Event::End(Tag::Item) => {
                // Handled in the list processing
            }
            Event::Text(text) => {
                if let Some(Node::CodeBlock {
                    ref mut content, ..
                }) = current_node
                {
                    content.push_str(&text);
                } else {
                    current_inline_nodes.push(InlineNode::Text(text.to_string()));
                }
            }
            Event::Code(code) => {
                current_inline_nodes.push(InlineNode::Code(code.to_string()));
            }
            Event::Html(html) => {
                let html_str = html.to_string();

                // Check for custom component syntax if enabled
                if options.custom_components && html_str.trim().starts_with("::") {
                    if html_str.trim().starts_with(":::") {
                        // Nested component (like tab inside tabs)
                        if let Some(component_name) = parse_component_start(&html_str) {
                            let attributes =
                                extract_component_attributes(&html_str).unwrap_or_default();

                            if !component_stack.is_empty() {
                                let child_component = (component_name, attributes, Vec::new());
                                let last_idx = component_stack.len() - 1;
                                component_stack[last_idx].2.push(Node::Component {
                                    name: child_component.0.clone(),
                                    attributes: child_component.1.clone(),
                                    children: Vec::new(),
                                });
                                component_stack.push(child_component);
                            }
                        }
                    } else if let Some(component_name) = parse_component_start(&html_str) {
                        let attributes =
                            extract_component_attributes(&html_str).unwrap_or_default();
                        component_stack.push((component_name, attributes, Vec::new()));
                    } else if html_str.trim() == "::" || html_str.trim() == ":::" {
                        // End of component
                        if let Some((name, attributes, children)) = component_stack.pop() {
                            let node = Node::Component {
                                name,
                                attributes,
                                children,
                            };

                            if !component_stack.is_empty() {
                                let last_idx = component_stack.len() - 1;
                                // Check if the last child of the parent component is already this component
                                if let Some(Node::Component {
                                    name: child_name,
                                    attributes: child_attrs,
                                    children: child_children,
                                }) = component_stack[last_idx].2.last_mut()
                                {
                                    if child_name == node.name()
                                        && *child_attrs == node.attributes()
                                    {
                                        // This is already a placeholder for this component - update its children
                                        *child_children = node.children();
                                        continue;
                                    }
                                }
                                component_stack[last_idx].2.push(node);
                            } else if !block_quote_stack.is_empty() {
                                let last_idx = block_quote_stack.len() - 1;
                                block_quote_stack[last_idx].push(node);
                            } else {
                                nodes.push(node);
                            }
                        }
                    } else {
                        nodes.push(Node::Html(html_str));
                    }
                } else {
                    nodes.push(Node::Html(html_str));
                }
            }
            Event::Start(Tag::Emphasis) => {
                let mut emphasis_nodes = Vec::new();

                // Extract emphasized content
                for next_event in events.by_ref() {
                    match next_event {
                        Event::Text(text) => {
                            emphasis_nodes.push(InlineNode::Text(text.to_string()));
                        }
                        Event::End(Tag::Emphasis) => {
                            break;
                        }
                        _ => {} // Simplify other events
                    }
                }

                current_inline_nodes.push(InlineNode::Emphasis(emphasis_nodes));
            }
            Event::Start(Tag::Strong) => {
                let mut strong_nodes = Vec::new();

                // Extract strong content
                for next_event in events.by_ref() {
                    match next_event {
                        Event::Text(text) => {
                            strong_nodes.push(InlineNode::Text(text.to_string()));
                        }
                        Event::End(Tag::Strong) => {
                            break;
                        }
                        _ => {} // Simplify other events
                    }
                }

                current_inline_nodes.push(InlineNode::Strong(strong_nodes));
            }
            Event::Start(Tag::Strikethrough) => {
                let mut strikethrough_nodes = Vec::new();

                // Extract strikethrough content
                for next_event in events.by_ref() {
                    match next_event {
                        Event::Text(text) => {
                            strikethrough_nodes.push(InlineNode::Text(text.to_string()));
                        }
                        Event::End(Tag::Strikethrough) => {
                            break;
                        }
                        _ => {} // Simplify other events
                    }
                }

                current_inline_nodes.push(InlineNode::Strikethrough(strikethrough_nodes));
            }
            Event::Start(Tag::Link(_link_type, url, title)) => {
                let url_str = url.to_string();
                let title_opt = if title.is_empty() {
                    None
                } else {
                    Some(title.to_string())
                };
                link_stack.push((url_str, title_opt, Vec::new()));
            }
            Event::End(Tag::Link(_, _, _)) => {
                if let Some((url, title, text)) = link_stack.pop() {
                    current_inline_nodes.push(InlineNode::Link { url, title, text });
                }
            }
            Event::Start(Tag::Image(_link_type, url, title)) => {
                let url_str = url.to_string();
                let title_opt = if title.is_empty() {
                    None
                } else {
                    Some(title.to_string())
                };
                // Collect alt text from next text event
                if let Some(Event::Text(alt)) = events.next() {
                    current_inline_nodes.push(InlineNode::Image {
                        url: url_str,
                        title: title_opt,
                        alt: alt.to_string(),
                    });
                } else {
                    current_inline_nodes.push(InlineNode::Image {
                        url: url_str,
                        title: title_opt,
                        alt: String::new(),
                    });
                }
                // Skip the end tag
                events.next();
            }
            Event::SoftBreak | Event::HardBreak => {
                current_inline_nodes.push(InlineNode::LineBreak);
            }
            Event::Start(Tag::Table(alignments)) => {
                table_headers = Vec::new();
                table_rows = Vec::new();
                table_alignments = alignments
                    .iter()
                    .map(|a| match a {
                        pulldown_cmark::Alignment::None => Alignment::None,
                        pulldown_cmark::Alignment::Left => Alignment::Left,
                        pulldown_cmark::Alignment::Center => Alignment::Center,
                        pulldown_cmark::Alignment::Right => Alignment::Right,
                    })
                    .collect();
            }
            Event::End(Tag::Table(_)) => {
                let node = Node::Table {
                    headers: table_headers.clone(),
                    rows: table_rows.clone(),
                    alignments: table_alignments.clone(),
                };

                if !block_quote_stack.is_empty() {
                    let last_idx = block_quote_stack.len() - 1;
                    block_quote_stack[last_idx].push(node);
                } else if !component_stack.is_empty() {
                    let last_idx = component_stack.len() - 1;
                    component_stack[last_idx].2.push(node);
                } else {
                    nodes.push(node);
                }

                table_headers.clear();
                table_rows.clear();
                table_alignments.clear();
            }
            Event::Start(Tag::TableHead) => {
                in_table_head = true;
            }
            Event::End(Tag::TableHead) => {
                in_table_head = false;
            }
            Event::Start(Tag::TableRow) => {
                in_table_row = true;
                current_table_row = Vec::new();
            }
            Event::End(Tag::TableRow) => {
                in_table_row = false;
                if !current_table_row.is_empty() {
                    if in_table_head {
                        table_headers = current_table_row.clone();
                    } else {
                        table_rows.push(current_table_row.clone());
                    }
                    current_table_row.clear();
                }
            }
            Event::Start(Tag::TableCell) => {
                current_table_cell = Vec::new();
            }
            Event::End(Tag::TableCell) => {
                if in_table_row {
                    current_table_row.push(current_table_cell.clone());
                    current_table_cell.clear();
                }
            }
            Event::Rule => {
                nodes.push(Node::ThematicBreak);
            }
            Event::FootnoteReference(_) => {
                // Not implemented in this example
            }
            Event::TaskListMarker(_) => {
                // Not implemented in this example
            }
            // Handle any other events that we haven't explicitly handled
            _ => {
                // For simplicity, we'll just ignore other events
            }
        }
    }

    Ok(nodes)
}

// Helper function to parse component syntax
fn parse_component_start(html: &str) -> Option<String> {
    let html = html.trim();
    if !html.starts_with("::") {
        return None;
    }

    let content = if html.starts_with(":::") {
        html.trim_start_matches(":::")
    } else {
        html.trim_start_matches("::")
    };

    let name_end = content.find('{').unwrap_or(content.len());
    let name = content[..name_end].trim();

    if name.is_empty() {
        None
    } else {
        Some(name.to_string())
    }
}

// Helper function to extract component attributes
fn extract_component_attributes(html: &str) -> Option<HashMap<String, String>> {
    let html = html.trim();

    if let Some(start) = html.find('{') {
        if let Some(end) = html.find('}') {
            let attrs_str = &html[start + 1..end];
            let mut attributes = HashMap::new();

            for attr_pair in attrs_str.split_whitespace() {
                if let Some(equals_pos) = attr_pair.find('=') {
                    let name = attr_pair[..equals_pos].trim();
                    let value_with_quotes = attr_pair[equals_pos + 1..].trim();
                    let value = value_with_quotes
                        .trim_start_matches('"')
                        .trim_start_matches('\'')
                        .trim_end_matches('"')
                        .trim_end_matches('\'');

                    attributes.insert(name.to_string(), value.to_string());
                }
            }

            return Some(attributes);
        }
    }

    None
}