ctb_formats_html/
markdown.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! HTML to Markdown conversion engine with table and formatting support.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use html5ever::driver::ParseOpts;
30use html5ever::parse_document;
31use html5ever::tendril::{StrTendril, TendrilSink};
32use html5ever::tree_builder::{
33    ElementFlags, NodeOrText, QuirksMode, TreeBuilderOpts, TreeSink,
34};
35use html5ever::{Attribute, ExpandedName, QualName};
36use std::borrow::Cow;
37use std::cell::{Cell, RefCell};
38use std::io::Cursor;
39use std::rc::{Rc, Weak};
40
41/// A DOM node representation for HTML parsing.
42struct Node {
43    parent: Cell<Option<Weak<Node>>>,
44    children: RefCell<Vec<Rc<Node>>>,
45    data: NodeData,
46}
47
48enum NodeData {
49    Document,
50    Doctype,
51    Text(RefCell<String>),
52    Comment(()),
53    Element {
54        name: QualName,
55        attrs: RefCell<Vec<Attribute>>,
56    },
57}
58
59impl Node {
60    fn new(data: NodeData) -> Rc<Self> {
61        Rc::new(Node {
62            parent: Cell::new(None),
63            children: RefCell::new(Vec::new()),
64            data,
65        })
66    }
67}
68
69struct DomSink {
70    document: Rc<Node>,
71    errors: RefCell<Vec<Cow<'static, str>>>,
72    quirks_mode: Cell<QuirksMode>,
73}
74
75impl DomSink {
76    fn new() -> Self {
77        DomSink {
78            document: Node::new(NodeData::Document),
79            errors: RefCell::new(Vec::new()),
80            quirks_mode: Cell::new(QuirksMode::NoQuirks),
81        }
82    }
83}
84
85impl TreeSink for DomSink {
86    type Handle = Rc<Node>;
87    type Output = Rc<Node>;
88    type ElemName<'a> = ExpandedName<'a>;
89
90    fn finish(self) -> Self::Output {
91        self.document
92    }
93
94    fn parse_error(&self, msg: Cow<'static, str>) {
95        self.errors.borrow_mut().push(msg);
96    }
97
98    fn get_document(&self) -> Self::Handle {
99        self.document.clone()
100    }
101
102    fn set_quirks_mode(&self, mode: QuirksMode) {
103        self.quirks_mode.set(mode);
104    }
105
106    fn same_node(&self, x: &Self::Handle, y: &Self::Handle) -> bool {
107        Rc::ptr_eq(x, y)
108    }
109
110    #[expect(
111        clippy::unreachable,
112        reason = "TreeSink contract guarantees elem_name is only invoked on elements"
113    )]
114    fn elem_name<'a>(&'a self, target: &'a Self::Handle) -> ExpandedName<'a> {
115        match &target.data {
116            NodeData::Element { name, .. } => name.expanded(),
117            _ => unreachable!(
118                "html5ever TreeSink contract guarantees elem_name is only called on element nodes"
119            ),
120        }
121    }
122
123    fn create_element(
124        &self,
125        name: QualName,
126        attrs: Vec<Attribute>,
127        _flags: ElementFlags,
128    ) -> Self::Handle {
129        Node::new(NodeData::Element {
130            name,
131            attrs: RefCell::new(attrs),
132        })
133    }
134
135    fn create_comment(&self, _text: StrTendril) -> Self::Handle {
136        Node::new(NodeData::Comment(()))
137    }
138
139    fn create_pi(
140        &self,
141        _target: StrTendril,
142        _data: StrTendril,
143    ) -> Self::Handle {
144        Node::new(NodeData::Comment(()))
145    }
146
147    fn append(&self, parent: &Self::Handle, child: NodeOrText<Self::Handle>) {
148        match child {
149            NodeOrText::AppendNode(node) => {
150                node.parent.set(Some(Rc::downgrade(parent)));
151                parent.children.borrow_mut().push(node);
152            }
153            NodeOrText::AppendText(text) => {
154                let mut children = parent.children.borrow_mut();
155                if let Some(last_child) = children.last() {
156                    if let NodeData::Text(ref contents) = last_child.data {
157                        contents.borrow_mut().push_str(&text);
158                        return;
159                    }
160                }
161                let new_node =
162                    Node::new(NodeData::Text(RefCell::new(text.to_string())));
163                new_node.parent.set(Some(Rc::downgrade(parent)));
164                children.push(new_node);
165            }
166        }
167    }
168
169    fn append_before_sibling(
170        &self,
171        sibling: &Self::Handle,
172        child: NodeOrText<Self::Handle>,
173    ) {
174        let Some(weak_parent) = sibling.parent.take() else {
175            return;
176        };
177        let Some(parent) = weak_parent.upgrade() else {
178            return;
179        };
180        sibling.parent.set(Some(weak_parent));
181
182        let mut children = parent.children.borrow_mut();
183        let Some(pos) = children.iter().position(|n| Rc::ptr_eq(n, sibling))
184        else {
185            return;
186        };
187
188        match child {
189            NodeOrText::AppendNode(node) => {
190                node.parent.set(Some(Rc::downgrade(&parent)));
191                children.insert(pos, node);
192            }
193            NodeOrText::AppendText(text) => {
194                if pos > 0 {
195                    let prev_idx = pos.saturating_sub(1);
196                    if let Some(prev) = children.get(prev_idx) {
197                        if let NodeData::Text(ref contents) = prev.data {
198                            contents.borrow_mut().push_str(&text);
199                            return;
200                        }
201                    }
202                }
203                let new_node =
204                    Node::new(NodeData::Text(RefCell::new(text.to_string())));
205                new_node.parent.set(Some(Rc::downgrade(&parent)));
206                children.insert(pos, new_node);
207            }
208        }
209    }
210
211    fn append_based_on_parent_node(
212        &self,
213        element: &Self::Handle,
214        prev_element: &Self::Handle,
215        child: NodeOrText<Self::Handle>,
216    ) {
217        if element.parent.take().is_some() {
218            self.append_before_sibling(element, child);
219        } else {
220            self.append(prev_element, child);
221        }
222    }
223
224    fn append_doctype_to_document(
225        &self,
226        _name: StrTendril,
227        _public_id: StrTendril,
228        _system_id: StrTendril,
229    ) {
230        let doctype = Node::new(NodeData::Doctype);
231        doctype.parent.set(Some(Rc::downgrade(&self.document)));
232        self.document.children.borrow_mut().push(doctype);
233    }
234
235    fn get_template_contents(&self, target: &Self::Handle) -> Self::Handle {
236        target.clone()
237    }
238
239    fn add_attrs_if_missing(
240        &self,
241        target: &Self::Handle,
242        attrs: Vec<Attribute>,
243    ) {
244        if let NodeData::Element {
245            attrs: ref current_attrs,
246            ..
247        } = target.data
248        {
249            let mut current = current_attrs.borrow_mut();
250            for attr in attrs {
251                if !current.iter().any(|a| a.name == attr.name) {
252                    current.push(attr);
253                }
254            }
255        }
256    }
257
258    fn remove_from_parent(&self, target: &Self::Handle) {
259        let Some(weak_parent) = target.parent.take() else {
260            return;
261        };
262        let Some(parent) = weak_parent.upgrade() else {
263            return;
264        };
265        let mut children = parent.children.borrow_mut();
266        if let Some(pos) = children.iter().position(|n| Rc::ptr_eq(n, target)) {
267            children.remove(pos);
268        }
269    }
270
271    fn reparent_children(
272        &self,
273        node: &Self::Handle,
274        new_parent: &Self::Handle,
275    ) {
276        let mut node_children = node.children.borrow_mut();
277        let mut new_children = new_parent.children.borrow_mut();
278        for child in node_children.drain(..) {
279            child.parent.set(Some(Rc::downgrade(new_parent)));
280            new_children.push(child);
281        }
282    }
283}
284
285/// Column alignment for Markdown tables.
286#[derive(Copy, Clone, Debug, PartialEq, Eq)]
287enum ColumnAlign {
288    Left,
289    Center,
290    Right,
291    None,
292}
293
294/// Cell structure for HTML tables.
295struct TableCell {
296    content: String,
297    is_header: bool,
298    align: ColumnAlign,
299}
300
301/// Row structure for HTML tables.
302struct TableRow {
303    cells: Vec<TableCell>,
304}
305
306/// Parse HTML byte slice into DOM tree.
307fn parse_html(html: &[u8]) -> Result<Rc<Node>> {
308    let cursor = Cursor::new(html);
309    let opts = ParseOpts {
310        tree_builder: TreeBuilderOpts {
311            drop_doctype: true,
312            ..Default::default()
313        },
314        ..Default::default()
315    };
316    parse_document(DomSink::new(), opts)
317        .from_utf8()
318        .read_from(&mut { cursor })
319        .map_err(|e| anyhow::anyhow!("Failed to parse HTML document: {e}"))
320}
321
322/// Convert an HTML document to Markdown formatted string.
323pub fn html_to_markdown(html: &[u8]) -> Result<String> {
324    let doc = parse_html(html)?;
325    let mut out = String::new();
326    render_children(&doc, &mut out, &RenderContext::default())?;
327    Ok(clean_output(&out))
328}
329
330#[derive(Clone, Default)]
331struct RenderContext {
332    list_depth: usize,
333    ordered_index: Option<usize>,
334    in_pre: bool,
335    in_blockquote: bool,
336    blockquote_depth: usize,
337    in_table_cell: bool,
338}
339
340fn get_attr(attrs: &[Attribute], name: &str) -> Option<String> {
341    attrs
342        .iter()
343        .find(|a| a.name.local.as_ref() == name)
344        .map(|a| a.value.to_string())
345}
346
347fn get_align_from_attrs(attrs: &[Attribute]) -> ColumnAlign {
348    if let Some(align) = get_attr(attrs, "align") {
349        match align.to_ascii_lowercase().as_str() {
350            "left" => return ColumnAlign::Left,
351            "center" => return ColumnAlign::Center,
352            "right" => return ColumnAlign::Right,
353            _ => {}
354        }
355    }
356    if let Some(style) = get_attr(attrs, "style") {
357        let style_lower = style.to_ascii_lowercase();
358        if style_lower.contains("text-align: center")
359            || style_lower.contains("text-align:center")
360        {
361            return ColumnAlign::Center;
362        }
363        if style_lower.contains("text-align: right")
364            || style_lower.contains("text-align:right")
365        {
366            return ColumnAlign::Right;
367        }
368        if style_lower.contains("text-align: left")
369            || style_lower.contains("text-align:left")
370        {
371            return ColumnAlign::Left;
372        }
373    }
374    ColumnAlign::None
375}
376
377fn render_children(
378    node: &Rc<Node>,
379    out: &mut String,
380    ctx: &RenderContext,
381) -> Result<()> {
382    let children = node.children.borrow();
383    for child in children.iter() {
384        render_node(child, out, ctx)?;
385    }
386    Ok(())
387}
388
389fn render_node(
390    node: &Rc<Node>,
391    out: &mut String,
392    ctx: &RenderContext,
393) -> Result<()> {
394    match &node.data {
395        NodeData::Document => render_children(node, out, ctx)?,
396        NodeData::Doctype | NodeData::Comment(()) => {}
397        NodeData::Text(text) => {
398            let s = text.borrow();
399            if ctx.in_pre {
400                out.push_str(&s);
401            } else {
402                let normalized = normalize_whitespace(&s);
403                out.push_str(&normalized);
404            }
405        }
406        NodeData::Element { name, attrs } => {
407            let tag = name.local.as_ref();
408            let attrs_borrow = attrs.borrow();
409            render_element(node, tag, &attrs_borrow, out, ctx)?;
410        }
411    }
412    Ok(())
413}
414
415fn normalize_whitespace(s: &str) -> String {
416    let mut res = String::with_capacity(s.len());
417    let mut prev_is_ws = false;
418    for ch in s.chars() {
419        if ch.is_whitespace() {
420            if !prev_is_ws {
421                res.push(' ');
422                prev_is_ws = true;
423            }
424        } else {
425            res.push(ch);
426            prev_is_ws = false;
427        }
428    }
429    res
430}
431
432fn ensure_blank_lines(out: &mut String, count: usize) {
433    let mut trailing_newlines = 0usize;
434    for ch in out.chars().rev() {
435        if ch == '\n' {
436            trailing_newlines = trailing_newlines.saturating_add(1);
437        } else {
438            break;
439        }
440    }
441    if !out.is_empty() {
442        while trailing_newlines < count {
443            out.push('\n');
444            trailing_newlines = trailing_newlines.saturating_add(1);
445        }
446    }
447}
448
449fn render_element(
450    node: &Rc<Node>,
451    tag: &str,
452    attrs: &[Attribute],
453    out: &mut String,
454    ctx: &RenderContext,
455) -> Result<()> {
456    match tag {
457        "head" | "script" | "style" | "meta" | "link" | "noscript"
458        | "template" => {
459            // Ignored elements
460        }
461        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
462            ensure_blank_lines(out, 2);
463            let level = match tag {
464                "h1" => 1,
465                "h2" => 2,
466                "h3" => 3,
467                "h4" => 4,
468                "h5" => 5,
469                "h6" => 6,
470                _ => 1,
471            };
472            for _ in 0..level {
473                out.push('#');
474            }
475            out.push(' ');
476            let mut content = String::new();
477            render_children(node, &mut content, ctx)?;
478            out.push_str(content.trim());
479            ensure_blank_lines(out, 2);
480        }
481        "p" => {
482            ensure_blank_lines(out, 2);
483            render_children(node, out, ctx)?;
484            ensure_blank_lines(out, 2);
485        }
486        "br" => {
487            if ctx.in_table_cell {
488                out.push_str("<br>");
489            } else {
490                out.push('\n');
491            }
492        }
493        "hr" => {
494            ensure_blank_lines(out, 2);
495            out.push_str("---");
496            ensure_blank_lines(out, 2);
497        }
498        "strong" | "b" => {
499            let mut content = String::new();
500            render_children(node, &mut content, ctx)?;
501            let trimmed = content.trim();
502            if !trimmed.is_empty() {
503                if content.starts_with(' ') {
504                    out.push(' ');
505                }
506                out.push_str("**");
507                out.push_str(trimmed);
508                out.push_str("**");
509                if content.ends_with(' ') {
510                    out.push(' ');
511                }
512            }
513        }
514        "em" | "i" => {
515            let mut content = String::new();
516            render_children(node, &mut content, ctx)?;
517            let trimmed = content.trim();
518            if !trimmed.is_empty() {
519                if content.starts_with(' ') {
520                    out.push(' ');
521                }
522                out.push('*');
523                out.push_str(trimmed);
524                out.push('*');
525                if content.ends_with(' ') {
526                    out.push(' ');
527                }
528            }
529        }
530        "s" | "del" | "strike" => {
531            let mut content = String::new();
532            render_children(node, &mut content, ctx)?;
533            let trimmed = content.trim();
534            if !trimmed.is_empty() {
535                if content.starts_with(' ') {
536                    out.push(' ');
537                }
538                out.push_str("~~");
539                out.push_str(trimmed);
540                out.push_str("~~");
541                if content.ends_with(' ') {
542                    out.push(' ');
543                }
544            }
545        }
546        "code" => {
547            if ctx.in_pre {
548                render_children(node, out, ctx)?;
549            } else {
550                let mut content = String::new();
551                let mut inner_ctx = ctx.clone();
552                inner_ctx.in_pre = true;
553                render_children(node, &mut content, &inner_ctx)?;
554                let trimmed = content.trim();
555                if !trimmed.is_empty() {
556                    out.push('`');
557                    out.push_str(trimmed);
558                    out.push('`');
559                }
560            }
561        }
562        "pre" => {
563            ensure_blank_lines(out, 2);
564            let mut lang = String::new();
565            // Look for <code class="language-xyz"> inside <pre>
566            for child in node.children.borrow().iter() {
567                if let NodeData::Element {
568                    ref name,
569                    ref attrs,
570                } = child.data
571                {
572                    if name.local.as_ref() == "code" {
573                        if let Some(class) = get_attr(&attrs.borrow(), "class")
574                        {
575                            for part in class.split_whitespace() {
576                                if let Some(l) = part.strip_prefix("language-")
577                                {
578                                    lang = l.to_string();
579                                    break;
580                                }
581                                if let Some(l) = part.strip_prefix("lang-") {
582                                    lang = l.to_string();
583                                    break;
584                                }
585                            }
586                        }
587                    }
588                }
589            }
590            out.push_str("```");
591            out.push_str(&lang);
592            out.push('\n');
593
594            let mut code_content = String::new();
595            let mut pre_ctx = ctx.clone();
596            pre_ctx.in_pre = true;
597            render_children(node, &mut code_content, &pre_ctx)?;
598
599            // Strip single leading/trailing newline if any
600            let trimmed_code = code_content.trim_matches('\n');
601            out.push_str(trimmed_code);
602            out.push('\n');
603            out.push_str("```");
604            ensure_blank_lines(out, 2);
605        }
606        "blockquote" => {
607            ensure_blank_lines(out, 2);
608            let mut inner = String::new();
609            let mut bq_ctx = ctx.clone();
610            bq_ctx.in_blockquote = true;
611            bq_ctx.blockquote_depth = bq_ctx.blockquote_depth.saturating_add(1);
612            render_children(node, &mut inner, &bq_ctx)?;
613
614            let trimmed_inner = inner.trim();
615            for line in trimmed_inner.lines() {
616                out.push_str("> ");
617                out.push_str(line);
618                out.push('\n');
619            }
620            ensure_blank_lines(out, 2);
621        }
622        "ul" => {
623            ensure_blank_lines(out, 1);
624            let mut list_ctx = ctx.clone();
625            list_ctx.list_depth = ctx.list_depth.saturating_add(1);
626            list_ctx.ordered_index = None;
627            render_children(node, out, &list_ctx)?;
628            ensure_blank_lines(out, 1);
629        }
630        "ol" => {
631            ensure_blank_lines(out, 1);
632            let mut list_ctx = ctx.clone();
633            list_ctx.list_depth = ctx.list_depth.saturating_add(1);
634            // Reason for fallback: HTML <ol> elements default to starting count at 1 if start attribute is omitted or non-numeric
635            let start: usize = get_attr(attrs, "start")
636                .and_then(|s| s.parse::<usize>().ok())
637                .unwrap_or(1);
638            list_ctx.ordered_index = Some(start);
639            render_children(node, out, &list_ctx)?;
640            ensure_blank_lines(out, 1);
641        }
642        "li" => {
643            ensure_blank_lines(out, 1);
644            let indent_spaces =
645                ctx.list_depth.saturating_sub(1).saturating_mul(2);
646            for _ in 0..indent_spaces {
647                out.push(' ');
648            }
649            if let Some(idx) = ctx.ordered_index {
650                out.push_str(&format!("{idx}. "));
651            } else {
652                out.push_str("* ");
653            }
654            let mut item_content = String::new();
655            render_children(node, &mut item_content, ctx)?;
656            let trimmed = item_content.trim();
657            out.push_str(trimmed);
658            out.push('\n');
659        }
660        "a" => {
661            let href = get_attr(attrs, "href");
662            let title = get_attr(attrs, "title");
663            let mut link_text = String::new();
664            render_children(node, &mut link_text, ctx)?;
665            let trimmed_text = link_text.trim();
666
667            if let Some(url) = href {
668                if trimmed_text.is_empty() {
669                    out.push_str(&format!("<{url}>"));
670                } else if let Some(t) = title {
671                    out.push_str(&format!("[{trimmed_text}]({url} \"{t}\")"));
672                } else {
673                    out.push_str(&format!("[{trimmed_text}]({url})"));
674                }
675            } else {
676                out.push_str(trimmed_text);
677            }
678        }
679        "img" => {
680            // Reason for fallback: img elements without src attribute default to empty string
681            let src = get_attr(attrs, "src").unwrap_or_default();
682            // Reason for fallback: img elements without alt attribute default to empty string
683            let alt = get_attr(attrs, "alt").unwrap_or_default();
684            let title = get_attr(attrs, "title");
685            if let Some(t) = title {
686                out.push_str(&format!("![{alt}]({src} \"{t}\")"));
687            } else {
688                out.push_str(&format!("![{alt}]({src})"));
689            }
690        }
691        "table" => {
692            ensure_blank_lines(out, 2);
693            render_table(node, out)?;
694            ensure_blank_lines(out, 2);
695        }
696        "div" | "article" | "section" | "main" | "header" | "footer"
697        | "nav" => {
698            ensure_blank_lines(out, 1);
699            render_children(node, out, ctx)?;
700            ensure_blank_lines(out, 1);
701        }
702        _ => {
703            render_children(node, out, ctx)?;
704        }
705    }
706    Ok(())
707}
708
709fn collect_table_rows(node: &Rc<Node>, rows: &mut Vec<TableRow>) -> Result<()> {
710    for child in node.children.borrow().iter() {
711        if let NodeData::Element { ref name, .. } = child.data {
712            let tag = name.local.as_ref();
713            match tag {
714                "tr" => {
715                    let mut cells = Vec::new();
716                    for cell_node in child.children.borrow().iter() {
717                        if let NodeData::Element {
718                            ref name,
719                            ref attrs,
720                        } = cell_node.data
721                        {
722                            let cell_tag = name.local.as_ref();
723                            if cell_tag == "td" || cell_tag == "th" {
724                                let is_header = cell_tag == "th";
725                                let align =
726                                    get_align_from_attrs(&attrs.borrow());
727                                let mut cell_content = String::new();
728                                let cell_ctx = RenderContext {
729                                    in_table_cell: true,
730                                    ..Default::default()
731                                };
732                                render_children(
733                                    cell_node,
734                                    &mut cell_content,
735                                    &cell_ctx,
736                                )?;
737                                // Clean cell content: replace newlines with space, escape pipes
738                                let cleaned =
739                                    sanitize_cell_content(cell_content.trim());
740                                cells.push(TableCell {
741                                    content: cleaned,
742                                    is_header,
743                                    align,
744                                });
745                            }
746                        }
747                    }
748                    if !cells.is_empty() {
749                        rows.push(TableRow { cells });
750                    }
751                }
752                "thead" | "tbody" | "tfoot" => {
753                    collect_table_rows(child, rows)?;
754                }
755                _ => {}
756            }
757        }
758    }
759    Ok(())
760}
761
762fn sanitize_cell_content(content: &str) -> String {
763    let mut out = String::with_capacity(content.len());
764    let mut prev_is_ws = false;
765    for ch in content.chars() {
766        match ch {
767            '|' => {
768                out.push_str("\\|");
769                prev_is_ws = false;
770            }
771            '\n' | '\r' | '\t' => {
772                if !prev_is_ws {
773                    out.push(' ');
774                    prev_is_ws = true;
775                }
776            }
777            c => {
778                if c.is_whitespace() {
779                    if !prev_is_ws {
780                        out.push(' ');
781                        prev_is_ws = true;
782                    }
783                } else {
784                    out.push(c);
785                    prev_is_ws = false;
786                }
787            }
788        }
789    }
790    out
791}
792
793fn render_table(table_node: &Rc<Node>, out: &mut String) -> Result<()> {
794    let mut rows = Vec::new();
795    collect_table_rows(table_node, &mut rows)?;
796
797    if rows.is_empty() {
798        return Ok(());
799    }
800
801    let col_count = match rows.iter().map(|r| r.cells.len()).max() {
802        Some(c) => c,
803        None => 0,
804    };
805    if col_count == 0 {
806        return Ok(());
807    }
808
809    // Determine column alignments
810    let mut aligns = vec![ColumnAlign::None; col_count];
811    for row in &rows {
812        for (i, cell) in row.cells.iter().enumerate() {
813            if i < col_count && cell.align != ColumnAlign::None {
814                if let Some(align_slot) = aligns.get_mut(i) {
815                    *align_slot = cell.align;
816                }
817            }
818        }
819    }
820
821    let first_row_is_header = rows
822        .first()
823        .is_some_and(|r| r.cells.iter().any(|c| c.is_header));
824
825    let (header_cells, data_rows_start) = if first_row_is_header {
826        (rows.first().map(|r| &r.cells), 1usize)
827    } else {
828        // If no explicit <th> in the table, use first row as header
829        (rows.first().map(|r| &r.cells), 1usize)
830    };
831
832    // Header row
833    out.push('|');
834    for col_idx in 0..col_count {
835        out.push(' ');
836        if let Some(cells) = header_cells {
837            if let Some(cell) = cells.get(col_idx) {
838                out.push_str(&cell.content);
839            }
840        }
841        out.push_str(" |");
842    }
843    out.push('\n');
844
845    // Delimiter row
846    out.push('|');
847    for col_idx in 0..col_count {
848        out.push(' ');
849        let align = match aligns.get(col_idx) {
850            Some(&a) => a,
851            None => ColumnAlign::None,
852        };
853        match align {
854            ColumnAlign::Left => out.push_str(":---"),
855            ColumnAlign::Center => out.push_str(":---:"),
856            ColumnAlign::Right => out.push_str("---:"),
857            ColumnAlign::None => out.push_str("---"),
858        }
859        out.push_str(" |");
860    }
861    out.push('\n');
862
863    // Data rows
864    for row in rows.iter().skip(data_rows_start) {
865        out.push('|');
866        for col_idx in 0..col_count {
867            out.push(' ');
868            if let Some(cell) = row.cells.get(col_idx) {
869                out.push_str(&cell.content);
870            }
871            out.push_str(" |");
872        }
873        out.push('\n');
874    }
875
876    Ok(())
877}
878
879fn clean_output(s: &str) -> String {
880    let mut result = String::with_capacity(s.len());
881    let mut consecutive_newlines = 0usize;
882
883    for line in s.lines() {
884        let trimmed_end = line.trim_end();
885        if trimmed_end.is_empty() {
886            consecutive_newlines = consecutive_newlines.saturating_add(1);
887            if consecutive_newlines <= 2 {
888                result.push('\n');
889            }
890        } else {
891            consecutive_newlines = 0;
892            if !result.is_empty() && !result.ends_with('\n') {
893                result.push('\n');
894            }
895            result.push_str(trimmed_end);
896            result.push('\n');
897        }
898    }
899
900    result.trim().to_string()
901}
902
903/// Convert HTML bytes to Markdown.
904pub fn html2md(html: Vec<u8>) -> Result<Vec<u8>> {
905    let md = html_to_markdown(html.as_slice())?;
906    Ok(md.into_bytes())
907}
908
909/// Convert HTML bytes to Markdown with width specification.
910pub fn html2md_with_width(html: Vec<u8>, _width: u16) -> Result<Vec<u8>> {
911    html2md(html)
912}
913
914#[cfg(test)]
915#[allow(
916    clippy::panic,
917    clippy::expect_used,
918    clippy::unwrap_used,
919    clippy::unwrap_in_result,
920    clippy::panic_in_result_fn,
921    clippy::indexing_slicing,
922    clippy::arithmetic_side_effects,
923    reason = "Standard repository test boilerplate"
924)]
925mod tests {
926    use super::*;
927
928    #[crate::ctb_test]
929    fn test_html2md_links_and_images() -> Result<()> {
930        let html = b"<p>Check <a href=\"https://example.com/\">this link</a> and <img src=\"img.png\" alt=\"An image\" />.</p>";
931        let md = html2md(html.to_vec())?;
932        let md_str = String::from_utf8(md)?;
933        assert_eq!(
934            md_str.trim(),
935            "Check [this link](https://example.com/) and ![An image](img.png)."
936        );
937        Ok(())
938    }
939
940    #[crate::ctb_test]
941    fn test_html2md_formatting_and_code() -> Result<()> {
942        let html = b"<p><b>Bold</b>, <i>Italic</i>, <code>inline code</code>, <del>deleted</del>.</p>";
943        let md = html2md(html.to_vec())?;
944        let md_str = String::from_utf8(md)?;
945        assert_eq!(
946            md_str.trim(),
947            "**Bold**, *Italic*, `inline code`, ~~deleted~~."
948        );
949        Ok(())
950    }
951
952    #[crate::ctb_test]
953    fn test_html2md_headings_and_pre() -> Result<()> {
954        let html = b"<h1>Heading 1</h1><h2>Heading 2</h2><pre><code class=\"language-rust\">fn main() {\n    println!(\"Hello\");\n}</code></pre>";
955        let md = html2md(html.to_vec())?;
956        let md_str = String::from_utf8(md)?;
957        assert!(md_str.contains("# Heading 1"));
958        assert!(md_str.contains("## Heading 2"));
959        assert!(md_str.contains(
960            "```rust\nfn main() {\n    println!(\"Hello\");\n}\n```"
961        ));
962        Ok(())
963    }
964
965    #[crate::ctb_test]
966    fn test_html2md_table_with_alignment_and_escaping() -> Result<()> {
967        let html = b"<table>\
968            <thead>\
969                <tr><th align=\"left\">Item</th><th align=\"center\">Qty</th><th align=\"right\">Price</th></tr>\
970            </thead>\
971            <tbody>\
972                <tr><td>Widget A | Standard</td><td>10</td><td>$5.00</td></tr>\
973                <tr><td>Widget B</td><td>2</td><td>$12.50</td></tr>\
974            </tbody>\
975        </table>";
976        let md = html2md(html.to_vec())?;
977        let md_str = String::from_utf8(md)?;
978        assert!(md_str.contains("| Item | Qty | Price |"));
979        assert!(md_str.contains("| :--- | :---: | ---: |"));
980        assert!(md_str.contains("| Widget A \\| Standard | 10 | $5.00 |"));
981        assert!(md_str.contains("| Widget B | 2 | $12.50 |"));
982        Ok(())
983    }
984
985    #[crate::ctb_test]
986    fn test_html2md_table_without_thead() -> Result<()> {
987        let html = b"<table>\
988            <tr><td>First</td><td>Second</td></tr>\
989            <tr><td>1</td><td>2</td></tr>\
990        </table>";
991        let md = html2md(html.to_vec())?;
992        let md_str = String::from_utf8(md)?;
993        assert!(md_str.contains("| First | Second |"));
994        assert!(md_str.contains("| --- | --- |"));
995        assert!(md_str.contains("| 1 | 2 |"));
996        Ok(())
997    }
998}