use std::collections::BTreeSet;
use std::fmt;
use serde::Serialize;
use crate::namespaces::{MC, W, W14, W15};
use crate::opc::PartFs;
use crate::xmllinq::{Dom, NodeId, XName};
#[doc(hidden)]
pub mod tables;
#[doc(hidden)]
pub use tables::top_level_table_nodes;
pub use tables::{NestedTable, Table, TableCell};
pub const SCHEMA_VERSION: u32 = 1;
pub const SNAPSHOT_SCHEMA_VERSION: u32 = 3;
#[doc(hidden)]
pub const BODY_STORY: &str = "body";
#[doc(hidden)]
pub const STORY_KINDS: &[&str] = &["header", "footer", "footnotes", "endnotes"];
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Paragraph {
pub index: usize,
pub id: String,
pub text: String,
pub style: Option<String>,
pub numbered: bool,
pub in_table: bool,
pub page_break: bool,
pub runs: Vec<Span>,
pub limitations: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Span {
pub start: usize,
pub end: usize,
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub highlight: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct Summary {
pub paragraphs: usize,
pub tables: usize,
pub fields: usize,
pub sections: usize,
pub comments: usize,
pub revisions: usize,
pub footnotes: usize,
pub endnotes: usize,
pub headers: usize,
pub footers: usize,
pub images: usize,
pub list_numbering: bool,
pub track_changes: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub input_validity: Option<crate::validate::InputValidity>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Snapshot {
pub schema_version: u32,
pub source_sha256: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub track_changes: Option<Settle>,
pub summary: Summary,
pub paragraphs: Vec<Paragraph>,
pub stories: Vec<Story>,
pub tables: Vec<Table>,
pub controls: Vec<ContentControl>,
pub changes: Vec<crate::changes::Change>,
pub comments: Vec<crate::comments::CommentRecord>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Settle {
Accept,
Reject,
}
impl Snapshot {
pub fn retain(&mut self, body_paragraphs: &[usize]) {
self.retain_with(body_paragraphs, &[]);
}
#[doc(hidden)]
pub fn retain_with(&mut self, body_paragraphs: &[usize], stories: &[String]) {
let kept: BTreeSet<usize> = body_paragraphs.iter().copied().collect();
self.paragraphs
.retain(|p| body_index(Some(&p.id)).is_some_and(|n| kept.contains(&n)));
let in_story = |paragraph: Option<&String>| {
paragraph
.and_then(|p| crate::ids::paragraph_place(p))
.is_some_and(|(story, _)| stories.contains(&story))
};
self.changes.retain(|c| {
body_index(c.paragraph.as_ref()).is_some_and(|n| kept.contains(&n))
|| in_story(c.paragraph.as_ref())
});
self.comments.retain(|c| {
let first = body_index(c.paragraph.as_ref());
let last = body_index(c.last_paragraph.as_ref()).or(first);
match (first, last) {
(Some(a), Some(z)) => kept.range(a..=z.max(a)).next().is_some(),
_ => in_story(c.paragraph.as_ref()),
}
});
}
}
fn body_index(id: Option<&String>) -> Option<usize> {
crate::ids::paragraph_place(id?)
.filter(|(story, _)| story == "body")
.map(|(_, n)| n)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Story {
pub id: String,
pub kind: String,
pub part: String,
pub paragraphs: Vec<Paragraph>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ContentControl {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alias: Option<String>,
pub kind: String,
pub text: String,
pub paragraph_ids: Vec<String>,
pub locked: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub choices: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checked: Option<bool>,
pub placeholder: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InspectError {
Package(String),
MissingDocument,
Invalid(String),
Admission(crate::admission::AdmissionError),
}
impl fmt::Display for InspectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Package(message) => write!(f, "opening DOCX: {message}"),
Self::MissingDocument => f.write_str("DOCX has no main document part or body"),
Self::Invalid(message) => write!(f, "invalid DOCX content: {message}"),
Self::Admission(refused) => write!(f, "DOCX refused: {refused}"),
}
}
}
impl std::error::Error for InspectError {}
pub use crate::util::source_sha256;
pub fn paragraphs(docx: &[u8]) -> Result<Vec<Paragraph>, InspectError> {
let opened = Opened::open(docx)?;
Ok(body_paragraphs(&opened.dom, opened.body))
}
#[doc(hidden)]
pub fn paragraphs_and_stories_within(
docx: &[u8],
limits: crate::admission::InputLimits,
) -> Result<(Vec<Paragraph>, Vec<Story>), InspectError> {
let opened = Opened::open_within(docx, limits)?;
Ok((
body_paragraphs(&opened.dom, opened.body),
opened.stories_within(limits, false)?,
))
}
pub fn summary(docx: &[u8]) -> Result<Summary, InspectError> {
let opened = Opened::open(docx)?;
opened.summary()
}
pub fn stories(docx: &[u8]) -> Result<Vec<Story>, InspectError> {
Opened::open(docx)?.stories()
}
pub fn controls(docx: &[u8]) -> Result<Vec<ContentControl>, InspectError> {
let opened = Opened::open(docx)?;
Ok(collect_controls(&opened.dom, opened.body))
}
pub fn markdown(docx: &[u8]) -> Result<String, InspectError> {
let opened = Opened::open(docx)?;
let mut all = body_paragraphs(&opened.dom, opened.body);
for story in opened.stories()? {
all.extend(story.paragraphs);
}
Ok(render_markdown(&all))
}
pub fn tables(docx: &[u8]) -> Result<Vec<Table>, InspectError> {
let opened = Opened::open(docx)?;
Ok(tables::body_tables(&opened.dom, opened.body))
}
pub fn snapshot(docx: &[u8]) -> Result<Snapshot, InspectError> {
let mut opened = Opened::open(docx)?;
let summary = opened.summary()?;
let paragraphs = body_paragraphs(&opened.dom, opened.body);
let stories = opened.stories()?;
let tables = tables::body_tables(&opened.dom, opened.body);
let controls = collect_controls(&opened.dom, opened.body);
let changes = crate::changes::logical_changes_in(&opened.pkg);
let comments = crate::comments::comments_in(&mut opened).map_err(|e| match e {
crate::comments::CommentError::Admission(refused) => InspectError::Admission(refused),
crate::comments::CommentError::Package(m) => InspectError::Package(m),
})?;
Ok(Snapshot {
schema_version: SNAPSHOT_SCHEMA_VERSION,
source_sha256: source_sha256(docx),
track_changes: None,
summary,
paragraphs,
stories,
tables,
controls,
changes,
comments,
})
}
pub fn settled_snapshot(docx: &[u8], settle: Settle) -> Result<Snapshot, InspectError> {
let mut snapshot = snapshot(docx)?;
snapshot.track_changes = Some(settle);
if settle == Settle::Reject {
let mut opened = Opened::open(docx)?;
reject_text(&mut opened.dom, opened.body);
snapshot.paragraphs = body_paragraphs(&opened.dom, opened.body);
snapshot.tables = tables::body_tables(&opened.dom, opened.body);
snapshot.controls = collect_controls(&opened.dom, opened.body);
snapshot.stories = opened.stories_within(crate::admission::InputLimits::default(), true)?;
}
Ok(snapshot)
}
pub fn view_tables(
docx: &[u8],
settle: Option<Settle>,
) -> Result<Vec<(usize, Table)>, InspectError> {
let mut opened = Opened::open(docx)?;
if settle == Some(Settle::Reject) {
reject_text(&mut opened.dom, opened.body);
}
Ok(tables::body_tables(&opened.dom, opened.body)
.into_iter()
.map(|table| (table.index, table))
.collect())
}
fn reject_text(dom: &mut Dom, root: NodeId) {
for (change, kept) in [
("pPrChange", &["rPr", "sectPr"][..]),
("rPrChange", &[][..]),
] {
for node in dom.descendants(root, Some(&W::name(change))) {
let Some(properties) = dom.parent(node) else {
continue;
};
let old = dom
.elements(node, None)
.first()
.map(|&old| {
let kids = dom.nodes(old);
dom.remove_nodes(old);
kids
})
.unwrap_or_default();
let stay: Vec<NodeId> = dom
.elements(properties, None)
.into_iter()
.filter(|&e| kept.iter().any(|k| dom.name_is(e, &W::name(k))))
.collect();
dom.remove_nodes(properties);
for kid in old.into_iter().chain(stay) {
dom.add(properties, kid);
}
}
}
for local in ["ins", "moveTo"] {
for node in dom.descendants(root, Some(&W::name(local))) {
dom.remove(node);
}
}
for local in ["del", "moveFrom"] {
for node in dom.descendants(root, Some(&W::name(local))) {
let kids = dom.nodes(node);
dom.remove_nodes(node);
dom.replace_with(node, &kids);
}
}
for (from, to) in [("delText", "t"), ("delInstrText", "instrText")] {
for node in dom.descendants(root, Some(&W::name(from))) {
dom.set_name(node, W::name(to));
}
}
}
pub fn inspect_json(docx: &[u8]) -> Result<String, InspectError> {
serde_json::to_string(&snapshot(docx)?).map_err(|e| InspectError::Invalid(e.to_string()))
}
pub fn tables_text(tables: &[Table]) -> String {
let mut out = String::new();
if tables.is_empty() {
out.push_str("no tables\n");
}
for table in tables {
render_grid(
&mut out,
&format!("table {}", table.index),
&table.rows,
table.header_rows,
&table.widths_dxa,
&table.nested,
0,
);
}
out
}
fn render_grid(
out: &mut String,
label: &str,
rows: &[Vec<TableCell>],
header_rows: usize,
widths_dxa: &[u32],
nested: &[NestedTable],
depth: usize,
) {
use std::fmt::Write as _;
let indent = " ".repeat(depth);
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<String> = widths_dxa.iter().map(u32::to_string).collect();
let _ = writeln!(
out,
"{indent}{label}: {}x{columns} header_rows={header_rows} widths={}",
rows.len(),
widths.join(",")
);
for (r, row) in rows.iter().enumerate() {
let cells: Vec<String> = row
.iter()
.map(|cell| {
let ids = if cell.paragraph_ids.is_empty() {
"-".to_string()
} else {
cell.paragraph_ids
.iter()
.map(|id| crate::ids::short_paragraph(id))
.collect::<Vec<_>>()
.join(",")
};
let text = cell
.text
.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('\t', "\\t");
format!("{ids}={text}")
})
.collect();
let _ = writeln!(out, "{indent}{}", cells.join("\t"));
let row_prefix = format!("{r}.cell");
for child in nested.iter().filter(|child| {
child
.parent
.rsplit_once(".row")
.is_some_and(|(_, tail)| tail.starts_with(&row_prefix))
}) {
render_grid(
out,
&format!("nested in {}", child.parent),
&child.rows,
child.header_rows,
&child.widths_dxa,
&child.nested,
depth + 1,
);
}
}
}
pub fn render_markdown(paragraphs: &[Paragraph]) -> String {
let mut out = String::new();
for p in paragraphs {
out.push('[');
out.push_str(&p.id);
if let Some(style) = &p.style {
out.push(' ');
out.push_str(style);
}
out.push(']');
let body = markdown_body(p);
if !body.is_empty() {
out.push(' ');
out.push_str(&body);
}
out.push_str("\n\n");
}
if out.ends_with("\n\n") {
out.pop();
}
out
}
fn markdown_body(p: &Paragraph) -> String {
let chars: Vec<char> = p.text.chars().collect();
let mut out = String::new();
let mut cursor = 0;
for span in &p.runs {
let start = span.start.min(chars.len());
let end = span.end.min(chars.len());
if start > cursor {
out.extend(&chars[cursor..start]);
}
let piece: String = chars[start..end].iter().collect();
out.push_str(&emphasize(&piece, span));
cursor = end;
}
if cursor < chars.len() {
out.extend(&chars[cursor..]);
}
out.trim_end().to_string()
}
fn emphasize(piece: &str, span: &Span) -> String {
let core = piece.trim();
if core.is_empty() || (!span.bold && !span.italic && span.highlight.is_none()) {
return piece.to_string();
}
let lead = &piece[..piece.len() - piece.trim_start().len()];
let trail = &piece[piece.trim_end().len()..];
let mut open = String::new();
if span.highlight.is_some() {
open.push_str("==");
}
if span.bold {
open.push_str("**");
}
if span.italic {
open.push('*');
}
let close: String = open.chars().rev().collect();
format!("{lead}{open}{core}{close}{trail}")
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
#[doc(hidden)]
pub static REOPENED_PACKAGES: std::cell::Cell<usize> =
const { std::cell::Cell::new(0) };
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
fn bump_reopened_packages() {
REOPENED_PACKAGES.with(|count| count.set(count.get() + 1));
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[doc(hidden)]
pub fn reset_reopened_packages() {
REOPENED_PACKAGES.with(|count| count.set(0));
}
#[doc(hidden)]
pub struct Opened {
pub pkg: PartFs,
pub main: String,
pub dom: Dom,
pub document: NodeId,
pub body: NodeId,
}
impl Opened {
#[doc(hidden)]
pub fn open(bytes: &[u8]) -> Result<Self, InspectError> {
Self::open_within(bytes, crate::admission::InputLimits::default())
}
pub(crate) fn open_within(
bytes: &[u8],
limits: crate::admission::InputLimits,
) -> Result<Self, InspectError> {
#[cfg(test)]
bump_reopened_packages();
crate::admission::admit(bytes, limits).map_err(InspectError::Admission)?;
let normalized =
crate::strict_translation::strict_to_transitional_docx_within(bytes, limits)
.map_err(|error| InspectError::Package(error.to_string()))?;
let pkg = PartFs::open_within(&normalized, limits)
.map_err(|error| InspectError::Package(error.to_string()))?;
let main = main_part(&pkg)?;
let (dom, document, root) = parse_part_within(&pkg, &main, limits)?;
let body = dom
.element(root, &W::body())
.ok_or(InspectError::MissingDocument)?;
Ok(Self {
pkg,
main,
dom,
document,
body,
})
}
fn summary(&self) -> Result<Summary, InspectError> {
let (dom, body, pkg) = (&self.dom, self.body, &self.pkg);
let mut summary = Summary {
paragraphs: body_paragraphs(dom, body).len(),
tables: tables::top_level_table_nodes(dom, body).len(),
fields: dom.descendants(body, Some(&W::fld_simple())).len()
+ dom
.descendants(body, Some(&W::fld_char()))
.iter()
.filter(|&&node| dom.attribute(node, &W::name("fldCharType")) == Some("begin"))
.count(),
sections: dom
.descendants(body, Some(&W::sect_pr()))
.iter()
.filter(|&&node| {
!has_ancestor(dom, node, &W::name("sectPrChange"))
&& !has_ancestor(dom, node, &W::p_pr_change())
})
.count(),
list_numbering: !dom.descendants(body, Some(&W::num_pr())).is_empty(),
..Summary::default()
};
for name in pkg.parts() {
let mime = pkg.content_type_for(&name);
let mime = mime.as_deref();
if mime.is_some_and(|mime| mime.starts_with("image/")) {
summary.images += 1;
}
let wordprocessing = mime.is_some_and(|mime| {
mime.starts_with("application/vnd.openxmlformats-officedocument.wordprocessingml.")
});
if wordprocessing && name != self.main {
parse_part(pkg, &name)?;
}
}
summary.revisions = crate::changes::logical_changes_in(pkg).len();
for (kind, targets) in [
("header", self.related("header")),
("footer", self.related("footer")),
("comments", self.related("comments")),
("footnotes", self.related("footnotes")),
("endnotes", self.related("endnotes")),
("settings", self.related("settings")),
("styles", self.related("styles")),
] {
for target in targets {
let (part_dom, _, part_root) = parse_part(pkg, &target)?;
match kind {
"header" => summary.headers += 1,
"footer" => summary.footers += 1,
"comments" => {
part_dom.for_each_descendant_element(
part_root,
Some(&W::comment()),
|_| summary.comments += 1,
);
}
"footnotes" => {
summary.footnotes += note_count(&part_dom, part_root, "footnote");
}
"endnotes" => summary.endnotes += note_count(&part_dom, part_root, "endnote"),
"styles" => {
let numbered_style = part_dom
.descendants(part_root, Some(&W::name("style")))
.into_iter()
.any(|style| {
part_dom.attribute(style, &W::type_()) == Some("paragraph")
&& !part_dom.descendants(style, Some(&W::num_pr())).is_empty()
});
summary.list_numbering |= numbered_style;
}
_ => {
if let Some(setting) =
part_dom.element(part_root, &W::name("trackRevisions"))
{
summary.track_changes = match part_dom.attribute(setting, &W::val()) {
None | Some("true" | "1" | "on") => true,
Some("false" | "0" | "off") => false,
Some(value) => {
return Err(InspectError::Invalid(format!(
"{target}: invalid trackRevisions value {value}"
)));
}
};
}
}
}
}
}
Ok(summary)
}
#[doc(hidden)]
pub fn story_parts(&self) -> Vec<(String, &'static str, String)> {
let mut out = Vec::new();
for kind in STORY_KINDS.iter().copied() {
let mut parts: Vec<String> = self.related(kind).into_iter().collect();
parts.sort_by_key(|part| (part.len(), part.clone()));
for part in parts {
out.push((crate::ids::part_story(&part), kind, part));
}
}
out
}
fn stories(&self) -> Result<Vec<Story>, InspectError> {
self.stories_within(crate::admission::InputLimits::default(), false)
}
fn stories_within(
&self,
limits: crate::admission::InputLimits,
reject: bool,
) -> Result<Vec<Story>, InspectError> {
self.story_parts()
.into_iter()
.map(|(id, kind, part)| {
let (mut dom, _, root) = parse_part_within(&self.pkg, &part, limits)?;
if reject {
reject_text(&mut dom, root);
}
let paragraphs = paragraphs_of(&dom, story_paragraph_nodes(&dom, root), &id);
Ok(Story {
id,
kind: kind.to_string(),
part,
paragraphs,
})
})
.collect()
}
#[doc(hidden)]
pub fn related(&self, kind: &str) -> BTreeSet<String> {
self.pkg
.read_rels_for(&self.main)
.into_iter()
.flat_map(|rels| &rels.items)
.filter(|rel| {
rel.target_mode.as_deref() != Some("External")
&& rel.rel_type.rsplit('/').next() == Some(kind)
})
.map(|rel| self.pkg.resolve_rel_target(&self.main, &rel.target))
.collect()
}
}
fn main_part(pkg: &PartFs) -> Result<String, InspectError> {
pkg.main_document_part()
.or_else(|| {
pkg.part_bytes("word/document.xml")
.map(|_| "word/document.xml".to_string())
})
.ok_or(InspectError::MissingDocument)
}
#[doc(hidden)]
pub fn parse_part(pkg: &PartFs, name: &str) -> Result<(Dom, NodeId, NodeId), InspectError> {
parse_part_within(pkg, name, crate::admission::InputLimits::default())
}
fn parse_part_within(
pkg: &PartFs,
name: &str,
limits: crate::admission::InputLimits,
) -> Result<(Dom, NodeId, NodeId), InspectError> {
let bytes = pkg
.part_bytes(name)
.ok_or_else(|| InspectError::Invalid(format!("missing related part {name}")))?;
let xml = std::str::from_utf8(bytes)
.map_err(|error| InspectError::Invalid(format!("{name}: {error}")))?;
crate::xmllinq::parse::validate_xml_with_limits(xml, limits)
.map_err(|error| InspectError::Invalid(format!("{name}: {error}")))?;
let mut dom = Dom::new();
let document = dom.parse_xdocument(xml);
let root = dom
.root(document)
.ok_or_else(|| InspectError::Invalid(format!("{name}: missing XML root")))?;
Ok((dom, document, root))
}
fn has_ancestor(dom: &Dom, node: NodeId, name: &XName) -> bool {
!dom.ancestors(node, Some(name)).is_empty()
}
pub(crate) use crate::ooxml::text_box_names;
#[doc(hidden)]
pub fn in_text_box(dom: &Dom, node: NodeId) -> bool {
text_box_names()
.iter()
.any(|name| has_ancestor(dom, node, name))
}
fn holds_text_box(dom: &Dom, node: NodeId) -> bool {
text_box_names()
.iter()
.any(|name| !dom.descendants(node, Some(name)).is_empty())
}
fn note_count(dom: &Dom, root: NodeId, local: &str) -> usize {
dom.descendants(root, Some(&W::name(local)))
.iter()
.filter(|&&node| {
!matches!(
dom.attribute(node, &W::type_()),
Some("separator" | "continuationSeparator")
)
})
.count()
}
#[doc(hidden)]
pub fn body_paragraph_nodes(dom: &Dom, body: NodeId) -> Vec<NodeId> {
dom.descendants(body, Some(&W::p()))
.into_iter()
.filter(|&p| !in_text_box(dom, p))
.collect()
}
#[doc(hidden)]
pub fn body_control_nodes(dom: &Dom, body: NodeId) -> Vec<NodeId> {
dom.descendants(body, Some(&W::sdt()))
.into_iter()
.filter(|&sdt| !in_text_box(dom, sdt))
.collect()
}
#[doc(hidden)]
pub fn collect_controls(dom: &Dom, body: NodeId) -> Vec<ContentControl> {
let paragraphs = body_paragraph_nodes(dom, body);
let index: std::collections::HashMap<NodeId, usize> = paragraphs
.iter()
.enumerate()
.map(|(i, &p)| (p, i))
.collect();
let mut blocks = 0usize;
let mut inline: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
body_control_nodes(dom, body)
.into_iter()
.map(|sdt| {
let owner = dom
.ancestors(sdt, Some(&W::p()))
.first()
.and_then(|p| index.get(p).copied());
let id = match owner {
Some(i) => {
let k = inline.entry(i).or_default();
*k += 1;
format!("{}.cc{}", crate::ids::paragraph_id("body", i), *k - 1)
}
None => {
blocks += 1;
format!("cc{}", blocks - 1)
}
};
control_record(dom, sdt, id, &index)
})
.collect()
}
fn control_record(
dom: &Dom,
sdt: NodeId,
id: String,
index: &std::collections::HashMap<NodeId, usize>,
) -> ContentControl {
let pr = dom.element(sdt, &W::sdt_pr());
let child = |name: &XName| pr.and_then(|pr| dom.element(pr, name));
let val = |name: &XName| {
child(name)
.and_then(|e| dom.attribute(e, &W::val()))
.map(str::to_string)
};
let kind = pr.map_or("rich_text", |pr| control_kind(dom, pr));
let list = child(&W::name("dropDownList")).or_else(|| child(&W::name("comboBox")));
let choices = list
.map(|list| {
dom.elements(list, Some(&W::name("listItem")))
.into_iter()
.filter_map(|item| {
dom.attribute(item, &W::name("value"))
.or_else(|| dom.attribute(item, &W::name("displayText")))
.map(str::to_string)
})
.collect()
})
.unwrap_or_default();
let checked = child(&W14::name("checkbox")).map(|checkbox| {
dom.element(checkbox, &W14::name("checked"))
.and_then(|c| dom.attribute(c, &W14::name("val")))
.is_some_and(on_off)
});
let placeholder = child(&W::name("showingPlcHdr"))
.is_some_and(|e| dom.attribute(e, &W::val()).is_none_or(on_off));
let locked = matches!(
val(&W::name("lock")).as_deref(),
Some("contentLocked" | "sdtContentLocked")
);
let content = dom.element(sdt, &W::sdt_content());
let owner = dom.ancestors(sdt, Some(&W::p())).first().copied();
let (paragraph_ids, text) = match (owner, content) {
(Some(p), _) => {
let text = content.map_or_else(String::new, |c| project_container(dom, c).text);
(index.get(&p).map(|&i| vec![i]).unwrap_or_default(), text)
}
(None, Some(c)) => {
let inner: Vec<(usize, NodeId)> = dom
.descendants(c, Some(&W::p()))
.into_iter()
.filter_map(|p| index.get(&p).map(|&i| (i, p)))
.collect();
let text = inner
.iter()
.map(|&(_, p)| project_paragraph(dom, p).text)
.collect::<Vec<_>>()
.join("\n");
(inner.into_iter().map(|(i, _)| i).collect(), text)
}
(None, None) => (Vec::new(), String::new()),
};
ContentControl {
id,
tag: val(&W::name("tag")),
alias: val(&W::name("alias")),
kind: kind.to_string(),
text,
paragraph_ids: paragraph_ids
.into_iter()
.map(|i| crate::ids::paragraph_id("body", i))
.collect(),
locked,
choices,
checked,
placeholder,
}
}
fn on_off(value: &str) -> bool {
matches!(value, "1" | "true" | "on")
}
const SDT_PROPERTIES: &[&str] = &[
"rPr",
"alias",
"tag",
"id",
"lock",
"placeholder",
"temporary",
"showingPlcHdr",
"dataBinding",
"label",
"tabIndex",
];
fn control_kind(dom: &Dom, pr: NodeId) -> &'static str {
for child in dom.elements(pr, None) {
let Some(name) = dom.name(child) else {
continue;
};
let (ns, local) = (name.namespace_name(), name.local_name());
let kind = if ns == W::URI {
match local {
"text" => "text",
"richText" => "rich_text",
"dropDownList" => "drop_down",
"comboBox" => "combo_box",
"date" => "date",
"picture" => "picture",
"group" => "group",
"docPartObj" | "docPartList" => "building_block",
"citation" => "citation",
"bibliography" => "bibliography",
"equation" => "equation",
local if SDT_PROPERTIES.contains(&local) => continue,
_ => "unknown",
}
} else if ns == W14::URI {
match local {
"checkbox" => "checkbox",
_ => continue,
}
} else if ns == W15::URI {
match local {
"repeatingSection" | "repeatingSectionItem" => "repeating",
_ => continue,
}
} else {
"unknown"
};
return kind;
}
"rich_text"
}
#[doc(hidden)]
pub fn story_paragraph_nodes(dom: &Dom, root: NodeId) -> Vec<NodeId> {
body_paragraph_nodes(dom, root)
.into_iter()
.filter(|&p| {
!dom.ancestors(p, None).into_iter().any(|a| {
(dom.name_is(a, &W::footnote()) || dom.name_is(a, &W::endnote()))
&& matches!(
dom.attribute(a, &W::type_()),
Some("separator" | "continuationSeparator" | "continuationNotice")
)
})
})
.collect()
}
fn body_paragraphs(dom: &Dom, body: NodeId) -> Vec<Paragraph> {
paragraphs_of(dom, body_paragraph_nodes(dom, body), BODY_STORY)
}
fn paragraphs_of(dom: &Dom, nodes: Vec<NodeId>, story: &str) -> Vec<Paragraph> {
nodes
.into_iter()
.enumerate()
.map(|(index, p)| {
let projection = project_paragraph(dom, p);
let ppr = dom.element(p, &W::p_pr());
let style = ppr
.and_then(|ppr| dom.element(ppr, &W::p_style()))
.and_then(|s| dom.attribute(s, &W::val()))
.map(str::to_string);
let numbered = ppr.is_some_and(|ppr| dom.element(ppr, &W::num_pr()).is_some());
Paragraph {
index,
id: crate::ids::paragraph_id(story, index),
text: projection.text,
style,
numbered,
in_table: has_ancestor(dom, p, &W::tc()),
page_break: projection.page_break,
runs: projection.spans,
limitations: projection.limitations.into_iter().collect(),
}
})
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum Piece {
Text { t: NodeId, run: NodeId },
Glyph { element: NodeId, run: NodeId },
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub struct Segment {
pub start: usize,
pub end: usize,
pub piece: Piece,
pub direct: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[doc(hidden)]
pub struct Projection {
pub text: String,
pub segments: Vec<Segment>,
pub(crate) spans: Vec<Span>,
pub(crate) page_break: bool,
pub limitations: BTreeSet<String>,
pub field_marks: Vec<usize>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Format {
bold: bool,
italic: bool,
underline: bool,
highlight: Option<String>,
}
#[doc(hidden)]
pub fn project_paragraph(dom: &Dom, paragraph: NodeId) -> Projection {
let mut projection = Projection::default();
let mut formats: Vec<(usize, usize, Format)> = Vec::new();
let mut fields = 0;
walk_container(
dom,
paragraph,
true,
&mut fields,
&mut projection,
&mut formats,
);
projection.spans = merge_spans(&projection.text, formats);
projection
}
pub(crate) fn project_container(dom: &Dom, container: NodeId) -> Projection {
let mut projection = Projection::default();
let mut formats: Vec<(usize, usize, Format)> = Vec::new();
let mut fields = 0;
walk_container(
dom,
container,
false,
&mut fields,
&mut projection,
&mut formats,
);
projection.spans = merge_spans(&projection.text, formats);
projection
}
fn walk_container(
dom: &Dom,
container: NodeId,
direct: bool,
fields: &mut usize,
out: &mut Projection,
formats: &mut Vec<(usize, usize, Format)>,
) {
for child in dom.elements(container, None) {
let Some(name) = dom.name(child) else {
continue;
};
let ns = name.namespace_name();
let local = name.local_name();
if ns == MC::URI {
out.limitations.insert("alternate_content".into());
if local == "AlternateContent"
&& let Some(choice) = dom.element(child, &MC::name("Choice"))
{
walk_container(dom, choice, false, fields, out, formats);
}
continue;
}
if ns != W::URI {
out.limitations.insert(format!("unknown:{local}"));
continue;
}
match local {
"pPr" | "proofErr" | "bookmarkStart" | "bookmarkEnd" | "commentRangeStart"
| "commentRangeEnd" | "permStart" | "permEnd" | "moveFromRangeStart"
| "moveFromRangeEnd" | "moveToRangeStart" | "moveToRangeEnd" => {}
"del" | "moveFrom" => {
out.limitations.insert("revision".into());
}
"ins" | "moveTo" => {
out.limitations.insert("revision".into());
walk_container(dom, child, false, fields, out, formats);
}
"r" => walk_run(dom, child, direct, fields, out, formats),
"hyperlink" => {
out.limitations.insert("hyperlink".into());
walk_container(dom, child, false, fields, out, formats);
}
"fldSimple" => {
out.limitations.insert("field".into());
walk_container(dom, child, false, fields, out, formats);
}
"sdt" => {
out.limitations.insert("content_control".into());
if let Some(content) = dom.element(child, &W::sdt_content()) {
walk_container(dom, content, false, fields, out, formats);
}
}
"smartTag" | "customXml" | "dir" | "bdo" => {
walk_container(dom, child, false, fields, out, formats);
}
_ => {
out.limitations.insert(format!("unknown:{local}"));
}
}
}
}
fn walk_run(
dom: &Dom,
run: NodeId,
direct: bool,
fields: &mut usize,
out: &mut Projection,
formats: &mut Vec<(usize, usize, Format)>,
) {
let format = run_format(dom, run);
let start = out.text.len();
for child in dom.elements(run, None) {
let Some(name) = dom.name(child) else {
continue;
};
if name.namespace_name() == MC::URI {
out.limitations.insert("alternate_content".into());
if ["drawing", "pict", "object"]
.iter()
.any(|local| !dom.descendants(child, Some(&W::name(local))).is_empty())
{
out.limitations.insert("drawing".into());
}
if holds_text_box(dom, child) {
out.limitations.insert("text_box_omitted".into());
}
continue;
}
if name.namespace_name() != W::URI {
out.limitations
.insert(format!("unknown:{}", name.local_name()));
continue;
}
let direct = direct && *fields == 0;
let glyph = |out: &mut Projection, ch: char| {
let s = out.text.len();
out.text.push(ch);
out.segments.push(Segment {
start: s,
end: out.text.len(),
piece: Piece::Glyph {
element: child,
run,
},
direct,
});
};
match name.local_name() {
"t" => {
let s = out.text.len();
let value = dom.value_str(child);
out.text.push_str(&value);
out.segments.push(Segment {
start: s,
end: out.text.len(),
piece: Piece::Text { t: child, run },
direct,
});
}
"tab" | "ptab" => glyph(out, '\t'),
"cr" => glyph(out, '\n'),
"br" => match dom.attribute(child, &W::type_()) {
Some("page") => out.page_break = true,
Some("column") => {
out.limitations.insert("column_break".into());
}
_ => glyph(out, '\n'),
},
"noBreakHyphen" => glyph(out, '\u{2011}'),
"softHyphen" => glyph(out, '\u{00ad}'),
"sym" => {
out.limitations.insert("sym".into());
glyph(out, '\u{fffc}');
}
"fldChar" => {
out.limitations.insert("field".into());
out.field_marks.push(out.text.len());
match dom.attribute(child, &W::name("fldCharType")) {
Some("begin") => *fields += 1,
Some("end") => *fields = fields.saturating_sub(1),
_ => {}
}
}
"drawing" | "pict" | "object" => {
out.limitations.insert("drawing".into());
if holds_text_box(dom, child) {
out.limitations.insert("text_box_omitted".into());
}
}
"footnoteReference" | "endnoteReference" => {
out.limitations.insert("note_reference".into());
}
"rPr"
| "instrText"
| "delText"
| "delInstrText"
| "lastRenderedPageBreak"
| "commentReference"
| "annotationRef"
| "footnoteRef"
| "endnoteRef"
| "separator"
| "continuationSeparator"
| "dayShort"
| "dayLong"
| "monthShort"
| "monthLong"
| "yearShort"
| "yearLong"
| "pgNum" => {}
other => {
out.limitations.insert(format!("unknown:{other}"));
}
}
}
if out.text.len() > start {
formats.push((start, out.text.len(), format));
}
}
fn run_format(dom: &Dom, run: NodeId) -> Format {
let Some(rpr) = dom.element(run, &W::r_pr()) else {
return Format::default();
};
let on = |local: &str| -> bool {
dom.element(rpr, &W::name(local))
.is_some_and(|el| !matches!(dom.attribute(el, &W::val()), Some("false" | "0" | "off")))
};
let underline = dom
.element(rpr, &W::name("u"))
.is_some_and(|u| dom.attribute(u, &W::val()).is_none_or(|v| v != "none"));
let highlight = dom
.element(rpr, &W::name("highlight"))
.and_then(|h| dom.attribute(h, &W::val()))
.filter(|v| *v != "none")
.map(str::to_string);
Format {
bold: on("b"),
italic: on("i"),
underline,
highlight,
}
}
fn merge_spans(text: &str, formats: Vec<(usize, usize, Format)>) -> Vec<Span> {
let mut merged: Vec<(usize, usize, Format)> = Vec::new();
for (start, end, format) in formats {
if let Some(last) = merged.last_mut()
&& last.1 == start
&& last.2 == format
{
last.1 = end;
} else {
merged.push((start, end, format));
}
}
let char_at = |byte: usize| text[..byte].chars().count();
merged
.into_iter()
.map(|(start, end, format)| Span {
start: char_at(start),
end: char_at(end),
bold: format.bold,
italic: format.italic,
underline: format.underline,
highlight: format.highlight,
})
.collect()
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn sha256_is_lowercase_hex_of_the_bytes() {
assert_eq!(
source_sha256(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn markdown_moves_edge_whitespace_outside_emphasis() {
let span = Span {
start: 0,
end: 0,
bold: true,
italic: true,
underline: false,
highlight: Some("yellow".into()),
};
assert_eq!(emphasize(" Title ", &span), " ==***Title***== ");
assert_eq!(emphasize(" ", &span), " ");
let plain = Span {
bold: false,
italic: false,
highlight: None,
..span
};
assert_eq!(emphasize(" x ", &plain), " x ");
}
#[test]
fn markdown_of_empty_and_styled_paragraphs() {
let p = |id: &str, text: &str, style: Option<&str>| Paragraph {
index: 0,
id: id.into(),
text: text.into(),
style: style.map(str::to_string),
numbered: false,
in_table: false,
page_break: false,
runs: Vec::new(),
limitations: Vec::new(),
};
let md = render_markdown(&[p("p0", "Scope", Some("Heading1")), p("p1", "", None)]);
assert_eq!(md, "[p0 Heading1] Scope\n\n[p1]\n");
assert_eq!(render_markdown(&[]), "");
}
#[test]
fn spans_merge_only_adjacent_equal_formatting() {
let bold = Format {
bold: true,
..Format::default()
};
let spans = merge_spans(
"abcdef",
vec![
(0, 2, bold.clone()),
(2, 4, bold.clone()),
(4, 6, Format::default()),
],
);
assert_eq!(spans.len(), 2);
assert_eq!((spans[0].start, spans[0].end, spans[0].bold), (0, 4, true));
assert_eq!((spans[1].start, spans[1].end, spans[1].bold), (4, 6, false));
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod span_branch_tests {
use super::*;
fn format(bold: bool, highlight: Option<&str>) -> Format {
Format {
bold,
italic: false,
underline: false,
highlight: highlight.map(str::to_string),
}
}
#[test]
fn touching_equal_formats_merge_and_gaps_split() {
let text = "ab cd ef";
let spans = merge_spans(
text,
vec![
(0, 1, format(true, None)),
(1, 2, format(true, None)),
(3, 5, format(true, None)),
],
);
assert_eq!(
spans.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(),
[(0, 2), (3, 5)]
);
}
#[test]
fn highlight_alone_is_marked_and_space_stays_outside() {
let span = merge_spans("x", vec![(0, 1, format(false, Some("yellow")))]).remove(0);
assert_eq!(emphasize(" lit ", &span), " ==lit== ");
let plain = merge_spans("x", vec![(0, 1, format(false, None))]).remove(0);
assert_eq!(emphasize(" lit ", &plain), " lit ");
assert_eq!(emphasize(" ", &span), " ");
}
}