use super::{Align, Document, FBlock, FTable, Flow, Fmt, Inline, Kind, Para, VAlign, base64_encode, mime_of, model}; // --------------------------------------------------------------------------------------------- // Export /// Escape text for HTML content and attribute values. pub fn esc(s: &str) -> String { let mut o = String::with_capacity(s.len() + 8); for c in s.chars() { match c { '&' => o.push_str("&"), '<' => o.push_str("<"), '>' => o.push_str(">"), '"' => o.push_str("""), '\u{000C}' | '\u{000E}' => {} _ => o.push(c), } } o } /// A font name as a quoted CSS string. Quotes, `\` and control characters would end the string, /// and `;` and `,` the declaration or the family list for a reader that splits on them, so all of /// these are written as hex escapes ([`css_unescape`] reads them back). fn css_font_name(name: &str) -> String { let mut o = String::with_capacity(name.len() + 2); o.push('\''); for c in name.chars() { match c { '\0' => o.push('\u{FFFD}'), '\'' | '"' | '\\' | ';' | ',' => o.push_str(&format!("\\{:x} ", u32::from(c))), c if c.is_control() => o.push_str(&format!("\\{:x} ", u32::from(c))), c => o.push(c), } } o.push('\''); o } fn align_css(a: Option) -> Option<&'static str> { match a? { Align::Center => Some("text-align:center"), Align::Right => Some("text-align:right"), Align::Justify | Align::Distribute => Some("text-align:justify"), Align::Left => None, } } fn text_html(t: &str, at_start: bool) -> String { let mut o = String::new(); let mut prev_space = at_start; for c in t.chars() { match c { '\n' => { o.push_str("
"); prev_space = true; continue; } '\t' => o.push_str("\t"), ' ' if prev_space => o.push_str(" "), _ => o.push_str(&esc(&c.to_string())), } prev_space = c == ' '; } o } /// The tags that carry `f`'s character formatting: what opens them, and what closes them /// (innermost last, so the closes are written in reverse). fn fmt_tags(f: &Fmt) -> (String, Vec<&'static str>) { let mut open = String::new(); let mut close: Vec<&str> = Vec::new(); // A script or other non-web target is written as plain text (`is_safe_href`). if let Some(l) = f.link.as_deref().filter(|l| craft_wordmodel::link::is_safe_href(l)) { open.push_str(&format!("", esc(l))); close.push(""); } let mut tag = |o: &str, c: &'static str| { open.push_str(o); close.push(c); }; if f.bold { tag("", ""); } if f.italic { tag("", ""); } if f.underline { tag("", ""); } if f.strike { tag("", ""); } if f.sup { tag("", ""); } else if f.sub { tag("", ""); } if f.code { tag("", ""); } let mut css = Vec::new(); if let Some(c) = f.color { css.push(format!("color:#{}", c.hex())); } if let Some(c) = f.background { css.push(format!("background-color:#{}", c.hex())); } if let Some(s) = f.size { css.push(format!("font-size:{}pt", trim_num(s))); } if let Some(fam) = &f.font { css.push(format!("font-family:{}", esc(&css_font_name(fam)))); } if !css.is_empty() { open.push_str(&format!("", css.join(";"))); close.push(""); } (open, close) } /// Inline spans → HTML. pub fn inlines_html(inlines: &[Inline]) -> String { let mut o = String::new(); for i in inlines.iter() { match i { Inline::Text(t, f) => { let (open, close) = fmt_tags(f); let at_start = o.is_empty(); o.push_str(&open); o.push_str(&text_html(t, at_start)); for c in close.iter().rev() { o.push_str(c); } } // A phonetic guide: the base text with its reading in `` (#1681). HTML ruby has // no alignment or size, so the guide's own attributes stay in the document model. Inline::Ruby { base, ruby, fmt } => { let (open, close) = fmt_tags(fmt); let at_start = o.is_empty(); o.push_str(&open); o.push_str(&format!("{}{}", text_html(base, at_start), text_html(ruby, false))); for c in close.iter().rev() { o.push_str(c); } } Inline::Image(img) => { o.push_str(&format!( "\"{}\"", mime_of(&img.ext), base64_encode(&img.data), esc(&img.alt), (img.w / 0.75).round(), (img.h / 0.75).round() )); } Inline::Anchor(a) => o.push_str(&format!("", esc(a))), Inline::Note { .. } | Inline::Comment { .. } | Inline::CommentEnd(_) | Inline::Shape { .. } | Inline::Group { .. } | Inline::FieldStart(_) | Inline::FieldEnd | Inline::AnchorEnd(_) => {} // ASK and SET show nothing (see `model::shows_nothing`). Inline::Field { instr, .. } if model::shows_nothing(instr) => {} Inline::Field { result, fmt, .. } | Inline::Control { text: result, fmt, .. } => { let (open, close) = fmt_tags(fmt); let at_start = o.is_empty(); o.push_str(&open); o.push_str(&text_html(result, at_start)); for c in close.iter().rev() { o.push_str(c); } } // No picture to show: the browser shows the alt text in its place. Inline::Figure(alt) | Inline::Chart(craft_flow::Chart { alt, .. }) => o.push_str(&format!("\"{}\"", esc(alt))), // MathML, which browsers, Word and LibreOffice show as an equation (#816). Inline::Equation { linear, display } => o.push_str(&craft_math::mathml::linear_to_mathml(linear, *display)), } } o } fn trim_num(v: f32) -> String { let s = format!("{:.2}", v); s.trim_end_matches('0').trim_end_matches('.').to_string() } fn para_attrs(p: &Para) -> String { let mut css: Vec<&str> = Vec::new(); if let Some(a) = align_css(p.align) { css.push(a); } if p.page_break { css.push("break-before:page;page-break-before:always"); } if css.is_empty() { String::new() } else { format!(" style=\"{}\"", css.join(";")) } } fn para_html(p: &Para) -> String { let body = inlines_html(&p.inlines); let attrs = para_attrs(p); match p.kind { Kind::Heading(n) => format!("{body}", n = n.clamp(1, 6)), Kind::Title => format!("{body}"), Kind::Rule => "
".to_string(), _ if body.is_empty() => format!(" 

"), _ => format!("{body}

"), } } fn table_html(t: &FTable, out: &mut String, depth: usize) { out.push_str("\n"); for row in &t.rows { out.push_str(""); for c in row { if c.covered { continue; } let tag = if c.header { "th" } else { "td" }; let mut attrs = String::new(); if c.colspan > 1 { attrs.push_str(&format!(" colspan=\"{}\"", c.colspan)); } if c.rowspan > 1 { attrs.push_str(&format!(" rowspan=\"{}\"", c.rowspan)); } let v_css = match c.valign { Some(VAlign::Center) => "vertical-align:middle", Some(VAlign::Bottom) => "vertical-align:bottom", _ => "vertical-align:top", }; let mut css = vec!["padding:4px 6px".to_string(), v_css.to_string()]; if !t.borderless { css.insert(0, "border:1px solid #999".to_string()); } if let Some(s) = c.shading { css.push(format!("background-color:#{}", s.hex())); } let single = match c.blocks.as_slice() { [FBlock::Para(p)] if p.kind == Kind::Normal && p.list.is_none() && !p.page_break => Some(p), _ => None, }; if let Some(a) = single.and_then(|p| align_css(p.align)) { css.push(a.to_string()); } out.push_str(&format!("<{tag}{attrs} style=\"{}\">", css.join(";"))); match single { Some(p) => out.push_str(&inlines_html(&p.inlines)), None => { out.push('\n'); blocks_html(&c.blocks, out, depth + 1); } } out.push_str(&format!("")); } out.push_str("\n"); } out.push_str("
\n"); } fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) { let mut i = 0; while let Some(b) = blocks.get(i) { match b { FBlock::Table(t) => { if depth < model::MAX_DEPTH { table_html(t, out, depth); } i += 1; } FBlock::Para(p) if p.list.is_some() => { // Nested lists from consecutive list paragraphs. let mut stack: Vec<(bool, bool)> = Vec::new(); // (ordered, li open) while let Some(FBlock::Para(q)) = blocks.get(i) { let Some(li) = q.list else { break }; let lv = li.level.min(8) as usize; while stack.len() > lv + 1 { close_list(&mut stack, out); } if stack.len() == lv + 1 && stack.last().is_some_and(|s| s.0 != li.ordered) { close_list(&mut stack, out); } while stack.len() < lv + 1 { if let Some(top) = stack.last_mut() && !top.1 { out.push_str("
  • "); top.1 = true; } out.push_str(if li.ordered { "
      " } else { "
        " }); stack.push((li.ordered, false)); } if let Some(top) = stack.last_mut() { if top.1 { out.push_str("\n"); } top.1 = true; } let body = inlines_html(&q.inlines); let attrs = para_attrs(q); out.push_str(&format!("{body}")); i += 1; } while !stack.is_empty() { close_list(&mut stack, out); } out.push('\n'); } FBlock::Para(p) if p.kind == Kind::Code => { out.push_str("
        ");
                        let mut first = true;
                        while let Some(FBlock::Para(q)) = blocks.get(i) {
                            if q.kind != Kind::Code || q.list.is_some() {
                                break;
                            }
                            if !first {
                                out.push('\n');
                            }
                            first = false;
                            out.push_str(&esc(&q.text()));
                            i += 1;
                        }
                        out.push_str("
        \n"); } FBlock::Para(p) if p.kind == Kind::Quote => { out.push_str("
        \n"); while let Some(FBlock::Para(q)) = blocks.get(i) { if q.kind != Kind::Quote || q.list.is_some() { break; } out.push_str(¶_html(&Para { kind: Kind::Normal, ..q.clone() })); out.push('\n'); i += 1; } out.push_str("
        \n"); } FBlock::Para(p) => { out.push_str(¶_html(p)); out.push('\n'); i += 1; } } } } fn close_list(stack: &mut Vec<(bool, bool)>, out: &mut String) { if let Some((ordered, li_open)) = stack.pop() { if li_open { out.push_str(""); } out.push_str(if ordered { "
    " } else { "" }); } } /// A complete HTML document. pub fn export(doc: &Document) -> String { let flow = model::from_doc(doc); export_flow(&flow, doc.styles.default_chr.lang.as_deref().unwrap_or("en")) } /// `doc`'s content as an HTML fragment (no head or style sheet): what a copy puts on the system /// clipboard beside its text, equations as MathML (#816). pub fn export_fragment(doc: &Document) -> String { let flow = model::from_doc(doc); let mut out = String::from(""); blocks_html(&flow.blocks, &mut out, 0); out } pub fn export_flow(flow: &Flow, lang: &str) -> String { let m = &flow.meta; let mut out = String::new(); out.push_str("\n"); out.push_str(&format!("\n\n\n", esc(lang))); out.push_str("\n"); out.push_str(&format!("{}\n", esc(&m.title))); for (k, v) in [("author", &m.author), ("description", &m.description), ("keywords", &m.keywords), ("subject", &m.subject)] { if !v.is_empty() { out.push_str(&format!("\n", esc(v))); } } out.push_str( "\n\n\n", ); blocks_html(&flow.blocks, &mut out, 0); out.push_str("\n\n"); out }