f-office-docx 0.2.1

DOCX model and Word's layout rules.
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! The named edits of a DOCX file: replace text of a paragraph, set all the text of a
//! paragraph or a cell, insert a paragraph or an image before or after a block, insert a row
//! before or after a row, delete a block or a row, set the style of a paragraph or a table, and
//! add a comment to a paragraph or to text in it.
//!
//! Each names its block by the address of the text blocks ([`TextBlock`]) and finds the block's
//! element by its source span, so that the walk that numbers the addresses also finds their
//! elements. Each becomes splices of the bytes of the main document part ([`Splice`]); a
//! comment and an image also splice the other parts that they change and add new parts
//! ([`NewPart`]). `f_office::edit::apply` makes them with the raw edits of the same list, all
//! or none. The plan also says what the new file's text blocks must be ([`ExpectedBlocks`]),
//! the check after the edits.

mod build;
mod comment;
mod expected;
mod image;
mod parts;
mod rows;
mod styles;
#[cfg(test)]
mod tests;
mod text;

pub use expected::{ExpectedBlocks, Mismatch};
pub use image::ImageFile;

use std::collections::HashMap;
use std::fmt;
use std::ops::Range;

use f_office_opc::{Package, Relationship};
use f_office_units::Length;
use f_office_xml::{Document, Error as XmlError, Limits as XmlLimits, NodeId};

use crate::body::{ParagraphIds, first_column_width};
use crate::ns::{self, A, PIC, R, W, WP};
use crate::reader::PartReader;
use crate::styles::StyleKind;
use crate::table::row_cells;
use crate::text_blocks::{Address, AddressStep, PICTURE_MARKER, TextBlock, TextBlockKind};
use expected::Outcome;
use image::{Drawing, DrawingNamespaces};
use parts::Additions;
use styles::Styles;

/// One named edit of an edit list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NamedEdit {
    /// Replaces the text `find`, which must occur once in the paragraph's text, with `with`.
    /// The match may cross runs, but not a tab, a break, a field code, an object or the edge of
    /// a hyperlink, a content control, a smart tag, a simple field or custom XML. The new text
    /// takes the formatting of the first run of the match.
    Replace {
        /// The paragraph.
        at: Address,
        /// The text to find.
        find: String,
        /// The new text, without control characters.
        with: String,
    },
    /// Inserts a new paragraph with `text` before or after the paragraph or the table `at`.
    /// After a paragraph it takes the paragraph's properties without its section break, and
    /// the style that the paragraph's style names as the next one, as Word's Enter does; the
    /// text keeps the formatting of the paragraph's first run while the style stays the same.
    /// Before or after a table it gets no properties. `style`, an ID or a name of a paragraph
    /// style, wins.
    Insert {
        /// The paragraph or the table.
        at: Address,
        /// Before or after it.
        place: Place,
        /// The text, in which a tab (`\t`) becomes a tab and no other control character may
        /// stand.
        text: String,
        /// The paragraph style, by its ID or its name.
        style: Option<String>,
    },
    /// Deletes the paragraph, the table or the row `at`.
    Delete {
        /// The block or the row.
        at: Address,
    },
    /// Sets the style of the paragraph or the table `at`, by the style's ID or its name.
    Style {
        /// The paragraph or the table.
        at: Address,
        /// The style.
        style: String,
    },
    /// Sets all the text of the paragraph or the cell `at` to `text`. A paragraph keeps its
    /// properties and gets one run in the formatting of its first run. A cell keeps its
    /// properties and gets one paragraph with the properties of its first paragraph and one
    /// run in the formatting of that paragraph's first run. An empty text gets no run.
    SetText {
        /// The paragraph or the cell.
        at: Address,
        /// The text, in which a tab (`\t`) becomes a tab and no other control character may
        /// stand.
        text: String,
    },
    /// Inserts a new row before or after the row `at`. It takes the row's properties, and each
    /// new cell the properties of its cell and one paragraph with the properties of that cell's
    /// first paragraph. A new cell continues a vertical merge that goes on past the new row,
    /// and else takes part in none.
    InsertRow {
        /// The row.
        at: Address,
        /// Before or after it.
        place: Place,
        /// The texts of the first cells, at most one for each cell, each in the formatting of
        /// the first run of its cell's first paragraph; the other cells stay empty.
        cells: Vec<String>,
    },
    /// Adds a comment by `author` with `text` to the paragraph `at`: around its content, or
    /// around the one match of `find`, which follows the rules of a replace.
    Comment {
        /// The paragraph.
        at: Address,
        /// The comment's text, in which a tab becomes a tab and no other control character
        /// may stand.
        text: String,
        /// The text of the paragraph that the comment marks, or none for all of it.
        find: Option<String>,
        /// The comment's author, not empty.
        author: String,
    },
    /// Inserts a new paragraph with one inline picture before or after the paragraph or the
    /// table `at`, with the properties and the style that an insert gives it.
    InsertImage {
        /// The paragraph or the table.
        at: Address,
        /// Before or after it.
        place: Place,
        /// The image.
        image: ImageFile,
        /// The text that describes the image, not empty.
        alt: String,
        /// The width and the height of the drawing: both as given; one as given, with the
        /// other in the image's aspect; or neither, for the image's own size, made smaller in
        /// its aspect to the width of the first text column of the block's section when it is
        /// wider.
        size: (Option<Length>, Option<Length>),
    },
}

impl NamedEdit {
    /// The address that the edit names.
    #[must_use]
    pub const fn at(&self) -> &Address {
        match self {
            Self::Replace { at, .. }
            | Self::Insert { at, .. }
            | Self::Delete { at }
            | Self::Style { at, .. }
            | Self::SetText { at, .. }
            | Self::InsertRow { at, .. }
            | Self::Comment { at, .. }
            | Self::InsertImage { at, .. } => at,
        }
    }
}

/// Where an insert puts its paragraph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Place {
    /// Before the block.
    Before,
    /// After the block.
    After,
}

/// New bytes in place of a range of a part's bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Splice {
    /// The index of the edit in its list, from 0.
    pub edit: usize,
    /// The range of the part's bytes that the new bytes replace; empty for an insert.
    pub range: Range<usize>,
    /// The new XML.
    pub xml: String,
}

/// A new part of the package.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewPart {
    /// The index of the edit in its list, from 0, that first needs it.
    pub edit: usize,
    /// The part's name.
    pub name: String,
    /// The part's bytes.
    pub data: Vec<u8>,
}

/// What the named edits of a list make.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NamedPlan {
    /// The name of the main document part, which the splices change.
    pub part: String,
    /// The splices, in the order of the edits.
    pub splices: Vec<Splice>,
    /// The splices of the other parts that comments and images change, each with its part's
    /// name: the relationships of the main document part, the content types and the comments
    /// part.
    pub related: Vec<(String, Splice)>,
    /// The new parts: the picture files, and a comments part or a relationships part that the
    /// package does not have.
    pub new_parts: Vec<NewPart>,
    /// Whether a deleted block or row holds the reference of a footnote or an endnote, whose
    /// note stays in its part.
    pub notes_kept: bool,
    /// The text blocks that the new file must have.
    pub expected: ExpectedBlocks,
}

/// Why the named edits of a 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 NamedError {
    /// The index of the edit, or none for a fault of the whole file.
    pub edit: Option<usize>,
    /// The fault.
    pub fault: NamedFault,
}

/// What is wrong with a named edit, or with the file for all of them. Each message names the
/// fix.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NamedFault {
    /// The package has no main document part, or it does not parse.
    MainPart(String),
    /// The main document part holds tracked changes, which a named edit does not make.
    TrackedChanges,
    /// The file has no block or row at the address.
    NoBlock(Address),
    /// The address names an element of a header, a footer, a note or a text box, which a
    /// named edit does not change.
    OutsideBody(Address),
    /// The block at the address is of a kind that the edit does not take.
    WrongKind {
        /// The address.
        at: Address,
        /// What the edit needs.
        needs: &'static str,
    },
    /// The block was not read from an element of the main document part: F-Office made it, or
    /// the blocks are of another file.
    NoElement(Address),
    /// The part declares no prefix for WordprocessingML, so the edit cannot name its elements.
    NoPrefix,
    /// The text of a replace is empty.
    EmptyFind,
    /// The paragraph's text does not hold the text of a replace.
    TextNotFound,
    /// The paragraph's text outside its equations does not hold the text of a replace. The
    /// paragraph holds an equation, whose text its text block shows and a replace does not
    /// change.
    TextNotFoundOutsideEquations,
    /// The paragraph's text holds the text of a replace more than once.
    TextAmbiguous {
        /// How often it occurs.
        count: usize,
    },
    /// The match of a replace crosses an element that has no text of its own, such as `w:tab`.
    MatchCrossesElement {
        /// The element's name, such as `w:tab`.
        element: &'static str,
    },
    /// The match of a replace crosses the edge of an element that holds runs, such as
    /// `w:hyperlink`.
    MatchCrossesEdge {
        /// The element's name, such as `w:hyperlink`.
        element: &'static str,
    },
    /// Two replaces of one paragraph match overlapping text. The index of the other edit.
    MatchesOverlap {
        /// The index of the other edit, from 0.
        other: usize,
    },
    /// The new text holds a character that the edit cannot write.
    BadCharacter(char),
    /// The paragraph ends a section: its properties hold a `w:sectPr`.
    SectionBreak,
    /// The delete would leave a cell or the body without a paragraph at its end, also counting
    /// the blocks that earlier deletes of the list take away.
    NeedsParagraph,
    /// The row is the last row of its table that earlier deletes of the list leave.
    LastRow,
    /// The block holds one end of a range whose other end lies outside it.
    RangeEnd {
        /// The element at the end, such as `w:bookmarkStart`.
        element: &'static str,
    },
    /// The styles part has no style of this ID or name and kind.
    NoSuchStyle {
        /// The style that the edit gives.
        style: String,
        /// Its kind.
        kind: &'static str,
        /// The IDs of the styles of the kind whose ID holds the given text in any case, for
        /// the message.
        near: Vec<String>,
    },
    /// The new XML of an edit does not parse at its place, such as for a prefix that the
    /// copied properties use and that is declared on the block itself.
    NewXml(XmlError),
    /// The row holds a cell inside a content control, custom XML or alternate content, which
    /// a new row does not copy.
    WrappedCells,
    /// A new row gets more texts than its row has cells.
    TooManyCells {
        /// The number of texts.
        given: usize,
        /// The number of cells.
        cells: usize,
    },
    /// A new cell that continues a vertical merge gets a text, which stands in the merge's
    /// first cell.
    MergedCellText {
        /// The cell's number, from 1.
        cell: usize,
    },
    /// The comment has no author.
    EmptyAuthor,
    /// The image has no text that describes it.
    EmptyAlt,
    /// The width or the height of the image's drawing is not more than zero, or lies beyond
    /// the largest length of a file.
    ImageSize,
    /// The file uses the largest ID of this kind, such as `comment`.
    NoFreeId(&'static str),
    /// A part besides the main document part that the edit changes does not read.
    Part {
        /// The part's name.
        part: String,
        /// Why it does not read.
        why: String,
    },
}

impl fmt::Display for NamedFault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MainPart(why) => write!(f, "the main document part does not read: {why}"),
            Self::TrackedChanges => f.write_str(
                "the main document holds tracked changes, which a named edit does not make: accept or reject them in Word, or use a raw edit",
            ),
            Self::NoBlock(at) => write!(
                f,
                "the file has no block at {at}"
            ),
            Self::OutsideBody(at) => write!(
                f,
                "{at} lies in a header, a footer, a note or a text box, which a named edit does not change: use a raw edit"
            ),
            Self::WrongKind { at, needs } => write!(f, "the edit needs {needs}, and {at} is not one"),
            Self::NoElement(at) => write!(
                f,
                "the block at {at} has no element in the main document part: use a raw edit"
            ),
            Self::NoPrefix => f.write_str(
                "the main document part declares no prefix for WordprocessingML: use a raw edit",
            ),
            Self::EmptyFind => f.write_str("the find value is empty: give the text to replace"),
            Self::TextNotFound => f.write_str(
                "the paragraph's text does not hold the find value",
            ),
            Self::TextNotFoundOutsideEquations => f.write_str(
                "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\")",
            ),
            Self::TextAmbiguous { count } => write!(
                f,
                "the find value occurs {count} times in the paragraph: make it longer, so that it occurs once"
            ),
            Self::MatchCrossesElement { element } => write!(
                f,
                "the match crosses a {element} element, which has no text to replace: make the find value smaller, or use a raw edit"
            ),
            Self::MatchCrossesEdge { element } => write!(
                f,
                "the match crosses the edge of a {element} element: make the find value smaller, or use a raw edit"
            ),
            Self::MatchesOverlap { other } => write!(
                f,
                "its match overlaps the match of edit {other} in the same paragraph: make one replace of them"
            ),
            Self::BadCharacter(character) => write!(
                f,
                "the text holds U+{:04X}, which this edit cannot write: remove it, or use a raw edit",
                u32::from(*character)
            ),
            Self::SectionBreak => f.write_str(
                "the paragraph ends a section (its w:pPr holds w:sectPr): use a raw edit",
            ),
            Self::NeedsParagraph => f.write_str(
                "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",
            ),
            Self::LastRow => f.write_str(
                "the row is the last row of its table that the edits keep: delete the table",
            ),
            Self::RangeEnd { element } => write!(
                f,
                "the block holds a {element} whose other end lies outside it: delete the range too, or use a raw edit"
            ),
            Self::NoSuchStyle { style, kind, near } => write!(
                f,
                "the file has no {kind} style with the ID or the name {style}: give one of {}",
                if near.is_empty() {
                    "the styles of word/styles.xml".to_owned()
                } else {
                    near.join(", ")
                }
            ),
            Self::NewXml(_) => f.write_str(
                "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",
            ),
            Self::WrappedCells => f.write_str(
                "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",
            ),
            Self::TooManyCells { given, cells } => write!(
                f,
                "the edit gives {given} cell texts, and the row has {cells} cells: give at most one text for each cell"
            ),
            Self::MergedCellText { cell } => write!(
                f,
                "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"
            ),
            Self::EmptyAuthor => f.write_str(
                "a comment needs an author: supply a default author or an \"author\" field in the edit",
            ),
            Self::EmptyAlt => f.write_str(
                "an image needs a text that describes it: give an \"alt\" field that is not empty",
            ),
            Self::ImageSize => f.write_str(
                "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\"",
            ),
            Self::NoFreeId(kind) => write!(f, "the file uses the largest {kind} ID: use a raw edit"),
            Self::Part { part, why } => write!(f, "the part {part} does not read: {why}"),
        }
    }
}

impl std::error::Error for NamedFault {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NewXml(error) => Some(error),
            _ => None,
        }
    }
}

/// The elements of tracked changes in WordprocessingML (ECMA-376 Part 1, 17.13.5).
const TRACKED: [&str; 20] = [
    "ins",
    "del",
    "moveFrom",
    "moveTo",
    "moveFromRangeStart",
    "moveToRangeStart",
    "pPrChange",
    "rPrChange",
    "sectPrChange",
    "tblPrChange",
    "tblPrExChange",
    "trPrChange",
    "tcPrChange",
    "tblGridChange",
    "numberingChange",
    "cellIns",
    "cellDel",
    "cellMerge",
    "customXmlInsRangeStart",
    "customXmlDelRangeStart",
];

/// Plans the named edits `edits`, each with its index in its list, on the DOCX package
/// `package`, whose text blocks are `blocks` (the [`TextBlock`]s of a layout of it).
///
/// # Errors
///
/// Returns the first fault, with the index of its edit.
pub fn plan(
    package: &Package,
    blocks: &[TextBlock],
    edits: &[(usize, &NamedEdit)],
    limits: &XmlLimits,
) -> Result<NamedPlan, NamedError> {
    let whole = |fault| NamedError { edit: None, fault };
    let name = package
        .main_document()
        .map_err(|error| whole(NamedFault::MainPart(error.to_string())))?;
    let bytes = package.part(&name).ok_or_else(|| {
        whole(NamedFault::MainPart(format!(
            "the package has no part {name}"
        )))
    })?;
    let doc = Document::parse_with_aliases(bytes, limits, ns::STRICT_ALIASES)
        .map_err(|error| whole(NamedFault::MainPart(error.to_string())))?;
    let first = edits.first().map(|(index, _)| *index);
    if holds_tracked_changes(&doc) {
        return Err(NamedError {
            edit: first,
            fault: NamedFault::TrackedChanges,
        });
    }
    let styles = Styles::of(package, &name, limits);
    let main = Main::new(bytes, &doc, blocks);
    let ids = ParagraphIds::default();
    let mut planner = Planner {
        main: &main,
        styles: &styles,
        reader: PartReader::of_part(&doc, &name, &ids),
        additions: Additions::new(package, &name, limits),
        splices: Vec::new(),
        replaces: Vec::new(),
        inserts: Vec::new(),
        points: Vec::new(),
        outcomes: Vec::new(),
        notes_kept: false,
        deleted: Vec::new(),
    };
    for &(index, edit) in edits {
        planner.add(index, edit).map_err(|fault| NamedError {
            edit: Some(index),
            fault,
        })?;
    }
    planner.finish(name.clone(), blocks)
}

/// Whether the part holds an element of a tracked change.
fn holds_tracked_changes(doc: &Document) -> bool {
    let Ok(root) = doc.root() else {
        return false;
    };
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if TRACKED.iter().any(|local| doc.is(node, W, local)) {
            return true;
        }
        stack.extend(doc.child_elements(node));
    }
    false
}

/// The main document part: its bytes, its tree, the elements by the start of their spans, and
/// the text blocks by their addresses.
struct Main<'m> {
    /// The part's bytes.
    bytes: &'m [u8],
    /// The parsed part, with the namespaces of Strict read as those of Transitional.
    doc: &'m Document,
    /// Each element by the start of its span.
    elements: HashMap<usize, NodeId>,
    /// Each text block by its address.
    blocks: HashMap<&'m Address, &'m TextBlock>,
    /// The parent of each element.
    parents: HashMap<NodeId, NodeId>,
}

/// The element that an address names.
#[derive(Clone, Copy)]
enum Target {
    /// A paragraph (`w:p`).
    Paragraph(NodeId),
    /// A table (`w:tbl`).
    Table(NodeId),
    /// A row (`w:tr`) of a table of this many rows.
    Row {
        /// The row.
        node: NodeId,
        /// The number of rows of its table.
        rows: usize,
    },
}

impl<'m> Main<'m> {
    fn new(bytes: &'m [u8], doc: &'m Document, blocks: &'m [TextBlock]) -> Self {
        let mut elements = HashMap::new();
        let mut parents = HashMap::new();
        if let Ok(root) = doc.root() {
            let mut stack = vec![root];
            while let Some(node) = stack.pop() {
                if let Ok(span) = doc.span(node) {
                    elements.insert(span.start, node);
                }
                for child in doc.child_elements(node) {
                    parents.insert(child, node);
                    stack.push(child);
                }
            }
        }
        Self {
            bytes,
            doc,
            elements,
            blocks: blocks.iter().map(|block| (&block.address, block)).collect(),
            parents,
        }
    }

    /// The parent of the element `node`.
    fn parent(&self, node: NodeId) -> Option<NodeId> {
        self.parents.get(&node).copied()
    }

    /// The part's bytes in `range`, as text.
    fn text(&self, range: Range<usize>) -> String {
        String::from_utf8_lossy(self.bytes.get(range).unwrap_or_default()).into_owned()
    }

    /// The element whose span is `range` and whose name is `local`.
    fn element(
        &self,
        range: Option<&Range<usize>>,
        local: &str,
        at: &Address,
    ) -> Result<NodeId, NamedFault> {
        let range = range.ok_or_else(|| NamedFault::NoElement(at.clone()))?;
        self.elements
            .get(&range.start)
            .copied()
            .filter(|&node| {
                self.doc.span(node).is_ok_and(|span| span == *range) && self.doc.is(node, W, local)
            })
            .ok_or_else(|| NamedFault::NoElement(at.clone()))
    }

    /// The element at `at`.
    fn target(&self, at: &Address) -> Result<Target, NamedFault> {
        if let Some(table) = at.table_of_row() {
            let block = self
                .blocks
                .get(&table)
                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
            let (Some(AddressStep::Row(number)), TextBlockKind::Table { rows }) =
                (at.steps().last(), &block.kind)
            else {
                return Err(NamedFault::NoBlock(at.clone()));
            };
            let range = block
                .row_sources
                .get(number.get() - 1)
                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
            let node = self.element(range.as_ref(), "tr", at)?;
            return Ok(Target::Row { node, rows: *rows });
        }
        let block = self
            .blocks
            .get(at)
            .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
        Ok(match block.kind {
            TextBlockKind::Paragraph { .. } => {
                Target::Paragraph(self.element(block.source.as_ref(), "p", at)?)
            }
            TextBlockKind::Table { .. } => {
                Target::Table(self.element(block.source.as_ref(), "tbl", at)?)
            }
        })
    }

    /// The bytes of the span of `node`.
    fn span(&self, node: NodeId) -> Range<usize> {
        self.doc.span(node).unwrap_or(0..0)
    }

    /// The section break (`w:sectPr`) of the section that holds the block `node`: the first
    /// one of the body at or after the block, in the properties of a paragraph outside a table
    /// or at the end of the body.
    fn section_of(&self, node: NodeId) -> Option<NodeId> {
        let start = self.span(node).start;
        let in_cell = |mut current: NodeId| {
            while let Some(parent) = self.parent(current) {
                if self.doc.is(parent, W, "tc") {
                    return true;
                }
                current = parent;
            }
            false
        };
        self.elements
            .values()
            .copied()
            .filter(|&section| self.doc.is(section, W, "sectPr"))
            .filter(|&section| {
                self.parent(section).is_some_and(|parent| {
                    self.doc.is(parent, W, "body")
                        || (self.doc.is(parent, W, "pPr")
                            && self.parent(parent).is_some_and(|p| self.doc.is(p, W, "p")))
                })
            })
            .filter(|&section| !in_cell(section))
            .map(|section| (self.span(section).start, section))
            .filter(|(at, _)| *at >= start)
            .min_by_key(|(at, _)| *at)
            .map(|(_, section)| section)
    }
}

/// The plan of a list's named edits as it grows.
struct Planner<'p, 'm> {
    main: &'p Main<'m>,
    styles: &'p Styles,
    /// The reader of the main document part, for its rows and its sections.
    reader: PartReader<'p>,
    /// What comments and images add to the other parts.
    additions: Additions<'p>,
    splices: Vec<Splice>,
    /// The replaces of each paragraph, in the order of the list, by the paragraph.
    replaces: Vec<(NodeId, Vec<Replace<'p>>)>,
    /// The new paragraphs and rows.
    inserts: Vec<NewBlock>,
    /// The new XML at points inside elements.
    points: Vec<PointInsert>,
    outcomes: Vec<Outcome>,
    notes_kept: bool,
    /// The addresses of the blocks and rows that the list's deletes take away so far, against
    /// which each later delete checks what its cell, body or table keeps.
    deleted: Vec<Address>,
}

impl<'p> Planner<'p, '_> {
    /// Adds the edit `edit` of index `index`.
    fn add(&mut self, index: usize, edit: &'p NamedEdit) -> Result<(), NamedFault> {
        if !edit.at().in_body() {
            return Err(NamedFault::OutsideBody(edit.at().clone()));
        }
        match edit {
            NamedEdit::Replace { at, find, with } => self.replace(index, at, find, with),
            NamedEdit::Insert {
                at,
                place,
                text,
                style,
            } => self.insert(index, at, *place, text, style.as_deref()),
            NamedEdit::Delete { at } => self.delete(index, at),
            NamedEdit::Style { at, style } => self.style(index, at, style),
            NamedEdit::SetText { at, text } => self.set_text(index, at, text),
            NamedEdit::InsertRow { at, place, cells } => self.insert_row(index, at, *place, cells),
            NamedEdit::Comment {
                at,
                text,
                find,
                author,
            } => self.comment(index, at, text, find.as_deref(), author),
            NamedEdit::InsertImage {
                at,
                place,
                image,
                alt,
                size,
            } => self.insert_image(index, (at, *place), image, alt, *size),
        }
    }

    fn replace(
        &mut self,
        index: usize,
        at: &Address,
        find: &'p str,
        with: &'p str,
    ) -> Result<(), NamedFault> {
        if find.is_empty() {
            return Err(NamedFault::EmptyFind);
        }
        text::check_characters(with, false)?;
        let Target::Paragraph(node) = self.main.target(at)? else {
            return Err(wrong(at, "a paragraph"));
        };
        match self
            .replaces
            .iter_mut()
            .find(|(paragraph, _)| *paragraph == node)
        {
            Some((_, list)) => list.push((index, find, with)),
            None => self.replaces.push((node, vec![(index, find, with)])),
        }
        self.outcomes.push(Outcome::Replace {
            at: at.clone(),
            find: find.to_owned(),
            with: with.to_owned(),
        });
        Ok(())
    }

    fn insert(
        &mut self,
        index: usize,
        at: &Address,
        place: Place,
        text: &str,
        style: Option<&str>,
    ) -> Result<(), NamedFault> {
        text::check_characters(text, true)?;
        let (node, anchor) = match self.main.target(at)? {
            Target::Paragraph(node) => (node, Some(node)),
            Target::Table(node) => (node, None),
            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
        };
        let given = style
            .map(|style| self.styles.resolve(style, StyleKind::Paragraph))
            .transpose()?;
        let built = build::paragraph(
            self.main,
            self.styles,
            (node, anchor.is_some()),
            given,
            &|w| build::run_text(w, text),
        )?;
        self.insert_block(index, (node, place), built.xml)?;
        self.outcomes.push(Outcome::Insert {
            at: at.clone(),
            place,
            text: text.to_owned(),
            style: built.style,
        });
        Ok(())
    }

    fn delete(&mut self, index: usize, at: &Address) -> Result<(), NamedFault> {
        let node = match self.main.target(at)? {
            Target::Paragraph(node) => {
                if build::ends_section(self.main.doc, node) {
                    return Err(NamedFault::SectionBreak);
                }
                self.keeps_last_paragraph(at)?;
                node
            }
            Target::Table(node) => {
                self.keeps_last_paragraph(at)?;
                node
            }
            Target::Row { node, rows } => {
                let table = at.table_of_row();
                let gone = self
                    .deleted
                    .iter()
                    .filter(|row| row.table_of_row() == table)
                    .count();
                if rows <= gone + 1 {
                    return Err(NamedFault::LastRow);
                }
                node
            }
        };
        if let Some(element) = build::open_range(self.main.doc, node) {
            return Err(NamedFault::RangeEnd { element });
        }
        self.notes_kept |= build::holds_note_reference(self.main.doc, node);
        self.splices.push(Splice {
            edit: index,
            range: self.main.span(node),
            xml: String::new(),
        });
        self.outcomes.push(Outcome::Delete { at: at.clone() });
        self.deleted.push(at.clone());
        Ok(())
    }

    /// Checks that the cell or the body of the block `at` still ends with a paragraph when the
    /// block goes, after the blocks that earlier deletes of the list take away.
    fn keeps_last_paragraph(&self, at: &Address) -> Result<(), NamedFault> {
        let container = at.container();
        let mut siblings: Vec<&TextBlock> = self
            .main
            .blocks
            .values()
            .filter(|block| {
                block.address.steps().len() == at.steps().len()
                    && block.address.container() == container
                    && block.address != *at
                    && !self.deleted.contains(&block.address)
            })
            .copied()
            .collect();
        siblings.sort_by_key(|block| block.source.as_ref().map(|range| range.start));
        match siblings.last().map(|block| &block.kind) {
            Some(TextBlockKind::Paragraph { .. }) => Ok(()),
            _ => Err(NamedFault::NeedsParagraph),
        }
    }

    fn style(&mut self, index: usize, at: &Address, style: &str) -> Result<(), NamedFault> {
        let (node, kind, properties, element) = match self.main.target(at)? {
            Target::Paragraph(node) => (node, StyleKind::Paragraph, "pPr", "pStyle"),
            Target::Table(node) => (node, StyleKind::Table, "tblPr", "tblStyle"),
            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
        };
        let id = self.styles.resolve(style, kind)?;
        for (range, xml) in build::set_style(self.main, node, properties, element, &id)? {
            self.push(index, range, xml, Rank::Properties);
        }
        self.outcomes.push(Outcome::Style {
            at: at.clone(),
            style: (kind == StyleKind::Paragraph).then_some(id),
        });
        Ok(())
    }

    fn set_text(&mut self, index: usize, at: &Address, text: &str) -> Result<(), NamedFault> {
        text::check_characters(text, true)?;
        let (node, cell) = if let Some((row, number)) = at.row_of_cell() {
            let Target::Row { node: row, .. } = self.main.target(&row)? else {
                return Err(NamedFault::NoBlock(at.clone()));
            };
            let cells = row_cells(&mut self.reader, row);
            let cell = cells
                .get(number.get() - 1)
                .ok_or_else(|| NamedFault::NoBlock(at.clone()))?;
            (cell.node, true)
        } else {
            let Target::Paragraph(node) = self.main.target(at)? else {
                return Err(wrong(at, "a paragraph or a cell"));
            };
            (node, false)
        };
        let (content, style) = rows::new_content(self.main, (node, cell), text)?;
        build::check_content(self.main, node, &content)?;
        let properties = if cell { "tcPr" } else { "pPr" };
        let ((range, xml), notes) = rows::replaced_content(self.main, node, properties, &content)?;
        self.notes_kept |= notes;
        self.push(index, range, xml, Rank::Mark);
        self.outcomes.push(Outcome::SetText {
            at: at.clone(),
            text: text.to_owned(),
            style,
        });
        Ok(())
    }

    fn insert_row(
        &mut self,
        index: usize,
        at: &Address,
        place: Place,
        cells: &[String],
    ) -> Result<(), NamedFault> {
        for text in cells {
            text::check_characters(text, true)?;
        }
        let Target::Row { node, .. } = self.main.target(at)? else {
            return Err(wrong(at, "a row"));
        };
        let next = self.next_row(at);
        let row = rows::new_row(self.main, &mut self.reader, (node, place, next), cells)?;
        self.insert_block(index, (node, place), row.xml)?;
        self.outcomes.push(Outcome::InsertRow {
            at: at.clone(),
            place,
            cells: row.cells,
        });
        Ok(())
    }

    /// The row after the row `at` in its table, if it has one.
    fn next_row(&self, at: &Address) -> Option<NodeId> {
        let table = at.table_of_row()?;
        let Some(AddressStep::Row(number)) = at.steps().last() else {
            return None;
        };
        let next = table.then(AddressStep::Row(number.checked_add(1)?));
        match self.main.target(&next) {
            Ok(Target::Row { node, .. }) => Some(node),
            _ => None,
        }
    }

    fn comment(
        &mut self,
        index: usize,
        at: &Address,
        text: &str,
        find: Option<&str>,
        author: &str,
    ) -> Result<(), NamedFault> {
        if author.trim().is_empty() {
            return Err(NamedFault::EmptyAuthor);
        }
        text::check_characters(author, false)?;
        text::check_characters(text, true)?;
        let Target::Paragraph(node) = self.main.target(at)? else {
            return Err(wrong(at, "a paragraph"));
        };
        let id = self
            .additions
            .comment(index, self.main.doc, (author, text))?;
        for (range, xml) in comment::marks(self.main, (at, node), id, find)? {
            build::check_content(self.main, node, &xml)?;
            self.push(index, range, xml, Rank::Mark);
        }
        Ok(())
    }

    fn insert_image(
        &mut self,
        index: usize,
        (at, place): (&Address, Place),
        image: &ImageFile,
        alt: &str,
        size: (Option<Length>, Option<Length>),
    ) -> Result<(), NamedFault> {
        if alt.trim().is_empty() {
            return Err(NamedFault::EmptyAlt);
        }
        text::check_characters(alt, false)?;
        let (node, paragraph) = match self.main.target(at)? {
            Target::Paragraph(node) => (node, true),
            Target::Table(node) => (node, false),
            Target::Row { .. } => return Err(wrong(at, "a paragraph or a table")),
        };
        let column = self
            .main
            .section_of(node)
            .and_then(|section| first_column_width(&mut self.reader, section));
        let size = image::drawn_size(image, size, column)?;
        let (relationship, id, file) = self.additions.picture(index, self.main.doc, image)?;
        let namespaces = DrawingNamespaces {
            wp: self.additions.namespace(WP),
            a: self.additions.namespace(A),
            pic: self.additions.namespace(PIC),
            r: self.additions.namespace(R),
        };
        let drawing = Drawing {
            id,
            relationship: &relationship,
            file: &file,
            alt,
            size,
        };
        let built = build::paragraph(self.main, self.styles, (node, paragraph), None, &|w| {
            image::drawing(w, &namespaces, &drawing)
        })?;
        self.insert_block(index, (node, place), built.xml)?;
        self.outcomes.push(Outcome::Insert {
            at: at.clone(),
            place,
            text: PICTURE_MARKER.to_owned(),
            style: built.style,
        });
        Ok(())
    }

    /// Adds the new block `xml` of the edit `index` before or after the block or the row `node`.
    fn insert_block(
        &mut self,
        index: usize,
        (node, place): (NodeId, Place),
        xml: String,
    ) -> Result<(), NamedFault> {
        build::check_fragment(self.main, node, &xml)?;
        let span = self.main.span(node);
        let point = match place {
            Place::Before => span.start,
            Place::After => span.end,
        };
        self.inserts.push(NewBlock {
            point,
            place,
            edit: index,
            xml,
        });
        Ok(())
    }

    /// Adds the new XML `xml` of the edit `index` in place of `range`: to the new XML at one
    /// point, of rank `rank`, when the range is empty, and else to the splices.
    fn push(&mut self, edit: usize, range: Range<usize>, xml: String, rank: Rank) {
        if range.is_empty() {
            self.points.push(PointInsert {
                point: range.start,
                rank,
                edit,
                xml,
            });
        } else {
            self.splices.push(Splice { edit, range, xml });
        }
    }

    /// The plan, with the splices of the replaces of each paragraph and of the other parts.
    fn finish(mut self, part: String, blocks: &[TextBlock]) -> Result<NamedPlan, NamedError> {
        for (paragraph, list) in std::mem::take(&mut self.replaces) {
            let splices = text::replace(self.main.doc, paragraph, &list)?;
            self.splices.extend(splices);
        }
        let mut inserts = std::mem::take(&mut self.inserts);
        inserts.sort_by_key(|new| (new.point, new.place == Place::Before, new.edit));
        self.splices.extend(merged(
            inserts
                .into_iter()
                .map(|new| (new.point, new.edit, new.xml)),
        ));
        let mut points = std::mem::take(&mut self.points);
        points.sort_by_key(|new| (new.point, new.rank, new.edit));
        self.splices.extend(merged(
            points.into_iter().map(|new| (new.point, new.edit, new.xml)),
        ));
        self.splices.sort_by_key(|splice| splice.edit);
        let (related, new_parts) = self.additions.finish()?;
        Ok(NamedPlan {
            part,
            splices: self.splices,
            related,
            new_parts,
            notes_kept: self.notes_kept,
            expected: ExpectedBlocks::new(blocks, &self.outcomes),
        })
    }
}

/// The new XML at points as splices, one for each point, from `sorted`, each with its point,
/// the index of its edit and its XML, in the order in which they stand at their point.
///
/// The new blocks sort by their point, then those that go after the block before the point
/// before those that go before the block after it, then by the list, as the expected blocks
/// list them. The new XML inside an element sorts by its point, then new properties before
/// the marks of a comment, so that a `w:pPr` stays first, then by the list.
fn merged(sorted: impl Iterator<Item = (usize, usize, String)>) -> Vec<Splice> {
    let mut splices: Vec<Splice> = Vec::new();
    for (point, edit, xml) in sorted {
        match splices.last_mut() {
            Some(last) if last.range.start == point => last.xml.push_str(&xml),
            _ => splices.push(Splice {
                edit,
                range: point..point,
                xml,
            }),
        }
    }
    splices
}

/// One replace of a paragraph: the index of its edit, its find value and its new text.
type Replace<'p> = (usize, &'p str, &'p str);

/// A new paragraph or row of an insert: where it goes, before or after its block or row, the
/// index of its edit and its XML.
struct NewBlock {
    point: usize,
    place: Place,
    edit: usize,
    xml: String,
}

/// Where new XML inside an element stands among the new XML at its point.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Rank {
    /// New properties, which stand first in their element.
    Properties,
    /// A mark of a comment, or new content.
    Mark,
}

/// New XML at a point inside an element: the point, its rank, the index of its edit and the XML.
struct PointInsert {
    point: usize,
    rank: Rank,
    edit: usize,
    xml: String,
}

/// The fault of an edit at a block of a kind that it does not take.
fn wrong(at: &Address, needs: &'static str) -> NamedFault {
    NamedFault::WrongKind {
        at: at.clone(),
        needs,
    }
}

/// The relationship type, at its end, of the styles part.
const REL_STYLES: &str = ns::REL_STYLES;

/// The name of the styles part of the main document part `main`, if it has one.
fn styles_part(package: &Package, main: &str) -> Option<String> {
    let relationships = package.relationships(main).ok()?;
    Relationship::by_type(&relationships.relationships, REL_STYLES).map(|rel| rel.target.clone())
}