markdown2json 0.1.1

Reads a markdown file or directory of markdown documents and emits a structured JSON
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
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct CodeBlock {
    pub lang: Option<String>,
    pub meta: Option<String>,
    pub value: String,
    pub start_line: Option<usize>,
    pub end_line: Option<usize>,
}

#[derive(Debug, Clone)]
pub struct Section {
    pub title: String,
    pub level: u8,
    pub body_text: Vec<String>,
    pub code_blocks: Vec<CodeBlock>,
    pub start_line: Option<usize>,
    pub end_line: Option<usize>,
    pub heading_line: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct JsonCodeBlock {
    pub value: String,
    pub start_line: Option<usize>,
    pub end_line: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct JsonDocumentElement {
    pub file_path: String,
    pub header: String,
    pub text_blocks: Vec<String>,
    pub code_blocks: Vec<JsonCodeBlock>,
    pub start_line: Option<usize>,
    pub end_line: Option<usize>,
    pub heading_line: Option<usize>,
}

use markdown::message::Message;
use markdown::{self, ParseOptions, mdast};

/// Parse a markdown document into sections, each starting at a heading.
/// All text / code until the next heading belongs to that section.
///
/// Sections are *flat*: nested headings become separate sections, but
/// each still carries its heading level (`#` = 1, `##` = 2, …).

pub fn index_markdown(src: &str) -> Result<Vec<Section>, Message> {
    let ast = markdown::to_mdast(src, &ParseOptions::default())?;

    let root = match ast {
        mdast::Node::Root(root) => root,
        _ => unreachable!("to_mdast() always returns a Root at the top"),
    };

    let mut sections: Vec<Section> = Vec::new();
    let mut current: Option<Section> = None;

    for node in &root.children {
        match node {
            // === Headings start a new section ===
            mdast::Node::Heading(h) => {
                // Finish previous section, if any.
                if let Some(sec) = current.take() {
                    sections.push(sec);
                }

                let title = node_to_plain_text(node);

                current = Some(Section {
                    title,
                    level: h.depth,
                    body_text: Vec::new(),
                    code_blocks: Vec::new(),
                    start_line: node_start_line(node),
                    end_line: node_end_line(node),
                    heading_line: node_start_line(node),
                });
            }

            // === Paragraphs become body text ===
            mdast::Node::Paragraph(_) => {
                let text = node_to_plain_text(node);
                if text.trim().is_empty() {
                    continue;
                }

                let sec = current.get_or_insert_with(|| Section {
                    title: String::from("(preamble)"),
                    level: 0,
                    body_text: Vec::new(),
                    code_blocks: Vec::new(),
                    start_line: node_start_line(node),
                    end_line: node_end_line(node),
                    heading_line: None,
                });

                if !sec.body_text.is_empty() {
                    //sec.body_text.push_str("\n\n");
                }
                sec.body_text.push(text);
                update_section_end_line(sec, node_end_line(node));

                collect_inline_code_blocks(node, &mut sec.code_blocks);
            }

            // === Top-level fenced code blocks ===
            mdast::Node::Code(code) => {
                if let Some(sec) = current.as_mut() {
                    sec.code_blocks.push(CodeBlock {
                        lang: code.lang.clone(),
                        meta: code.meta.clone(),
                        value: code.value.clone(),
                        start_line: node_start_line(node),
                        end_line: node_end_line(node),
                    });
                    update_section_end_line(sec, node_end_line(node));
                } else {
                    // Code before any heading -> attach to a synthetic preamble section
                    let sec = Section {
                        title: String::from("(preamble)"),
                        level: 0,
                        body_text: Vec::new(),
                        code_blocks: vec![CodeBlock {
                            lang: code.lang.clone(),
                            meta: code.meta.clone(),
                            value: code.value.clone(),
                            start_line: node_start_line(node),
                            end_line: node_end_line(node),
                        }],
                        start_line: node_start_line(node),
                        end_line: node_end_line(node),
                        heading_line: None,
                    };
                    current = Some(sec);
                }
            }

            // === Inline code is indexed like fenced code ===
            mdast::Node::InlineCode(code) => {
                let inline_block = CodeBlock {
                    lang: None,
                    meta: None,
                    value: code.value.clone(),
                    start_line: node_start_line(node),
                    end_line: node_end_line(node),
                };

                if let Some(sec) = current.as_mut() {
                    sec.code_blocks.push(inline_block);
                    update_section_end_line(sec, node_end_line(node));
                } else {
                    let sec = Section {
                        title: String::from("(preamble)"),
                        level: 0,
                        body_text: Vec::new(),
                        code_blocks: vec![inline_block],
                        start_line: node_start_line(node),
                        end_line: node_end_line(node),
                        heading_line: None,
                    };
                    current = Some(sec);
                }
            }

            // === Block/inline content we treat as extra text ===
            //
            // We just flatten them to plain text and append to current section /
            // preamble. `node_to_plain_text` will walk their children.
            mdast::Node::Blockquote(_)
            | mdast::Node::FootnoteDefinition(_)
            | mdast::Node::MdxJsxFlowElement(_)
            | mdast::Node::List(_)
            | mdast::Node::MdxjsEsm(_)
            | mdast::Node::Toml(_)
            | mdast::Node::Yaml(_)
            | mdast::Node::Math(_)
            | mdast::Node::MdxFlowExpression(_)
            | mdast::Node::Table(_)
            | mdast::Node::TableRow(_)
            | mdast::Node::TableCell(_)
            | mdast::Node::ListItem(_)
            | mdast::Node::Definition(_)
            | mdast::Node::ThematicBreak(_)
            | mdast::Node::Html(_)
            // Phrasing / inline-like nodes (normally don’t show up at root,
            // but we handle them anyway to make the match exhaustive):
            | mdast::Node::Break(_)
            | mdast::Node::InlineMath(_)
            | mdast::Node::Delete(_)
            | mdast::Node::Emphasis(_)
            | mdast::Node::MdxTextExpression(_)
            | mdast::Node::FootnoteReference(_)
            | mdast::Node::Image(_)
            | mdast::Node::ImageReference(_)
            | mdast::Node::MdxJsxTextElement(_)
            | mdast::Node::Link(_)
            | mdast::Node::LinkReference(_)
            | mdast::Node::Strong(_)
            | mdast::Node::Text(_) => {
                let text = node_to_plain_text(node);
                if text.trim().is_empty() {
                    continue;
                }

                if let Some(sec) = current.as_mut() {
                    if !sec.body_text.is_empty() {
                        //sec.body_text.push_str("\n\n");
                    }
                    sec.body_text.push(text);
                    update_section_end_line(sec, node_end_line(node));
                } else {
                    let preamble = Section {
                        title: String::from("(preamble)"),
                        level: 0,
                        body_text: vec![text],
                        code_blocks: Vec::new(),
                        start_line: node_start_line(node),
                        end_line: node_end_line(node),
                        heading_line: None,
                    };
                    current = Some(preamble);
                }
            }

            // Root should not appear as a child of Root, but we include it
            // so the match is truly exhaustive and future-proof.
            mdast::Node::Root(_) => {
                // no-op
            }
        }
    }

    // Flush last section.
    if let Some(sec) = current.take() {
        sections.push(sec);
    }

    Ok(sections)
}

fn node_start_line(node: &mdast::Node) -> Option<usize> {
    node.position().map(|p| p.start.line)
}

fn node_end_line(node: &mdast::Node) -> Option<usize> {
    node.position().map(|p| p.end.line)
}

fn update_section_end_line(section: &mut Section, candidate_end_line: Option<usize>) {
    match (section.end_line, candidate_end_line) {
        (Some(current), Some(candidate)) => section.end_line = Some(current.max(candidate)),
        (None, Some(candidate)) => section.end_line = Some(candidate),
        _ => {}
    }
}
/// Collect human-readable text from a node (drops formatting, links, etc.).
fn node_to_plain_text(node: &mdast::Node) -> String {
    let mut out = String::new();
    collect_text(node, &mut out);
    out
}

fn collect_inline_code_blocks(node: &mdast::Node, out: &mut Vec<CodeBlock>) {
    match node {
        mdast::Node::InlineCode(code) => out.push(CodeBlock {
            lang: None,
            meta: None,
            value: code.value.clone(),
            start_line: node_start_line(node),
            end_line: node_end_line(node),
        }),
        _ => {
            if let Some(children) = node.children() {
                for child in children {
                    collect_inline_code_blocks(child, out);
                }
            }
        }
    }
}

fn collect_text(node: &mdast::Node, out: &mut String) {
    match node {
        mdast::Node::Text(t) => {
            out.push_str(&t.value);
        }
        mdast::Node::InlineCode(c) => {
            // Treat inline code as text for indexing
            out.push_str(&c.value);
        }
        _ => {
            if let Some(children) = node.children() {
                for child in children {
                    collect_text(child, out);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn heading_paragraph_and_code_are_grouped_into_one_section() {
        let src = r#"
# Introduction


This is the intro text.


```rust
fn main() {
println!(\"hello\");
}
```
"#;

        let sections = index_markdown(src).expect("parse ok");

        assert_eq!(sections.len(), 1);
        println!("{:?}", sections);

        let s = &sections[0];
        assert_eq!(s.title, "Introduction");
        assert_eq!(s.level, 1);

        // Body text
        assert!(
            s.body_text.contains(&"This is the intro text.".to_string()),
            "body_text = {:?}",
            s.body_text
        );

        // Code block
        assert_eq!(s.code_blocks.len(), 1);
        let cb = &s.code_blocks[0];
        assert_eq!(cb.lang.as_deref(), Some("rust"));
        assert!(cb.value.contains("println!("));
    }

    #[test]
    fn multiple_headings_become_multiple_sections() {
        let src = r#"
# Intro


Intro text.


## Details


More details here.


```python
print(\"hi\")
```
"#;

        let sections = index_markdown(src).expect("parse ok");

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

        let intro = &sections[0];
        assert_eq!(intro.title, "Intro");
        assert_eq!(intro.level, 1);
        assert!(intro.body_text.contains(&"Intro text.".to_string()));

        let details = &sections[1];
        assert_eq!(details.title, "Details");
        assert_eq!(details.level, 2);
        assert!(details.body_text[0].contains(&"More details here".to_string()));
        assert_eq!(details.code_blocks.len(), 1);
        assert_eq!(details.code_blocks[0].lang.as_deref(), Some("python"));
        // assert!(details.code_blocks[0].value.contains("print(\"hi\")"));
    }
    #[test]
    fn content_before_first_heading_goes_into_preamble_section() {
        let src = r#"
This is some text before any heading.


```bash
echo \"hello\"
```


# Heading


More text under heading.
"#;

        let sections = index_markdown(src).expect("parse ok");

        // We expect: (preamble), then Heading
        assert_eq!(sections.len(), 2);

        let preamble = &sections[0];
        assert_eq!(preamble.title, "(preamble)");
        assert_eq!(preamble.level, 0);
        assert!(preamble.body_text[0].contains(&"text before any heading".to_string()));
        assert_eq!(preamble.code_blocks.len(), 1);
        assert_eq!(preamble.code_blocks[0].lang.as_deref(), Some("bash"));
        // assert!(preamble.code_blocks[0].value.contains("echo \"hello\""));

        let heading = &sections[1];
        assert_eq!(heading.title, "Heading");
        assert_eq!(heading.level, 1);
        assert!(heading.body_text[0].contains(&"More text under heading".to_string()));
    }

    #[test]
    fn inline_formatting_is_flattened_to_plain_text() {
        let src = r#"
# Title


This is *bold* and `inline_code` and a [link](https://example.com).
    "#;

        let sections = index_markdown(src).expect("parse ok");

        assert_eq!(sections.len(), 1);
        let s = &sections[0];

        assert_eq!(s.title, "Title");
        let body = &s.body_text;

        // Our node_to_plain_text should keep the words, drop formatting
        assert!(body[0].contains(&"This is".to_string()), "{:?}", body);
        assert!(body[0].contains(&"bold".to_string()), "{:?}", body);
        assert!(body[0].contains(&"inline_code".to_string()));
        assert!(body[0].contains(&"link".to_string()));
    }

    #[test]
    fn inline_code_is_captured_as_code_blocks() {
        let src = r#"
# Title

Paragraph with `first` inline code and `second` snippet.
        "#;

        let sections = index_markdown(src).expect("parse ok");

        assert_eq!(sections.len(), 1);
        let s = &sections[0];

        let inline_values: Vec<&str> = s.code_blocks.iter().map(|cb| cb.value.as_str()).collect();

        assert!(inline_values.contains(&"first"));
        assert!(inline_values.contains(&"second"));
    }

    #[test]
    fn section_and_code_block_line_metadata_are_captured() {
        let src = "# Intro\nIntro paragraph.\n```rust\nfn main() {}\n```\n## Next\nTail text.\n";

        let sections = index_markdown(src).expect("parse ok");
        assert_eq!(sections.len(), 2);

        let intro = &sections[0];
        assert_eq!(intro.start_line, Some(1));
        assert_eq!(intro.heading_line, Some(1));
        assert_eq!(intro.end_line, Some(5));
        assert_eq!(intro.code_blocks.len(), 1);
        assert_eq!(intro.code_blocks[0].start_line, Some(3));
        assert_eq!(intro.code_blocks[0].end_line, Some(5));

        let next = &sections[1];
        assert_eq!(next.start_line, Some(6));
        assert_eq!(next.heading_line, Some(6));
        assert_eq!(next.end_line, Some(7));
    }

    #[test]
    fn preamble_section_has_no_heading_line_metadata() {
        let src = "Preamble text.\n# Heading\nUnder heading.\n";

        let sections = index_markdown(src).expect("parse ok");
        assert_eq!(sections.len(), 2);

        let preamble = &sections[0];
        assert_eq!(preamble.title, "(preamble)");
        assert_eq!(preamble.start_line, Some(1));
        assert_eq!(preamble.end_line, Some(1));
        assert_eq!(preamble.heading_line, None);
    }

    #[test]
    fn json_document_element_serializes_code_block_line_metadata() {
        let doc = JsonDocumentElement {
            file_path: "doc.md".to_string(),
            header: "Intro".to_string(),
            text_blocks: vec!["Body".to_string()],
            code_blocks: vec![JsonCodeBlock {
                value: "println!(\"hi\");".to_string(),
                start_line: Some(10),
                end_line: Some(12),
            }],
            start_line: Some(1),
            end_line: Some(12),
            heading_line: Some(1),
        };

        let value = serde_json::to_value(&doc).expect("serialize");
        assert_eq!(
            value["code_blocks"][0],
            json!({
                "value": "println!(\"hi\");",
                "start_line": 10,
                "end_line": 12
            })
        );
    }
}