Skip to main content

f_office_docx/
named_edits.rs

1//! The named edits of a DOCX file: replace text of a paragraph, set all the text of a
2//! paragraph or a cell, insert a paragraph or an image before or after a block, insert a row
3//! before or after a row, delete a block or a row, set the style of a paragraph or a table, and
4//! add a comment to a paragraph or to text in it.
5//!
6//! Each names its block by the address of the text blocks ([`TextBlock`]) and finds the block's
7//! element by its source span, so that the walk that numbers the addresses also finds their
8//! elements. Each becomes splices of the bytes of the main document part ([`Splice`]); a
9//! comment and an image also splice the other parts that they change and add new parts
10//! ([`NewPart`]). `f_office::edit::apply` makes them with the raw edits of the same list, all
11//! or none. The plan also says what the new file's text blocks must be ([`ExpectedBlocks`]),
12//! the check after the edits.
13
14mod build;
15mod comment;
16mod expected;
17mod image;
18mod parts;
19mod rows;
20mod styles;
21#[cfg(test)]
22mod tests;
23mod text;
24
25pub use expected::{ExpectedBlocks, Mismatch};
26pub use image::ImageFile;
27
28use std::collections::HashMap;
29use std::fmt;
30use std::ops::Range;
31
32use f_office_opc::{Package, Relationship};
33use f_office_units::Length;
34use f_office_xml::{Document, Error as XmlError, Limits as XmlLimits, NodeId};
35
36use crate::body::{ParagraphIds, first_column_width};
37use crate::ns::{self, A, PIC, R, W, WP};
38use crate::reader::PartReader;
39use crate::styles::StyleKind;
40use crate::table::row_cells;
41use crate::text_blocks::{Address, AddressStep, PICTURE_MARKER, TextBlock, TextBlockKind};
42use expected::Outcome;
43use image::{Drawing, DrawingNamespaces};
44use parts::Additions;
45use styles::Styles;
46
47/// One named edit of an edit list.
48#[derive(Clone, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum NamedEdit {
51    /// Replaces the text `find`, which must occur once in the paragraph's text, with `with`.
52    /// The match may cross runs, but not a tab, a break, a field code, an object or the edge of
53    /// a hyperlink, a content control, a smart tag, a simple field or custom XML. The new text
54    /// takes the formatting of the first run of the match.
55    Replace {
56        /// The paragraph.
57        at: Address,
58        /// The text to find.
59        find: String,
60        /// The new text, without control characters.
61        with: String,
62    },
63    /// Inserts a new paragraph with `text` before or after the paragraph or the table `at`.
64    /// After a paragraph it takes the paragraph's properties without its section break, and
65    /// the style that the paragraph's style names as the next one, as Word's Enter does; the
66    /// text keeps the formatting of the paragraph's first run while the style stays the same.
67    /// Before or after a table it gets no properties. `style`, an ID or a name of a paragraph
68    /// style, wins.
69    Insert {
70        /// The paragraph or the table.
71        at: Address,
72        /// Before or after it.
73        place: Place,
74        /// The text, in which a tab (`\t`) becomes a tab and no other control character may
75        /// stand.
76        text: String,
77        /// The paragraph style, by its ID or its name.
78        style: Option<String>,
79    },
80    /// Deletes the paragraph, the table or the row `at`.
81    Delete {
82        /// The block or the row.
83        at: Address,
84    },
85    /// Sets the style of the paragraph or the table `at`, by the style's ID or its name.
86    Style {
87        /// The paragraph or the table.
88        at: Address,
89        /// The style.
90        style: String,
91    },
92    /// Sets all the text of the paragraph or the cell `at` to `text`. A paragraph keeps its
93    /// properties and gets one run in the formatting of its first run. A cell keeps its
94    /// properties and gets one paragraph with the properties of its first paragraph and one
95    /// run in the formatting of that paragraph's first run. An empty text gets no run.
96    SetText {
97        /// The paragraph or the cell.
98        at: Address,
99        /// The text, in which a tab (`\t`) becomes a tab and no other control character may
100        /// stand.
101        text: String,
102    },
103    /// Inserts a new row before or after the row `at`. It takes the row's properties, and each
104    /// new cell the properties of its cell and one paragraph with the properties of that cell's
105    /// first paragraph. A new cell continues a vertical merge that goes on past the new row,
106    /// and else takes part in none.
107    InsertRow {
108        /// The row.
109        at: Address,
110        /// Before or after it.
111        place: Place,
112        /// The texts of the first cells, at most one for each cell, each in the formatting of
113        /// the first run of its cell's first paragraph; the other cells stay empty.
114        cells: Vec<String>,
115    },
116    /// Adds a comment by `author` with `text` to the paragraph `at`: around its content, or
117    /// around the one match of `find`, which follows the rules of a replace.
118    Comment {
119        /// The paragraph.
120        at: Address,
121        /// The comment's text, in which a tab becomes a tab and no other control character
122        /// may stand.
123        text: String,
124        /// The text of the paragraph that the comment marks, or none for all of it.
125        find: Option<String>,
126        /// The comment's author, not empty.
127        author: String,
128    },
129    /// Inserts a new paragraph with one inline picture before or after the paragraph or the
130    /// table `at`, with the properties and the style that an insert gives it.
131    InsertImage {
132        /// The paragraph or the table.
133        at: Address,
134        /// Before or after it.
135        place: Place,
136        /// The image.
137        image: ImageFile,
138        /// The text that describes the image, not empty.
139        alt: String,
140        /// The width and the height of the drawing: both as given; one as given, with the
141        /// other in the image's aspect; or neither, for the image's own size, made smaller in
142        /// its aspect to the width of the first text column of the block's section when it is
143        /// wider.
144        size: (Option<Length>, Option<Length>),
145    },
146}
147
148impl NamedEdit {
149    /// The address that the edit names.
150    #[must_use]
151    pub const fn at(&self) -> &Address {
152        match self {
153            Self::Replace { at, .. }
154            | Self::Insert { at, .. }
155            | Self::Delete { at }
156            | Self::Style { at, .. }
157            | Self::SetText { at, .. }
158            | Self::InsertRow { at, .. }
159            | Self::Comment { at, .. }
160            | Self::InsertImage { at, .. } => at,
161        }
162    }
163}
164
165/// Where an insert puts its paragraph.
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub enum Place {
168    /// Before the block.
169    Before,
170    /// After the block.
171    After,
172}
173
174/// New bytes in place of a range of a part's bytes.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Splice {
177    /// The index of the edit in its list, from 0.
178    pub edit: usize,
179    /// The range of the part's bytes that the new bytes replace; empty for an insert.
180    pub range: Range<usize>,
181    /// The new XML.
182    pub xml: String,
183}
184
185/// A new part of the package.
186#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct NewPart {
188    /// The index of the edit in its list, from 0, that first needs it.
189    pub edit: usize,
190    /// The part's name.
191    pub name: String,
192    /// The part's bytes.
193    pub data: Vec<u8>,
194}
195
196/// What the named edits of a list make.
197#[derive(Clone, Debug, PartialEq, Eq)]
198#[non_exhaustive]
199pub struct NamedPlan {
200    /// The name of the main document part, which the splices change.
201    pub part: String,
202    /// The splices, in the order of the edits.
203    pub splices: Vec<Splice>,
204    /// The splices of the other parts that comments and images change, each with its part's
205    /// name: the relationships of the main document part, the content types and the comments
206    /// part.
207    pub related: Vec<(String, Splice)>,
208    /// The new parts: the picture files, and a comments part or a relationships part that the
209    /// package does not have.
210    pub new_parts: Vec<NewPart>,
211    /// Whether a deleted block or row holds the reference of a footnote or an endnote, whose
212    /// note stays in its part.
213    pub notes_kept: bool,
214    /// The text blocks that the new file must have.
215    pub expected: ExpectedBlocks,
216}
217
218/// Why the named edits of a list could not be made: the fault, with the index of the edit that
219/// has it, from 0, when one edit has it.
220#[derive(Clone, Debug, PartialEq, Eq)]
221pub struct NamedError {
222    /// The index of the edit, or none for a fault of the whole file.
223    pub edit: Option<usize>,
224    /// The fault.
225    pub fault: NamedFault,
226}
227
228/// What is wrong with a named edit, or with the file for all of them. Each message names the
229/// fix.
230#[derive(Clone, Debug, PartialEq, Eq)]
231#[non_exhaustive]
232pub enum NamedFault {
233    /// The package has no main document part, or it does not parse.
234    MainPart(String),
235    /// The main document part holds tracked changes, which a named edit does not make.
236    TrackedChanges,
237    /// The file has no block or row at the address.
238    NoBlock(Address),
239    /// The address names an element of a header, a footer, a note or a text box, which a
240    /// named edit does not change.
241    OutsideBody(Address),
242    /// The block at the address is of a kind that the edit does not take.
243    WrongKind {
244        /// The address.
245        at: Address,
246        /// What the edit needs.
247        needs: &'static str,
248    },
249    /// The block was not read from an element of the main document part: F-Office made it, or
250    /// the blocks are of another file.
251    NoElement(Address),
252    /// The part declares no prefix for WordprocessingML, so the edit cannot name its elements.
253    NoPrefix,
254    /// The text of a replace is empty.
255    EmptyFind,
256    /// The paragraph's text does not hold the text of a replace.
257    TextNotFound,
258    /// The paragraph's text outside its equations does not hold the text of a replace. The
259    /// paragraph holds an equation, whose text its text block shows and a replace does not
260    /// change.
261    TextNotFoundOutsideEquations,
262    /// The paragraph's text holds the text of a replace more than once.
263    TextAmbiguous {
264        /// How often it occurs.
265        count: usize,
266    },
267    /// The match of a replace crosses an element that has no text of its own, such as `w:tab`.
268    MatchCrossesElement {
269        /// The element's name, such as `w:tab`.
270        element: &'static str,
271    },
272    /// The match of a replace crosses the edge of an element that holds runs, such as
273    /// `w:hyperlink`.
274    MatchCrossesEdge {
275        /// The element's name, such as `w:hyperlink`.
276        element: &'static str,
277    },
278    /// Two replaces of one paragraph match overlapping text. The index of the other edit.
279    MatchesOverlap {
280        /// The index of the other edit, from 0.
281        other: usize,
282    },
283    /// The new text holds a character that the edit cannot write.
284    BadCharacter(char),
285    /// The paragraph ends a section: its properties hold a `w:sectPr`.
286    SectionBreak,
287    /// The delete would leave a cell or the body without a paragraph at its end, also counting
288    /// the blocks that earlier deletes of the list take away.
289    NeedsParagraph,
290    /// The row is the last row of its table that earlier deletes of the list leave.
291    LastRow,
292    /// The block holds one end of a range whose other end lies outside it.
293    RangeEnd {
294        /// The element at the end, such as `w:bookmarkStart`.
295        element: &'static str,
296    },
297    /// The styles part has no style of this ID or name and kind.
298    NoSuchStyle {
299        /// The style that the edit gives.
300        style: String,
301        /// Its kind.
302        kind: &'static str,
303        /// The IDs of the styles of the kind whose ID holds the given text in any case, for
304        /// the message.
305        near: Vec<String>,
306    },
307    /// The new XML of an edit does not parse at its place, such as for a prefix that the
308    /// copied properties use and that is declared on the block itself.
309    NewXml(XmlError),
310    /// The row holds a cell inside a content control, custom XML or alternate content, which
311    /// a new row does not copy.
312    WrappedCells,
313    /// A new row gets more texts than its row has cells.
314    TooManyCells {
315        /// The number of texts.
316        given: usize,
317        /// The number of cells.
318        cells: usize,
319    },
320    /// A new cell that continues a vertical merge gets a text, which stands in the merge's
321    /// first cell.
322    MergedCellText {
323        /// The cell's number, from 1.
324        cell: usize,
325    },
326    /// The comment has no author.
327    EmptyAuthor,
328    /// The image has no text that describes it.
329    EmptyAlt,
330    /// The width or the height of the image's drawing is not more than zero, or lies beyond
331    /// the largest length of a file.
332    ImageSize,
333    /// The file uses the largest ID of this kind, such as `comment`.
334    NoFreeId(&'static str),
335    /// A part besides the main document part that the edit changes does not read.
336    Part {
337        /// The part's name.
338        part: String,
339        /// Why it does not read.
340        why: String,
341    },
342}
343
344impl fmt::Display for NamedFault {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        match self {
347            Self::MainPart(why) => write!(f, "the main document part does not read: {why}"),
348            Self::TrackedChanges => f.write_str(
349                "the main document holds tracked changes, which a named edit does not make: accept or reject them in Word, or use a raw edit",
350            ),
351            Self::NoBlock(at) => write!(
352                f,
353                "the file has no block at {at}"
354            ),
355            Self::OutsideBody(at) => write!(
356                f,
357                "{at} lies in a header, a footer, a note or a text box, which a named edit does not change: use a raw edit"
358            ),
359            Self::WrongKind { at, needs } => write!(f, "the edit needs {needs}, and {at} is not one"),
360            Self::NoElement(at) => write!(
361                f,
362                "the block at {at} has no element in the main document part: use a raw edit"
363            ),
364            Self::NoPrefix => f.write_str(
365                "the main document part declares no prefix for WordprocessingML: use a raw edit",
366            ),
367            Self::EmptyFind => f.write_str("the find value is empty: give the text to replace"),
368            Self::TextNotFound => f.write_str(
369                "the paragraph's text does not hold the find value",
370            ),
371            Self::TextNotFoundOutsideEquations => f.write_str(
372                "the paragraph's text outside its equations does not hold the find value; a replace does not change equation text: change an equation with a raw edit (\"op\": \"xml\")",
373            ),
374            Self::TextAmbiguous { count } => write!(
375                f,
376                "the find value occurs {count} times in the paragraph: make it longer, so that it occurs once"
377            ),
378            Self::MatchCrossesElement { element } => write!(
379                f,
380                "the match crosses a {element} element, which has no text to replace: make the find value smaller, or use a raw edit"
381            ),
382            Self::MatchCrossesEdge { element } => write!(
383                f,
384                "the match crosses the edge of a {element} element: make the find value smaller, or use a raw edit"
385            ),
386            Self::MatchesOverlap { other } => write!(
387                f,
388                "its match overlaps the match of edit {other} in the same paragraph: make one replace of them"
389            ),
390            Self::BadCharacter(character) => write!(
391                f,
392                "the text holds U+{:04X}, which this edit cannot write: remove it, or use a raw edit",
393                u32::from(*character)
394            ),
395            Self::SectionBreak => f.write_str(
396                "the paragraph ends a section (its w:pPr holds w:sectPr): use a raw edit",
397            ),
398            Self::NeedsParagraph => f.write_str(
399                "a cell and the body must end with a paragraph, and the delete leaves none at the end: delete less, or insert a paragraph first",
400            ),
401            Self::LastRow => f.write_str(
402                "the row is the last row of its table that the edits keep: delete the table",
403            ),
404            Self::RangeEnd { element } => write!(
405                f,
406                "the block holds a {element} whose other end lies outside it: delete the range too, or use a raw edit"
407            ),
408            Self::NoSuchStyle { style, kind, near } => write!(
409                f,
410                "the file has no {kind} style with the ID or the name {style}: give one of {}",
411                if near.is_empty() {
412                    "the styles of word/styles.xml".to_owned()
413                } else {
414                    near.join(", ")
415                }
416            ),
417            Self::NewXml(_) => f.write_str(
418                "the new XML does not parse at its place, because the copied properties use a prefix that the block itself declares: use a raw edit",
419            ),
420            Self::WrappedCells => f.write_str(
421                "the row holds a cell inside a content control, custom XML or alternate content, which a new row does not copy: use a raw edit",
422            ),
423            Self::TooManyCells { given, cells } => write!(
424                f,
425                "the edit gives {given} cell texts, and the row has {cells} cells: give at most one text for each cell"
426            ),
427            Self::MergedCellText { cell } => write!(
428                f,
429                "cell {cell} of the new row continues a vertical merge, whose text stands in the merge's first cell: give an empty text for it"
430            ),
431            Self::EmptyAuthor => f.write_str(
432                "a comment needs an author: supply a default author or an \"author\" field in the edit",
433            ),
434            Self::EmptyAlt => f.write_str(
435                "an image needs a text that describes it: give an \"alt\" field that is not empty",
436            ),
437            Self::ImageSize => f.write_str(
438                "the width or the height of the image's drawing is not more than zero, or too large for a file: give another \"width\" or \"height\"",
439            ),
440            Self::NoFreeId(kind) => write!(f, "the file uses the largest {kind} ID: use a raw edit"),
441            Self::Part { part, why } => write!(f, "the part {part} does not read: {why}"),
442        }
443    }
444}
445
446impl std::error::Error for NamedFault {
447    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
448        match self {
449            Self::NewXml(error) => Some(error),
450            _ => None,
451        }
452    }
453}
454
455/// The elements of tracked changes in WordprocessingML (ECMA-376 Part 1, 17.13.5).
456const TRACKED: [&str; 20] = [
457    "ins",
458    "del",
459    "moveFrom",
460    "moveTo",
461    "moveFromRangeStart",
462    "moveToRangeStart",
463    "pPrChange",
464    "rPrChange",
465    "sectPrChange",
466    "tblPrChange",
467    "tblPrExChange",
468    "trPrChange",
469    "tcPrChange",
470    "tblGridChange",
471    "numberingChange",
472    "cellIns",
473    "cellDel",
474    "cellMerge",
475    "customXmlInsRangeStart",
476    "customXmlDelRangeStart",
477];
478
479/// Plans the named edits `edits`, each with its index in its list, on the DOCX package
480/// `package`, whose text blocks are `blocks` (the [`TextBlock`]s of a layout of it).
481///
482/// # Errors
483///
484/// Returns the first fault, with the index of its edit.
485pub fn plan(
486    package: &Package,
487    blocks: &[TextBlock],
488    edits: &[(usize, &NamedEdit)],
489    limits: &XmlLimits,
490) -> Result<NamedPlan, NamedError> {
491    let whole = |fault| NamedError { edit: None, fault };
492    let name = package
493        .main_document()
494        .map_err(|error| whole(NamedFault::MainPart(error.to_string())))?;
495    let bytes = package.part(&name).ok_or_else(|| {
496        whole(NamedFault::MainPart(format!(
497            "the package has no part {name}"
498        )))
499    })?;
500    let doc = Document::parse_with_aliases(bytes, limits, ns::STRICT_ALIASES)
501        .map_err(|error| whole(NamedFault::MainPart(error.to_string())))?;
502    let first = edits.first().map(|(index, _)| *index);
503    if holds_tracked_changes(&doc) {
504        return Err(NamedError {
505            edit: first,
506            fault: NamedFault::TrackedChanges,
507        });
508    }
509    let styles = Styles::of(package, &name, limits);
510    let main = Main::new(bytes, &doc, blocks);
511    let ids = ParagraphIds::default();
512    let mut planner = Planner {
513        main: &main,
514        styles: &styles,
515        reader: PartReader::of_part(&doc, &name, &ids),
516        additions: Additions::new(package, &name, limits),
517        splices: Vec::new(),
518        replaces: Vec::new(),
519        inserts: Vec::new(),
520        points: Vec::new(),
521        outcomes: Vec::new(),
522        notes_kept: false,
523        deleted: Vec::new(),
524    };
525    for &(index, edit) in edits {
526        planner.add(index, edit).map_err(|fault| NamedError {
527            edit: Some(index),
528            fault,
529        })?;
530    }
531    planner.finish(name.clone(), blocks)
532}
533
534/// Whether the part holds an element of a tracked change.
535fn holds_tracked_changes(doc: &Document) -> bool {
536    let Ok(root) = doc.root() else {
537        return false;
538    };
539    let mut stack = vec![root];
540    while let Some(node) = stack.pop() {
541        if TRACKED.iter().any(|local| doc.is(node, W, local)) {
542            return true;
543        }
544        stack.extend(doc.child_elements(node));
545    }
546    false
547}
548
549/// The main document part: its bytes, its tree, the elements by the start of their spans, and
550/// the text blocks by their addresses.
551struct Main<'m> {
552    /// The part's bytes.
553    bytes: &'m [u8],
554    /// The parsed part, with the namespaces of Strict read as those of Transitional.
555    doc: &'m Document,
556    /// Each element by the start of its span.
557    elements: HashMap<usize, NodeId>,
558    /// Each text block by its address.
559    blocks: HashMap<&'m Address, &'m TextBlock>,
560    /// The parent of each element.
561    parents: HashMap<NodeId, NodeId>,
562}
563
564/// The element that an address names.
565#[derive(Clone, Copy)]
566enum Target {
567    /// A paragraph (`w:p`).
568    Paragraph(NodeId),
569    /// A table (`w:tbl`).
570    Table(NodeId),
571    /// A row (`w:tr`) of a table of this many rows.
572    Row {
573        /// The row.
574        node: NodeId,
575        /// The number of rows of its table.
576        rows: usize,
577    },
578}
579
580impl<'m> Main<'m> {
581    fn new(bytes: &'m [u8], doc: &'m Document, blocks: &'m [TextBlock]) -> Self {
582        let mut elements = HashMap::new();
583        let mut parents = HashMap::new();
584        if let Ok(root) = doc.root() {
585            let mut stack = vec![root];
586            while let Some(node) = stack.pop() {
587                if let Ok(span) = doc.span(node) {
588                    elements.insert(span.start, node);
589                }
590                for child in doc.child_elements(node) {
591                    parents.insert(child, node);
592                    stack.push(child);
593                }
594            }
595        }
596        Self {
597            bytes,
598            doc,
599            elements,
600            blocks: blocks.iter().map(|block| (&block.address, block)).collect(),
601            parents,
602        }
603    }
604
605    /// The parent of the element `node`.
606    fn parent(&self, node: NodeId) -> Option<NodeId> {
607        self.parents.get(&node).copied()
608    }
609
610    /// The part's bytes in `range`, as text.
611    fn text(&self, range: Range<usize>) -> String {
612        String::from_utf8_lossy(self.bytes.get(range).unwrap_or_default()).into_owned()
613    }
614
615    /// The element whose span is `range` and whose name is `local`.
616    fn element(
617        &self,
618        range: Option<&Range<usize>>,
619        local: &str,
620        at: &Address,
621    ) -> Result<NodeId, NamedFault> {
622        let range = range.ok_or_else(|| NamedFault::NoElement(at.clone()))?;
623        self.elements
624            .get(&range.start)
625            .copied()
626            .filter(|&node| {
627                self.doc.span(node).is_ok_and(|span| span == *range) && self.doc.is(node, W, local)
628            })
629            .ok_or_else(|| NamedFault::NoElement(at.clone()))
630    }
631
632    /// The element at `at`.
633    fn target(&self, at: &Address) -> Result<Target, NamedFault> {
634        if let Some(table) = at.table_of_row() {
635            let block = self
636                .blocks
637                .get(&table)
638                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
639            let (Some(AddressStep::Row(number)), TextBlockKind::Table { rows }) =
640                (at.steps().last(), &block.kind)
641            else {
642                return Err(NamedFault::NoBlock(at.clone()));
643            };
644            let range = block
645                .row_sources
646                .get(number.get() - 1)
647                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
648            let node = self.element(range.as_ref(), "tr", at)?;
649            return Ok(Target::Row { node, rows: *rows });
650        }
651        let block = self
652            .blocks
653            .get(at)
654            .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
655        Ok(match block.kind {
656            TextBlockKind::Paragraph { .. } => {
657                Target::Paragraph(self.element(block.source.as_ref(), "p", at)?)
658            }
659            TextBlockKind::Table { .. } => {
660                Target::Table(self.element(block.source.as_ref(), "tbl", at)?)
661            }
662        })
663    }
664
665    /// The bytes of the span of `node`.
666    fn span(&self, node: NodeId) -> Range<usize> {
667        self.doc.span(node).unwrap_or(0..0)
668    }
669
670    /// The section break (`w:sectPr`) of the section that holds the block `node`: the first
671    /// one of the body at or after the block, in the properties of a paragraph outside a table
672    /// or at the end of the body.
673    fn section_of(&self, node: NodeId) -> Option<NodeId> {
674        let start = self.span(node).start;
675        let in_cell = |mut current: NodeId| {
676            while let Some(parent) = self.parent(current) {
677                if self.doc.is(parent, W, "tc") {
678                    return true;
679                }
680                current = parent;
681            }
682            false
683        };
684        self.elements
685            .values()
686            .copied()
687            .filter(|&section| self.doc.is(section, W, "sectPr"))
688            .filter(|&section| {
689                self.parent(section).is_some_and(|parent| {
690                    self.doc.is(parent, W, "body")
691                        || (self.doc.is(parent, W, "pPr")
692                            && self.parent(parent).is_some_and(|p| self.doc.is(p, W, "p")))
693                })
694            })
695            .filter(|&section| !in_cell(section))
696            .map(|section| (self.span(section).start, section))
697            .filter(|(at, _)| *at >= start)
698            .min_by_key(|(at, _)| *at)
699            .map(|(_, section)| section)
700    }
701}
702
703/// The plan of a list's named edits as it grows.
704struct Planner<'p, 'm> {
705    main: &'p Main<'m>,
706    styles: &'p Styles,
707    /// The reader of the main document part, for its rows and its sections.
708    reader: PartReader<'p>,
709    /// What comments and images add to the other parts.
710    additions: Additions<'p>,
711    splices: Vec<Splice>,
712    /// The replaces of each paragraph, in the order of the list, by the paragraph.
713    replaces: Vec<(NodeId, Vec<Replace<'p>>)>,
714    /// The new paragraphs and rows.
715    inserts: Vec<NewBlock>,
716    /// The new XML at points inside elements.
717    points: Vec<PointInsert>,
718    outcomes: Vec<Outcome>,
719    notes_kept: bool,
720    /// The addresses of the blocks and rows that the list's deletes take away so far, against
721    /// which each later delete checks what its cell, body or table keeps.
722    deleted: Vec<Address>,
723}
724
725impl<'p> Planner<'p, '_> {
726    /// Adds the edit `edit` of index `index`.
727    fn add(&mut self, index: usize, edit: &'p NamedEdit) -> Result<(), NamedFault> {
728        if !edit.at().in_body() {
729            return Err(NamedFault::OutsideBody(edit.at().clone()));
730        }
731        match edit {
732            NamedEdit::Replace { at, find, with } => self.replace(index, at, find, with),
733            NamedEdit::Insert {
734                at,
735                place,
736                text,
737                style,
738            } => self.insert(index, at, *place, text, style.as_deref()),
739            NamedEdit::Delete { at } => self.delete(index, at),
740            NamedEdit::Style { at, style } => self.style(index, at, style),
741            NamedEdit::SetText { at, text } => self.set_text(index, at, text),
742            NamedEdit::InsertRow { at, place, cells } => self.insert_row(index, at, *place, cells),
743            NamedEdit::Comment {
744                at,
745                text,
746                find,
747                author,
748            } => self.comment(index, at, text, find.as_deref(), author),
749            NamedEdit::InsertImage {
750                at,
751                place,
752                image,
753                alt,
754                size,
755            } => self.insert_image(index, (at, *place), image, alt, *size),
756        }
757    }
758
759    fn replace(
760        &mut self,
761        index: usize,
762        at: &Address,
763        find: &'p str,
764        with: &'p str,
765    ) -> Result<(), NamedFault> {
766        if find.is_empty() {
767            return Err(NamedFault::EmptyFind);
768        }
769        text::check_characters(with, false)?;
770        let Target::Paragraph(node) = self.main.target(at)? else {
771            return Err(wrong(at, "a paragraph"));
772        };
773        match self
774            .replaces
775            .iter_mut()
776            .find(|(paragraph, _)| *paragraph == node)
777        {
778            Some((_, list)) => list.push((index, find, with)),
779            None => self.replaces.push((node, vec![(index, find, with)])),
780        }
781        self.outcomes.push(Outcome::Replace {
782            at: at.clone(),
783            find: find.to_owned(),
784            with: with.to_owned(),
785        });
786        Ok(())
787    }
788
789    fn insert(
790        &mut self,
791        index: usize,
792        at: &Address,
793        place: Place,
794        text: &str,
795        style: Option<&str>,
796    ) -> Result<(), NamedFault> {
797        text::check_characters(text, true)?;
798        let (node, anchor) = match self.main.target(at)? {
799            Target::Paragraph(node) => (node, Some(node)),
800            Target::Table(node) => (node, None),
801            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
802        };
803        let given = style
804            .map(|style| self.styles.resolve(style, StyleKind::Paragraph))
805            .transpose()?;
806        let built = build::paragraph(
807            self.main,
808            self.styles,
809            (node, anchor.is_some()),
810            given,
811            &|w| build::run_text(w, text),
812        )?;
813        self.insert_block(index, (node, place), built.xml)?;
814        self.outcomes.push(Outcome::Insert {
815            at: at.clone(),
816            place,
817            text: text.to_owned(),
818            style: built.style,
819        });
820        Ok(())
821    }
822
823    fn delete(&mut self, index: usize, at: &Address) -> Result<(), NamedFault> {
824        let node = match self.main.target(at)? {
825            Target::Paragraph(node) => {
826                if build::ends_section(self.main.doc, node) {
827                    return Err(NamedFault::SectionBreak);
828                }
829                self.keeps_last_paragraph(at)?;
830                node
831            }
832            Target::Table(node) => {
833                self.keeps_last_paragraph(at)?;
834                node
835            }
836            Target::Row { node, rows } => {
837                let table = at.table_of_row();
838                let gone = self
839                    .deleted
840                    .iter()
841                    .filter(|row| row.table_of_row() == table)
842                    .count();
843                if rows <= gone + 1 {
844                    return Err(NamedFault::LastRow);
845                }
846                node
847            }
848        };
849        if let Some(element) = build::open_range(self.main.doc, node) {
850            return Err(NamedFault::RangeEnd { element });
851        }
852        self.notes_kept |= build::holds_note_reference(self.main.doc, node);
853        self.splices.push(Splice {
854            edit: index,
855            range: self.main.span(node),
856            xml: String::new(),
857        });
858        self.outcomes.push(Outcome::Delete { at: at.clone() });
859        self.deleted.push(at.clone());
860        Ok(())
861    }
862
863    /// Checks that the cell or the body of the block `at` still ends with a paragraph when the
864    /// block goes, after the blocks that earlier deletes of the list take away.
865    fn keeps_last_paragraph(&self, at: &Address) -> Result<(), NamedFault> {
866        let container = at.container();
867        let mut siblings: Vec<&TextBlock> = self
868            .main
869            .blocks
870            .values()
871            .filter(|block| {
872                block.address.steps().len() == at.steps().len()
873                    && block.address.container() == container
874                    && block.address != *at
875                    && !self.deleted.contains(&block.address)
876            })
877            .copied()
878            .collect();
879        siblings.sort_by_key(|block| block.source.as_ref().map(|range| range.start));
880        match siblings.last().map(|block| &block.kind) {
881            Some(TextBlockKind::Paragraph { .. }) => Ok(()),
882            _ => Err(NamedFault::NeedsParagraph),
883        }
884    }
885
886    fn style(&mut self, index: usize, at: &Address, style: &str) -> Result<(), NamedFault> {
887        let (node, kind, properties, element) = match self.main.target(at)? {
888            Target::Paragraph(node) => (node, StyleKind::Paragraph, "pPr", "pStyle"),
889            Target::Table(node) => (node, StyleKind::Table, "tblPr", "tblStyle"),
890            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
891        };
892        let id = self.styles.resolve(style, kind)?;
893        for (range, xml) in build::set_style(self.main, node, properties, element, &id)? {
894            self.push(index, range, xml, Rank::Properties);
895        }
896        self.outcomes.push(Outcome::Style {
897            at: at.clone(),
898            style: (kind == StyleKind::Paragraph).then_some(id),
899        });
900        Ok(())
901    }
902
903    fn set_text(&mut self, index: usize, at: &Address, text: &str) -> Result<(), NamedFault> {
904        text::check_characters(text, true)?;
905        let (node, cell) = if let Some((row, number)) = at.row_of_cell() {
906            let Target::Row { node: row, .. } = self.main.target(&row)? else {
907                return Err(NamedFault::NoBlock(at.clone()));
908            };
909            let cells = row_cells(&mut self.reader, row);
910            let cell = cells
911                .get(number.get() - 1)
912                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
913            (cell.node, true)
914        } else {
915            let Target::Paragraph(node) = self.main.target(at)? else {
916                return Err(wrong(at, "a paragraph or a cell"));
917            };
918            (node, false)
919        };
920        let (content, style) = rows::new_content(self.main, (node, cell), text)?;
921        build::check_content(self.main, node, &content)?;
922        let properties = if cell { "tcPr" } else { "pPr" };
923        let ((range, xml), notes) = rows::replaced_content(self.main, node, properties, &content)?;
924        self.notes_kept |= notes;
925        self.push(index, range, xml, Rank::Mark);
926        self.outcomes.push(Outcome::SetText {
927            at: at.clone(),
928            text: text.to_owned(),
929            style,
930        });
931        Ok(())
932    }
933
934    fn insert_row(
935        &mut self,
936        index: usize,
937        at: &Address,
938        place: Place,
939        cells: &[String],
940    ) -> Result<(), NamedFault> {
941        for text in cells {
942            text::check_characters(text, true)?;
943        }
944        let Target::Row { node, .. } = self.main.target(at)? else {
945            return Err(wrong(at, "a row"));
946        };
947        let next = self.next_row(at);
948        let row = rows::new_row(self.main, &mut self.reader, (node, place, next), cells)?;
949        self.insert_block(index, (node, place), row.xml)?;
950        self.outcomes.push(Outcome::InsertRow {
951            at: at.clone(),
952            place,
953            cells: row.cells,
954        });
955        Ok(())
956    }
957
958    /// The row after the row `at` in its table, if it has one.
959    fn next_row(&self, at: &Address) -> Option<NodeId> {
960        let table = at.table_of_row()?;
961        let Some(AddressStep::Row(number)) = at.steps().last() else {
962            return None;
963        };
964        let next = table.then(AddressStep::Row(number.checked_add(1)?));
965        match self.main.target(&next) {
966            Ok(Target::Row { node, .. }) => Some(node),
967            _ => None,
968        }
969    }
970
971    fn comment(
972        &mut self,
973        index: usize,
974        at: &Address,
975        text: &str,
976        find: Option<&str>,
977        author: &str,
978    ) -> Result<(), NamedFault> {
979        if author.trim().is_empty() {
980            return Err(NamedFault::EmptyAuthor);
981        }
982        text::check_characters(author, false)?;
983        text::check_characters(text, true)?;
984        let Target::Paragraph(node) = self.main.target(at)? else {
985            return Err(wrong(at, "a paragraph"));
986        };
987        let id = self
988            .additions
989            .comment(index, self.main.doc, (author, text))?;
990        for (range, xml) in comment::marks(self.main, (at, node), id, find)? {
991            build::check_content(self.main, node, &xml)?;
992            self.push(index, range, xml, Rank::Mark);
993        }
994        Ok(())
995    }
996
997    fn insert_image(
998        &mut self,
999        index: usize,
1000        (at, place): (&Address, Place),
1001        image: &ImageFile,
1002        alt: &str,
1003        size: (Option<Length>, Option<Length>),
1004    ) -> Result<(), NamedFault> {
1005        if alt.trim().is_empty() {
1006            return Err(NamedFault::EmptyAlt);
1007        }
1008        text::check_characters(alt, false)?;
1009        let (node, paragraph) = match self.main.target(at)? {
1010            Target::Paragraph(node) => (node, true),
1011            Target::Table(node) => (node, false),
1012            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
1013        };
1014        let column = self
1015            .main
1016            .section_of(node)
1017            .and_then(|section| first_column_width(&mut self.reader, section));
1018        let size = image::drawn_size(image, size, column)?;
1019        let (relationship, id, file) = self.additions.picture(index, self.main.doc, image)?;
1020        let namespaces = DrawingNamespaces {
1021            wp: self.additions.namespace(WP),
1022            a: self.additions.namespace(A),
1023            pic: self.additions.namespace(PIC),
1024            r: self.additions.namespace(R),
1025        };
1026        let drawing = Drawing {
1027            id,
1028            relationship: &relationship,
1029            file: &file,
1030            alt,
1031            size,
1032        };
1033        let built = build::paragraph(self.main, self.styles, (node, paragraph), None, &|w| {
1034            image::drawing(w, &namespaces, &drawing)
1035        })?;
1036        self.insert_block(index, (node, place), built.xml)?;
1037        self.outcomes.push(Outcome::Insert {
1038            at: at.clone(),
1039            place,
1040            text: PICTURE_MARKER.to_owned(),
1041            style: built.style,
1042        });
1043        Ok(())
1044    }
1045
1046    /// Adds the new block `xml` of the edit `index` before or after the block or the row `node`.
1047    fn insert_block(
1048        &mut self,
1049        index: usize,
1050        (node, place): (NodeId, Place),
1051        xml: String,
1052    ) -> Result<(), NamedFault> {
1053        build::check_fragment(self.main, node, &xml)?;
1054        let span = self.main.span(node);
1055        let point = match place {
1056            Place::Before => span.start,
1057            Place::After => span.end,
1058        };
1059        self.inserts.push(NewBlock {
1060            point,
1061            place,
1062            edit: index,
1063            xml,
1064        });
1065        Ok(())
1066    }
1067
1068    /// Adds the new XML `xml` of the edit `index` in place of `range`: to the new XML at one
1069    /// point, of rank `rank`, when the range is empty, and else to the splices.
1070    fn push(&mut self, edit: usize, range: Range<usize>, xml: String, rank: Rank) {
1071        if range.is_empty() {
1072            self.points.push(PointInsert {
1073                point: range.start,
1074                rank,
1075                edit,
1076                xml,
1077            });
1078        } else {
1079            self.splices.push(Splice { edit, range, xml });
1080        }
1081    }
1082
1083    /// The plan, with the splices of the replaces of each paragraph and of the other parts.
1084    fn finish(mut self, part: String, blocks: &[TextBlock]) -> Result<NamedPlan, NamedError> {
1085        for (paragraph, list) in std::mem::take(&mut self.replaces) {
1086            let splices = text::replace(self.main.doc, paragraph, &list)?;
1087            self.splices.extend(splices);
1088        }
1089        let mut inserts = std::mem::take(&mut self.inserts);
1090        inserts.sort_by_key(|new| (new.point, new.place == Place::Before, new.edit));
1091        self.splices.extend(merged(
1092            inserts
1093                .into_iter()
1094                .map(|new| (new.point, new.edit, new.xml)),
1095        ));
1096        let mut points = std::mem::take(&mut self.points);
1097        points.sort_by_key(|new| (new.point, new.rank, new.edit));
1098        self.splices.extend(merged(
1099            points.into_iter().map(|new| (new.point, new.edit, new.xml)),
1100        ));
1101        self.splices.sort_by_key(|splice| splice.edit);
1102        let (related, new_parts) = self.additions.finish()?;
1103        Ok(NamedPlan {
1104            part,
1105            splices: self.splices,
1106            related,
1107            new_parts,
1108            notes_kept: self.notes_kept,
1109            expected: ExpectedBlocks::new(blocks, &self.outcomes),
1110        })
1111    }
1112}
1113
1114/// The new XML at points as splices, one for each point, from `sorted`, each with its point,
1115/// the index of its edit and its XML, in the order in which they stand at their point.
1116///
1117/// The new blocks sort by their point, then those that go after the block before the point
1118/// before those that go before the block after it, then by the list, as the expected blocks
1119/// list them. The new XML inside an element sorts by its point, then new properties before
1120/// the marks of a comment, so that a `w:pPr` stays first, then by the list.
1121fn merged(sorted: impl Iterator<Item = (usize, usize, String)>) -> Vec<Splice> {
1122    let mut splices: Vec<Splice> = Vec::new();
1123    for (point, edit, xml) in sorted {
1124        match splices.last_mut() {
1125            Some(last) if last.range.start == point => last.xml.push_str(&xml),
1126            _ => splices.push(Splice {
1127                edit,
1128                range: point..point,
1129                xml,
1130            }),
1131        }
1132    }
1133    splices
1134}
1135
1136/// One replace of a paragraph: the index of its edit, its find value and its new text.
1137type Replace<'p> = (usize, &'p str, &'p str);
1138
1139/// A new paragraph or row of an insert: where it goes, before or after its block or row, the
1140/// index of its edit and its XML.
1141struct NewBlock {
1142    point: usize,
1143    place: Place,
1144    edit: usize,
1145    xml: String,
1146}
1147
1148/// Where new XML inside an element stands among the new XML at its point.
1149#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1150enum Rank {
1151    /// New properties, which stand first in their element.
1152    Properties,
1153    /// A mark of a comment, or new content.
1154    Mark,
1155}
1156
1157/// New XML at a point inside an element: the point, its rank, the index of its edit and the XML.
1158struct PointInsert {
1159    point: usize,
1160    rank: Rank,
1161    edit: usize,
1162    xml: String,
1163}
1164
1165/// The fault of an edit at a block of a kind that it does not take.
1166fn wrong(at: &Address, needs: &'static str) -> NamedFault {
1167    NamedFault::WrongKind {
1168        at: at.clone(),
1169        needs,
1170    }
1171}
1172
1173/// The relationship type, at its end, of the styles part.
1174const REL_STYLES: &str = ns::REL_STYLES;
1175
1176/// The name of the styles part of the main document part `main`, if it has one.
1177fn styles_part(package: &Package, main: &str) -> Option<String> {
1178    let relationships = package.relationships(main).ok()?;
1179    Relationship::by_type(&relationships.relationships, REL_STYLES).map(|rel| rel.target.clone())
1180}