sherwood 0.7.0

A static site generator with built-in development server
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
use anyhow::Result;
use markdown::mdast::{Node, Root};
use markdown::{Constructs, Options, ParseOptions, to_html_with_options, to_mdast};
use serde::Deserialize;
use std::path::Path;

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Frontmatter {
    pub title: Option<String>,
    pub date: Option<String>,
    pub list: Option<bool>,
    pub page_template: Option<String>,
    pub sort_by: Option<String>,
    pub sort_order: Option<String>,
    pub tags: Option<Vec<String>>,
    pub excerpt: Option<String>,
}

#[derive(Debug, Clone)]
pub struct MarkdownFile {
    pub path: std::path::PathBuf,
    pub content: String,
    pub frontmatter: Frontmatter,
    pub title: String,
}

pub struct MarkdownParser {
    parse_options: ParseOptions,
}

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

impl MarkdownParser {
    pub fn new() -> Self {
        let parse_options = ParseOptions {
            constructs: Constructs {
                frontmatter: true,
                ..Default::default()
            },
            ..ParseOptions::default()
        };

        Self { parse_options }
    }

    pub fn parse_markdown_file(file_path: &Path) -> Result<MarkdownFile> {
        let content = std::fs::read_to_string(file_path)?;
        let parser = Self::new();
        parser.parse_content(&content, file_path)
    }

    fn parse_content(&self, content: &str, file_path: &Path) -> Result<MarkdownFile> {
        // Parse AST once for both frontmatter and title extraction
        let root = to_mdast(content, &self.parse_options)
            .map_err(|e| anyhow::anyhow!("Failed to parse markdown: {}", e))?;

        // Extract frontmatter and clean content using AST
        let (frontmatter, markdown_content) = match &root {
            Node::Root(root_node) => self.extract_frontmatter_from_root(root_node, content),
            _ => Ok((Frontmatter::default(), content.to_string())),
        }?;

        // Extract title from frontmatter, first h1 from AST, or filename
        let title = frontmatter
            .title
            .clone()
            .or_else(|| Self::extract_title_from_ast(&root))
            .unwrap_or_else(|| {
                file_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("Untitled")
                    .to_string()
            });

        // Extract excerpt if not present in frontmatter
        let mut frontmatter = frontmatter;
        if frontmatter.excerpt.is_none() {
            frontmatter.excerpt = self.extract_excerpt_from_markdown(&markdown_content);
        }

        // Convert markdown content to HTML immediately
        let html_content = self.convert_markdown_to_html(&markdown_content)?;

        Ok(MarkdownFile {
            path: file_path.to_path_buf(),
            content: html_content, // Now always HTML
            frontmatter,
            title,
        })
    }

    fn extract_frontmatter_from_root(
        &self,
        root: &Root,
        original_content: &str,
    ) -> Result<(Frontmatter, String)> {
        let mut frontmatter = Frontmatter::default();
        let mut frontmatter_end_byte = None;

        #[allow(clippy::never_loop)]
        for child in root.children.iter() {
            match child {
                Node::Toml(toml_node) => {
                    if let Ok(parsed) = toml::from_str::<Frontmatter>(&toml_node.value) {
                        frontmatter = parsed;
                    }

                    // Get position information for content extraction
                    if let Some(position) = &toml_node.position {
                        frontmatter_end_byte = Some(position.end.offset);
                    }
                    break;
                }
                Node::Yaml(yaml_node) => {
                    if let Ok(parsed) = serde_yaml::from_str::<Frontmatter>(&yaml_node.value) {
                        frontmatter = parsed;
                    }

                    if let Some(position) = &yaml_node.position {
                        frontmatter_end_byte = Some(position.end.offset);
                    }
                    break;
                }
                _ => break,
            }
        }

        // Use AST position information for clean content extraction
        let markdown_content =
            self.extract_content_using_ast_position(original_content, frontmatter_end_byte);

        Ok((frontmatter, markdown_content))
    }

    #[allow(dead_code)]
    fn parse_frontmatter(&self, content: &str) -> Result<(Frontmatter, String)> {
        let root = to_mdast(content, &self.parse_options)
            .map_err(|e| anyhow::anyhow!("Failed to parse markdown: {}", e))?;

        match root {
            Node::Root(root) => self.extract_frontmatter_from_root(&root, content),
            _ => Ok((Frontmatter::default(), content.to_string())),
        }
    }

    fn extract_content_using_ast_position(
        &self,
        original_content: &str,
        frontmatter_end_byte: Option<usize>,
    ) -> String {
        match frontmatter_end_byte {
            Some(end_byte) => {
                // Convert byte offset to char offset safely
                let content_bytes = original_content.as_bytes();

                if end_byte >= content_bytes.len() {
                    // Frontmatter extends to end of content, return empty
                    return String::new();
                }

                // Find the content after frontmatter
                let remaining_bytes = &content_bytes[end_byte..];

                // Convert back to string and clean up leading whitespace
                let content_str = String::from_utf8_lossy(remaining_bytes);

                // Trim leading newlines and whitespace
                content_str.trim_start().to_string()
            }
            None => {
                // No frontmatter found, return original content
                original_content.to_string()
            }
        }
    }

    /// Convert markdown string to HTML with semantic enhancements
    fn convert_markdown_to_html(&self, markdown: &str) -> Result<String> {
        let options = Options::gfm(); // GFM includes strikethrough, tables, footnotes

        let html_output = to_html_with_options(markdown, &options)
            .map_err(|e| anyhow::anyhow!("Failed to parse markdown: {}", e))?;

        Ok(self.enhance_semantics(&html_output))
    }

    /// Apply semantic enhancements to HTML content (moved from renderer)
    fn enhance_semantics(&self, html: &str) -> String {
        let mut enhanced = html.to_string();

        // Wrap paragraphs in semantic sections if they seem like articles
        enhanced = wrap_articles(&enhanced);

        // Add semantic structure to lists
        enhanced = enhance_lists(&enhanced);

        enhanced
    }

    /// Extract plain text content from AST nodes recursively
    fn extract_text_from_nodes(nodes: &[Node]) -> String {
        nodes
            .iter()
            .map(|node| match node {
                Node::Text(text) => text.value.clone(),
                Node::Emphasis(emphasis) => Self::extract_text_from_nodes(&emphasis.children),
                Node::Strong(strong) => Self::extract_text_from_nodes(&strong.children),
                Node::InlineCode(code) => code.value.clone(),
                Node::Delete(delete) => Self::extract_text_from_nodes(&delete.children),
                Node::Link(link) => Self::extract_text_from_nodes(&link.children),
                Node::Image(image) => {
                    // Use alt text for images in headings
                    image.alt.clone()
                }
                Node::InlineMath(math) => math.value.clone(),
                // MDX nodes
                Node::MdxTextExpression(_) | Node::MdxJsxTextElement(_) => {
                    // For MDX content, we'll extract text if possible or skip
                    String::new()
                }
                _ => String::new(),
            })
            .collect::<Vec<String>>()
            .join("")
    }

    /// Extract plain text excerpt from markdown AST (first paragraph)
    /// Strips all formatting, returns full paragraph text
    pub fn extract_excerpt_from_markdown(&self, markdown: &str) -> Option<String> {
        let root = to_mdast(markdown, &self.parse_options).ok()?;
        self.extract_first_paragraph_from_ast(&root)
    }

    /// Extract first paragraph text from AST, stripping formatting
    fn extract_first_paragraph_from_ast(&self, root: &Node) -> Option<String> {
        if let Node::Root(root_node) = root {
            for child in &root_node.children {
                if let Node::Paragraph(para) = child {
                    let text = Self::extract_text_from_nodes(&para.children);
                    let trimmed = text.trim();
                    if !trimmed.is_empty() {
                        return Some(trimmed.to_string());
                    }
                }
            }
        }
        None
    }

    /// Extract plain text excerpt from content (for non-markdown parsers)
    /// Splits by double newlines to find first paragraph
    pub fn extract_excerpt_from_plain_text(content: &str) -> Option<String> {
        // Split by double newlines to find first paragraph
        let first_para = content.split("\n\n").next()?.trim();
        if !first_para.is_empty() {
            Some(first_para.to_string())
        } else {
            None
        }
    }

    /// Extract title from AST by finding the first H1 heading
    fn extract_title_from_ast(root: &Node) -> Option<String> {
        if let Node::Root(root_node) = root {
            for child in &root_node.children {
                if let Node::Heading(heading) = child
                    && heading.depth == 1
                {
                    let title_text = Self::extract_text_from_nodes(&heading.children);
                    if !title_text.trim().is_empty() {
                        return Some(title_text.trim().to_string());
                    }
                }
            }
        }
        None
    }
}

fn wrap_articles(html: &str) -> String {
    // Simple heuristic: if content has multiple headings, wrap in article tags
    let heading_count = html.matches("<h").count();
    if heading_count > 1 {
        format!("<article>\n{}\n</article>", html)
    } else {
        html.to_string()
    }
}

fn enhance_lists(html: &str) -> String {
    // Convert plain lists to more semantic versions when appropriate
    html.replace("<ul>", "<ul class=\"content-list\">")
        .replace("<ol>", "<ol class=\"numbered-list\">")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_toml_frontmatter_parsing() {
        let content = r#"+++
title = "Test Title"
date = "2024-01-15"
list = true
+++

# Content

This is the markdown content."#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(frontmatter.date, Some("2024-01-15".to_string()));
        assert_eq!(frontmatter.list, Some(true));
        assert_eq!(frontmatter.page_template, None);
        assert!(markdown_content.contains("# Content"));
    }

    #[test]
    fn test_yaml_frontmatter_parsing() {
        let content = r#"---
title: "Test Title"
date: "2024-01-15"
list: true
---

# Content

This is the markdown content."#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(frontmatter.date, Some("2024-01-15".to_string()));
        assert_eq!(frontmatter.list, Some(true));
        assert_eq!(frontmatter.page_template, None);
        assert!(markdown_content.contains("# Content"));
    }

    #[test]
    fn test_no_frontmatter() {
        let content = r#"# Simple Content

This content has no frontmatter."#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, None);
        assert_eq!(frontmatter.date, None);
        assert_eq!(frontmatter.list, None);
        assert_eq!(markdown_content, content);
    }

    #[test]
    fn test_invalid_toml_frontmatter() {
        let content = r#"+++
title = "Test Title"
invalid toml syntax
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok()); // Should fall back to default

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, None);
    }

    #[test]
    fn test_invalid_yaml_frontmatter() {
        let content = r#"---
title: "Test Title"
invalid: yaml: syntax::
---

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok()); // Should fall back to default

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, None);
    }

    #[test]
    fn test_partial_frontmatter_toml() {
        let content = r#"+++
title = "Only Title"
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Only Title".to_string()));
        assert_eq!(frontmatter.date, None);
        assert_eq!(frontmatter.list, None);
        assert_eq!(frontmatter.page_template, None);
    }

    #[test]
    fn test_page_template_field_toml() {
        let content = r#"+++
title = "Test Title"
page_template = "custom.stpl"
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(frontmatter.page_template, Some("custom.stpl".to_string()));
        assert!(markdown_content.contains("# Content"));
    }

    #[test]
    fn test_page_template_field_yaml() {
        let content = r#"---
title: "Test Title"
page_template: "custom.stpl"
---

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(frontmatter.page_template, Some("custom.stpl".to_string()));
        assert!(markdown_content.contains("# Content"));
    }

    #[test]
    fn test_malformed_delimiters() {
        let content = r#"+++
title = "Test Title"
---
# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, None); // Should not parse as valid frontmatter
        assert_eq!(
            markdown_content,
            "+++\ntitle = \"Test Title\"\n---\n# Content"
        ); // Markdown crate treats malformed frontmatter as regular content
    }

    #[test]
    fn test_empty_frontmatter_toml() {
        let content = r#"+++
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, None);
        assert_eq!(frontmatter.date, None);
        assert_eq!(frontmatter.list, None);
        assert_eq!(frontmatter.page_template, None);
        assert!(markdown_content.contains("# Content"));
    }

    #[test]
    fn test_markdown_file_parsing() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"+++
title = "File Test"
date = "2024-01-20"
+++

# Test File

This is a test file."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "File Test");
        assert_eq!(result.frontmatter.title, Some("File Test".to_string()));
        assert_eq!(result.frontmatter.date, Some("2024-01-20".to_string()));
        // Now content is HTML, not markdown
        assert!(result.content.contains("<h1>Test File</h1>"));
        assert!(result.content.contains("<p>This is a test file.</p>"));
        assert_eq!(result.path, file_path);

        Ok(())
    }

    #[test]
    fn test_title_extraction_from_h1() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"
# Simple Title

This content has no frontmatter title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Simple Title");
        assert_eq!(result.frontmatter.title, None);
        // Content should be HTML now
        assert!(result.content.contains("<h1>Simple Title</h1>"));

        Ok(())
    }

    #[test]
    fn test_title_extraction_from_filename() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("my-filename.md");

        let content = r#"Some content without H1 heading."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "my-filename");

        Ok(())
    }

    #[test]
    fn test_title_priority() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"+++
title = "Frontmatter Title"
+++

# H1 Title

Content."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Frontmatter title should have highest priority
        assert_eq!(result.title, "Frontmatter Title");

        Ok(())
    }

    #[test]
    fn test_sort_fields_parsing() {
        let content = r#"+++
title = "Test Title"
date = "2024-01-15"
list = true
sort_by = "date"
sort_order = "desc"
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.sort_by, Some("date".to_string()));
        assert_eq!(frontmatter.sort_order, Some("desc".to_string()));
    }

    #[test]
    fn test_sort_fields_yaml_parsing() {
        let content = r#"---
title: "Test Title"
date: "2024-01-15"
list: true
sort_by: "title"
sort_order: "asc"
---

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.sort_by, Some("title".to_string()));
        assert_eq!(frontmatter.sort_order, Some("asc".to_string()));
    }

    #[test]
    fn test_tags_field_toml_parsing() {
        let content = r#"+++
title = "Test Title"
tags = ["rust", "web-development", "ssg"]
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(
            frontmatter.tags,
            Some(vec![
                "rust".to_string(),
                "web-development".to_string(),
                "ssg".to_string()
            ])
        );
    }

    #[test]
    fn test_tags_field_yaml_parsing() {
        let content = r#"---
title: "Test Title"
tags:
  - rust
  - web-development
  - ssg
---

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(
            frontmatter.tags,
            Some(vec![
                "rust".to_string(),
                "web-development".to_string(),
                "ssg".to_string()
            ])
        );
    }

    #[test]
    fn test_empty_tags_field() {
        let content = r#"+++
title = "Test Title"
tags = []
+++

# Content"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, _) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Test Title".to_string()));
        assert_eq!(frontmatter.tags, Some(vec![]));
    }

    #[test]
    fn test_gray_matter_toml_delimiters() {
        let content = r#"+++
title = "Delimiter Test"
+++

# Testing TOML delimiters with markdown crate"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Delimiter Test".to_string()));

        // Verify frontmatter is completely removed from markdown content
        assert_eq!(
            markdown_content.trim(),
            "# Testing TOML delimiters with markdown crate"
        );
    }

    #[test]
    fn test_gray_matter_yaml_delimiters() {
        let content = r#"---
title: "Delimiter Test"
---

# Testing YAML delimiters with markdown crate"#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content);
        assert!(result.is_ok());

        let (frontmatter, markdown_content) = result.unwrap();
        assert_eq!(frontmatter.title, Some("Delimiter Test".to_string()));

        // Verify frontmatter is completely removed from markdown content
        assert_eq!(
            markdown_content.trim(),
            "# Testing YAML delimiters with markdown crate"
        );
    }

    #[test]
    fn test_ast_guided_frontmatter_extraction() {
        let parser = MarkdownParser::new();

        let content = r#"+++
title = "Test Article"
date = "2023-01-01"
tags = ["test", "extraction"]
+++

# Main Content

This is the main content of the article.

## Subsection

More content here."#;

        let (frontmatter, markdown_content) = parser.parse_frontmatter(content).unwrap();

        // Verify frontmatter is parsed correctly
        assert_eq!(frontmatter.title, Some("Test Article".to_string()));
        assert_eq!(frontmatter.date, Some("2023-01-01".to_string()));
        assert_eq!(
            frontmatter.tags,
            Some(vec!["test".to_string(), "extraction".to_string()])
        );

        // Verify frontmatter is completely removed from markdown content
        assert!(!markdown_content.contains("title = \"Test Article\""));
        assert!(!markdown_content.contains("date = \"2023-01-01\""));
        assert!(!markdown_content.contains("+++"));

        // Verify content structure is preserved
        let markdown_lines: Vec<&str> = markdown_content.trim().lines().collect();
        assert_eq!(markdown_lines[0], "# Main Content");
        assert!(markdown_content.contains("## Subsection"));
        assert!(markdown_content.contains("More content here."));
    }

    #[test]
    fn test_ast_title_extraction_simple() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# Simple Title

This content has a simple H1 title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Simple Title");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_with_emphasis() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# Title with *emphasis* and **bold**

This content has a complex H1 title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Title with emphasis and bold");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_with_inline_code() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# Title with `code` and more text

This content has inline code in the title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Title with code and more text");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_with_link() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# Title with [a link](https://example.com) text

This content has a link in the title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Title with a link text");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_complex_formatting() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# Title with *italic*, **bold**, `code`, and [links](https://example.com)

This content has all types of inline formatting."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(result.title, "Title with italic, bold, code, and links");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_ignores_h2_and_below() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"## H2 Title
### H3 Title

This content has no H1 title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Should fall back to filename since no H1 found
        assert_eq!(result.title, "test");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_first_h1_only() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"# First Title
# Second Title

This content has multiple H1 titles."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Should extract the first H1 only
        assert_eq!(result.title, "First Title");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_with_frontmatter_priority() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"+++
title = "Frontmatter Title"
+++

# H1 Title

This content has both frontmatter and H1 title."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Frontmatter title should take priority
        assert_eq!(result.title, "Frontmatter Title");
        assert_eq!(
            result.frontmatter.title,
            Some("Frontmatter Title".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_empty_heading() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"#

This content has an empty H1 heading."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Should fall back to filename since H1 is empty
        assert_eq!(result.title, "test");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_title_extraction_whitespace_only() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = "#
   
This content has a whitespace-only H1 heading.";

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        // Should fall back to filename since H1 contains only whitespace
        assert_eq!(result.title, "test");
        assert_eq!(result.frontmatter.title, None);

        Ok(())
    }

    #[test]
    fn test_ast_vs_string_parsing_compatibility() -> Result<()> {
        let temp_dir = tempdir()?;

        // Test cases that should work the same for both methods
        let test_cases = vec![
            ("simple", "# Simple Title\nContent here.", "Simple Title"),
            (
                "with-space",
                "# Title with space\nContent here.",
                "Title with space",
            ),
            (
                "with-punctuation",
                "# Title, with punctuation!\nContent here.",
                "Title, with punctuation!",
            ),
        ];

        for (filename, content, expected_title) in test_cases {
            let file_path = temp_dir.path().join(format!("{}.md", filename));
            fs::write(&file_path, content)?;

            let result = MarkdownParser::parse_markdown_file(&file_path)?;
            assert_eq!(
                result.title, expected_title,
                "Failed for case: {}",
                filename
            );
        }

        Ok(())
    }

    #[test]
    fn test_excerpt_in_frontmatter() {
        let content = r#"+++
title = "Test"
excerpt = "This is a custom excerpt"
+++

# Content

More content here."#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content).unwrap();
        assert_eq!(
            result.0.excerpt,
            Some("This is a custom excerpt".to_string())
        );
    }

    #[test]
    fn test_excerpt_extraction_from_markdown() {
        let content = r#"
# Title

This is the first paragraph with **bold** and *italic* text.

This is the second paragraph."#;

        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(
            excerpt,
            Some("This is the first paragraph with bold and italic text.".to_string())
        );
    }

    #[test]
    fn test_excerpt_extraction_empty_content() {
        let content = "";
        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(excerpt, None);
    }

    #[test]
    fn test_excerpt_extraction_no_paragraphs() {
        let content = "# Just a heading";
        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(excerpt, None);
    }

    #[test]
    fn test_excerpt_extraction_with_code() {
        let content = r#"
# Title

This paragraph has `inline code` and **bold** text.

More content."#;

        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(
            excerpt,
            Some("This paragraph has inline code and bold text.".to_string())
        );
    }

    #[test]
    fn test_excerpt_extraction_with_links() {
        let content = r#"
# Title

This paragraph has a [link](https://example.com) and more text.

More content."#;

        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(
            excerpt,
            Some("This paragraph has a link and more text.".to_string())
        );
    }

    #[test]
    fn test_excerpt_extraction_complex_markdown() {
        let content = r#"
# Title

This paragraph has **bold**, *italic*, `code`, and [links](https://example.com) all mixed together.

Second paragraph here."#;

        let parser = MarkdownParser::new();
        let excerpt = parser.extract_excerpt_from_markdown(content);
        assert_eq!(
            excerpt,
            Some(
                "This paragraph has bold, italic, code, and links all mixed together.".to_string()
            )
        );
    }

    #[test]
    fn test_excerpt_parsing_with_frontmatter() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"+++
title = "Test Title"
+++

# First Title

This is the first paragraph that should be extracted as an excerpt.

This is the second paragraph."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(
            result.frontmatter.excerpt,
            Some("This is the first paragraph that should be extracted as an excerpt.".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_excerpt_priority_frontmatter_over_extraction() -> Result<()> {
        let temp_dir = tempdir()?;
        let file_path = temp_dir.path().join("test.md");

        let content = r#"+++
title = "Test Title"
excerpt = "Custom excerpt from frontmatter"
+++

# First Title

This is the first paragraph that should NOT be extracted because frontmatter has an excerpt.

This is the second paragraph."#;

        fs::write(&file_path, content)?;

        let result = MarkdownParser::parse_markdown_file(&file_path)?;

        assert_eq!(
            result.frontmatter.excerpt,
            Some("Custom excerpt from frontmatter".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_excerpt_in_yaml_frontmatter() {
        let content = r#"---
title: "Test"
excerpt: "YAML excerpt"
---

# Content

More content here."#;

        let parser = MarkdownParser::new();
        let result = parser.parse_frontmatter(content).unwrap();
        assert_eq!(result.0.excerpt, Some("YAML excerpt".to_string()));
    }

    #[test]
    fn test_plain_text_excerpt_extraction() {
        assert_eq!(
            MarkdownParser::extract_excerpt_from_plain_text(
                "First paragraph.\n\nSecond paragraph."
            ),
            Some("First paragraph.".to_string())
        );
    }

    #[test]
    fn test_plain_text_excerpt_single_paragraph() {
        let content = "Just one paragraph without double newlines.";
        assert_eq!(
            MarkdownParser::extract_excerpt_from_plain_text(content),
            Some("Just one paragraph without double newlines.".to_string())
        );
    }

    #[test]
    fn test_plain_text_excerpt_empty() {
        assert_eq!(MarkdownParser::extract_excerpt_from_plain_text(""), None);
    }

    #[test]
    fn test_plain_text_excerpt_whitespace_only() {
        assert_eq!(
            MarkdownParser::extract_excerpt_from_plain_text("   \n\n   "),
            None
        );
    }
}