Skip to main content

jubarte_opc/
settings.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Document settings an edit plan writes into `word/settings.xml`: Track
6//! Changes on or off, `updateFields` on open, and editing restrictions.
7//!
8//! Every element lands in `CT_Settings` sequence ([`SETTINGS_ORDER`](crate::settings::SETTINGS_ORDER), the
9//! schema order held by `tests/schema_consistency.rs` against
10//! `tests/data/wml_main_schema.json`), so Word reads the part back. A
11//! package without a settings part gets one, with its relationship and
12//! content type, the first time a request is applied.
13//!
14//! Entry points: [`apply_settings`](crate::settings::apply_settings) to write into an open [`PartFs`](crate::opc::PartFs) given
15//! the main part's name, and [`apply_settings_to_docx`](crate::settings::apply_settings_to_docx) for the byte-for-byte
16//! form an edit plan returns. [`SettingsRequest`](crate::settings::SettingsRequest) is what an operation
17//! builds; [`Protection`](crate::settings::Protection) and [`ProtectionEdit`](crate::settings::ProtectionEdit) cover `documentProtection`.
18
19use serde::{Deserialize, Serialize};
20
21use crate::namespaces::{M, W, W14, W15};
22use crate::opc::PartFs;
23use crate::xmllinq::{Dom, NodeId, XName};
24
25const SL: &str = "http://schemas.openxmlformats.org/schemaLibrary/2006/main";
26const SETTINGS_REL: &str =
27    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
28const SETTINGS_CT: &str =
29    "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml";
30
31/// The children of `w:settings` in `CT_Settings` sequence, as
32/// `(namespace URI, local name)`. New settings go in the position the schema
33/// expects; [`set_child`] refuses to leave an unknown name in the middle.
34pub const SETTINGS_ORDER: &[(&str, &str)] = &[
35    (W::URI, "writeProtection"),
36    (W::URI, "view"),
37    (W::URI, "zoom"),
38    (W::URI, "removePersonalInformation"),
39    (W::URI, "removeDateAndTime"),
40    (W::URI, "doNotDisplayPageBoundaries"),
41    (W::URI, "displayBackgroundShape"),
42    (W::URI, "printPostScriptOverText"),
43    (W::URI, "printFractionalCharacterWidth"),
44    (W::URI, "printFormsData"),
45    (W::URI, "embedTrueTypeFonts"),
46    (W::URI, "embedSystemFonts"),
47    (W::URI, "saveSubsetFonts"),
48    (W::URI, "saveFormsData"),
49    (W::URI, "mirrorMargins"),
50    (W::URI, "alignBordersAndEdges"),
51    (W::URI, "bordersDoNotSurroundHeader"),
52    (W::URI, "bordersDoNotSurroundFooter"),
53    (W::URI, "gutterAtTop"),
54    (W::URI, "hideSpellingErrors"),
55    (W::URI, "hideGrammaticalErrors"),
56    (W::URI, "activeWritingStyle"),
57    (W::URI, "proofState"),
58    (W::URI, "formsDesign"),
59    (W::URI, "attachedTemplate"),
60    (W::URI, "linkStyles"),
61    (W::URI, "stylePaneFormatFilter"),
62    (W::URI, "stylePaneSortMethod"),
63    (W::URI, "documentType"),
64    (W::URI, "mailMerge"),
65    (W::URI, "revisionView"),
66    (W::URI, "trackRevisions"),
67    (W::URI, "doNotTrackMoves"),
68    (W::URI, "doNotTrackFormatting"),
69    (W::URI, "documentProtection"),
70    (W::URI, "autoFormatOverride"),
71    (W::URI, "styleLockTheme"),
72    (W::URI, "styleLockQFSet"),
73    (W::URI, "defaultTabStop"),
74    (W::URI, "autoHyphenation"),
75    (W::URI, "consecutiveHyphenLimit"),
76    (W::URI, "hyphenationZone"),
77    (W::URI, "doNotHyphenateCaps"),
78    (W::URI, "showEnvelope"),
79    (W::URI, "summaryLength"),
80    (W::URI, "clickAndTypeStyle"),
81    (W::URI, "defaultTableStyle"),
82    (W::URI, "evenAndOddHeaders"),
83    (W::URI, "bookFoldRevPrinting"),
84    (W::URI, "bookFoldPrinting"),
85    (W::URI, "bookFoldPrintingSheets"),
86    (W::URI, "drawingGridHorizontalSpacing"),
87    (W::URI, "drawingGridVerticalSpacing"),
88    (W::URI, "displayHorizontalDrawingGridEvery"),
89    (W::URI, "displayVerticalDrawingGridEvery"),
90    (W::URI, "doNotUseMarginsForDrawingGridOrigin"),
91    (W::URI, "drawingGridHorizontalOrigin"),
92    (W::URI, "drawingGridVerticalOrigin"),
93    (W::URI, "doNotShadeFormData"),
94    (W::URI, "noPunctuationKerning"),
95    (W::URI, "characterSpacingControl"),
96    (W::URI, "printTwoOnOne"),
97    (W::URI, "strictFirstAndLastChars"),
98    (W::URI, "noLineBreaksAfter"),
99    (W::URI, "noLineBreaksBefore"),
100    (W::URI, "savePreviewPicture"),
101    (W::URI, "doNotValidateAgainstSchema"),
102    (W::URI, "saveInvalidXml"),
103    (W::URI, "ignoreMixedContent"),
104    (W::URI, "alwaysShowPlaceholderText"),
105    (W::URI, "doNotDemarcateInvalidXml"),
106    (W::URI, "saveXmlDataOnly"),
107    (W::URI, "useXSLTWhenSaving"),
108    (W::URI, "saveThroughXslt"),
109    (W::URI, "showXMLTags"),
110    (W::URI, "alwaysMergeEmptyNamespace"),
111    (W::URI, "updateFields"),
112    (W::URI, "hdrShapeDefaults"),
113    (W::URI, "footnotePr"),
114    (W::URI, "endnotePr"),
115    (W::URI, "compat"),
116    (W::URI, "docVars"),
117    (W::URI, "rsids"),
118    (M::URI, "mathPr"),
119    (W::URI, "uiCompat97To2003"),
120    (W::URI, "attachedSchema"),
121    (W::URI, "themeFontLang"),
122    (W::URI, "clrSchemeMapping"),
123    (W::URI, "doNotIncludeSubdocsInStats"),
124    (W::URI, "doNotAutoCompressPictures"),
125    (W::URI, "forceUpgrade"),
126    (W::URI, "captions"),
127    (W::URI, "readModeInkLockDown"),
128    (SL, "schemaLibrary"),
129    (W::URI, "shapeDefaults"),
130    (W::URI, "decimalSymbol"),
131    (W::URI, "listSeparator"),
132    (W14::URI, "docId"),
133    (W14::URI, "discardImageEditingData"),
134    (W14::URI, "defaultImageDpi"),
135    (W14::URI, "conflictMode"),
136    (W15::URI, "chartTrackingRefBased"),
137    (W15::URI, "docId"),
138];
139
140/// What `w:documentProtection` allows (`ST_DocProtect`).
141///
142/// [`Self::None`] removes the element entirely: the document is unrestricted.
143/// The other variants are the four values Word's Restrict Editing pane lets
144/// you pick (`readOnly`, `comments`, `trackedChanges`, `forms`).
145#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
146#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
147#[serde(rename_all = "camelCase")]
148pub enum ProtectionEdit {
149    /// No restriction: the element is removed.
150    None,
151    /// No changes.
152    ReadOnly,
153    /// Comments only.
154    Comments,
155    /// Every change is tracked.
156    TrackedChanges,
157    /// Filling in forms only.
158    Forms,
159}
160
161impl ProtectionEdit {
162    /// The exact `w:edit` value Word writes on the wire
163    /// (`"none"`, `"readOnly"`, `"comments"`, `"trackedChanges"`,
164    /// `"forms"`).
165    fn value(self) -> &'static str {
166        match self {
167            Self::None => "none",
168            Self::ReadOnly => "readOnly",
169            Self::Comments => "comments",
170            Self::TrackedChanges => "trackedChanges",
171            Self::Forms => "forms",
172        }
173    }
174}
175
176fn default_true() -> bool {
177    true
178}
179
180/// An editing restriction. Without a password this is what Word's
181/// Restrict Editing pane calls "No password (just this single user can
182/// remove the restriction)": the restriction is checked but any user can
183/// turn it off.
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
185#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
186#[serde(deny_unknown_fields)]
187pub struct Protection {
188    /// What the restriction allows (`ST_DocProtect`).
189    pub edit: ProtectionEdit,
190    #[serde(default = "default_true")]
191    /// `w:enforcement="1"` when true. False records the element
192    /// unenforced; Word shows it greyed out in the Restrict Editing pane.
193    pub enforcement: bool,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    /// Word's legacy password hash. Always refused: a hashed password is
196    /// never written, because the matcher has nothing to compare against.
197    pub password: Option<String>,
198}
199
200/// The settings one plan operation writes. `None` on a field leaves the
201/// existing value on the wire; `Some(true)` adds the element,
202/// `Some(false)` removes it.
203#[derive(Clone, Debug, Default, PartialEq, Eq)]
204pub struct SettingsRequest {
205    /// `w:trackRevisions`: present when true, removed when false.
206    pub track_revisions: Option<bool>,
207    /// `w:updateFields`: present when true, removed when false.
208    pub update_fields: Option<bool>,
209    /// `w:documentProtection`, replaced whole; `edit: none` removes it.
210    pub protection: Option<Protection>,
211}
212
213impl SettingsRequest {
214    /// A short human-readable description of what this request writes,
215    /// for a report line: never the password; protection prints its edit
216    /// value and whether it is enforced.
217    #[must_use]
218    pub fn describe(&self) -> String {
219        let mut parts = Vec::new();
220        if let Some(on) = self.track_revisions {
221            parts.push(format!("track_revisions={on}"));
222        }
223        if let Some(on) = self.update_fields {
224            parts.push(format!("update_fields={on}"));
225        }
226        if let Some(p) = &self.protection {
227            let enforced = if p.enforcement {
228                "enforced"
229            } else {
230                "not enforced"
231            };
232            parts.push(format!("protection={} {enforced}", p.edit.value()));
233        }
234        format!("{{settings {}}}", parts.join(" "))
235    }
236}
237
238/// The rank of `node` in [`SETTINGS_ORDER`], if it is a known child.
239fn rank(dom: &Dom, node: NodeId) -> Option<usize> {
240    let name = dom.name(node)?;
241    SETTINGS_ORDER
242        .iter()
243        .position(|&(ns, local)| name.namespace_name() == ns && name.local_name() == local)
244}
245
246/// Insert or replace `<w:local attrs/>` under `root`, ordered against the
247/// children already there by the `CT_Settings` sequence
248/// ([`SETTINGS_ORDER`]). Elements that are schema-incorrect (an unknown
249/// local, the wrong namespace) stay where their position lets them.
250pub fn set_child(dom: &mut Dom, root: NodeId, local: &str, attrs: &[(&str, &str)]) -> NodeId {
251    remove_child(dom, root, local);
252    let ours = SETTINGS_ORDER
253        .iter()
254        .position(|&(ns, l)| ns == W::URI && l == local)
255        .expect("a CT_Settings child");
256    let node = dom.new_element(W::name(local));
257    for (name, value) in attrs {
258        dom.set_attribute_value(node, &W::name(name), Some(value));
259    }
260    let next = dom
261        .elements(root, None)
262        .into_iter()
263        .find(|&child| rank(dom, child).is_some_and(|r| r > ours));
264    match next {
265        Some(next) => dom.add_before_self(next, node),
266        None => dom.add(root, node),
267    }
268    node
269}
270
271/// Remove every `<w:local>` child of `root` (none or many). No-op when the
272/// element is absent.
273pub fn remove_child(dom: &mut Dom, root: NodeId, local: &str) {
274    let name: XName = W::name(local);
275    for child in dom.elements(root, Some(&name)) {
276        dom.remove(child);
277    }
278}
279
280/// Apply `request` to the settings root.
281fn apply_to_root(dom: &mut Dom, root: NodeId, request: &SettingsRequest) {
282    for (local, on) in [
283        ("trackRevisions", request.track_revisions),
284        ("updateFields", request.update_fields),
285    ] {
286        match on {
287            Some(true) => {
288                set_child(dom, root, local, &[]);
289            }
290            Some(false) => remove_child(dom, root, local),
291            None => {}
292        }
293    }
294    if let Some(protection) = &request.protection {
295        if protection.edit == ProtectionEdit::None {
296            remove_child(dom, root, "documentProtection");
297        } else {
298            let enforcement = if protection.enforcement { "1" } else { "0" };
299            set_child(
300                dom,
301                root,
302                "documentProtection",
303                &[
304                    ("edit", protection.edit.value()),
305                    ("enforcement", enforcement),
306                ],
307            );
308        }
309    }
310}
311
312/// The main part's settings part, created with its relationship and
313/// content type when the package has none.
314fn settings_part(pkg: &mut PartFs, main: &str) -> String {
315    let existing = pkg.read_rels_for(main).and_then(|rels| {
316        rels.items
317            .iter()
318            .find(|r| r.rel_type == SETTINGS_REL && r.target_mode.as_deref() != Some("External"))
319            .map(|r| r.target.clone())
320    });
321    if let Some(target) = existing {
322        return pkg.resolve_rel_target(main, &target);
323    }
324    let part = match main.rsplit_once('/') {
325        Some((dir, _)) => format!("{dir}/settings.xml"),
326        None => "settings.xml".to_string(),
327    };
328    if pkg.part_bytes(&part).is_none() {
329        let xml = format!(
330            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
331<w:settings xmlns:w="{}"/>"#,
332            W::URI
333        );
334        pkg.set_part(&part, xml.into_bytes());
335    }
336    pkg.add_content_type_override(&format!("/{part}"), SETTINGS_CT);
337    pkg.add_document_relationship(main, SETTINGS_REL, "settings.xml");
338    part
339}
340
341/// Apply `request` into the package's settings part, creating it with its
342/// relationship and content type when the package has none.
343///
344/// # Errors
345///
346/// A message when the part the main document rels name is not a
347/// `w:settings` part (the package is corrupt or the part has been edited
348/// out of shape).
349pub fn apply_settings(
350    pkg: &mut PartFs,
351    main: &str,
352    request: &SettingsRequest,
353) -> Result<(), String> {
354    let part = settings_part(pkg, main);
355    let xml = pkg.part_string(&part).unwrap_or_default();
356    let mut dom = Dom::new();
357    let doc = dom.parse_xdocument(&xml);
358    let root = dom
359        .root(doc)
360        .filter(|&r| dom.name_is(r, &W::name("settings")))
361        .ok_or_else(|| format!("{part} is not a w:settings part"))?;
362    apply_to_root(&mut dom, root, request);
363    pkg.set_part(&part, dom.serialize_document(doc).into_bytes());
364    Ok(())
365}
366
367/// The children of `w:compat` that come before `w:doNotExpandShiftReturn`
368/// in `CT_Compat`.
369const BEFORE_SHIFT_RETURN: [&str; 10] = [
370    "useSingleBorderforContiguousCells",
371    "wpJustification",
372    "noTabHangInd",
373    "noLeading",
374    "spaceForUL",
375    "noColumnBalance",
376    "balanceSingleByteDoubleByteWidth",
377    "noExtraLineSpacing",
378    "doNotLeaveBackslashAlone",
379    "ulTrailSpace",
380];
381
382/// Word's "Don't justify lines ending in soft line break"
383/// (`w:compat/w:doNotExpandShiftReturn`, ECMA-376 17.15.3.10) turned on
384/// under the settings `root`, in schema order.
385fn do_not_expand_shift_return(dom: &mut Dom, root: NodeId) {
386    let compat = match dom.elements(root, Some(&W::name("compat"))).first() {
387        Some(&compat) => compat,
388        None => set_child(dom, root, "compat", &[]),
389    };
390    for old in dom.elements(compat, Some(&W::name("doNotExpandShiftReturn"))) {
391        dom.remove(old);
392    }
393    let node = dom.new_element(W::name("doNotExpandShiftReturn"));
394    let next = dom.elements(compat, None).into_iter().find(|&child| {
395        !dom.name(child).is_some_and(|name| {
396            name.namespace_name() == W::URI && BEFORE_SHIFT_RETURN.contains(&name.local_name())
397        })
398    });
399    match next {
400        Some(next) => dom.add_before_self(next, node),
401        None => dom.add(compat, node),
402    }
403}
404
405/// [`do_not_expand_shift_return`] on a whole package: a justified line
406/// that ends in a line break is not stretched to the margin.
407#[doc(hidden)]
408pub fn no_stretched_line_breaks(docx: &[u8]) -> Result<Vec<u8>, String> {
409    let mut pkg = PartFs::open(docx).map_err(|e| e.to_string())?;
410    let main = pkg
411        .main_document_part()
412        .ok_or("the package has no main document part")?;
413    let part = settings_part(&mut pkg, &main);
414    let xml = pkg.part_string(&part).unwrap_or_default();
415    let mut dom = Dom::new();
416    let doc = dom.parse_xdocument(&xml);
417    let root = dom
418        .root(doc)
419        .filter(|&r| dom.name_is(r, &W::name("settings")))
420        .ok_or_else(|| format!("{part} is not a w:settings part"))?;
421    do_not_expand_shift_return(&mut dom, root);
422    pkg.set_part(&part, dom.serialize_document(doc).into_bytes());
423    pkg.to_zip().map_err(|e| e.to_string())
424}
425
426/// [`apply_settings`] on a whole package.
427pub fn apply_settings_to_docx(docx: &[u8], request: &SettingsRequest) -> Result<Vec<u8>, String> {
428    let mut pkg = PartFs::open(docx).map_err(|e| e.to_string())?;
429    let main = pkg
430        .main_document_part()
431        .ok_or("the package has no main document part")?;
432    apply_settings(&mut pkg, &main, request)?;
433    pkg.to_zip().map_err(|e| e.to_string())
434}
435
436#[cfg(test)]
437#[cfg_attr(all(coverage_nightly, test), coverage(off))]
438mod tests {
439    use super::*;
440
441    fn settings(children: &str) -> (Dom, NodeId, NodeId) {
442        let mut dom = Dom::new();
443        let doc = dom.parse_xdocument(&format!(
444            r#"<w:settings xmlns:w="{}">{children}</w:settings>"#,
445            W::URI
446        ));
447        let root = dom.root(doc).unwrap();
448        (dom, doc, root)
449    }
450
451    #[test]
452    fn each_protection_is_spelled_on_the_wire_as_in_the_xml() {
453        for edit in [
454            ProtectionEdit::None,
455            ProtectionEdit::ReadOnly,
456            ProtectionEdit::Comments,
457            ProtectionEdit::TrackedChanges,
458            ProtectionEdit::Forms,
459        ] {
460            let wire = serde_json::to_string(&edit).unwrap();
461            assert_eq!(wire, format!("\"{}\"", edit.value()), "{edit:?}");
462            assert_eq!(serde_json::from_str::<ProtectionEdit>(&wire).unwrap(), edit);
463        }
464    }
465
466    #[test]
467    fn a_shift_return_flag_lands_in_compat_in_schema_order() {
468        for (compat, expected) in [
469            (
470                r#"<w:compat><w:ulTrailSpace/><w:spacingInWholePoints/><w:compatSetting w:name="x" w:uri="u" w:val="1"/></w:compat>"#,
471                r#"<w:compat><w:ulTrailSpace /><w:doNotExpandShiftReturn /><w:spacingInWholePoints /><w:compatSetting"#,
472            ),
473            (
474                r#"<w:compat><w:doNotExpandShiftReturn w:val="0"/></w:compat>"#,
475                "<w:compat><w:doNotExpandShiftReturn /></w:compat>",
476            ),
477            (
478                r#"<w:zoom w:percent="90"/><w:rsids/>"#,
479                r#"<w:zoom w:percent="90" /><w:compat><w:doNotExpandShiftReturn /></w:compat><w:rsids />"#,
480            ),
481        ] {
482            let (mut dom, doc, root) = settings(compat);
483            do_not_expand_shift_return(&mut dom, root);
484            let xml = dom.serialize_document(doc);
485            assert!(xml.contains(expected), "{xml}");
486        }
487    }
488
489    #[test]
490    fn a_child_lands_before_the_first_later_one_and_after_unknown_ones() {
491        let (mut dom, doc, root) =
492            settings(r#"<w:zoom w:percent="90"/><x:vendor xmlns:x="urn:x"/><w:compat/>"#);
493        set_child(&mut dom, root, "updateFields", &[]);
494        set_child(&mut dom, root, "trackRevisions", &[]);
495        let xml = dom.serialize_document(doc);
496        let at = |s: &str| xml.find(s).unwrap();
497        assert!(at("zoom") < at("trackRevisions"), "{xml}");
498        assert!(at("vendor") < at("trackRevisions"), "{xml}");
499        assert!(at("trackRevisions") < at("updateFields"), "{xml}");
500        assert!(at("updateFields") < at("compat"), "{xml}");
501    }
502
503    #[test]
504    fn a_child_with_no_later_one_is_appended() {
505        let (mut dom, doc, root) = settings(r#"<w:zoom w:percent="90"/>"#);
506        set_child(&mut dom, root, "updateFields", &[]);
507        let xml = dom.serialize_document(doc);
508        assert!(xml.ends_with("<w:updateFields /></w:settings>"), "{xml}");
509    }
510
511    #[test]
512    fn the_description_names_each_setting_given() {
513        let request = SettingsRequest {
514            track_revisions: Some(true),
515            update_fields: None,
516            protection: Some(Protection {
517                edit: ProtectionEdit::Forms,
518                enforcement: false,
519                password: None,
520            }),
521        };
522        assert_eq!(
523            request.describe(),
524            "{settings track_revisions=true protection=forms not enforced}"
525        );
526    }
527
528    #[test]
529    fn a_part_that_is_not_settings_is_refused() {
530        let mut pkg =
531            PartFs::open(include_bytes!("../../../tests/fixtures/split/minimal.docx")).unwrap();
532        let main = pkg.main_document_part().unwrap();
533        let part = settings_part(&mut pkg, &main);
534        pkg.set_part(&part, b"<nope/>".to_vec());
535        let e = apply_settings(&mut pkg, &main, &SettingsRequest::default()).unwrap_err();
536        assert!(e.contains("not a w:settings part"), "{e}");
537    }
538}