Skip to main content

f_office/
edit.rs

1//! Edits of a DOCX file: a list of edits, made
2//! all or none ([`apply`]), each of which names the file as it was before the list. A raw edit
3//! names an element of any XML part by its path ([`XmlEdit`]); a named edit names a block of the
4//! body by its address ([`NamedEdit`]), and the DOCX crate makes it into splices of the main
5//! document part, and for a comment or an image also of the parts that it changes, with the
6//! parts that it adds ([`f_office_docx::named_edits`]).
7//!
8//! An edit replaces the bytes of an element's span in its part and keeps every other byte of
9//! the part ([`f_office_xml::Document::span`]), and the package writer keeps every other byte
10//! of the package ([`f_office_opc::write_package`]). With the feature `json`, [`parse`] reads
11//! an edit list from its JSON form.
12
13mod image;
14#[cfg(feature = "json")]
15mod json;
16mod path;
17#[cfg(test)]
18mod tests;
19
20pub use f_office_docx::named_edits::{
21    ExpectedBlocks, ImageFile, Mismatch, NamedEdit, NamedFault, Place,
22};
23pub use image::{ImageError, image_file};
24#[cfg(feature = "json")]
25pub use json::{ListContext, ListError, parse};
26pub use path::{Path, PathError};
27
28use std::borrow::Cow;
29use std::collections::BTreeMap;
30use std::fmt;
31use std::ops::Range;
32
33use f_office_docx::named_edits::{self, NamedError, NewPart};
34use f_office_opc::{Limits, Package, PartChange, Relationship, WriteError, write_package};
35use f_office_xml::{Document, Equality, Error as XmlError, NodeId, NodeKind};
36
37use crate::{TextBlock, Warned, Warning, Warnings};
38
39/// One edit of an edit list.
40#[derive(Clone, Debug, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Edit {
43    /// The raw edit (`xml`): replaces the XML of one element of any XML part.
44    Xml(XmlEdit),
45    /// A named edit of a block of the body: replace, set text, insert a paragraph, a row or an
46    /// image, delete, style or comment.
47    Named(NamedEdit),
48}
49
50/// What [`apply`] makes: the new file, and the text blocks that it must have.
51#[derive(Clone, Debug, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct Edited {
54    /// The new DOCX file.
55    pub docx: Vec<u8>,
56    /// The text blocks that the new file must have, which a caller compares with those of
57    /// its layout (`Document::text_blocks`): none when the list has no named edit, or a raw
58    /// edit of the main document part, whose effect on the blocks the edits do not know.
59    pub expected: Option<ExpectedBlocks>,
60}
61
62/// The raw edit: replaces the element at `at` of the XML part `part`, which must equal
63/// `expect`, with `xml`.
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct XmlEdit {
66    /// The part's name, which may start with `/` and differ in the case of its ASCII letters
67    /// from the name in the package.
68    pub part: String,
69    /// Where the element lies in the part.
70    pub at: Path,
71    /// The element as the edit expects to find it. It parses with the namespace declarations
72    /// in scope at the element, and must equal the element by namespace
73    /// ([`Equality::ByNamespace`]): the same names by their namespace URI, the same attributes in
74    /// any order, and the same text, exactly. White space around the element, outside it, does
75    /// not count.
76    pub expect: String,
77    /// The new XML: no node, which deletes the element, one or several. It parses with the
78    /// namespace declarations in scope at the element's parent, so each prefix that it uses
79    /// must be declared there or in it.
80    pub xml: String,
81}
82
83/// The limits of an edit list. Start from [`EditLimits::default`] and set the limits that
84/// differ, so that a new limit breaks no caller.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub struct EditLimits {
88    /// The largest edit list that [`parse`] reads, in bytes.
89    pub max_list_bytes: usize,
90    /// The most edits of one list.
91    pub max_edits: usize,
92    /// The largest `xml` or `expect` value of one edit, in bytes.
93    pub max_xml_bytes: usize,
94    /// The largest image file of an image edit, in bytes.
95    pub max_image_bytes: usize,
96    /// The limits of the package and of its XML parts.
97    pub package: Limits,
98}
99
100impl Default for EditLimits {
101    fn default() -> Self {
102        Self {
103            max_list_bytes: 16 << 20,
104            max_edits: 10_000,
105            max_xml_bytes: 4 << 20,
106            max_image_bytes: 32 << 20,
107            package: Limits::default(),
108        }
109    }
110}
111
112/// Why an edit list could not be made: the fault, with the index of the edit that has it, from
113/// 0, when one edit has it.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct EditError {
116    /// The index of the edit in its list, from 0, or `None` for a fault of the whole list.
117    pub edit: Option<usize>,
118    /// The fault.
119    pub fault: EditFault,
120}
121
122/// What is wrong with an edit list or with one edit.
123#[derive(Clone, Debug, PartialEq, Eq)]
124#[non_exhaustive]
125pub enum EditFault {
126    /// The list holds more edits than [`EditLimits::max_edits`].
127    TooManyEdits {
128        /// The limit.
129        limit: usize,
130    },
131    /// The file does not open as a package.
132    Package(f_office_opc::Error),
133    /// An `xml` or `expect` value is larger than [`EditLimits::max_xml_bytes`].
134    XmlTooLarge {
135        /// The limit.
136        limit: usize,
137    },
138    /// The package holds no part of this name.
139    NoSuchPart(String),
140    /// The part does not parse as XML.
141    PartNotXml(XmlError),
142    /// The part is not in UTF-8, so its elements have no spans; it names this encoding.
143    PartNotUtf8(String),
144    /// The path uses a prefix that the part's root element does not declare.
145    UndeclaredPathPrefix(String),
146    /// A step of the path, from 1, matches no element.
147    NoElement {
148        /// The step.
149        step: usize,
150    },
151    /// A step of the path, from 1, matches more than one element and has no test.
152    Ambiguous {
153        /// The step.
154        step: usize,
155        /// The number of elements that it matches.
156        count: usize,
157    },
158    /// The `expect` value does not parse at the element.
159    ExpectNotXml(XmlError),
160    /// The `expect` value holds no element, or more than one node besides white space.
161    ExpectNotOneElement,
162    /// The element differs from the `expect` value.
163    ExpectDiffers,
164    /// The `xml` value does not parse at the element's place, such as for a prefix that is
165    /// declared neither there nor in it ([`XmlError::UndeclaredPrefix`]).
166    XmlNotValid(XmlError),
167    /// The element of this edit and the element of an earlier edit of the list overlap: one
168    /// is the other, or holds it. The index of the other edit, from 0.
169    Overlap {
170        /// The index of the other edit.
171        other: usize,
172    },
173    /// The part with the new XML of its edits does not parse; this edit is the first of them.
174    PartBroken(XmlError),
175    /// The package writer could not write the new package.
176    Write(WriteError),
177    /// A named edit does not fit the file.
178    Named(NamedFault),
179}
180
181impl fmt::Display for EditError {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self.edit {
184            Some(index) => write!(f, "edit {index} of the list (from 0): {}", self.fault),
185            None => self.fault.fmt(f),
186        }
187    }
188}
189
190impl std::error::Error for EditError {
191    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
192        self.fault.source()
193    }
194}
195
196impl fmt::Display for EditFault {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            Self::TooManyEdits { limit } => {
200                write!(f, "the list holds more than {limit} edits: split it into several lists")
201            }
202            Self::Package(_) => f.write_str("the file does not open as a package"),
203            Self::XmlTooLarge { limit } => write!(
204                f,
205                "an xml or expect value is larger than {limit} bytes: edit a smaller element"
206            ),
207            Self::NoSuchPart(name) => write!(
208                f,
209                "the package has no part {name}: name a part as the package names it, such as word/document.xml"
210            ),
211            Self::PartNotXml(_) => f.write_str("the part does not parse as XML"),
212            Self::PartNotUtf8(encoding) => write!(
213                f,
214                "the part is in {encoding}, not in UTF-8, so a raw edit cannot change it"
215            ),
216            Self::UndeclaredPathPrefix(prefix) => write!(
217                f,
218                "the path uses the prefix {prefix}, which the part's root element does not declare: use a prefix that it declares"
219            ),
220            Self::NoElement { step } => write!(
221                f,
222                "step {step} of the path matches no element in the part"
223            ),
224            Self::Ambiguous { step, count } => write!(
225                f,
226                "step {step} of the path matches {count} elements: add [N], from 1, or [@name='value'] to the step"
227            ),
228            Self::ExpectNotXml(_) => f.write_str("the expect value does not parse at the element"),
229            Self::ExpectNotOneElement => f.write_str(
230                "the expect value must hold the one element that the path names, and nothing besides white space",
231            ),
232            Self::ExpectDiffers => f.write_str(
233                "the element differs from the expect value: read the current XML at that path and expect that",
234            ),
235            Self::XmlNotValid(_) => f.write_str(
236                "the xml value does not parse at the element's place: declare each prefix that it uses there or in it",
237            ),
238            Self::Overlap { other } => write!(
239                f,
240                "its element and the element of edit {other} overlap: make one edit of them"
241            ),
242            Self::PartBroken(_) => f.write_str("the part with the new XML does not parse"),
243            Self::Write(_) => f.write_str("the new package could not be written"),
244            Self::Named(fault) => fault.fmt(f),
245        }
246    }
247}
248
249impl std::error::Error for EditFault {
250    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
251        match self {
252            Self::Package(error) => Some(error),
253            Self::PartNotXml(error)
254            | Self::ExpectNotXml(error)
255            | Self::XmlNotValid(error)
256            | Self::PartBroken(error) => Some(error),
257            Self::Write(error) => Some(error),
258            Self::Named(fault) => fault.source(),
259            _ => None,
260        }
261    }
262}
263
264/// The relationship type, at its end, of a package's digital signature origin (ECMA-376
265/// Part 2, 13.2.4).
266const SIGNATURE_ORIGIN: &str = "/digital-signature/origin";
267
268/// The folder of the parts of a package's digital signatures, which signing programs write.
269const SIGNATURES_FOLDER: &str = "_xmlsignatures/";
270
271/// Makes the edits of `edits` in the DOCX file `docx`, all or none, and gives the new file with
272/// the text blocks that it must have. Each edit names the file as it was before the list. A named
273/// edit names a block of `blocks`, the text blocks of the file's layout
274/// ([`Document::text_blocks`](crate::Document::text_blocks)); a list of raw edits only may pass
275/// none. With no edit, the new file is `docx`. The warning [`Warning::SignatureBroken`] comes when
276/// an edit changes a signed package, and [`Warning::NoteKept`] when a deleted block holds the
277/// reference of a footnote or an endnote.
278///
279/// # Errors
280///
281/// Returns the first fault, with the index of its edit: a list beyond [`EditLimits`], a file
282/// that does not open, an edit that does not fit the file, two edits whose elements overlap,
283/// or a package that the writer does not write.
284pub fn apply(
285    docx: &[u8],
286    blocks: &[TextBlock],
287    edits: &[Edit],
288    limits: &EditLimits,
289) -> Result<Warned<Edited>, EditError> {
290    if edits.len() > limits.max_edits {
291        return Err(whole(EditFault::TooManyEdits {
292            limit: limits.max_edits,
293        }));
294    }
295    let package =
296        Package::open(docx, &limits.package).map_err(|error| whole(EditFault::Package(error)))?;
297    let mut parts: BTreeMap<&str, Part<'_>> = BTreeMap::new();
298    let mut named = Vec::new();
299    for (index, edit) in edits.iter().enumerate() {
300        match edit {
301            Edit::Xml(edit) => add_xml(&package, (index, edit), limits, &mut parts)?,
302            Edit::Named(edit) => named.push((index, edit)),
303        }
304    }
305    let mut warnings = Warnings::new();
306    let (expected, new_parts) = if named.is_empty() {
307        (None, Vec::new())
308    } else {
309        add_named(&package, blocks, &named, limits, &mut parts, &mut warnings)?
310    };
311    let mut spliced = Vec::with_capacity(parts.len());
312    for (name, part) in parts {
313        spliced.push((name, part.spliced(limits)?));
314    }
315    let changes: Vec<PartChange<'_>> = spliced
316        .iter()
317        .map(|(name, data)| PartChange::Replace { name, data })
318        .chain(new_parts.iter().map(|part| PartChange::Add {
319            name: &part.name,
320            data: &part.data,
321        }))
322        .collect();
323    let bytes = write_package(docx, &changes, &limits.package)
324        .map_err(|error| whole(EditFault::Write(error)))?;
325    if !changes.is_empty() && signed(&package) {
326        warnings.push(Warning::SignatureBroken);
327    }
328    Ok(Warned::new(
329        Edited {
330            docx: bytes,
331            expected,
332        },
333        warnings,
334    ))
335}
336
337/// Adds the replacement of the raw edit `edit`, at `index` of its list, to its part.
338fn add_xml<'p>(
339    package: &'p Package,
340    (index, edit): (usize, &'p XmlEdit),
341    limits: &EditLimits,
342    parts: &mut BTreeMap<&'p str, Part<'p>>,
343) -> Result<(), EditError> {
344    let at_edit = |fault| EditError {
345        edit: Some(index),
346        fault,
347    };
348    let (_, part) = open_part(package, &edit.part, limits, parts).map_err(at_edit)?;
349    let span = locate(part, edit, limits).map_err(at_edit)?;
350    part.replacements.push(Replacement {
351        span,
352        edit: index,
353        xml: Cow::Borrowed(&edit.xml),
354    });
355    Ok(())
356}
357
358/// Adds the splices of the named edits `named`, each with its index in the list, to the main
359/// document part and to the other parts that they change, and gives the text blocks that the new
360/// file must have, with the new parts. The blocks are none when a raw edit of the list also
361/// changes the main document part, since the named edits do not know what it does to them.
362fn add_named<'p>(
363    package: &'p Package,
364    blocks: &[TextBlock],
365    named: &[(usize, &NamedEdit)],
366    limits: &EditLimits,
367    parts: &mut BTreeMap<&'p str, Part<'p>>,
368    warnings: &mut Warnings,
369) -> Result<(Option<ExpectedBlocks>, Vec<NewPart>), EditError> {
370    let plan = named_edits::plan(package, blocks, named, &limits.package.xml).map_err(
371        |NamedError { edit, fault }| EditError {
372            edit,
373            fault: EditFault::Named(fault),
374        },
375    )?;
376    let first = named.first().map(|(index, _)| *index);
377    let (_, part) = open_part(package, &plan.part, limits, parts)
378        .map_err(|fault| EditError { edit: first, fault })?;
379    let raw = !part.replacements.is_empty();
380    part.replacements
381        .extend(plan.splices.into_iter().map(|splice| Replacement {
382            span: splice.range,
383            edit: splice.edit,
384            xml: Cow::Owned(splice.xml),
385        }));
386    for (name, splice) in plan.related {
387        let (_, part) = open_part(package, &name, limits, parts).map_err(|fault| EditError {
388            edit: Some(splice.edit),
389            fault,
390        })?;
391        part.replacements.push(Replacement {
392            span: splice.range,
393            edit: splice.edit,
394            xml: Cow::Owned(splice.xml),
395        });
396    }
397    if plan.notes_kept {
398        warnings.push(Warning::NoteKept);
399    }
400    Ok(((!raw).then_some(plan.expected), plan.new_parts))
401}
402
403/// The XML of the element at `at` of the part `part` of the DOCX file `docx`: the bytes of its
404/// span, as the part holds them, which a raw edit can take as its `expect`.
405///
406/// # Errors
407///
408/// Returns the fault, with no index: a file that does not open, a part that it does not hold or
409/// that is not XML in UTF-8, or a path that names no element.
410pub fn element_xml(
411    docx: &[u8],
412    part: &str,
413    at: &Path,
414    limits: &EditLimits,
415) -> Result<String, EditError> {
416    let package =
417        Package::open(docx, &limits.package).map_err(|error| whole(EditFault::Package(error)))?;
418    let mut parts = BTreeMap::new();
419    let (_, opened) = open_part(&package, part, limits, &mut parts).map_err(whole)?;
420    let (id, _) = at.resolve(&opened.document).map_err(whole)?;
421    let span = opened.span(id).map_err(whole)?;
422    let bytes = opened.bytes.get(span).unwrap_or_default();
423    Ok(String::from_utf8_lossy(bytes).into_owned())
424}
425
426/// An error of the whole list or call, with no index.
427const fn whole(fault: EditFault) -> EditError {
428    EditError { edit: None, fault }
429}
430
431/// One part that the list edits: its bytes, as parsed, and the replacements of its edits.
432struct Part<'p> {
433    /// The part's bytes.
434    bytes: &'p [u8],
435    /// The parsed part.
436    document: Document,
437    /// The replacements of the edits of the part, in the order of the list.
438    replacements: Vec<Replacement<'p>>,
439}
440
441/// The new XML of one edit, in place of the bytes of a span: an element's span, or for a new
442/// paragraph of a named edit an empty span at its place.
443struct Replacement<'e> {
444    /// The span that it replaces.
445    span: Range<usize>,
446    /// The index of its edit.
447    edit: usize,
448    /// The new XML: a raw edit's own, or what a named edit makes.
449    xml: Cow<'e, str>,
450}
451
452/// The part `name` of `package`, parsed once for the whole list, with the name under which the
453/// package holds it.
454fn open_part<'p, 'm>(
455    package: &'p Package,
456    name: &str,
457    limits: &EditLimits,
458    parts: &'m mut BTreeMap<&'p str, Part<'p>>,
459) -> Result<(&'p str, &'m mut Part<'p>), EditFault> {
460    let held = package
461        .part_name(name)
462        .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
463    if !parts.contains_key(held) {
464        let bytes = package
465            .part(held)
466            .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
467        let document =
468            Document::parse(bytes, &limits.package.xml).map_err(EditFault::PartNotXml)?;
469        let root = document.root().map_err(EditFault::PartNotXml)?;
470        if let Err(XmlError::NotUtf8(encoding)) = document.span(root) {
471            return Err(EditFault::PartNotUtf8(encoding));
472        }
473        parts.insert(
474            held,
475            Part {
476                bytes,
477                document,
478                replacements: Vec::new(),
479            },
480        );
481    }
482    let part = parts
483        .get_mut(held)
484        .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
485    Ok((held, part))
486}
487
488/// The span of the element that `edit` names in `part`, after the checks of its `expect` and
489/// its `xml` values.
490fn locate(part: &Part<'_>, edit: &XmlEdit, limits: &EditLimits) -> Result<Range<usize>, EditFault> {
491    if edit.xml.len() > limits.max_xml_bytes || edit.expect.len() > limits.max_xml_bytes {
492        return Err(EditFault::XmlTooLarge {
493            limit: limits.max_xml_bytes,
494        });
495    }
496    let document = &part.document;
497    let (id, parent) = edit.at.resolve(document)?;
498    let xml_limits = &limits.package.xml;
499    let expected = Document::parse_fragment(
500        edit.expect.as_bytes(),
501        &document.namespaces_in_scope(id),
502        xml_limits,
503    )
504    .map_err(EditFault::ExpectNotXml)?;
505    let found = expected.document();
506    let nodes: Vec<NodeId> = expected
507        .nodes()
508        .iter()
509        .copied()
510        .filter(|&node| !matches!(found.kind(node), Some(NodeKind::Text(text)) if text.trim().is_empty()))
511        .collect();
512    let [node] = nodes.as_slice() else {
513        return Err(EditFault::ExpectNotOneElement);
514    };
515    if found.element(*node).is_none() {
516        return Err(EditFault::ExpectNotOneElement);
517    }
518    if !document.same_tree(id, (found, *node), Equality::ByNamespace) {
519        return Err(EditFault::ExpectDiffers);
520    }
521    Document::parse_fragment(
522        edit.xml.as_bytes(),
523        &document.namespaces_in_scope(parent),
524        xml_limits,
525    )
526    .map_err(EditFault::XmlNotValid)?;
527    part.span(id)
528}
529
530impl Part<'_> {
531    /// The span of the element `id`.
532    fn span(&self, id: NodeId) -> Result<Range<usize>, EditFault> {
533        self.document.span(id).map_err(|error| match error {
534            XmlError::NotUtf8(encoding) => EditFault::PartNotUtf8(encoding),
535            other => EditFault::PartNotXml(other),
536        })
537    }
538
539    /// The part's bytes with the new XML of its edits in place of their spans, which must not
540    /// overlap, and which must parse.
541    fn spliced(mut self, limits: &EditLimits) -> Result<Vec<u8>, EditError> {
542        // An empty span sorts before a span that starts at its place, so that a new paragraph
543        // before an element stays before that element's new XML.
544        self.replacements.sort_by_key(|replacement| {
545            (
546                replacement.span.start,
547                replacement.span.end,
548                replacement.edit,
549            )
550        });
551        for pair in self.replacements.windows(2) {
552            if let [before, after] = pair
553                && after.span.start < before.span.end
554            {
555                return Err(EditError {
556                    edit: Some(before.edit.max(after.edit)),
557                    fault: EditFault::Overlap {
558                        other: before.edit.min(after.edit),
559                    },
560                });
561            }
562        }
563        let mut bytes = Vec::with_capacity(self.bytes.len());
564        let mut cursor = 0;
565        for replacement in &self.replacements {
566            bytes.extend_from_slice(
567                self.bytes
568                    .get(cursor..replacement.span.start)
569                    .unwrap_or_default(),
570            );
571            bytes.extend_from_slice(replacement.xml.as_bytes());
572            cursor = replacement.span.end;
573        }
574        bytes.extend_from_slice(self.bytes.get(cursor..).unwrap_or_default());
575        if let Err(error) = Document::parse(&bytes, &limits.package.xml) {
576            let first = self
577                .replacements
578                .iter()
579                .map(|replacement| replacement.edit)
580                .min();
581            return Err(EditError {
582                edit: first,
583                fault: EditFault::PartBroken(error),
584            });
585        }
586        Ok(bytes)
587    }
588}
589
590/// Whether the package is signed: a package relationship names a digital signature origin, or
591/// a part lies in the folder of signatures.
592fn signed(package: &Package) -> bool {
593    let origin = package
594        .relationships("")
595        .is_ok_and(|part| Relationship::by_type(&part.relationships, SIGNATURE_ORIGIN).is_some());
596    origin
597        || package.part_names().any(|name| {
598            name.get(..SIGNATURES_FOLDER.len())
599                .is_some_and(|folder| folder.eq_ignore_ascii_case(SIGNATURES_FOLDER))
600        })
601}