1mod 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#[derive(Clone, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum NamedEdit {
51 Replace {
56 at: Address,
58 find: String,
60 with: String,
62 },
63 Insert {
70 at: Address,
72 place: Place,
74 text: String,
77 style: Option<String>,
79 },
80 Delete {
82 at: Address,
84 },
85 Style {
87 at: Address,
89 style: String,
91 },
92 SetText {
97 at: Address,
99 text: String,
102 },
103 InsertRow {
108 at: Address,
110 place: Place,
112 cells: Vec<String>,
115 },
116 Comment {
119 at: Address,
121 text: String,
124 find: Option<String>,
126 author: String,
128 },
129 InsertImage {
132 at: Address,
134 place: Place,
136 image: ImageFile,
138 alt: String,
140 size: (Option<Length>, Option<Length>),
145 },
146}
147
148impl NamedEdit {
149 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub enum Place {
168 Before,
170 After,
172}
173
174#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Splice {
177 pub edit: usize,
179 pub range: Range<usize>,
181 pub xml: String,
183}
184
185#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct NewPart {
188 pub edit: usize,
190 pub name: String,
192 pub data: Vec<u8>,
194}
195
196#[derive(Clone, Debug, PartialEq, Eq)]
198#[non_exhaustive]
199pub struct NamedPlan {
200 pub part: String,
202 pub splices: Vec<Splice>,
204 pub related: Vec<(String, Splice)>,
208 pub new_parts: Vec<NewPart>,
211 pub notes_kept: bool,
214 pub expected: ExpectedBlocks,
216}
217
218#[derive(Clone, Debug, PartialEq, Eq)]
221pub struct NamedError {
222 pub edit: Option<usize>,
224 pub fault: NamedFault,
226}
227
228#[derive(Clone, Debug, PartialEq, Eq)]
231#[non_exhaustive]
232pub enum NamedFault {
233 MainPart(String),
235 TrackedChanges,
237 NoBlock(Address),
239 OutsideBody(Address),
242 WrongKind {
244 at: Address,
246 needs: &'static str,
248 },
249 NoElement(Address),
252 NoPrefix,
254 EmptyFind,
256 TextNotFound,
258 TextNotFoundOutsideEquations,
262 TextAmbiguous {
264 count: usize,
266 },
267 MatchCrossesElement {
269 element: &'static str,
271 },
272 MatchCrossesEdge {
275 element: &'static str,
277 },
278 MatchesOverlap {
280 other: usize,
282 },
283 BadCharacter(char),
285 SectionBreak,
287 NeedsParagraph,
290 LastRow,
292 RangeEnd {
294 element: &'static str,
296 },
297 NoSuchStyle {
299 style: String,
301 kind: &'static str,
303 near: Vec<String>,
306 },
307 NewXml(XmlError),
310 WrappedCells,
313 TooManyCells {
315 given: usize,
317 cells: usize,
319 },
320 MergedCellText {
323 cell: usize,
325 },
326 EmptyAuthor,
328 EmptyAlt,
330 ImageSize,
333 NoFreeId(&'static str),
335 Part {
337 part: String,
339 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
455const 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
479pub 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
534fn 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
549struct Main<'m> {
552 bytes: &'m [u8],
554 doc: &'m Document,
556 elements: HashMap<usize, NodeId>,
558 blocks: HashMap<&'m Address, &'m TextBlock>,
560 parents: HashMap<NodeId, NodeId>,
562}
563
564#[derive(Clone, Copy)]
566enum Target {
567 Paragraph(NodeId),
569 Table(NodeId),
571 Row {
573 node: NodeId,
575 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 fn parent(&self, node: NodeId) -> Option<NodeId> {
607 self.parents.get(&node).copied()
608 }
609
610 fn text(&self, range: Range<usize>) -> String {
612 String::from_utf8_lossy(self.bytes.get(range).unwrap_or_default()).into_owned()
613 }
614
615 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 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 fn span(&self, node: NodeId) -> Range<usize> {
667 self.doc.span(node).unwrap_or(0..0)
668 }
669
670 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(|§ion| self.doc.is(section, W, "sectPr"))
688 .filter(|§ion| {
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(|§ion| !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
703struct Planner<'p, 'm> {
705 main: &'p Main<'m>,
706 styles: &'p Styles,
707 reader: PartReader<'p>,
709 additions: Additions<'p>,
711 splices: Vec<Splice>,
712 replaces: Vec<(NodeId, Vec<Replace<'p>>)>,
714 inserts: Vec<NewBlock>,
716 points: Vec<PointInsert>,
718 outcomes: Vec<Outcome>,
719 notes_kept: bool,
720 deleted: Vec<Address>,
723}
724
725impl<'p> Planner<'p, '_> {
726 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 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 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 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 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 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
1114fn 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
1136type Replace<'p> = (usize, &'p str, &'p str);
1138
1139struct NewBlock {
1142 point: usize,
1143 place: Place,
1144 edit: usize,
1145 xml: String,
1146}
1147
1148#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1150enum Rank {
1151 Properties,
1153 Mark,
1155}
1156
1157struct PointInsert {
1159 point: usize,
1160 rank: Rank,
1161 edit: usize,
1162 xml: String,
1163}
1164
1165fn wrong(at: &Address, needs: &'static str) -> NamedFault {
1167 NamedFault::WrongKind {
1168 at: at.clone(),
1169 needs,
1170 }
1171}
1172
1173const REL_STYLES: &str = ns::REL_STYLES;
1175
1176fn 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}