Files: a Word chunk that asks to keep its source formatting keeps it (w:matchSrc)

An alternative format chunk holding a Word document with w:matchSrc keeps its
own styles: a style the document already has comes along under a new id, the
chunk's document defaults (and Word's, where they say nothing) go into its
base styles, and its unstyled paragraphs use its own Normal. Without
w:matchSrc the document's styles win, as before. Adopting another document
now also renumbers table styles and the revisions of table, row and cell
property changes.

A document whose chunk shares style names with it (Normal with an exact line
height, an italic Subtitle) ran a page longer than in Word: the chunk's tables
took the document's styles. It now keeps its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NaxvogandClaude Opus 5.5 authored and Naxvog committed 2026-11-02 07:04:31 +01:00
1 parent 89c0d516ae
commit 868fffa6fe
5 files changed
+384 -76

No files matched your search

+184 -50
View File
@@ -389,25 +389,10 @@ fn restyle_block(b: &mut Block, from: &str, to: &Option<String>, depth: usize) -
}
}
/// One past the highest permission range id in `blocks`.
fn perm_end<'a>(blocks: impl Iterator<Item = &'a Arc<Block>>) -> u32 {
let mut end = 0u32;
for b in blocks {
each_para(b, 0, &mut |p| {
for o in &p.objects {
if let InlineObject::PermStart { id, .. } | InlineObject::PermEnd { id } = o {
end = end.max(id.saturating_add(1));
}
}
});
}
end
}
/// Text box story ids of a paragraph's shapes.
/// What [`Document::adopt`] renumbers in another document's content: media keys, lists, note
/// and comment stories, comment ids, text boxes (one it doesn't bring is dropped) and revisions
/// (after ours, at `rev`).
/// What [`Document::adopt_with`] renumbers in another document's content: media keys, lists,
/// note and comment stories, comment ids, text boxes (one it doesn't bring is dropped), revisions
/// (after ours, at `rev`; an id past the `revs` it brings is dropped) and styles (those kept under new ids; unstyled paragraphs take
/// `default_style` when it's given).
struct Relink<'a> {
media: &'a BTreeMap<String, String>,
nums: &'a BTreeMap<u32, u32>,
@@ -417,37 +402,97 @@ struct Relink<'a> {
/// Added to permission range ids: ours come first.
perms: u32,
rev: u32,
revs: u32,
styles: &'a BTreeMap<String, String>,
default_style: Option<&'a str>,
}
impl Relink<'_> {
// shortcut: tracked changes of table, row and cell properties keep their revision ids; renumber them too when tables from other documents carry revisions.
fn block(&self, b: &mut Block) {
each_para_mut(b, 0, &mut |p| self.para(p));
// Its own stack, like `each_para_mut`: tables however deeply nested are relinked (#1339).
let mut todo = vec![b];
while let Some(b) = todo.pop() {
match b {
Block::Para(p) => self.para(p),
Block::Table(t) => {
self.style(&mut t.props.style);
self.shift_change(&mut t.props.fmt_change);
if let Some(c) = t.props.fmt_change.as_mut() {
self.style(&mut c.old.style);
}
for row in t.rows.iter_mut() {
self.shift_change(&mut row.props.fmt_change);
for cell in row.cells.iter_mut() {
self.shift_change(&mut cell.props.fmt_change);
todo.extend(cell.blocks.iter_mut().map(Arc::make_mut));
}
}
}
}
}
}
fn style(&self, id: &mut Option<String>) {
if let Some(new) = id.as_ref().and_then(|i| self.styles.get(i)) {
*id = Some(new.clone());
}
}
/// A paragraph's style: unstyled ones take `default_style` when it's given.
fn para_style(&self, id: &mut Option<String>) {
match (&*id, self.default_style) {
(None, Some(d)) => *id = Some(d.to_string()),
_ => self.style(id),
}
}
fn num(&self, n: &mut Option<crate::props::NumRef>) {
if let Some(n) = n.as_mut()
&& n.num != 0
{
n.num = self.nums.get(&n.num).copied().unwrap_or(0);
}
}
/// Our id for the other document's revision `r`, if it has one.
fn rev_id(&self, r: u32) -> Option<u32> {
if r < self.revs { self.rev.checked_add(r) } else { None }
}
fn shift_change<T>(&self, c: &mut Option<Box<crate::props::PropChange<T>>>) {
match (c.as_ref().and_then(|c| self.rev_id(c.rev)), c.as_mut()) {
(Some(v), Some(x)) => x.rev = v,
_ => *c = None,
}
}
fn para(&self, p: &mut Paragraph) {
// A tracked change's old formatting names lists as the live one does.
let old = p.props.fmt_change.as_mut().and_then(|f| f.old.numbering.as_mut());
for n in p.props.numbering.iter_mut().chain(old) {
if n.num != 0 {
n.num = self.nums.get(&n.num).copied().unwrap_or(0);
}
self.num(&mut p.props.numbering);
self.para_style(&mut p.props.style);
for r in &mut p.runs {
self.style(&mut r.props.style);
}
let shift = |r: &mut u32| *r = r.saturating_add(self.rev);
self.style(&mut p.mark.style);
for c in p.runs.iter_mut().map(|r| &mut r.props).chain([&mut p.mark]) {
c.ins.iter_mut().chain(c.del.iter_mut()).for_each(shift);
c.ins = c.ins.and_then(|r| self.rev_id(r));
c.del = c.del.and_then(|r| self.rev_id(r));
self.shift_change(&mut c.fmt_change);
// A tracked change's old formatting names styles and lists as the live one does.
if let Some(f) = c.fmt_change.as_mut() {
shift(&mut f.rev);
self.style(&mut f.old.style);
}
}
self.shift_change(&mut p.props.fmt_change);
if let Some(f) = p.props.fmt_change.as_mut() {
shift(&mut f.rev);
self.para_style(&mut f.old.style);
self.num(&mut f.old.numbering);
}
if let Some(f) = p.section.as_deref_mut().and_then(|s| s.fmt_change.as_mut()) {
shift(&mut f.rev);
if let Some(s) = p.section.as_deref_mut() {
self.shift_change(&mut s.fmt_change);
}
if let Some(f) = p.props.num_change.as_mut() {
shift(&mut f.rev);
match (p.props.num_change.as_ref().and_then(|c| self.rev_id(c.rev)), p.props.num_change.as_mut()) {
(Some(v), Some(c)) => c.rev = v,
_ => p.props.num_change = None,
}
for o in &mut p.objects {
self.object(o, 0);
@@ -490,6 +535,22 @@ impl Relink<'_> {
}
}
/// One past the highest permission range id in `blocks`.
fn perm_end<'a>(blocks: impl Iterator<Item = &'a Arc<Block>>) -> u32 {
let mut end = 0u32;
for b in blocks {
each_para(b, 0, &mut |p| {
for o in &p.objects {
if let InlineObject::PermStart { id, .. } | InlineObject::PermEnd { id } = o {
end = end.max(id.saturating_add(1));
}
}
});
}
end
}
/// Text box story ids of a paragraph's shapes.
fn box_ids(p: &Paragraph) -> impl Iterator<Item = u32> + '_ {
p.objects.iter().flat_map(InlineObject::text_boxes)
}
@@ -971,12 +1032,46 @@ impl Document {
/// revisions renumbered so they can't collide with ours; a style we already have by id stays
/// ours), and its text boxes ride in [`Fragment::parts`].
pub fn adopt(&mut self, src: Document) -> Fragment {
self.adopt_in(src, &mut 0)
self.adopt_with(src, false)
}
/// [`Self::adopt`], its permission range ids from at least `perms` on (and past ours);
/// [`Self::adopt`]; with `keep_styles` its content keeps its own formatting (Word's
/// `w:matchSrc`): a style whose id we already have comes along under a new id, and its
/// document defaults go into its base styles, which its unstyled paragraphs then use.
pub fn adopt_with(&mut self, src: Document, keep_styles: bool) -> Fragment {
self.adopt_in(src, keep_styles, &mut 0)
}
/// [`Self::adopt_with`], its permission range ids from at least `perms` on (and past ours);
/// `perms` moves past them.
fn adopt_in(&mut self, src: Document, perms: &mut u32) -> Fragment {
fn adopt_in(&mut self, mut src: Document, keep_styles: bool, perms: &mut u32) -> Fragment {
let mut renamed = BTreeMap::new();
let mut default_style = None;
if keep_styles {
if src.styles.get("Normal").is_none() {
src.styles.upsert(crate::styles::Style { id: "Normal".into(), name: "Normal".into(), ..Default::default() });
}
// Ids given out here are taken too: two styles never get the same new one.
let mut given = std::collections::HashSet::new();
let room = src.styles.styles.len().saturating_mul(2).saturating_add(self.styles.styles.len()).saturating_add(1);
for st in &src.styles.styles {
if self.styles.get(&st.id).is_some() {
let fresh = (1..=room)
.map(|n| format!("{}{n}", st.id))
.find(|id| self.styles.get(id).is_none() && src.styles.get(id).is_none() && !given.contains(id));
if let Some(fresh) = fresh {
given.insert(fresh.clone());
renamed.insert(st.id.clone(), fresh);
}
}
}
default_style = Some(renamed.get("Normal").cloned().unwrap_or_else(|| "Normal".into()));
}
let restyle = |id: &mut Option<String>| {
if let Some(new) = id.as_ref().and_then(|i| renamed.get(i)) {
*id = Some(new.clone());
}
};
let mut media = BTreeMap::new();
for (key, data) in &src.media {
let ext = key.rsplit_once('.').map(|(_, e)| e).unwrap_or("png");
@@ -987,7 +1082,9 @@ impl Document {
for (i, a) in src.numbering.abstracts.iter().enumerate() {
let id = next_abs.saturating_add(i as u32);
abs_map.insert(a.id, id);
self.numbering.abstracts.push(crate::numbering::AbstractNum { id, ..a.clone() });
let mut a = crate::numbering::AbstractNum { id, ..a.clone() };
a.levels.iter_mut().for_each(|l| restyle(&mut l.style));
self.numbering.abstracts.push(a);
}
let next_num = self.numbering.nums.iter().map(|n| n.id.saturating_add(1)).max().unwrap_or(1).max(1);
let mut nums = BTreeMap::new();
@@ -995,7 +1092,9 @@ impl Document {
let id = next_num.saturating_add(i as u32);
nums.insert(n.id, id);
let abstract_id = abs_map.get(&n.abstract_id).copied().unwrap_or(n.abstract_id);
self.numbering.nums.push(crate::numbering::Num { id, abstract_id, ..n.clone() });
let mut n = crate::numbering::Num { id, abstract_id, ..n.clone() };
n.level_overrides.iter_mut().for_each(|(_, l)| restyle(&mut l.style));
self.numbering.nums.push(n);
}
let renumber = |n: &mut Option<crate::props::NumRef>| {
if let Some(n) = n.as_mut()
@@ -1004,11 +1103,35 @@ impl Document {
n.num = nums.get(&n.num).copied().unwrap_or(0);
}
};
// What a style in the other document doesn't set comes from its defaults there, and
// Word's own (no space, single lines) where those don't say.
let mut para_defaults = src.styles.default_para.clone();
para_defaults.space_before.get_or_insert(0.0);
para_defaults.space_after.get_or_insert(0.0);
para_defaults.line_spacing.get_or_insert(crate::props::LineSpacing::Multiple(1.0));
for st in &src.styles.styles {
let mut st = st.clone();
// Our defaults stay ours.
st.default = false;
if keep_styles {
if let Some(new) = renamed.get(&st.id) {
st.name = format!("{} ({new})", st.name);
st.id = new.clone();
}
restyle(&mut st.based_on);
restyle(&mut st.next);
restyle(&mut st.linked);
// A character style's runs get the defaults through their paragraph's style.
if st.based_on.is_none() && st.kind != crate::styles::StyleKind::Character {
let mut chr = src.styles.default_chr.clone();
chr.overlay(&st.chr);
st.chr = chr;
let mut para = para_defaults.clone();
para.overlay(&st.para);
st.para = para;
}
}
if self.styles.get(&st.id).is_none() {
let mut st = st.clone();
// Our defaults stay ours.
st.default = false;
renumber(&mut st.para.numbering);
self.styles.upsert(st);
}
@@ -1034,7 +1157,18 @@ impl Document {
// Its permission ranges are numbered after ours, so no end of theirs closes one of ours.
let first_perm = perm_end(self.body.iter().chain(self.parts.values().flat_map(|p| p.blocks.iter()))).max(*perms);
*perms = first_perm.saturating_add(perm_end(src.body.iter().chain(src.parts.values().flat_map(|p| p.blocks.iter()))));
let link = Relink { media: &media, nums: &nums, notes: &notes, comments: &comments, boxes: &boxes, perms: first_perm, rev };
let link = Relink {
media: &media,
nums: &nums,
notes: &notes,
comments: &comments,
boxes: &boxes,
perms: first_perm,
rev,
revs: u32::try_from(src.revisions.len()).unwrap_or(u32::MAX),
styles: &renamed,
default_style: default_style.as_deref(),
};
let mut parts = boxes.clone();
for part in parts.values_mut() {
part.blocks.iter_mut().for_each(|b| link.block(Arc::make_mut(b)));
@@ -1062,12 +1196,12 @@ impl Document {
Fragment { blocks, parts }
}
/// [`Self::adopt`] as blocks to place in a story directly (a reader building one): its text
/// boxes already have stories of their own here. `perms` is the first permission range id the
/// reader hasn't given out (ranges it holds aren't in this document yet); it moves past the
/// adopted ones.
pub fn adopt_blocks(&mut self, src: Document, perms: &mut u32) -> Vec<Block> {
let Fragment { mut blocks, parts } = self.adopt_in(src, perms);
/// [`Self::adopt_with`] as blocks to place in a story directly (a reader building one): its
/// text boxes already have stories of their own here. `perms` is the first permission range
/// id the reader hasn't given out (ranges it holds aren't in this document yet); it moves past
/// the adopted ones.
pub fn adopt_blocks(&mut self, src: Document, keep_styles: bool, perms: &mut u32) -> Vec<Block> {
let Fragment { mut blocks, parts } = self.adopt_in(src, keep_styles, perms);
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
blocks
+85 -22
View File
@@ -688,6 +688,8 @@ fn adopting_a_document_renumbers_what_it_refers_to() {
let p = theirs.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.numbering = Some(crate::props::NumRef { num: list, level: 0 });
p.runs[0].props.del = Some(0);
// An insertion naming a revision it doesn't have.
p.runs[0].props.ins = Some(7);
let props = p.props_of_char(0).clone();
p.insert_object(0, InlineObject::NoteRef { kind: NoteKind::Footnote, id: note, custom: String::new() }, &props).unwrap();
p.insert_object(0, InlineObject::CommentStart { id: 0 }, &props).unwrap();
@@ -701,6 +703,7 @@ fn adopting_a_document_renumbers_what_it_refers_to() {
// Their deletion is their revision, after ours.
let del = p.runs.iter().find_map(|r| r.props.del).unwrap();
assert_eq!(ours.revisions.get(del as usize).map(|r| r.kind), Some(RevisionKind::Delete));
assert!(p.runs.iter().all(|r| r.props.ins.is_none()));
// Their note and comment come along under ids of their own.
let (note_id, comment_id) = p.objects.iter().fold((None, None), |(n, c), o| match o {
InlineObject::NoteRef { id, .. } => (Some(*id), c),
@@ -720,6 +723,55 @@ fn adopting_a_document_renumbers_what_it_refers_to() {
assert_eq!(text(our_note).as_deref(), Some("our note"));
}
#[test]
fn a_kept_character_style_leaves_what_it_doesnt_set_to_the_paragraph_style() {
use crate::styles::{Style, StyleKind, StyleSheet};
let mut ours = doc(&["ours"]);
let mut theirs = doc(&["theirs"]);
theirs.styles = StyleSheet::empty();
theirs.styles.default_chr = CharProps { size: Some(9.0), ..Default::default() };
let big = CharProps { size: Some(20.0), ..Default::default() };
theirs.styles.upsert(Style { id: "Big".into(), name: "Big".into(), chr: big, ..Default::default() });
theirs.styles.upsert(Style { id: "Link".into(), name: "Link".into(), kind: StyleKind::Character, ..Default::default() });
let p = theirs.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.style = Some("Big".into());
p.runs[0].props.style = Some("Link".into());
let frag = ours.adopt_with(theirs, true);
let Some(Block::Para(p)) = frag.blocks.first() else { panic!() };
assert_eq!(ours.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props).size, 20.0);
}
#[test]
fn kept_styles_renamed_on_adoption_are_renamed_in_list_levels_too() {
use crate::styles::Style;
let mut ours = doc(&["ours"]);
ours.styles.upsert(Style { id: "Heading1".into(), name: "heading 1".into(), ..Default::default() });
let mut theirs = doc(&["theirs"]);
theirs.styles.upsert(Style { id: "Heading1".into(), name: "heading 1".into(), ..Default::default() });
let list = theirs.numbering.add_list(crate::numbering::ListKind::Numbered);
let abs = theirs.numbering.nums.iter().find(|n| n.id == list).map(|n| n.abstract_id).unwrap();
let a = theirs.numbering.abstracts.iter_mut().find(|a| a.id == abs).unwrap();
a.levels[0].style = Some("Heading1".into());
let level = a.levels[0].clone();
theirs.numbering.nums.iter_mut().find(|n| n.id == list).unwrap().level_overrides.push((1, level));
let before = ours.numbering.abstracts.len();
ours.adopt_with(theirs, true);
let copied = &ours.numbering.abstracts[before..];
let styles: Vec<_> = copied
.iter()
.flat_map(|a| a.levels.iter())
.chain(ours.numbering.nums.iter().flat_map(|n| n.level_overrides.iter().map(|(_, l)| l)))
.filter_map(|l| l.style.clone())
.collect();
assert_eq!(styles.len(), 2, "{styles:?}");
for st in &styles {
assert_ne!(st, "Heading1");
assert!(ours.styles.get(st).is_some(), "{st}");
}
}
#[test]
fn an_adopted_section_breaks_tracked_change_names_its_revision() {
use crate::{Revision, RevisionKind, SectionProps};
@@ -737,36 +789,47 @@ fn an_adopted_section_breaks_tracked_change_names_its_revision() {
}
#[test]
fn an_adopted_tracked_format_change_keeps_its_old_list() {
fn an_adopted_tracked_format_change_keeps_its_old_styles_and_list() {
use crate::props::{NumRef, ParaProps, PropChange};
use crate::{Revision, RevisionKind};
let mut ours = doc(&["ours"]);
let our_list = ours.numbering.add_list(crate::numbering::ListKind::Bullet);
let mut theirs = doc(&["theirs"]);
theirs.revisions.push(Revision { kind: RevisionKind::Format, ..Revision::default() });
let list = theirs.numbering.add_list(crate::numbering::ListKind::Bullet);
assert_eq!(list, our_list);
let p = theirs.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.props.numbering = Some(NumRef { num: list, level: 0 });
p.props.fmt_change = PropChange::boxed(0, ParaProps { numbering: Some(NumRef { num: list, level: 0 }), ..ParaProps::default() });
for keep in [false, true] {
let mut ours = doc(&["ours"]);
let our_list = ours.numbering.add_list(crate::numbering::ListKind::Bullet);
let mut theirs = doc(&["theirs"]);
theirs.revisions.push(Revision { kind: RevisionKind::Format, ..Revision::default() });
let list = theirs.numbering.add_list(crate::numbering::ListKind::Bullet);
assert_eq!(list, our_list);
let p = theirs.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
// Live and old props name the same styles (ours has them too) and their list.
p.props.style = Some("Quote".into());
p.props.numbering = Some(NumRef { num: list, level: 0 });
let old = ParaProps { style: Some("Quote".into()), numbering: Some(NumRef { num: list, level: 0 }), ..ParaProps::default() };
p.props.fmt_change = PropChange::boxed(0, old);
p.runs[0].props.style = Some("Strong".into());
p.runs[0].props.fmt_change = PropChange::boxed(0, CharProps { style: Some("Strong".into()), ..CharProps::default() });
let frag = ours.adopt(theirs);
let Some(Block::Para(p)) = frag.blocks.first() else { panic!() };
let old = &p.props.fmt_change.as_ref().unwrap().old;
assert_eq!(old.numbering, p.props.numbering);
assert_ne!(old.numbering.map(|n| n.num), Some(our_list));
let frag = ours.adopt_with(theirs, keep);
let Some(Block::Para(p)) = frag.blocks.first() else { panic!() };
let old = &p.props.fmt_change.as_ref().unwrap().old;
assert_eq!((&old.style, old.numbering), (&p.props.style, p.props.numbering), "keep_styles {keep}");
assert_ne!(old.numbering.map(|n| n.num), Some(our_list));
let run = &p.runs[0].props;
assert_eq!(run.fmt_change.as_ref().unwrap().old.style, run.style, "keep_styles {keep}");
}
}
#[test]
fn adopted_styles_never_become_our_defaults() {
use crate::styles::{Style, StyleKind};
let mut ours = doc(&["ours"]);
let mut theirs = doc(&["theirs"]);
// A localized default character style, and one whose id we have too.
theirs.styles.upsert(Style { id: "Absatz".into(), kind: StyleKind::Character, default: true, ..Default::default() });
theirs.styles.upsert(Style { id: "Strong".into(), kind: StyleKind::Character, default: true, ..Default::default() });
ours.adopt(theirs);
assert!(ours.styles.styles.iter().all(|s| !s.default));
for keep in [false, true] {
let mut ours = doc(&["ours"]);
let mut theirs = doc(&["theirs"]);
// A localized default character style, and one whose id we have too.
theirs.styles.upsert(Style { id: "Absatz".into(), kind: StyleKind::Character, default: true, ..Default::default() });
theirs.styles.upsert(Style { id: "Strong".into(), kind: StyleKind::Character, default: true, ..Default::default() });
ours.adopt_with(theirs, keep);
assert!(ours.styles.styles.iter().all(|s| !s.default), "keep_styles {keep}");
}
}
#[test]
+19
View File
@@ -448,6 +448,25 @@ fn box_para(story: u32, id: u32) -> Blocks {
vec![para_block(p)]
}
#[test]
fn adopting_relinks_lists_in_deeply_nested_tables() {
// As #1339: a list paragraph 20 tables down takes the list it is brought in with.
let mut ours = Document::from_text("ours");
let our_list = ours.numbering.add_list(numbering::ListKind::Bullet);
let mut theirs = Document::from_text("theirs");
let list = theirs.numbering.add_list(numbering::ListKind::Bullet);
assert_eq!(list, our_list);
let mut p = Paragraph::with_text("item", CharProps::default());
p.props.numbering = Some(props::NumRef { num: list, level: 0 });
theirs.body = nested_tables(20, vec![para_block(p)]);
let mut nums = Vec::new();
for b in &ours.adopt(theirs).blocks {
edit::each_para(b, 0, &mut |p| nums.extend(p.props.numbering.map(|n| n.num)));
}
assert_eq!(nums.len(), 1);
assert_ne!(nums[0], our_list);
}
#[test]
fn text_boxes_shown_from_deeply_nested_tables_are_kept() {
// #1339: the paragraph walk stopped 16 tables down, so a box shown only from deeper was taken
+6 -2
View File
@@ -62,7 +62,8 @@ impl Reader<'_> {
let ct = self.content_types.get_or_insert_with(|| ContentTypes::read(pkg)).of(&part).unwrap_or("").to_string();
let chunk = AltChunk { content_type: &ct, part: &part, bytes };
// A WordprocessingML chunk is a package; one that isn't Word's fails to read (logged).
let doc = if bytes.starts_with(b"PK\x03\x04") { self.read_nested(bytes, depth) } else { self.chunks.import.and_then(|f| f(&chunk)) };
let is_docx = bytes.starts_with(b"PK\x03\x04");
let doc = if is_docx { self.read_nested(bytes, depth) } else { self.chunks.import.and_then(|f| f(&chunk)) };
let Some(mut doc) = doc else {
log::warn!("docx: alternative format chunk {part} ({ct}) is in a format WordCraft can't bring in");
return;
@@ -76,7 +77,10 @@ impl Reader<'_> {
p.section = None;
}
}
let mut blocks = self.doc.adopt_blocks(doc, &mut self.next_perm);
// `w:matchSrc`: a Word document's content keeps its own styles (other formats' formatting
// is their own already).
let keep = is_docx && e.child("w:altChunkPr").and_then(|p| p.child("w:matchSrc")).is_some_and(crate::units::on_off);
let mut blocks = self.doc.adopt_blocks(doc, keep, &mut self.next_perm);
// Bookmarks and comment marks read before the chunk stay before it.
self.flush_pending_before(sc, out, &mut blocks);
out.extend(blocks.into_iter().map(Arc::new));
+90 -2
View File
@@ -16,18 +16,33 @@ fn p(text: &str) -> String {
/// A package whose body is `body`, with the chunk `afchunk.{ext}` (content type `ct`) as `rIdC`.
fn package(body: &str, chunk: Option<(&str, &str, &[u8])>) -> Vec<u8> {
package_styled(body, chunk, None)
}
/// [`package`] with a styles part holding `styles`.
fn package_styled(body: &str, chunk: Option<(&str, &str, &[u8])>, styles: Option<&str>) -> Vec<u8> {
let doc = format!(r#"<w:document {NS}><w:body>{body}<w:sectPr/></w:body></w:document>"#);
let mut files: Vec<(String, Vec<u8>)> = vec![("_rels/.rels".into(), ROOT_RELS.into()), ("word/document.xml".into(), doc.into_bytes())];
let mut types = String::from(
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>"#,
);
let mut rels = String::new();
if let Some((ext, ct, bytes)) = chunk {
types.push_str(&format!(r#"<Default Extension="{ext}" ContentType="{ct}"/>"#));
rels.push_str(&format!(r#"<Relationship Id="rIdC" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.{ext}"/>"#));
files.push((format!("word/afchunk.{ext}"), bytes.to_vec()));
}
if let Some(styles) = styles {
rels.push_str(
r#"<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#,
);
files.push(("word/styles.xml".into(), format!(r#"<w:styles {NS}>{styles}</w:styles>"#).into_bytes()));
}
if !rels.is_empty() {
files.push((
"word/_rels/document.xml.rels".into(),
format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdC" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.{ext}"/></Relationships>"#).into_bytes(),
format!(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{rels}</Relationships>"#).into_bytes(),
));
files.push((format!("word/afchunk.{ext}"), bytes.to_vec()));
}
types.push_str(r#"<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#);
files.push(("[Content_Types].xml".into(), types.into_bytes()));
@@ -210,6 +225,79 @@ fn a_wordprocessing_chunk_is_read_without_an_importer_and_flows_in_its_section()
assert_eq!(d.sections().len(), 1);
}
/// Styles a matchSrc chunk brings under new ids get distinct ones: with `A` and `A1` ours and
/// `A` to `A10` the chunk's, its `A` and `A1` both renamed don't land on one id (the second then
/// lost, its paragraphs taking the first's formatting), and keep their formatting through a save.
#[test]
fn match_src_gives_each_renamed_style_its_own_id() {
let style = |id: &str, half_points: u32| {
format!(r#"<w:style w:type="paragraph" w:styleId="{id}"><w:name w:val="{id}"/><w:rPr><w:sz w:val="{half_points}"/></w:rPr></w:style>"#)
};
let ours: String = ["A", "A1"].iter().map(|id| style(id, 22)).collect();
let mut theirs = style("A", 20) + &style("A1", 28);
for n in 2..=10 {
theirs += &style(&format!("A{n}"), 16);
}
let para = |id: &str, text: &str| format!(r#"<w:p><w:pPr><w:pStyle w:val="{id}"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#);
let inner = package_styled(&(para("A", "ten") + &para("A1", "fourteen")), None, Some(&theirs));
let body = format!(r#"{}<w:altChunk r:id="rIdC"><w:altChunkPr><w:matchSrc/></w:altChunkPr></w:altChunk>"#, p("Ours"));
let d = read(&package_styled(&body, Some(("docx", DOCX_MAIN, &inner)), Some(&ours))).unwrap();
let check = |d: &Document| {
let look = |text: &str| {
d.body
.iter()
.find_map(|b| match &**b {
Block::Para(p) if p.text == text => {
Some((p.props.style.clone(), d.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(0)).size))
}
_ => None,
})
.unwrap()
};
let ((ten, ten_size), (fourteen, fourteen_size)) = (look("ten"), look("fourteen"));
assert_ne!(ten, fourteen);
assert_eq!((ten_size, fourteen_size), (10.0, 14.0));
};
check(&d);
check(&read(&wordcraft_docx::write(&d).unwrap()).unwrap());
}
#[test]
fn match_src_keeps_a_word_chunks_own_formatting() {
// Both define Normal and Subtitle differently, and the chunk's defaults differ from ours.
let ours = r#"<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="200"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:pPr><w:spacing w:after="248" w:line="248" w:lineRule="exact"/></w:pPr></w:style><w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:rPr><w:i/></w:rPr></w:style>"#;
let theirs = r#"<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="24"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:basedOn w:val="Normal"/></w:style>"#;
let inner = package_styled(
&format!(r#"{}<w:p><w:pPr><w:pStyle w:val="Subtitle"/></w:pPr><w:r><w:t>Sub</w:t></w:r></w:p>"#, p("Plain")),
None,
Some(theirs),
);
for match_src in [true, false] {
let pr = if match_src { "<w:altChunkPr><w:matchSrc/></w:altChunkPr>" } else { "" };
let body = format!(r#"{}<w:altChunk r:id="rIdC">{pr}</w:altChunk>"#, p("Ours"));
let d = read(&package_styled(&body, Some(("docx", DOCX_MAIN, &inner)), Some(ours))).unwrap();
let look = |i: usize| match &*d.body[i] {
Block::Para(p) => {
let para = d.styles.resolve_para(&p.props);
let chr = d.styles.resolve_char(p.props.style.as_deref(), p.props_of_char(0));
(para.space_after, chr.size, chr.italic)
}
b => panic!("{b:?}"),
};
// Ours stays ours either way.
assert_eq!(look(0), (12.4, 11.0, false));
if match_src {
// The chunk's own Normal (its 12 pt, Word's no space after) and its Subtitle (not italic).
assert_eq!(look(1), (0.0, 12.0, false));
assert_eq!(look(2), (0.0, 12.0, false));
} else {
// Without it the chunk takes our styles (our Subtitle stands on our defaults).
assert_eq!(look(1), (12.4, 11.0, false));
assert_eq!(look(2), (10.0, 11.0, true));
}
}
}
#[test]
fn nested_wordprocessing_chunks_stop_at_a_depth() {
let mut bytes = package(&p("Deepest"), None);