f-office 0.2.1

Renders Office Open XML documents the way Microsoft Office does.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Edits of a DOCX file: a list of edits, made
//! all or none ([`apply`]), each of which names the file as it was before the list. A raw edit
//! names an element of any XML part by its path ([`XmlEdit`]); a named edit names a block of the
//! body by its address ([`NamedEdit`]), and the DOCX crate makes it into splices of the main
//! document part, and for a comment or an image also of the parts that it changes, with the
//! parts that it adds ([`f_office_docx::named_edits`]).
//!
//! An edit replaces the bytes of an element's span in its part and keeps every other byte of
//! the part ([`f_office_xml::Document::span`]), and the package writer keeps every other byte
//! of the package ([`f_office_opc::write_package`]). With the feature `json`, [`parse`] reads
//! an edit list from its JSON form.

mod image;
#[cfg(feature = "json")]
mod json;
mod path;
#[cfg(test)]
mod tests;

pub use f_office_docx::named_edits::{
    ExpectedBlocks, ImageFile, Mismatch, NamedEdit, NamedFault, Place,
};
pub use image::{ImageError, image_file};
#[cfg(feature = "json")]
pub use json::{ListContext, ListError, parse};
pub use path::{Path, PathError};

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::ops::Range;

use f_office_docx::named_edits::{self, NamedError, NewPart};
use f_office_opc::{Limits, Package, PartChange, Relationship, WriteError, write_package};
use f_office_xml::{Document, Equality, Error as XmlError, NodeId, NodeKind};

use crate::{TextBlock, Warned, Warning, Warnings};

/// One edit of an edit list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Edit {
    /// The raw edit (`xml`): replaces the XML of one element of any XML part.
    Xml(XmlEdit),
    /// A named edit of a block of the body: replace, set text, insert a paragraph, a row or an
    /// image, delete, style or comment.
    Named(NamedEdit),
}

/// What [`apply`] makes: the new file, and the text blocks that it must have.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Edited {
    /// The new DOCX file.
    pub docx: Vec<u8>,
    /// The text blocks that the new file must have, which a caller compares with those of
    /// its layout (`Document::text_blocks`): none when the list has no named edit, or a raw
    /// edit of the main document part, whose effect on the blocks the edits do not know.
    pub expected: Option<ExpectedBlocks>,
}

/// The raw edit: replaces the element at `at` of the XML part `part`, which must equal
/// `expect`, with `xml`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XmlEdit {
    /// The part's name, which may start with `/` and differ in the case of its ASCII letters
    /// from the name in the package.
    pub part: String,
    /// Where the element lies in the part.
    pub at: Path,
    /// The element as the edit expects to find it. It parses with the namespace declarations
    /// in scope at the element, and must equal the element by namespace
    /// ([`Equality::ByNamespace`]): the same names by their namespace URI, the same attributes in
    /// any order, and the same text, exactly. White space around the element, outside it, does
    /// not count.
    pub expect: String,
    /// The new XML: no node, which deletes the element, one or several. It parses with the
    /// namespace declarations in scope at the element's parent, so each prefix that it uses
    /// must be declared there or in it.
    pub xml: String,
}

/// The limits of an edit list. Start from [`EditLimits::default`] and set the limits that
/// differ, so that a new limit breaks no caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EditLimits {
    /// The largest edit list that [`parse`] reads, in bytes.
    pub max_list_bytes: usize,
    /// The most edits of one list.
    pub max_edits: usize,
    /// The largest `xml` or `expect` value of one edit, in bytes.
    pub max_xml_bytes: usize,
    /// The largest image file of an image edit, in bytes.
    pub max_image_bytes: usize,
    /// The limits of the package and of its XML parts.
    pub package: Limits,
}

impl Default for EditLimits {
    fn default() -> Self {
        Self {
            max_list_bytes: 16 << 20,
            max_edits: 10_000,
            max_xml_bytes: 4 << 20,
            max_image_bytes: 32 << 20,
            package: Limits::default(),
        }
    }
}

/// Why an edit list could not be made: the fault, with the index of the edit that has it, from
/// 0, when one edit has it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditError {
    /// The index of the edit in its list, from 0, or `None` for a fault of the whole list.
    pub edit: Option<usize>,
    /// The fault.
    pub fault: EditFault,
}

/// What is wrong with an edit list or with one edit.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EditFault {
    /// The list holds more edits than [`EditLimits::max_edits`].
    TooManyEdits {
        /// The limit.
        limit: usize,
    },
    /// The file does not open as a package.
    Package(f_office_opc::Error),
    /// An `xml` or `expect` value is larger than [`EditLimits::max_xml_bytes`].
    XmlTooLarge {
        /// The limit.
        limit: usize,
    },
    /// The package holds no part of this name.
    NoSuchPart(String),
    /// The part does not parse as XML.
    PartNotXml(XmlError),
    /// The part is not in UTF-8, so its elements have no spans; it names this encoding.
    PartNotUtf8(String),
    /// The path uses a prefix that the part's root element does not declare.
    UndeclaredPathPrefix(String),
    /// A step of the path, from 1, matches no element.
    NoElement {
        /// The step.
        step: usize,
    },
    /// A step of the path, from 1, matches more than one element and has no test.
    Ambiguous {
        /// The step.
        step: usize,
        /// The number of elements that it matches.
        count: usize,
    },
    /// The `expect` value does not parse at the element.
    ExpectNotXml(XmlError),
    /// The `expect` value holds no element, or more than one node besides white space.
    ExpectNotOneElement,
    /// The element differs from the `expect` value.
    ExpectDiffers,
    /// The `xml` value does not parse at the element's place, such as for a prefix that is
    /// declared neither there nor in it ([`XmlError::UndeclaredPrefix`]).
    XmlNotValid(XmlError),
    /// The element of this edit and the element of an earlier edit of the list overlap: one
    /// is the other, or holds it. The index of the other edit, from 0.
    Overlap {
        /// The index of the other edit.
        other: usize,
    },
    /// The part with the new XML of its edits does not parse; this edit is the first of them.
    PartBroken(XmlError),
    /// The package writer could not write the new package.
    Write(WriteError),
    /// A named edit does not fit the file.
    Named(NamedFault),
}

impl fmt::Display for EditError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.edit {
            Some(index) => write!(f, "edit {index} of the list (from 0): {}", self.fault),
            None => self.fault.fmt(f),
        }
    }
}

impl std::error::Error for EditError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.fault.source()
    }
}

impl fmt::Display for EditFault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooManyEdits { limit } => {
                write!(f, "the list holds more than {limit} edits: split it into several lists")
            }
            Self::Package(_) => f.write_str("the file does not open as a package"),
            Self::XmlTooLarge { limit } => write!(
                f,
                "an xml or expect value is larger than {limit} bytes: edit a smaller element"
            ),
            Self::NoSuchPart(name) => write!(
                f,
                "the package has no part {name}: name a part as the package names it, such as word/document.xml"
            ),
            Self::PartNotXml(_) => f.write_str("the part does not parse as XML"),
            Self::PartNotUtf8(encoding) => write!(
                f,
                "the part is in {encoding}, not in UTF-8, so a raw edit cannot change it"
            ),
            Self::UndeclaredPathPrefix(prefix) => write!(
                f,
                "the path uses the prefix {prefix}, which the part's root element does not declare: use a prefix that it declares"
            ),
            Self::NoElement { step } => write!(
                f,
                "step {step} of the path matches no element in the part"
            ),
            Self::Ambiguous { step, count } => write!(
                f,
                "step {step} of the path matches {count} elements: add [N], from 1, or [@name='value'] to the step"
            ),
            Self::ExpectNotXml(_) => f.write_str("the expect value does not parse at the element"),
            Self::ExpectNotOneElement => f.write_str(
                "the expect value must hold the one element that the path names, and nothing besides white space",
            ),
            Self::ExpectDiffers => f.write_str(
                "the element differs from the expect value: read the current XML at that path and expect that",
            ),
            Self::XmlNotValid(_) => f.write_str(
                "the xml value does not parse at the element's place: declare each prefix that it uses there or in it",
            ),
            Self::Overlap { other } => write!(
                f,
                "its element and the element of edit {other} overlap: make one edit of them"
            ),
            Self::PartBroken(_) => f.write_str("the part with the new XML does not parse"),
            Self::Write(_) => f.write_str("the new package could not be written"),
            Self::Named(fault) => fault.fmt(f),
        }
    }
}

impl std::error::Error for EditFault {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Package(error) => Some(error),
            Self::PartNotXml(error)
            | Self::ExpectNotXml(error)
            | Self::XmlNotValid(error)
            | Self::PartBroken(error) => Some(error),
            Self::Write(error) => Some(error),
            Self::Named(fault) => fault.source(),
            _ => None,
        }
    }
}

/// The relationship type, at its end, of a package's digital signature origin (ECMA-376
/// Part 2, 13.2.4).
const SIGNATURE_ORIGIN: &str = "/digital-signature/origin";

/// The folder of the parts of a package's digital signatures, which signing programs write.
const SIGNATURES_FOLDER: &str = "_xmlsignatures/";

/// Makes the edits of `edits` in the DOCX file `docx`, all or none, and gives the new file with
/// the text blocks that it must have. Each edit names the file as it was before the list. A named
/// edit names a block of `blocks`, the text blocks of the file's layout
/// ([`Document::text_blocks`](crate::Document::text_blocks)); a list of raw edits only may pass
/// none. With no edit, the new file is `docx`. The warning [`Warning::SignatureBroken`] comes when
/// an edit changes a signed package, and [`Warning::NoteKept`] when a deleted block holds the
/// reference of a footnote or an endnote.
///
/// # Errors
///
/// Returns the first fault, with the index of its edit: a list beyond [`EditLimits`], a file
/// that does not open, an edit that does not fit the file, two edits whose elements overlap,
/// or a package that the writer does not write.
pub fn apply(
    docx: &[u8],
    blocks: &[TextBlock],
    edits: &[Edit],
    limits: &EditLimits,
) -> Result<Warned<Edited>, EditError> {
    if edits.len() > limits.max_edits {
        return Err(whole(EditFault::TooManyEdits {
            limit: limits.max_edits,
        }));
    }
    let package =
        Package::open(docx, &limits.package).map_err(|error| whole(EditFault::Package(error)))?;
    let mut parts: BTreeMap<&str, Part<'_>> = BTreeMap::new();
    let mut named = Vec::new();
    for (index, edit) in edits.iter().enumerate() {
        match edit {
            Edit::Xml(edit) => add_xml(&package, (index, edit), limits, &mut parts)?,
            Edit::Named(edit) => named.push((index, edit)),
        }
    }
    let mut warnings = Warnings::new();
    let (expected, new_parts) = if named.is_empty() {
        (None, Vec::new())
    } else {
        add_named(&package, blocks, &named, limits, &mut parts, &mut warnings)?
    };
    let mut spliced = Vec::with_capacity(parts.len());
    for (name, part) in parts {
        spliced.push((name, part.spliced(limits)?));
    }
    let changes: Vec<PartChange<'_>> = spliced
        .iter()
        .map(|(name, data)| PartChange::Replace { name, data })
        .chain(new_parts.iter().map(|part| PartChange::Add {
            name: &part.name,
            data: &part.data,
        }))
        .collect();
    let bytes = write_package(docx, &changes, &limits.package)
        .map_err(|error| whole(EditFault::Write(error)))?;
    if !changes.is_empty() && signed(&package) {
        warnings.push(Warning::SignatureBroken);
    }
    Ok(Warned::new(
        Edited {
            docx: bytes,
            expected,
        },
        warnings,
    ))
}

/// Adds the replacement of the raw edit `edit`, at `index` of its list, to its part.
fn add_xml<'p>(
    package: &'p Package,
    (index, edit): (usize, &'p XmlEdit),
    limits: &EditLimits,
    parts: &mut BTreeMap<&'p str, Part<'p>>,
) -> Result<(), EditError> {
    let at_edit = |fault| EditError {
        edit: Some(index),
        fault,
    };
    let (_, part) = open_part(package, &edit.part, limits, parts).map_err(at_edit)?;
    let span = locate(part, edit, limits).map_err(at_edit)?;
    part.replacements.push(Replacement {
        span,
        edit: index,
        xml: Cow::Borrowed(&edit.xml),
    });
    Ok(())
}

/// Adds the splices of the named edits `named`, each with its index in the list, to the main
/// document part and to the other parts that they change, and gives the text blocks that the new
/// file must have, with the new parts. The blocks are none when a raw edit of the list also
/// changes the main document part, since the named edits do not know what it does to them.
fn add_named<'p>(
    package: &'p Package,
    blocks: &[TextBlock],
    named: &[(usize, &NamedEdit)],
    limits: &EditLimits,
    parts: &mut BTreeMap<&'p str, Part<'p>>,
    warnings: &mut Warnings,
) -> Result<(Option<ExpectedBlocks>, Vec<NewPart>), EditError> {
    let plan = named_edits::plan(package, blocks, named, &limits.package.xml).map_err(
        |NamedError { edit, fault }| EditError {
            edit,
            fault: EditFault::Named(fault),
        },
    )?;
    let first = named.first().map(|(index, _)| *index);
    let (_, part) = open_part(package, &plan.part, limits, parts)
        .map_err(|fault| EditError { edit: first, fault })?;
    let raw = !part.replacements.is_empty();
    part.replacements
        .extend(plan.splices.into_iter().map(|splice| Replacement {
            span: splice.range,
            edit: splice.edit,
            xml: Cow::Owned(splice.xml),
        }));
    for (name, splice) in plan.related {
        let (_, part) = open_part(package, &name, limits, parts).map_err(|fault| EditError {
            edit: Some(splice.edit),
            fault,
        })?;
        part.replacements.push(Replacement {
            span: splice.range,
            edit: splice.edit,
            xml: Cow::Owned(splice.xml),
        });
    }
    if plan.notes_kept {
        warnings.push(Warning::NoteKept);
    }
    Ok(((!raw).then_some(plan.expected), plan.new_parts))
}

/// The XML of the element at `at` of the part `part` of the DOCX file `docx`: the bytes of its
/// span, as the part holds them, which a raw edit can take as its `expect`.
///
/// # Errors
///
/// Returns the fault, with no index: a file that does not open, a part that it does not hold or
/// that is not XML in UTF-8, or a path that names no element.
pub fn element_xml(
    docx: &[u8],
    part: &str,
    at: &Path,
    limits: &EditLimits,
) -> Result<String, EditError> {
    let package =
        Package::open(docx, &limits.package).map_err(|error| whole(EditFault::Package(error)))?;
    let mut parts = BTreeMap::new();
    let (_, opened) = open_part(&package, part, limits, &mut parts).map_err(whole)?;
    let (id, _) = at.resolve(&opened.document).map_err(whole)?;
    let span = opened.span(id).map_err(whole)?;
    let bytes = opened.bytes.get(span).unwrap_or_default();
    Ok(String::from_utf8_lossy(bytes).into_owned())
}

/// An error of the whole list or call, with no index.
const fn whole(fault: EditFault) -> EditError {
    EditError { edit: None, fault }
}

/// One part that the list edits: its bytes, as parsed, and the replacements of its edits.
struct Part<'p> {
    /// The part's bytes.
    bytes: &'p [u8],
    /// The parsed part.
    document: Document,
    /// The replacements of the edits of the part, in the order of the list.
    replacements: Vec<Replacement<'p>>,
}

/// The new XML of one edit, in place of the bytes of a span: an element's span, or for a new
/// paragraph of a named edit an empty span at its place.
struct Replacement<'e> {
    /// The span that it replaces.
    span: Range<usize>,
    /// The index of its edit.
    edit: usize,
    /// The new XML: a raw edit's own, or what a named edit makes.
    xml: Cow<'e, str>,
}

/// The part `name` of `package`, parsed once for the whole list, with the name under which the
/// package holds it.
fn open_part<'p, 'm>(
    package: &'p Package,
    name: &str,
    limits: &EditLimits,
    parts: &'m mut BTreeMap<&'p str, Part<'p>>,
) -> Result<(&'p str, &'m mut Part<'p>), EditFault> {
    let held = package
        .part_name(name)
        .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
    if !parts.contains_key(held) {
        let bytes = package
            .part(held)
            .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
        let document =
            Document::parse(bytes, &limits.package.xml).map_err(EditFault::PartNotXml)?;
        let root = document.root().map_err(EditFault::PartNotXml)?;
        if let Err(XmlError::NotUtf8(encoding)) = document.span(root) {
            return Err(EditFault::PartNotUtf8(encoding));
        }
        parts.insert(
            held,
            Part {
                bytes,
                document,
                replacements: Vec::new(),
            },
        );
    }
    let part = parts
        .get_mut(held)
        .ok_or_else(|| EditFault::NoSuchPart(name.to_owned()))?;
    Ok((held, part))
}

/// The span of the element that `edit` names in `part`, after the checks of its `expect` and
/// its `xml` values.
fn locate(part: &Part<'_>, edit: &XmlEdit, limits: &EditLimits) -> Result<Range<usize>, EditFault> {
    if edit.xml.len() > limits.max_xml_bytes || edit.expect.len() > limits.max_xml_bytes {
        return Err(EditFault::XmlTooLarge {
            limit: limits.max_xml_bytes,
        });
    }
    let document = &part.document;
    let (id, parent) = edit.at.resolve(document)?;
    let xml_limits = &limits.package.xml;
    let expected = Document::parse_fragment(
        edit.expect.as_bytes(),
        &document.namespaces_in_scope(id),
        xml_limits,
    )
    .map_err(EditFault::ExpectNotXml)?;
    let found = expected.document();
    let nodes: Vec<NodeId> = expected
        .nodes()
        .iter()
        .copied()
        .filter(|&node| !matches!(found.kind(node), Some(NodeKind::Text(text)) if text.trim().is_empty()))
        .collect();
    let [node] = nodes.as_slice() else {
        return Err(EditFault::ExpectNotOneElement);
    };
    if found.element(*node).is_none() {
        return Err(EditFault::ExpectNotOneElement);
    }
    if !document.same_tree(id, (found, *node), Equality::ByNamespace) {
        return Err(EditFault::ExpectDiffers);
    }
    Document::parse_fragment(
        edit.xml.as_bytes(),
        &document.namespaces_in_scope(parent),
        xml_limits,
    )
    .map_err(EditFault::XmlNotValid)?;
    part.span(id)
}

impl Part<'_> {
    /// The span of the element `id`.
    fn span(&self, id: NodeId) -> Result<Range<usize>, EditFault> {
        self.document.span(id).map_err(|error| match error {
            XmlError::NotUtf8(encoding) => EditFault::PartNotUtf8(encoding),
            other => EditFault::PartNotXml(other),
        })
    }

    /// The part's bytes with the new XML of its edits in place of their spans, which must not
    /// overlap, and which must parse.
    fn spliced(mut self, limits: &EditLimits) -> Result<Vec<u8>, EditError> {
        // An empty span sorts before a span that starts at its place, so that a new paragraph
        // before an element stays before that element's new XML.
        self.replacements.sort_by_key(|replacement| {
            (
                replacement.span.start,
                replacement.span.end,
                replacement.edit,
            )
        });
        for pair in self.replacements.windows(2) {
            if let [before, after] = pair
                && after.span.start < before.span.end
            {
                return Err(EditError {
                    edit: Some(before.edit.max(after.edit)),
                    fault: EditFault::Overlap {
                        other: before.edit.min(after.edit),
                    },
                });
            }
        }
        let mut bytes = Vec::with_capacity(self.bytes.len());
        let mut cursor = 0;
        for replacement in &self.replacements {
            bytes.extend_from_slice(
                self.bytes
                    .get(cursor..replacement.span.start)
                    .unwrap_or_default(),
            );
            bytes.extend_from_slice(replacement.xml.as_bytes());
            cursor = replacement.span.end;
        }
        bytes.extend_from_slice(self.bytes.get(cursor..).unwrap_or_default());
        if let Err(error) = Document::parse(&bytes, &limits.package.xml) {
            let first = self
                .replacements
                .iter()
                .map(|replacement| replacement.edit)
                .min();
            return Err(EditError {
                edit: first,
                fault: EditFault::PartBroken(error),
            });
        }
        Ok(bytes)
    }
}

/// Whether the package is signed: a package relationship names a digital signature origin, or
/// a part lies in the folder of signatures.
fn signed(package: &Package) -> bool {
    let origin = package
        .relationships("")
        .is_ok_and(|part| Relationship::by_type(&part.relationships, SIGNATURE_ORIGIN).is_some());
    origin
        || package.part_names().any(|name| {
            name.get(..SIGNATURES_FOLDER.len())
                .is_some_and(|folder| folder.eq_ignore_ascii_case(SIGNATURES_FOLDER))
        })
}