Skip to main content

jubarte_edit/edit/
sections.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `page_setup`: page size, orientation and margins of the last section or
6//! of every section. Each section's `w:pgSz` and `w:pgMar` are rewritten in
7//! `CT_SectPr` order, keeping what the plan does not change; a document
8//! without a final `w:sectPr` gets one, starting from Word's default Letter
9//! page with one-inch margins. The comparer records the old geometry in
10//! `w:sectPrChange`.
11//!
12//! Backs the `page_setup` plan operation: [`SectionScope`], [`PageSize`],
13//! [`Orientation`] and [`Margins`] are its `section`, `page`, `orientation`
14//! and `margins_dxa` fields.
15
16use serde::{Deserialize, Serialize};
17
18use crate::inspect::Opened;
19use crate::namespaces::W;
20use crate::xmllinq::{Dom, NodeId};
21
22use super::{EditError, EditOutcome, Transaction, err};
23
24/// Which sections a [`super::OperationKind::PageSetup`] changes.
25#[derive(
26    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
27)]
28#[serde(rename_all = "snake_case")]
29pub enum SectionScope {
30    /// The document's last section (the body's final `w:sectPr`).
31    #[default]
32    Last,
33    /// Every section: the mid-document breaks and the final one.
34    All,
35}
36
37/// A paper size, by name or in twentieths of a point.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
39#[serde(untagged)]
40pub enum PageSize {
41    /// A named paper size; the orientation orders its sides.
42    Named(Paper),
43    /// A custom size; keeps its sides unless an orientation is given.
44    Custom(CustomPage),
45}
46
47/// Named paper sizes.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
49#[serde(rename_all = "snake_case")]
50pub enum Paper {
51    /// US Letter, 8.5 x 11 inches.
52    Letter,
53    /// ISO A4, 210 x 297 mm.
54    A4,
55}
56
57/// A custom page size in twentieths of a point (1440 per inch).
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
59#[serde(deny_unknown_fields)]
60pub struct CustomPage {
61    /// Page width in twentieths of a point, 1 to 31_680 (22 inches).
62    #[schemars(range(min = 1, max = MAX_SIDE))]
63    pub width_dxa: u32,
64    /// Page height in twentieths of a point, 1 to 31_680 (22 inches).
65    #[schemars(range(min = 1, max = MAX_SIDE))]
66    pub height_dxa: u32,
67}
68
69/// Page orientation.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
71#[serde(rename_all = "snake_case")]
72pub enum Orientation {
73    /// Taller than wide.
74    Portrait,
75    /// Wider than tall (`w:orient="landscape"`).
76    Landscape,
77}
78
79/// Page margins in twentieths of a point; fields not given keep the
80/// section's. Top and bottom may be negative, as in Word: text then ignores
81/// the header or footer.
82#[derive(
83    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
84)]
85#[serde(deny_unknown_fields)]
86pub struct Margins {
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    #[schemars(range(min = -31_680, max = MAX_SIDE))]
89    /// Top margin in twentieths of a point.
90    pub top: Option<i32>,
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    #[schemars(range(min = 0, max = MAX_SIDE))]
93    /// Right margin in twentieths of a point.
94    pub right: Option<u32>,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    #[schemars(range(min = -31_680, max = MAX_SIDE))]
97    /// Bottom margin in twentieths of a point.
98    pub bottom: Option<i32>,
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    #[schemars(range(min = 0, max = MAX_SIDE))]
101    /// Left margin in twentieths of a point.
102    pub left: Option<u32>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    #[schemars(range(min = 0, max = MAX_SIDE))]
105    /// Distance from the page top to the header, in twentieths of a point.
106    pub header: Option<u32>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    #[schemars(range(min = 0, max = MAX_SIDE))]
109    /// Distance from the page bottom to the footer, in twentieths of a
110    /// point.
111    pub footer: Option<u32>,
112}
113
114/// The largest page side Word accepts: 22 inches.
115const MAX_SIDE: u32 = 31_680;
116
117/// A section's page geometry, all in twentieths of a point.
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119#[doc(hidden)]
120pub struct Geometry {
121    width: u32,
122    height: u32,
123    landscape: bool,
124    /// `paper code` of the source page, kept while the size stays.
125    keep_code: bool,
126    top: i64,
127    right: i64,
128    bottom: i64,
129    left: i64,
130    header: i64,
131    footer: i64,
132    gutter: i64,
133}
134
135impl Geometry {
136    /// Word's default section: Letter, portrait, one-inch margins.
137    const WORD_DEFAULT: Self = Self {
138        width: 12_240,
139        height: 15_840,
140        landscape: false,
141        keep_code: true,
142        top: 1440,
143        right: 1440,
144        bottom: 1440,
145        left: 1440,
146        header: 720,
147        footer: 720,
148        gutter: 0,
149    };
150
151    /// The geometry `sect` sets, Word's default for what it leaves out.
152    fn of(dom: &Dom, sect: Option<NodeId>) -> Self {
153        let mut g = Self::WORD_DEFAULT;
154        let Some(sect) = sect else { return g };
155        let read = |el: NodeId, local: &str| {
156            dom.attribute(el, &W::name(local))
157                .and_then(|v| v.trim().parse::<i64>().ok())
158        };
159        if let Some(size) = dom.element(sect, &W::name("pgSz")) {
160            let side = |v: Option<i64>| v.and_then(|v| u32::try_from(v).ok());
161            g.width = side(read(size, "w")).unwrap_or(g.width);
162            g.height = side(read(size, "h")).unwrap_or(g.height);
163            g.landscape = dom.attribute(size, &W::name("orient")) == Some("landscape");
164        }
165        if let Some(margins) = dom.element(sect, &W::name("pgMar")) {
166            for (local, slot) in [
167                ("top", &mut g.top),
168                ("right", &mut g.right),
169                ("bottom", &mut g.bottom),
170                ("left", &mut g.left),
171                ("header", &mut g.header),
172                ("footer", &mut g.footer),
173                ("gutter", &mut g.gutter),
174            ] {
175                if let Some(v) = read(margins, local) {
176                    *slot = v;
177                }
178            }
179        }
180        g
181    }
182
183    /// The geometry after the plan's changes, or why it is refused.
184    fn changed(
185        mut self,
186        page: Option<PageSize>,
187        orientation: Option<Orientation>,
188        margins: Margins,
189    ) -> Result<Self, String> {
190        let custom = matches!(page, Some(PageSize::Custom(_)));
191        if let Some(page) = page {
192            let (w, h) = match page {
193                PageSize::Named(Paper::Letter) => (12_240, 15_840),
194                PageSize::Named(Paper::A4) => (11_906, 16_838),
195                PageSize::Custom(CustomPage {
196                    width_dxa,
197                    height_dxa,
198                }) => (width_dxa, height_dxa),
199            };
200            for side in [w, h] {
201                if !(1..=MAX_SIDE).contains(&side) {
202                    return Err(format!(
203                        "page side {side} is outside 1..={MAX_SIDE} (22 inches)"
204                    ));
205                }
206            }
207            if (w, h) != (self.width, self.height) {
208                self.keep_code = false;
209            }
210            (self.width, self.height) = (w, h);
211        }
212        let landscape = match orientation {
213            Some(o) => o == Orientation::Landscape,
214            None if custom => self.width > self.height,
215            None => self.landscape,
216        };
217        if !custom || orientation.is_some() {
218            let (short, long) = (self.width.min(self.height), self.width.max(self.height));
219            (self.width, self.height) = if landscape {
220                (long, short)
221            } else {
222                (short, long)
223            };
224        }
225        self.landscape = landscape;
226        let set = |slot: &mut i64, value: Option<i64>| {
227            if let Some(value) = value {
228                *slot = value;
229            }
230        };
231        set(&mut self.top, margins.top.map(i64::from));
232        set(&mut self.right, margins.right.map(i64::from));
233        set(&mut self.bottom, margins.bottom.map(i64::from));
234        set(&mut self.left, margins.left.map(i64::from));
235        set(&mut self.header, margins.header.map(i64::from));
236        set(&mut self.footer, margins.footer.map(i64::from));
237        let limit = i64::from(MAX_SIDE);
238        for (name, value) in [
239            ("top", self.top),
240            ("bottom", self.bottom),
241            ("left", self.left),
242            ("right", self.right),
243            ("header", self.header),
244            ("footer", self.footer),
245        ] {
246            if value.abs() > limit {
247                return Err(format!(
248                    "margin {name} {value} is outside -{limit}..={limit}"
249                ));
250            }
251        }
252        if self.left + self.right + self.gutter >= i64::from(self.width) {
253            return Err(format!(
254                "left and right margins ({} + {}) leave no text width on a page {} wide",
255                self.left, self.right, self.width
256            ));
257        }
258        if self.top.abs() + self.bottom.abs() >= i64::from(self.height) {
259            return Err(format!(
260                "top and bottom margins ({} + {}) leave no text height on a page {} high",
261                self.top, self.bottom, self.height
262            ));
263        }
264        Ok(self)
265    }
266}
267
268pub(crate) use crate::ooxml::sect_rank;
269
270/// `sect`'s child `local`, created at its schema position when absent.
271fn sect_child(dom: &mut Dom, sect: NodeId, local: &str) -> NodeId {
272    if let Some(found) = dom.element(sect, &W::name(local)) {
273        return found;
274    }
275    let child = dom.new_element(W::name(local));
276    let rank = sect_rank(local);
277    let after = dom.elements(sect, None).into_iter().rev().find(|&c| {
278        dom.name(c)
279            .is_some_and(|n| n.namespace_name() == W::URI && sect_rank(n.local_name()) <= rank)
280    });
281    match after {
282        Some(after) => dom.add_after_self(after, child),
283        None => dom.add_first(sect, child),
284    }
285    child
286}
287
288/// Write `geometry` into `sect`'s `w:pgSz` and `w:pgMar`.
289pub(super) fn write_geometry(dom: &mut Dom, sect: NodeId, geometry: &Geometry) {
290    let size = sect_child(dom, sect, "pgSz");
291    dom.set_attribute_value(size, &W::w(), Some(&geometry.width.to_string()));
292    dom.set_attribute_value(size, &W::name("h"), Some(&geometry.height.to_string()));
293    dom.set_attribute_value(
294        size,
295        &W::name("orient"),
296        geometry.landscape.then_some("landscape"),
297    );
298    if !geometry.keep_code {
299        dom.set_attribute_value(size, &W::name("code"), None);
300    }
301    let margins = sect_child(dom, sect, "pgMar");
302    for (local, value) in [
303        ("top", geometry.top),
304        ("right", geometry.right),
305        ("bottom", geometry.bottom),
306        ("left", geometry.left),
307        ("header", geometry.header),
308        ("footer", geometry.footer),
309        ("gutter", geometry.gutter),
310    ] {
311        dom.set_attribute_value(margins, &W::name(local), Some(&value.to_string()));
312    }
313}
314
315/// The sections a page setup changes: `None` stands for a final section the
316/// body lacks, which apply creates.
317pub(super) type Targets = Vec<(Option<NodeId>, Geometry)>;
318
319impl Transaction<'_> {
320    /// The body's section properties in document order, the final one last
321    /// (`None` when the body has no final `w:sectPr`). Recorded old
322    /// properties inside revision marks do not count.
323    fn sections(&self) -> Vec<Option<NodeId>> {
324        let dom = &self.opened.dom;
325        let body = self.opened.body;
326        let last = dom.element(body, &W::sect_pr());
327        let mut out: Vec<Option<NodeId>> = mid_sections(dom, body).into_iter().map(Some).collect();
328        out.push(last);
329        out
330    }
331
332    /// Resolve a `page_setup`: each target section with its new geometry.
333    pub(super) fn resolve_page_setup(
334        &self,
335        scope: SectionScope,
336        page: Option<PageSize>,
337        orientation: Option<Orientation>,
338        margins: Margins,
339        outcome: &mut EditOutcome,
340    ) -> Result<Targets, (String, String)> {
341        if page.is_none() && orientation.is_none() && margins == Margins::default() {
342            return Err((
343                "INVALID_EDIT".into(),
344                "page_setup needs page, orientation or margins_dxa".into(),
345            ));
346        }
347        let mut sections = self.sections();
348        if scope == SectionScope::Last {
349            sections = sections.split_off(sections.len() - 1);
350        }
351        outcome.matches = sections.len();
352        let mut targets = Vec::new();
353        for sect in sections {
354            let geometry = Geometry::of(&self.opened.dom, sect)
355                .changed(page, orientation, margins)
356                .map_err(|m| ("INVALID_EDIT".to_string(), m))?;
357            targets.push((sect, geometry));
358        }
359        Ok(targets)
360    }
361
362    /// Apply resolved page setups; a missing final `w:sectPr` is appended to
363    /// the body.
364    pub(super) fn apply_page_setup(&mut self, targets: &Targets) {
365        for (sect, geometry) in targets {
366            let sect = match sect {
367                Some(sect) => *sect,
368                None => match self.opened.dom.element(self.opened.body, &W::sect_pr()) {
369                    Some(created) => created,
370                    None => {
371                        let created = self.opened.dom.new_element(W::sect_pr());
372                        self.opened.dom.add(self.opened.body, created);
373                        created
374                    }
375                },
376            };
377            write_geometry(&mut self.opened.dom, sect, geometry);
378        }
379    }
380}
381
382/// Mid-document `w:sectPr`s under `body`, in document order: the final one
383/// and recorded old properties inside revision marks are left out.
384fn mid_sections(dom: &Dom, body: NodeId) -> Vec<NodeId> {
385    let last = dom.element(body, &W::sect_pr());
386    dom.descendants(body, Some(&W::sect_pr()))
387        .into_iter()
388        .filter(|&s| Some(s) != last)
389        .filter(|&s| {
390            dom.ancestors(s, None).into_iter().all(|a| {
391                !dom.name(a)
392                    .is_some_and(|n| matches!(n.local_name(), "sectPrChange" | "pPrChange"))
393            })
394        })
395        .collect()
396}
397
398/// `w:pgSz` and `w:pgMar` of a section, attributes sorted, for comparison.
399fn geometry_signature(dom: &Dom, sect: NodeId) -> Vec<(String, Vec<(String, String)>)> {
400    ["pgSz", "pgMar"]
401        .iter()
402        .map(|local| {
403            let mut attrs: Vec<(String, String)> = dom
404                .element(sect, &W::name(local))
405                .map(|el| {
406                    dom.attributes(el)
407                        .into_iter()
408                        .map(|(name, value)| (name.clark(), value))
409                        .collect()
410                })
411                .unwrap_or_default();
412            attrs.sort();
413            ((*local).to_string(), attrs)
414        })
415        .collect()
416}
417
418/// The comparer records old section properties for the final section only.
419/// Give every mid-document section whose page size or margins changed a
420/// `w:sectPrChange` holding the base's properties (without header and
421/// footer references, which `CT_SectPrBase` leaves out), as Word does.
422/// Sections pair up by order: no edit adds or removes a section break.
423pub(super) fn record_mid_changes(
424    redline: &[u8],
425    base: &[u8],
426    author: &str,
427    date: &str,
428) -> Result<Vec<u8>, EditError> {
429    let open = |bytes| Opened::open(bytes).map_err(|e| err("COMPARE_FAILED", None, e.to_string()));
430    let mut red = open(redline)?;
431    let old = open(base)?;
432    let red_sections = mid_sections(&red.dom, red.body);
433    let old_sections = mid_sections(&old.dom, old.body);
434    if red_sections.len() != old_sections.len() {
435        return Ok(redline.to_vec());
436    }
437    let mut next_id = red
438        .dom
439        .descendants(red.body, None)
440        .into_iter()
441        .filter_map(|n| red.dom.attribute(n, &W::id())?.parse::<u64>().ok())
442        .max()
443        .map_or(1, |max| max + 1);
444    let mut changed = false;
445    for (&now, &was) in red_sections.iter().zip(&old_sections) {
446        if red.dom.element(now, &W::name("sectPrChange")).is_some()
447            || geometry_signature(&red.dom, now) == geometry_signature(&old.dom, was)
448        {
449            continue;
450        }
451        let record = red.dom.new_element(W::name("sectPrChange"));
452        red.dom
453            .set_attribute_value(record, &W::id(), Some(&next_id.to_string()));
454        next_id += 1;
455        red.dom
456            .set_attribute_value(record, &W::author(), Some(author));
457        red.dom.set_attribute_value(record, &W::date(), Some(date));
458        let props = red.dom.new_element(W::sect_pr());
459        for child in old.dom.elements(was, None) {
460            let skip = old.dom.name(child).is_some_and(|n| {
461                matches!(
462                    n.local_name(),
463                    "headerReference" | "footerReference" | "sectPrChange"
464                )
465            });
466            if !skip {
467                let xml = old.dom.serialize_element(child);
468                let fragment = red.dom.parse_xdocument(&format!(
469                    r#"<w:sectPr xmlns:w="{}">{xml}</w:sectPr>"#,
470                    W::URI
471                ));
472                if let Some(wrapper) = red.dom.root(fragment) {
473                    for copied in red.dom.elements(wrapper, None) {
474                        red.dom.add(props, copied);
475                    }
476                }
477            }
478        }
479        red.dom.add(record, props);
480        red.dom.add(now, record);
481        changed = true;
482    }
483    if !changed {
484        return Ok(redline.to_vec());
485    }
486    let xml = red.dom.serialize_document(red.document);
487    let main = red.main.clone();
488    red.pkg.set_part(&main, xml.into_bytes());
489    red.pkg
490        .to_zip()
491        .map_err(|e| err("PACKAGE_WRITE", None, e.to_string()))
492}
493
494/// Whether two page setups change a section in common.
495pub(super) fn targets_overlap(a: &Targets, b: &Targets) -> bool {
496    a.iter().any(|(x, _)| b.iter().any(|(y, _)| x == y))
497}
498
499#[cfg(test)]
500#[cfg_attr(all(coverage_nightly, test), coverage(off))]
501mod tests {
502    use super::*;
503
504    fn letter() -> Geometry {
505        Geometry::WORD_DEFAULT
506    }
507
508    #[test]
509    fn named_pages_follow_the_orientation() {
510        let a4 = letter()
511            .changed(
512                Some(PageSize::Named(Paper::A4)),
513                Some(Orientation::Landscape),
514                Margins::default(),
515            )
516            .unwrap();
517        assert_eq!((a4.width, a4.height, a4.landscape), (16_838, 11_906, true));
518        assert!(!a4.keep_code);
519        let turned = a4
520            .changed(
521                Some(PageSize::Named(Paper::Letter)),
522                None,
523                Margins::default(),
524            )
525            .unwrap();
526        assert_eq!(
527            (turned.width, turned.height, turned.landscape),
528            (15_840, 12_240, true)
529        );
530        let upright = turned
531            .changed(None, Some(Orientation::Portrait), Margins::default())
532            .unwrap();
533        assert_eq!(
534            (upright.width, upright.height, upright.landscape),
535            (12_240, 15_840, false)
536        );
537    }
538
539    #[test]
540    fn custom_pages_keep_their_sides_unless_an_orientation_is_given() {
541        let wide = PageSize::Custom(CustomPage {
542            width_dxa: 16_000,
543            height_dxa: 9_000,
544        });
545        let g = letter()
546            .changed(Some(wide), None, Margins::default())
547            .unwrap();
548        assert_eq!((g.width, g.height, g.landscape), (16_000, 9_000, true));
549        let g = letter()
550            .changed(Some(wide), Some(Orientation::Portrait), Margins::default())
551            .unwrap();
552        assert_eq!((g.width, g.height, g.landscape), (9_000, 16_000, false));
553    }
554
555    #[test]
556    fn margins_must_leave_text_room_and_stay_in_range() {
557        let tight = Margins {
558            left: Some(6000),
559            right: Some(6240),
560            ..Margins::default()
561        };
562        assert!(letter().changed(None, None, tight).is_err());
563        let tall = Margins {
564            top: Some(-8000),
565            bottom: Some(7840),
566            ..Margins::default()
567        };
568        assert!(letter().changed(None, None, tall).is_err());
569        let huge = Margins {
570            header: Some(40_000),
571            ..Margins::default()
572        };
573        assert!(letter().changed(None, None, huge).is_err());
574        let fine = Margins {
575            top: Some(-720),
576            ..Margins::default()
577        };
578        assert_eq!(letter().changed(None, None, fine).unwrap().top, -720);
579        let zero = PageSize::Custom(CustomPage {
580            width_dxa: 0,
581            height_dxa: 100,
582        });
583        assert!(
584            letter()
585                .changed(Some(zero), None, Margins::default())
586                .is_err()
587        );
588    }
589
590    #[test]
591    fn section_children_go_in_schema_order() {
592        let mut dom = Dom::new();
593        let doc = dom.parse_xdocument(&format!(
594            r#"<w:sectPr xmlns:w="{}"><w:headerReference/><w:cols/><w:docGrid/></w:sectPr>"#,
595            W::URI
596        ));
597        let sect = dom.root(doc).unwrap();
598        write_geometry(&mut dom, sect, &letter());
599        let names: Vec<String> = dom
600            .elements(sect, None)
601            .into_iter()
602            .map(|c| dom.name(c).unwrap().local_name().to_string())
603            .collect();
604        assert_eq!(
605            names,
606            ["headerReference", "pgSz", "pgMar", "cols", "docGrid"]
607        );
608    }
609}
610
611#[cfg(test)]
612#[cfg_attr(all(coverage_nightly, test), coverage(off))]
613mod mid_section_authored_history_boundary_tests {
614    use super::*;
615    use crate::opc::PartFs;
616    const DATE: &str = "2001-02-03T04:05:06Z";
617    fn package(revised: bool, prior: bool) -> Vec<u8> {
618        let mut pkg = PartFs::open(include_bytes!(
619            "../../../../tests/fixtures/word_probes/tokens/cell_a.docx"
620        ))
621        .unwrap();
622        pkg.set_part(
623            "word/owned-header.xml",
624            format!(
625                "<w:hdr xmlns:w='{}'><w:p><w:r><w:t>owned header</w:t></w:r></w:p></w:hdr>",
626                W::URI
627            )
628            .into_bytes(),
629        );
630        pkg.set_part(
631            "word/owned-footer.xml",
632            format!(
633                "<w:ftr xmlns:w='{}'><w:p><w:r><w:t>owned footer</w:t></w:r></w:p></w:ftr>",
634                W::URI
635            )
636            .into_bytes(),
637        );
638        pkg.add_content_type_override(
639            "/word/owned-header.xml",
640            "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
641        );
642        pkg.add_content_type_override(
643            "/word/owned-footer.xml",
644            "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
645        );
646        let header = pkg.add_document_relationship(
647            "word/document.xml",
648            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
649            "owned-header.xml",
650        );
651        let footer = pkg.add_document_relationship(
652            "word/document.xml",
653            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",
654            "owned-footer.xml",
655        );
656        let history = if prior {
657            "<w:sectPrChange w:id='45' w:author='Prior owner' w:date='2000-01-02T03:04:05Z'><w:sectPr><w:pgSz w:w='10000' w:h='14000'/></w:sectPr></w:sectPrChange>"
658        } else {
659            ""
660        };
661        let (width, height, orientation) = if revised {
662            (15840, 12240, " w:orient='landscape'")
663        } else {
664            (12240, 15840, "")
665        };
666        let xml = format!(
667            "<w:document xmlns:w='{}' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships'><w:body><w:p><w:pPr><w:sectPr><w:headerReference w:type='default' r:id='{header}'/><w:footerReference w:type='default' r:id='{footer}'/><w:pgSz w:w='{width}' w:h='{height}'{orientation}/><w:pgMar w:top='1440' w:right='1440' w:bottom='1440' w:left='1440'/>{history}</w:sectPr></w:pPr><w:bookmarkStart w:id='400' w:name='Clause'/><w:r><w:rPr><w:b/></w:rPr><w:t>owned first section</w:t></w:r><w:bookmarkEnd w:id='400'/></w:p><w:p><w:r><w:t>independent final section</w:t></w:r></w:p><w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",
668            W::URI
669        );
670        pkg.set_part("word/document.xml", xml.into_bytes());
671        pkg.to_zip().unwrap()
672    }
673    #[test]
674    fn unchanged_and_already_recorded_mid_sections_preserve_exact_package_and_attribution() {
675        let base = package(false, false);
676        for revised in [false, true] {
677            let redline = package(revised, true);
678            let out = record_mid_changes(&redline, &base, "New owner", DATE).unwrap();
679            assert_eq!(
680                out, redline,
681                "existing history must remain exact even when live geometry differs"
682            );
683            let pkg = PartFs::open(&out).unwrap();
684            let mut dom = Dom::new();
685            let document = dom.parse_xdocument(&pkg.part_string("word/document.xml").unwrap());
686            let root = dom.root(document).unwrap();
687            let records = dom.descendants(root, Some(&W::name("sectPrChange")));
688            assert_eq!(records.len(), 1);
689            assert_eq!(dom.attribute(records[0], &W::id()), Some("45"));
690            assert_eq!(dom.attribute(records[0], &W::author()), Some("Prior owner"));
691            assert_eq!(
692                dom.attribute(records[0], &W::date()),
693                Some("2000-01-02T03:04:05Z")
694            );
695        }
696        let redline = package(false, false);
697        assert_eq!(
698            record_mid_changes(&redline, &base, "New owner", DATE).unwrap(),
699            redline
700        );
701    }
702    #[test]
703    fn changed_mid_section_records_only_authored_base_properties_and_preserves_relationship_owners()
704    {
705        let base = package(false, false);
706        let redline = package(true, false);
707        let source_base = PartFs::open(&base).unwrap();
708        let source_red = PartFs::open(&redline).unwrap();
709        let out = record_mid_changes(&redline, &base, "New owner", DATE).unwrap();
710        let result = PartFs::open(&out).unwrap();
711        for part in source_red.parts() {
712            if part != "word/document.xml" {
713                assert_eq!(
714                    result.part_bytes(&part),
715                    source_red.part_bytes(&part),
716                    "independent part {part}"
717                );
718            }
719        }
720        assert_eq!(
721            result.part_bytes("word/_rels/document.xml.rels"),
722            source_red.part_bytes("word/_rels/document.xml.rels")
723        );
724        let mut dom = Dom::new();
725        let document = dom.parse_xdocument(&result.part_string("word/document.xml").unwrap());
726        let root = dom.root(document).unwrap();
727        let body = dom.element(root, &W::body()).unwrap();
728        let sections = mid_sections(&dom, body);
729        assert_eq!(sections.len(), 1);
730        let live = sections[0];
731        assert_eq!(
732            dom.elements(live, Some(&W::name("headerReference"))).len(),
733            1
734        );
735        assert_eq!(
736            dom.elements(live, Some(&W::name("footerReference"))).len(),
737            1
738        );
739        let record = dom.element(live, &W::name("sectPrChange")).unwrap();
740        assert_eq!(dom.attribute(record, &W::id()), Some("401"));
741        assert_eq!(dom.attribute(record, &W::author()), Some("New owner"));
742        assert_eq!(dom.attribute(record, &W::date()), Some(DATE));
743        let old = dom.element(record, &W::sect_pr()).unwrap();
744        assert_eq!(
745            dom.elements(old, None)
746                .iter()
747                .map(|&n| dom.name(n).unwrap())
748                .collect::<Vec<_>>(),
749            vec![W::name("pgSz"), W::name("pgMar")]
750        );
751        let mut original = Dom::new();
752        let original_doc =
753            original.parse_xdocument(&source_base.part_string("word/document.xml").unwrap());
754        let original_root = original.root(original_doc).unwrap();
755        let original_body = original.element(original_root, &W::body()).unwrap();
756        let original_section = mid_sections(&original, original_body)[0];
757        let mut expected_geometry = geometry_signature(&original, original_section);
758        // Foreign-DOM property clones carry the source prefix binding on
759        // each copied element. This lexical declaration preserves exactly
760        // the authored expanded names and every original geometry attribute.
761        for (_, attrs) in &mut expected_geometry {
762            attrs.push(("{http://www.w3.org/2000/xmlns/}w".into(), W::URI.into()));
763            attrs.sort();
764        }
765        assert_eq!(geometry_signature(&dom, old), expected_geometry);
766        let children = dom.elements(body, None);
767        assert_eq!(dom.value(children[0]), "owned first section");
768        assert_eq!(dom.value(children[1]), "independent final section");
769        assert_eq!(
770            dom.attribute(
771                dom.element(live, &W::name("pgSz")).unwrap(),
772                &W::name("orient")
773            ),
774            Some("landscape")
775        );
776        assert_eq!(
777            record_mid_changes(&out, &base, "Another owner", DATE).unwrap(),
778            out,
779            "second recording must be exact identity"
780        );
781    }
782}