h2md 0.1.0

HTML to Markdown converter powered by a browser-grade HTML parser
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
use h2md::convert;

/// Helper: convert HTML to Markdown, trimming surrounding whitespace.
fn h(input: &str) -> String {
    let mut out = Vec::new();
    convert(input.as_bytes(), &mut out).expect("conversion failed");
    String::from_utf8(out)
        .expect("output was not valid UTF-8")
        .trim()
        .to_owned()
}

/// Helper: convert and return the raw output without trimming.
fn h_raw(input: &str) -> String {
    let mut out = Vec::new();
    convert(input.as_bytes(), &mut out).expect("conversion failed");
    String::from_utf8(out).expect("output was not valid UTF-8")
}

// Headings

#[test]
fn heading_levels() {
    for level in 1..=6 {
        let tag = format!("h{level}");
        let html = format!("<{tag}>Hello</{tag}>");
        let hashes = "#".repeat(level);
        assert_eq!(h(&html), format!("{hashes} Hello"));
    }
}

#[test]
fn heading_with_inline_markup() {
    assert_eq!(h("<h2>Bold <strong>move</strong></h2>"), "## Bold **move**");
}

// Paragraphs

#[test]
fn plain_paragraph() {
    assert_eq!(h("<p>Hello world</p>"), "Hello world");
}

#[test]
fn consecutive_paragraphs() {
    assert_eq!(h("<p>First</p><p>Second</p>"), "First\n\nSecond");
}

#[test]
fn paragraph_with_inline() {
    assert_eq!(
        h("<p>This is <strong>bold</strong> and <em>italic</em>.</p>"),
        "This is **bold** and *italic*."
    );
}

// Inline elements

#[test]
fn bold_strong() {
    assert_eq!(h("<strong>x</strong>"), "**x**");
    assert_eq!(h("<b>x</b>"), "**x**");
}

#[test]
fn italic_em() {
    assert_eq!(h("<em>x</em>"), "*x*");
    assert_eq!(h("<i>x</i>"), "*x*");
}

#[test]
fn strikethrough() {
    assert_eq!(h("<del>x</del>"), "~~x~~");
    assert_eq!(h("<s>x</s>"), "~~x~~");
    assert_eq!(h("<strike>x</strike>"), "~~x~~");
}

#[test]
fn link() {
    assert_eq!(
        h(r#"<a href="https://example.com">click</a>"#),
        "[click](https://example.com)"
    );
}

#[test]
fn link_without_href() {
    assert_eq!(h("<a>click</a>"), "[click]()");
}

#[test]
fn image() {
    assert_eq!(
        h(r#"<img src="a.png" alt="Alt text">"#),
        "![Alt text](a.png)"
    );
}

#[test]
fn image_without_alt() {
    assert_eq!(h(r#"<img src="a.png">"#), "![](a.png)");
}

#[test]
fn inline_code() {
    assert_eq!(h("<code>let x = 1;</code>"), "`let x = 1;`");
}

#[test]
fn inline_code_with_backticks() {
    assert_eq!(h("<code>a`b</code>"), "``a`b``");
}

// Lists

#[test]
fn unordered_list() {
    assert_eq!(
        h("<ul><li>one</li><li>two</li><li>three</li></ul>"),
        "- one\n- two\n- three"
    );
}

#[test]
fn ordered_list() {
    assert_eq!(
        h("<ol><li>first</li><li>second</li><li>third</li></ol>"),
        "1. first\n2. second\n3. third"
    );
}

#[test]
fn nested_list() {
    let html = "<ul>\
         <li>A\
         <ul><li>A1</li><li>A2</li></ul>\
         </li>\
         <li>B</li>\
         </ul>";
    let md = h(html);
    assert!(md.contains("- A\n"), "outer item: {md:?}");
    assert!(md.contains("  - A1\n"), "nested item A1: {md:?}");
    assert!(md.contains("  - A2"), "nested item A2: {md:?}");
    assert!(md.contains("- B"), "outer item B: {md:?}");
}

#[test]
fn nested_ordered_in_unordered() {
    let html = "<ul>\
         <li>Items\
         <ol><li>one</li><li>two</li></ol>\
         </li>\
         </ul>";
    let md = h(html);
    assert!(md.contains("- Items\n"), "outer item: {md:?}");
    assert!(md.contains("  1. one\n"), "nested item one: {md:?}");
    assert!(md.contains("  2. two"), "nested item two: {md:?}");
}

// Blockquotes

#[test]
fn blockquote_single_line() {
    assert_eq!(h("<blockquote>Hello</blockquote>"), "> Hello");
}

#[test]
fn blockquote_multiline() {
    assert_eq!(
        h("<blockquote><p>Line one</p><p>Line two</p></blockquote>"),
        "> Line one\n> \n> Line two"
    );
}

#[test]
fn blockquote_with_inline() {
    assert_eq!(
        h("<blockquote><strong>Bold quote</strong></blockquote>"),
        "> **Bold quote**"
    );
}

// Code blocks

#[test]
fn pre_block() {
    assert_eq!(h("<pre>fn main() {}\n</pre>"), "```\nfn main() {}\n```");
}

#[test]
fn pre_with_language() {
    assert_eq!(
        h("<pre><code class=\"language-rust\">let x = 1;</code></pre>"),
        "```rust\nlet x = 1;\n```"
    );
}

#[test]
fn pre_preserves_whitespace() {
    assert_eq!(
        h("<pre>  indented\n    more\n</pre>"),
        "```\n  indented\n    more\n```"
    );
}

// Tables

#[test]
fn table_with_headers() {
    let md = h("<table>\
         <tr><th>Name</th><th>Age</th></tr>\
         <tr><td>Alice</td><td>30</td></tr>\
         <tr><td>Bob</td><td>25</td></tr>\
         </table>");
    assert!(md.contains("| Name  | Age |"), "header row: {md:?}");
    assert!(md.contains("| ----- | --- |"), "separator: {md:?}");
    assert!(md.contains("| Alice | 30  |"), "data row 1: {md:?}");
    assert!(md.contains("| Bob   | 25  |"), "data row 2: {md:?}");
}

#[test]
fn table_without_explicit_headers() {
    let md = h("<table>\
         <tr><td>A</td><td>B</td></tr>\
         <tr><td>C</td><td>D</td></tr>\
         </table>");
    assert!(md.contains("| A"), "row with A: {md:?}");
    assert!(md.contains("| B"), "row with B: {md:?}");
    assert!(md.contains("| C"), "row with C: {md:?}");
    assert!(md.contains("| D"), "row with D: {md:?}");
    assert!(md.contains("| ---"), "separator: {md:?}");
}

#[test]
fn table_with_thead() {
    let md = h("<table>\
         <thead><tr><th>X</th></tr></thead>\
         <tbody><tr><td>1</td></tr></tbody>\
         </table>");
    assert!(md.contains("| X"), "header: {md:?}");
    assert!(md.contains("| ---"), "separator: {md:?}");
    assert!(md.contains("| 1"), "data: {md:?}");
}

#[test]
fn table_with_ragged_rows() {
    let md = h("<table>\
         <tr><td>A</td><td>B</td><td>C</td></tr>\
         <tr><td>D</td></tr>\
         </table>");
    assert!(md.contains("| A"), "row 1 col 1: {md:?}");
    assert!(md.contains("| D"), "row 2 col 1: {md:?}");
}

// Horizontal rules and line breaks

#[test]
fn horizontal_rule() {
    let md = h("<p>above</p><hr><p>below</p>");
    assert!(md.contains("above"), "above text: {md:?}");
    assert!(md.contains("---"), "horizontal rule: {md:?}");
    assert!(md.contains("below"), "below text: {md:?}");
}

#[test]
fn br_tag() {
    let md = h("<p>line one<br>line two</p>");
    assert!(
        md.contains("line one  \n"),
        "br as two trailing spaces: {md:?}"
    );
    assert!(md.contains("line two"), "second line: {md:?}");
}

#[test]
fn br_inside_pre() {
    let md = h("<pre>a<br>b</pre>");
    assert!(md.contains("a\nb"), "br as newline in pre: {md:?}");
}

// Whitespace normalization

#[test]
fn collapses_whitespace() {
    assert_eq!(h("<p>Hello     world</p>"), "Hello world");
}

#[test]
fn trims_leading_whitespace() {
    assert_eq!(h("<p>   Hello</p>"), "Hello");
}

#[test]
fn ignores_multiple_newlines_in_text() {
    assert_eq!(h("<p>Hello\n\n\nworld</p>"), "Hello world");
}

// Structural / div-like elements

#[test]
fn div_as_block() {
    let md = h("<p>before</p><div><p>inside</p></div><p>after</p>");
    assert!(md.contains("before"), "before: {md:?}");
    assert!(md.contains("inside"), "inside: {md:?}");
    assert!(md.contains("after"), "after: {md:?}");
    let before_pos = md.find("before").expect("before");
    let inside_pos = md.find("inside").expect("inside");
    let after_pos = md.find("after").expect("after");
    assert!(before_pos < inside_pos, "before comes before inside");
    assert!(inside_pos < after_pos, "inside comes before after");
}

#[test]
fn section_as_block() {
    assert_eq!(h("<section><p>content</p></section>"), "content");
}

// Stripped elements

#[test]
fn script_stripped() {
    assert_eq!(h("<p>visible</p><script>alert('xss')</script>"), "visible");
}

#[test]
fn style_stripped() {
    assert_eq!(h("<p>visible</p><style>body{}</style>"), "visible");
}

#[test]
fn head_stripped() {
    assert_eq!(
        h("<html><head><title>x</title></head><body><p>visible</p></body></html>"),
        "visible"
    );
}

// Comments and doctype

#[test]
fn html_comment_stripped() {
    assert_eq!(h("<p>visible</p><!-- a comment -->"), "visible");
}

// Unknown tags

#[test]
fn unknown_tag_children_rendered() {
    assert_eq!(h("<foo><p>Hello</p></foo>"), "Hello");
}

// Complex / integration

#[test]
fn full_document() {
    let html = concat!(
        "<h1>Title</h1>",
        "<p>A <strong>bold</strong> paragraph.</p>",
        "<ul><li>one</li><li>two</li></ul>",
        "<blockquote>Nice quote</blockquote>",
    );
    let md = h(html);
    assert!(md.contains("# Title"), "heading: {md:?}");
    assert!(md.contains("A **bold** paragraph."), "paragraph: {md:?}");
    assert!(md.contains("- one\n- two"), "list items: {md:?}");
    assert!(md.contains("> Nice quote"), "blockquote: {md:?}");
}

#[test]
fn nested_inline_elements() {
    assert_eq!(
        h("<p><strong><em>bold italic</em></strong></p>"),
        "***bold italic***"
    );
}

#[test]
fn link_with_bold_text() {
    assert_eq!(
        h(r#"<a href="https://example.com"><strong>link</strong></a>"#),
        "[**link**](https://example.com)"
    );
}

#[test]
fn image_in_paragraph() {
    assert_eq!(
        h(r#"<p><img src="photo.jpg" alt="A photo"></p>"#),
        "![A photo](photo.jpg)"
    );
}

#[test]
fn multiple_paragraphs_with_mixed_content() {
    let html = concat!(
        "<h2>Section</h2>",
        "<p>First paragraph.</p>",
        "<p>Second with <a href=\"/url\">a link</a>.</p>",
        "<hr>",
        "<p>After rule.</p>",
    );
    let md = h(html);
    assert!(md.contains("## Section"), "heading: {md:?}");
    assert!(md.contains("First paragraph."), "first para: {md:?}");
    assert!(md.contains("[a link](/url)"), "link: {md:?}");
    assert!(md.contains("---"), "hr: {md:?}");
    assert!(md.contains("After rule."), "last para: {md:?}");
}

// Raw output format

#[test]
fn block_output_has_blank_line_prefix_and_suffix() {
    let raw = h_raw("<p>Hello</p>");
    assert!(
        raw.starts_with("\n\n"),
        "block output starts with blank line: {raw:?}"
    );
    assert!(
        raw.ends_with("\n\n"),
        "block output ends with blank line: {raw:?}"
    );
}

#[test]
fn inline_output_has_trailing_newline_only() {
    let raw = h_raw("<strong>x</strong>");
    assert_eq!(raw, "**x**\n");
}

#[test]
fn finalize_appends_newline_when_missing() {
    let raw = h_raw("<strong>x</strong>");
    assert!(
        raw.ends_with('\n'),
        "finalize ensures trailing newline: {raw:?}"
    );
}

// Regression tests for bug fixes

#[test]
fn nested_blockquote() {
    let md = h("<blockquote><blockquote>inner</blockquote></blockquote>");
    assert!(md.contains("> > inner"), "nested blockquote: {md:?}");
}

#[test]
fn pre_inside_blockquote() {
    let md = h("<blockquote><pre>code\n</pre></blockquote>");
    assert!(
        md.contains("> ```"),
        "opening fence inside blockquote: {md:?}"
    );
    assert!(
        md.contains("> code"),
        "code content inside blockquote: {md:?}"
    );
    assert!(
        md.contains("> ```"),
        "closing fence inside blockquote: {md:?}"
    );
}

#[test]
fn blockquote_with_pre_and_text() {
    let md = h("<blockquote><p>before</p><pre>code\n</pre><p>after</p></blockquote>");
    assert!(md.contains("> before"), "text before pre: {md:?}");
    assert!(md.contains("> code"), "code content: {md:?}");
    assert!(md.contains("> after"), "text after pre: {md:?}");
}

#[test]
fn th_outside_thead() {
    let md = h("<table>\
         <tr><th>Name</th><th>Age</th></tr>\
         <tr><td>Alice</td><td>30</td></tr>\
         </table>");
    assert!(md.contains("| Name"), "header cell Name: {md:?}");
    assert!(md.contains("| ---"), "separator row: {md:?}");
    assert!(md.contains("| Alice"), "data cell: {md:?}");
}

#[test]
fn inline_with_marker_chars() {
    let md = h("<strong>a ** b</strong>");
    assert!(
        md.contains("__a ** b__"),
        "uses alternative delimiter: {md:?}"
    );
}

#[test]
fn link_with_parentheses() {
    let md = h(r#"<a href="http://example.com/(foo)">click</a>"#);
    assert!(
        md.contains("<http://example.com/(foo)>"),
        "URL wrapped in angle brackets: {md:?}"
    );
}

// Excessive newline regression tests

#[test]
fn no_excessive_blank_lines_with_empty_paragraphs() {
    let raw = h_raw("<p></p><p>Hello</p><p></p>");
    assert!(
        !raw.contains("\n\n\n"),
        "excessive blank lines in raw output: {raw:?}"
    );
}

#[test]
fn no_excessive_blank_lines_with_empty_heading() {
    let raw = h_raw("<h1></h1><p>Hello</p>");
    assert!(
        !raw.contains("\n\n\n"),
        "excessive blank lines in raw output: {raw:?}"
    );
}

#[test]
fn no_excessive_blank_lines_with_empty_blockquote() {
    let raw = h_raw("<blockquote></blockquote><p>Hello</p>");
    assert!(
        !raw.contains("\n\n\n"),
        "excessive blank lines in raw output: {raw:?}"
    );
}

#[test]
fn no_excessive_blank_lines_with_multiple_empty_blocks() {
    let raw = h_raw("<h1></h1><p></p><div></div><p>Hello</p>");
    assert!(
        !raw.contains("\n\n\n"),
        "excessive blank lines in raw output: {raw:?}"
    );
}

// Security tests

// Bug reproduction tests

#[test]
fn code_with_double_backticks() {
    // <code>``</code> produces "`` `` ``" which CommonMark parses as
    // an empty code span (opening `` at pos 0, closing `` at pos 3)
    // followed by literal " ``". The backtick content is lost.
    // Correct output should use triple backtick delimiters: "``` `` ```"
    let md = h("<code>``</code>");
    // The rendered code span should preserve both backticks
    assert!(
        md.contains("```") || md.contains("````"),
        "should use 3+ backtick delimiters for content with 2 backticks: {md:?}"
    );
}

#[test]
fn code_with_backticks_in_middle() {
    // <code>a``b</code> with double backticks in the middle of content.
    // Using `` as delimiters means the `` in the content is mistaken for
    // the closing delimiter. "`` a``b ``" parses as code span "a" then
    // literal "b ``".
    let md = h("<code>a``b</code>");
    assert!(
        md.contains("```") || md.contains("````"),
        "should use 3+ backtick delimiters when content has 2 consecutive backticks: {md:?}"
    );
}

#[test]
fn code_with_leading_trailing_spaces() {
    // CommonMark strips one leading and one trailing space from code spans.
    // " hello " rendered with ` hello ` becomes "hello" (spaces lost).
    // Should use double backticks with padding: "``  hello  ``"
    let md = h("<code> hello </code>");
    // The spaces should be preserved - check that the output uses
    // double backticks with extra padding
    assert!(
        md.starts_with("``") && !md.starts_with("````"),
        "should use double backtick delimiters for content with leading/trailing spaces: {md:?}"
    );
    // Verify there are extra padding spaces inside the delimiters
    assert!(
        md.contains("``  hello  ``"),
        "should have padding spaces around content: {md:?}"
    );
}

#[test]
fn code_with_only_spaces() {
    // <code> </code> - a single space. "` `" would be parsed as an empty
    // code span (space stripped). With "``   ``" (3 spaces), CommonMark
    // strips one from each end, preserving the single space.
    let md = h("<code> </code>");
    assert_eq!(md, "``   ``");
}

#[test]
fn ol_start_attribute() {
    // <ol start="5"> should produce "5. fifth" not "1. fifth"
    let md = h("<ol start=\"5\"><li>fifth</li><li>sixth</li></ol>");
    assert!(
        md.contains("5. fifth"),
        "should respect start attribute: {md:?}"
    );
    assert!(
        md.contains("6. sixth"),
        "should increment from start value: {md:?}"
    );
}

#[test]
fn link_with_space_in_url() {
    // URLs with spaces break markdown link syntax.
    // [text](http://example.com/path with spaces) -> broken
    // Should wrap in angle brackets: [text](<http://example.com/path with spaces>)
    let md = h(r#"<a href="http://example.com/path with spaces">click</a>"#);
    assert!(
        md.contains("<http://example.com/path with spaces>"),
        "URL with spaces should be wrapped in angle brackets: {md:?}"
    );
}

#[test]
fn image_with_space_in_src() {
    // Same issue for images - URLs with spaces need angle brackets
    let md = h(r#"<img src="http://example.com/img photo.png" alt="photo">"#);
    assert!(
        md.contains("<http://example.com/img photo.png>"),
        "image src with spaces should be wrapped in angle brackets: {md:?}"
    );
}

#[test]
fn deeply_nested_html_returns_error() {
    // Create deeply nested HTML using nested UL elements
    // Each UL contains one LI which contains another UL, creating true nesting
    let mut html = String::from("<ul><li>");
    for _ in 0..250 {
        html.push_str("<ul><li>");
    }
    html.push_str("content");
    for _ in 0..250 {
        html.push_str("</li></ul>");
    }
    html.push_str("</li></ul>");

    let mut out = Vec::new();
    let result = h2md::convert(html.as_bytes(), &mut out);
    assert!(result.is_err(), "deeply nested HTML should return error");
    if let Err(e) = result {
        assert!(
            e.to_string().contains("exceeds maximum depth"),
            "error should mention depth: {e}"
        );
    }
}