pter 0.1.0

Plain Text Email Renderer — convert HTML email bodies into readable markdown
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
use scraper::node::Node;
use scraper::{ElementRef, Html};

use crate::elements::{self, BlockKind, ElementAction, InlineKind};
use crate::replies;
use crate::tables;
use crate::whitespace;

/// Convert an HTML email body into readable markdown.
///
/// This is the main entry point for pter. Pass in an HTML string
/// (just the body, not MIME structure) and get back clean markdown.
///
/// ```
/// let md = pter::convert("<p>Hello <strong>world</strong></p>");
/// assert_eq!(md, "Hello **world**");
/// ```
pub fn convert(html: &str) -> String {
    if html.is_empty() {
        return String::new();
    }

    let document = Html::parse_document(html);
    let mut ctx = Context::new();
    walk_children(document.root_element(), &mut ctx);
    whitespace::normalize(&ctx.output)
}

/// Conversion state threaded through the tree walk.
struct Context {
    output: String,
    /// Current list nesting depth (for indentation).
    list_depth: u32,
    /// Whether we're inside a <pre> block (preserve whitespace).
    in_pre: bool,
    /// Whether we're inside an <a> tag (don't nest links).
    in_link: bool,
    /// Stack of list types for proper ordered/unordered rendering.
    list_stack: Vec<ListType>,
}

#[derive(Clone, Copy)]
enum ListType {
    Unordered,
    Ordered(u32), // current item number
}

impl Context {
    fn new() -> Self {
        Self {
            output: String::with_capacity(4096),
            list_depth: 0,
            in_pre: false,
            in_link: false,
            list_stack: Vec::new(),
        }
    }

    fn push(&mut self, s: &str) {
        self.output.push_str(s);
    }

    fn push_char(&mut self, c: char) {
        self.output.push(c);
    }

    fn ensure_blank_line(&mut self) {
        let trimmed = self.output.trim_end_matches(' ');
        if trimmed.is_empty() {
            return;
        }
        if trimmed.ends_with("\n\n") {
            return;
        }
        self.output.truncate(trimmed.len());
        self.output.push_str("\n\n");
    }

    fn ensure_newline(&mut self) {
        if !self.output.is_empty() && !self.output.ends_with('\n') {
            self.output.push('\n');
        }
    }

    fn list_indent(&self) -> String {
        if self.list_depth <= 1 {
            return String::new();
        }
        "  ".repeat((self.list_depth - 1) as usize)
    }
}

/// Walk all children of a node, converting each to markdown.
fn walk_children(parent: ElementRef, ctx: &mut Context) {
    for child in parent.children() {
        match child.value() {
            Node::Text(text) => {
                handle_text(&text.text, ctx);
            }
            Node::Element(_) => {
                if let Some(el_ref) = ElementRef::wrap(child) {
                    handle_element(el_ref, ctx);
                }
            }
            _ => {}
        }
    }
}

/// Handle a text node.
fn handle_text(text: &str, ctx: &mut Context) {
    if ctx.in_pre {
        ctx.push(text);
        return;
    }

    // Collapse whitespace in normal flow
    let mut last_was_space = ctx.output.ends_with(' ') || ctx.output.ends_with('\n');
    for ch in text.chars() {
        if ch.is_ascii_whitespace() {
            if !last_was_space {
                ctx.push_char(' ');
                last_was_space = true;
            }
        } else {
            ctx.push_char(ch);
            last_was_space = false;
        }
    }
}

/// Handle an element node — classify it and render accordingly.
fn handle_element(el: ElementRef, ctx: &mut Context) {
    let element = el.value();

    // Check hidden elements
    if elements::is_hidden(element) {
        return;
    }

    // Check for reply boundaries before normal classification.
    // Reply boundaries (gmail_quote, type=cite, etc.) get rendered
    // as blockquotes regardless of their actual element type.
    if replies::is_reply_boundary(el) {
        render_reply_block(el, ctx);
        return;
    }

    // Check for Outlook-style "From: ... Sent: ..." separator blocks.
    // These introduce quoted content that follows them.
    if replies::is_outlook_separator(el) {
        ctx.ensure_blank_line();
        // Render the separator header as attribution
        let text: String = el.text().collect();
        let trimmed = text.split_whitespace().collect::<Vec<_>>().join(" ");
        ctx.push(&trimmed);
        ctx.ensure_blank_line();
        return;
    }

    match elements::classify(element) {
        ElementAction::Skip => {}
        ElementAction::Transparent => walk_children(el, ctx),
        ElementAction::Block(kind) => handle_block(el, ctx, kind),
        ElementAction::Inline(kind) => handle_inline(el, ctx, kind),
    }
}

fn handle_block(el: ElementRef, ctx: &mut Context, kind: BlockKind) {
    match kind {
        BlockKind::Paragraph => {
            ctx.ensure_blank_line();
            walk_children(el, ctx);
            ctx.ensure_blank_line();
        }

        BlockKind::Heading(level) => {
            ctx.ensure_blank_line();
            let prefix = "#".repeat(level as usize);
            ctx.push(&prefix);
            ctx.push_char(' ');
            walk_children(el, ctx);
            ctx.ensure_blank_line();
        }

        BlockKind::Blockquote => {
            ctx.ensure_blank_line();
            // Render children into a temporary buffer, then prefix each line with >
            let mut inner_ctx = Context::new();
            inner_ctx.in_pre = ctx.in_pre;
            inner_ctx.in_link = ctx.in_link;
            walk_children(el, &mut inner_ctx);
            let inner = whitespace::normalize(&inner_ctx.output);
            for line in inner.lines() {
                ctx.push("> ");
                ctx.push(line);
                ctx.push_char('\n');
            }
            ctx.push_char('\n');
        }

        BlockKind::UnorderedList => {
            ctx.ensure_blank_line();
            ctx.list_depth += 1;
            ctx.list_stack.push(ListType::Unordered);
            walk_children(el, ctx);
            ctx.list_stack.pop();
            ctx.list_depth -= 1;
            ctx.ensure_blank_line();
        }

        BlockKind::OrderedList => {
            ctx.ensure_blank_line();
            ctx.list_depth += 1;
            ctx.list_stack.push(ListType::Ordered(0));
            walk_children(el, ctx);
            ctx.list_stack.pop();
            ctx.list_depth -= 1;
            ctx.ensure_blank_line();
        }

        BlockKind::ListItem => {
            ctx.ensure_newline();
            let indent = ctx.list_indent();
            ctx.push(&indent);

            // Determine bullet or number
            let marker = match ctx.list_stack.last_mut() {
                Some(ListType::Unordered) => "- ".to_string(),
                Some(ListType::Ordered(n)) => {
                    *n += 1;
                    format!("{}. ", *n)
                }
                None => "- ".to_string(),
            };
            ctx.push(&marker);
            walk_children(el, ctx);
            ctx.ensure_newline();
        }

        BlockKind::PreFormatted => {
            ctx.ensure_blank_line();
            ctx.push("```\n");
            ctx.in_pre = true;
            walk_children(el, ctx);
            ctx.in_pre = false;
            ctx.ensure_newline();
            ctx.push("```");
            ctx.ensure_blank_line();
        }

        BlockKind::HorizontalRule => {
            ctx.ensure_blank_line();
            ctx.push("---");
            ctx.ensure_blank_line();
        }

        BlockKind::Table => {
            ctx.ensure_blank_line();
            if tables::is_data_table(el) {
                let (headers, rows) = tables::extract_table_data(el);
                let md = tables::render_markdown_table(&headers, &rows);
                if !md.is_empty() {
                    ctx.push(&md);
                }
            } else {
                // Layout table — unwrap and render cell contents directly
                render_layout_table(el, ctx);
            }
            ctx.ensure_blank_line();
        }

        BlockKind::Div => {
            // Divs act as block separators but don't add their own markup
            ctx.ensure_blank_line();
            walk_children(el, ctx);
            ctx.ensure_blank_line();
        }
    }
}

fn handle_inline(el: ElementRef, ctx: &mut Context, kind: InlineKind) {
    match kind {
        InlineKind::Bold => {
            ctx.push("**");
            walk_children(el, ctx);
            ctx.push("**");
        }

        InlineKind::Italic => {
            ctx.push("*");
            walk_children(el, ctx);
            ctx.push("*");
        }

        InlineKind::Strikethrough => {
            ctx.push("~~");
            walk_children(el, ctx);
            ctx.push("~~");
        }

        InlineKind::Code => {
            if ctx.in_pre {
                // Inside a <pre>, don't double-wrap
                walk_children(el, ctx);
            } else {
                ctx.push("`");
                walk_children(el, ctx);
                ctx.push("`");
            }
        }

        InlineKind::Link => {
            if ctx.in_link {
                // Don't nest links
                walk_children(el, ctx);
                return;
            }

            let href = el.value().attr("href").unwrap_or("");

            if href.is_empty() || href == "#" {
                walk_children(el, ctx);
                return;
            }

            // Collect the link text
            let mut text_ctx = Context::new();
            text_ctx.in_link = true;
            walk_children(el, &mut text_ctx);
            let text = text_ctx.output.trim().to_string();

            if text.is_empty() {
                // Link with no text — just show the URL
                ctx.push(href);
            } else if text == href {
                // Link text matches URL — no need for markdown link syntax
                ctx.push(href);
            } else {
                ctx.push("[");
                ctx.push(&text);
                ctx.push("](");
                ctx.push(href);
                ctx.push(")");
            }
        }

        InlineKind::Image => {
            let element = el.value();
            if elements::is_tracking_pixel(element) {
                return;
            }

            let alt = element.attr("alt").unwrap_or("");
            let src = element.attr("src").unwrap_or("");

            if src.is_empty() {
                return;
            }

            ctx.push("![");
            ctx.push(alt);
            ctx.push("](");
            ctx.push(src);
            ctx.push(")");
        }

        InlineKind::LineBreak => {
            ctx.push_char('\n');
        }

        InlineKind::Superscript => {
            ctx.push("^");
            walk_children(el, ctx);
        }

        InlineKind::Subscript => {
            ctx.push("~");
            walk_children(el, ctx);
        }
    }
}

/// Render a reply boundary as a quoted block.
///
/// This is the same rendering logic as `<blockquote>` — children are
/// rendered into a temporary buffer and each line gets `> ` prefixed.
/// Attribution lines (e.g. "On ... wrote:") are rendered above the quote.
fn render_reply_block(el: ElementRef, ctx: &mut Context) {
    ctx.ensure_blank_line();

    // Look for attribution text
    if let Some(attribution) = replies::find_attribution(el) {
        ctx.push(&attribution);
        ctx.push_char('\n');
    }

    // Render children into temp buffer, then prefix with >
    let mut inner_ctx = Context::new();
    inner_ctx.in_pre = ctx.in_pre;
    inner_ctx.in_link = ctx.in_link;
    walk_children(el, &mut inner_ctx);
    let inner = whitespace::normalize(&inner_ctx.output);

    if !inner.is_empty() {
        for line in inner.lines() {
            ctx.push("> ");
            ctx.push(line);
            ctx.push_char('\n');
        }
        ctx.push_char('\n');
    }
}

/// Unwrap a layout table by rendering cell contents sequentially.
///
/// Walks through rows and cells, rendering each cell's content as if
/// the table wrapper didn't exist. This handles the common email pattern
/// of wrapping everything in `<table><tr><td>...</td></tr></table>`.
fn render_layout_table(table: ElementRef, ctx: &mut Context) {
    for descendant in table.descendants() {
        if let Some(el_ref) = ElementRef::wrap(descendant) {
            let name = el_ref.value().name();
            if name == "td" || name == "th" {
                // Check if the cell itself is hidden
                if !elements::is_hidden(el_ref.value()) {
                    walk_children(el_ref, ctx);
                    ctx.ensure_blank_line();
                }
            }
        }
    }
}

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

    // -- Basic elements --

    #[test]
    fn empty_input() {
        assert_eq!(convert(""), "");
    }

    #[test]
    fn plain_text() {
        assert_eq!(convert("hello world"), "hello world");
    }

    #[test]
    fn paragraph() {
        assert_eq!(convert("<p>one</p><p>two</p>"), "one\n\ntwo");
    }

    #[test]
    fn headings() {
        assert_eq!(convert("<h1>Title</h1>"), "# Title");
        assert_eq!(convert("<h3>Sub</h3>"), "### Sub");
    }

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

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

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

    #[test]
    fn link_empty_href() {
        assert_eq!(convert(r#"<a href="">click</a>"#), "click");
    }

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

    #[test]
    fn tracking_pixel_skipped() {
        assert_eq!(convert(r#"<img src="track.gif" width="1" height="1">"#), "");
    }

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

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

    #[test]
    fn nested_list() {
        let html = "<ul><li>outer<ul><li>inner</li></ul></li></ul>";
        let md = convert(html);
        assert!(md.contains("- outer"));
        assert!(md.contains("  - inner"));
    }

    #[test]
    fn nested_list_exact_indent_depth_2() {
        // At depth 2, `list_indent` returns `"  "` (exactly two spaces, one indent level).
        // Catches `list_indent` mutations:
        //   - `(depth - 1)` → `(depth + 1)`: would produce 3 indent levels (6 spaces).
        //   - `(depth - 1)` → `(depth / 1)`: would produce 2 indent levels (4 spaces).
        // Either makes this exact-match assertion fail.
        // (The converter emits a blank line before each nested list — that's a
        // separate stylistic question; the *indent* is what we're pinning down here.)
        assert_eq!(
            convert("<ul><li>A<ul><li>B</li></ul></li></ul>"),
            "- A\n\n  - B"
        );
    }

    #[test]
    fn triple_nested_list_exact_indent_depth_3() {
        // At depth 3, indent is exactly `"    "` (four spaces).
        assert_eq!(
            convert("<ul><li>A<ul><li>B<ul><li>C</li></ul></li></ul></li></ul>"),
            "- A\n\n  - B\n\n    - C"
        );
    }

    #[test]
    fn sibling_top_level_lists_have_no_indent_after_nesting() {
        // After a nested <ul> closes, `list_depth -= 1` must execute to return
        // to outer scope. If mutated to `+= 1` or `/= 1`, list_depth stays
        // elevated and the SECOND top-level list ends up incorrectly indented.
        let md = convert(
            "<ul><li>A<ul><li>B</li></ul></li></ul><ul><li>C</li></ul>",
        );
        // The second list's "C" item must appear at column 0, not indented.
        // We check the exact substring "\n- C" (newline then no leading whitespace).
        assert!(
            md.contains("\n- C"),
            "second top-level list must not be indented after a nested list closes; got: {md:?}"
        );
        // And explicitly: it must NOT appear with leading spaces.
        assert!(
            !md.contains("\n  - C"),
            "second list incorrectly indented; got: {md:?}"
        );
    }

    #[test]
    fn ordered_list_decrements_depth_after_nesting() {
        // Same shape but with <ol> — exercises the L218 `-= 1` mutation in the
        // OrderedList block, distinct from UnorderedList's L208.
        let md = convert(
            "<ol><li>A<ol><li>B</li></ol></li></ol><ol><li>C</li></ol>",
        );
        assert!(md.contains("\n1. C"), "second ol must restart at depth 1: {md:?}");
        assert!(!md.contains("\n  1. C"), "second ol indented incorrectly: {md:?}");
    }

    #[test]
    fn blockquote() {
        assert_eq!(convert("<blockquote>quoted text</blockquote>"), "> quoted text");
    }

    #[test]
    fn nested_blockquote() {
        let html = "<blockquote>outer<blockquote>inner</blockquote></blockquote>";
        let md = convert(html);
        assert!(md.contains("> outer"));
        assert!(md.contains("> > inner"));
    }

    #[test]
    fn preformatted() {
        let html = "<pre><code>fn main() {\n    println!(\"hi\");\n}</code></pre>";
        let md = convert(html);
        assert!(md.starts_with("```\n"));
        assert!(md.contains("fn main()"));
        assert!(md.ends_with("\n```"));
    }

    #[test]
    fn horizontal_rule() {
        assert_eq!(convert("<p>above</p><hr><p>below</p>"), "above\n\n---\n\nbelow");
    }

    #[test]
    fn br_tag() {
        assert_eq!(convert("line one<br>line two"), "line one\nline two");
    }

    #[test]
    fn strikethrough() {
        assert_eq!(convert("<del>removed</del>"), "~~removed~~");
    }

    #[test]
    fn inline_code() {
        assert_eq!(convert("use <code>pter</code> here"), "use `pter` here");
    }

    #[test]
    fn script_and_style_stripped() {
        assert_eq!(
            convert("<p>text</p><script>alert('x')</script><style>.x{}</style>"),
            "text"
        );
    }

    #[test]
    fn unknown_elements_transparent() {
        assert_eq!(convert("<span>hello</span>"), "hello");
    }

    #[test]
    fn hidden_element_skipped() {
        assert_eq!(
            convert(r#"<p>visible</p><div style="display:none">hidden</div>"#),
            "visible"
        );
    }

    #[test]
    fn whitespace_collapsed() {
        assert_eq!(convert("  lots   of   space  "), "lots of space");
    }

    #[test]
    fn entities_decoded() {
        // html5ever decodes entities during parsing
        assert_eq!(convert("<p>&amp; &lt; &gt; &quot;</p>"), "& < > \"");
    }

    #[test]
    fn sup_and_sub() {
        assert_eq!(convert("x<sup>2</sup>"), "x^2");
        assert_eq!(convert("H<sub>2</sub>O"), "H~2O");
    }

    // -- Div / section as block separator --

    #[test]
    fn div_separates_blocks() {
        assert_eq!(convert("<div>one</div><div>two</div>"), "one\n\ntwo");
    }

    // -- Tables --

    #[test]
    fn layout_table_single_cell_unwrapped() {
        let html = "<table><tr><td><p>Hello world</p></td></tr></table>";
        assert_eq!(convert(html), "Hello world");
    }

    #[test]
    fn layout_table_multi_column_linearized() {
        let html = "<table><tr><td>Left</td><td>Right</td></tr></table>";
        let md = convert(html);
        assert!(md.contains("Left"));
        assert!(md.contains("Right"));
    }

    #[test]
    fn data_table_rendered_as_markdown() {
        let html = "<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>";
        let md = convert(html);
        assert!(md.contains("| Name | Age |"));
        assert!(md.contains("| --- | --- |"));
        assert!(md.contains("| Alice | 30 |"));
        assert!(md.contains("| Bob | 25 |"));
    }

    #[test]
    fn nested_layout_tables_unwrapped() {
        let html = "<table><tr><td>\
                     <table><tr><td>Inner content</td></tr></table>\
                     </td></tr></table>";
        let md = convert(html);
        assert!(md.contains("Inner content"));
        assert!(!md.contains("|"));
    }

    #[test]
    fn presentation_role_is_layout() {
        let html = r#"<table role="presentation"><tr><td>Content</td><td>&nbsp;</td></tr></table>"#;
        let md = convert(html);
        assert!(md.contains("Content"));
        assert!(!md.contains("|"));
    }

    #[test]
    fn spacer_element_hidden() {
        let html = r#"<p>real</p><div style="font-size:0">spacer</div><p>also real</p>"#;
        let md = convert(html);
        assert!(md.contains("real"));
        assert!(!md.contains("spacer"));
        assert!(md.contains("also real"));
    }

    // -- Combined --

    #[test]
    fn mixed_content() {
        let html = r#"
            <h1>Subject</h1>
            <p>Hello <strong>Max</strong>,</p>
            <p>Check out <a href="https://example.com">this link</a>.</p>
            <ul>
                <li>Item one</li>
                <li>Item two</li>
            </ul>
        "#;
        let md = convert(html);
        assert!(md.starts_with("# Subject"));
        assert!(md.contains("Hello **Max**,"));
        assert!(md.contains("[this link](https://example.com)"));
        assert!(md.contains("- Item one\n- Item two"));
    }
}