1#![allow(dead_code)]
13
14use std::collections::BTreeMap;
15use std::ops::Range;
16
17use crate::domain::document::projection::{ResolvedSlice, project, text_node_mut};
18use crate::domain::document::{
19 Document, Element, Node, Role, TextNode, empty_paragraph, empty_row, normalize_element,
20};
21
22#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
24pub(crate) struct NodePath(Vec<usize>);
25
26impl NodePath {
27 pub(crate) fn new(path: Vec<usize>) -> Self {
29 Self(path)
30 }
31
32 pub(crate) fn as_slice(&self) -> &[usize] {
34 &self.0
35 }
36
37 pub(crate) fn parent(&self) -> Self {
39 let mut path = self.0.clone();
40 path.pop();
41 Self(path)
42 }
43
44 pub(crate) fn index(&self) -> usize {
46 self.0.last().copied().unwrap_or(0)
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub(crate) enum InlineFragment {
53 Text(String),
55 LineBreak,
57 ParagraphBreak,
59 Tab,
61}
62
63impl InlineFragment {
64 pub(crate) fn as_text(&self) -> &str {
66 match self {
67 InlineFragment::Text(text) => text,
68 InlineFragment::LineBreak | InlineFragment::ParagraphBreak => "\n",
69 InlineFragment::Tab => "\t",
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub(crate) struct TextTarget {
77 pub(crate) paragraph: NodePath,
79 pub(crate) slices: Vec<ResolvedSlice>,
81}
82
83#[derive(Debug, Clone, PartialEq)]
85pub(crate) enum Edit {
86 ReplaceText {
88 target: TextTarget,
90 fragments: Vec<InlineFragment>,
92 preserve_space: bool,
94 },
95 RemoveBlocks {
97 parent: NodePath,
99 range: Range<usize>,
101 },
102 RemoveRows {
104 parent: NodePath,
106 range: Range<usize>,
108 },
109 RepeatBlocks {
111 parent: NodePath,
113 range: Range<usize>,
115 iterations: Vec<Plan>,
117 },
118 RepeatRows {
120 parent: NodePath,
122 range: Range<usize>,
124 iterations: Vec<Plan>,
126 },
127}
128
129#[derive(Debug, Clone, PartialEq, Default)]
131pub(crate) struct Plan {
132 edits: Vec<Edit>,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
137#[non_exhaustive]
138pub enum PlanError {
139 #[error("overlapping edits: {first} and {second}")]
141 OverlappingEdits {
142 first: String,
144 second: String,
146 },
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
151pub(crate) enum ApplyError {
152 #[error("missing target at path {path:?}")]
154 MissingTarget {
155 path: Vec<usize>,
157 },
158 #[error("removal at path {path:?} would delete section properties")]
160 RangeIncludesSectionProperties {
161 path: Vec<usize>,
163 },
164 #[error("text slice at {path:?} no longer resolves")]
166 MissingSlice {
167 path: Vec<usize>,
169 },
170}
171
172impl Plan {
173 pub(crate) fn new(edits: Vec<Edit>) -> Result<Self, PlanError> {
175 check_overlaps(&edits)?;
176 Ok(Self { edits })
177 }
178
179 pub(crate) fn empty() -> Self {
181 Self { edits: Vec::new() }
182 }
183
184 pub(crate) fn edits(&self) -> &[Edit] {
186 &self.edits
187 }
188
189 pub(crate) fn is_empty(&self) -> bool {
191 self.edits.is_empty()
192 }
193}
194
195pub(crate) fn apply(root: &Element, plan: &Plan, prefix: &str) -> Result<Element, ApplyError> {
199 let mut root = root.clone();
200 let mut bookmarks = BookmarkCounter::scan(&root);
201 apply_in_place(&mut root, plan, prefix, &mut bookmarks)?;
202 Ok(root)
203}
204
205fn apply_in_place(
206 root: &mut Element,
207 plan: &Plan,
208 prefix: &str,
209 bookmarks: &mut BookmarkCounter,
210) -> Result<(), ApplyError> {
211 let mut order: Vec<usize> = (0..plan.edits.len()).collect();
212 order.sort_by(|left, right| {
213 plan.edits
214 .get(*right)
215 .map(key)
216 .cmp(&plan.edits.get(*left).map(key))
217 });
218
219 for index in order {
220 let Some(edit) = plan.edits.get(index) else {
221 continue;
222 };
223 match edit {
224 Edit::ReplaceText {
225 target,
226 fragments,
227 preserve_space,
228 } => apply_text(root, target, fragments, *preserve_space, prefix)?,
229 Edit::RemoveBlocks { parent, range } => {
230 remove_range(root, parent, range, Unit::Blocks, prefix)?;
231 }
232 Edit::RemoveRows { parent, range } => {
233 remove_range(root, parent, range, Unit::Rows, prefix)?;
234 }
235 Edit::RepeatBlocks {
236 parent,
237 range,
238 iterations,
239 } => repeat(
240 root,
241 parent,
242 range,
243 iterations,
244 Unit::Blocks,
245 prefix,
246 bookmarks,
247 )?,
248 Edit::RepeatRows {
249 parent,
250 range,
251 iterations,
252 } => repeat(
253 root,
254 parent,
255 range,
256 iterations,
257 Unit::Rows,
258 prefix,
259 bookmarks,
260 )?,
261 }
262 }
263
264 normalize_element(root, prefix);
265 Ok(())
266}
267
268fn key(edit: &Edit) -> Vec<usize> {
270 match edit {
271 Edit::ReplaceText { target, .. } => {
272 let mut path = target.paragraph.as_slice().to_vec();
273 let offset = target.slices.first().map_or(0, |slice| slice.start);
274 path.push(offset);
275 path
276 }
277 Edit::RemoveBlocks { parent, range }
278 | Edit::RemoveRows { parent, range }
279 | Edit::RepeatBlocks { parent, range, .. }
280 | Edit::RepeatRows { parent, range, .. } => {
281 let mut path = parent.as_slice().to_vec();
282 path.push(range.start);
283 path
284 }
285 }
286}
287
288fn describe(edit: &Edit) -> String {
289 match edit {
290 Edit::ReplaceText { target, .. } => format!("text at {:?}", target.paragraph.as_slice()),
291 Edit::RemoveBlocks { parent, range } => {
292 format!("blocks {:?} at {:?}", range, parent.as_slice())
293 }
294 Edit::RemoveRows { parent, range } => {
295 format!("rows {:?} at {:?}", range, parent.as_slice())
296 }
297 Edit::RepeatBlocks { parent, range, .. } => {
298 format!("repeated blocks {:?} at {:?}", range, parent.as_slice())
299 }
300 Edit::RepeatRows { parent, range, .. } => {
301 format!("repeated rows {:?} at {:?}", range, parent.as_slice())
302 }
303 }
304}
305
306type RangeRecord = (usize, usize, usize);
308
309type TextKey = (Vec<usize>, Vec<usize>, usize);
311
312fn check_overlaps(edits: &[Edit]) -> Result<(), PlanError> {
319 let mut block_ranges: BTreeMap<Vec<usize>, Vec<RangeRecord>> = BTreeMap::new();
320 let mut text_ranges: BTreeMap<TextKey, Vec<RangeRecord>> = BTreeMap::new();
321
322 for (index, edit) in edits.iter().enumerate() {
323 match edit {
324 Edit::RemoveBlocks { parent, range }
325 | Edit::RemoveRows { parent, range }
326 | Edit::RepeatBlocks { parent, range, .. }
327 | Edit::RepeatRows { parent, range, .. } => {
328 block_ranges
329 .entry(parent.as_slice().to_vec())
330 .or_default()
331 .push((range.start, range.end, index));
332 }
333 Edit::ReplaceText { target, .. } => {
334 for slice in &target.slices {
335 text_ranges
336 .entry((
337 target.paragraph.as_slice().to_vec(),
338 slice.element_path.clone(),
339 slice.node_index,
340 ))
341 .or_default()
342 .push((slice.start, slice.end, index));
343 }
344 }
345 }
346 }
347
348 for ranges in block_ranges.values_mut() {
349 ranges.sort_unstable();
350 reject_first_overlap(ranges, edits)?;
351 }
352
353 for ranges in text_ranges.values_mut() {
354 ranges.sort_unstable();
355 reject_first_overlap(ranges, edits)?;
356 }
357
358 for (index, edit) in edits.iter().enumerate() {
362 let Edit::ReplaceText { target, .. } = edit else {
363 continue;
364 };
365 let paragraph = target.paragraph.as_slice();
366 for level in 0..paragraph.len() {
367 let Some(prefix) = paragraph.get(..level) else {
368 continue;
369 };
370 let Some(ranges) = block_ranges.get(prefix) else {
371 continue;
372 };
373 let Some(&position) = paragraph.get(level) else {
374 continue;
375 };
376 let after = ranges.partition_point(|(start, _, _)| *start <= position);
377 if after == 0 {
378 continue;
379 }
380 let Some(&(_, end, other)) = ranges.get(after - 1) else {
381 continue;
382 };
383 if position < end && other != index {
384 return Err(overlapping(edits, other, index));
385 }
386 }
387 }
388
389 Ok(())
390}
391
392fn reject_first_overlap(ranges: &[(usize, usize, usize)], edits: &[Edit]) -> Result<(), PlanError> {
397 let mut furthest = 0;
398 let mut owner = usize::MAX;
399 for &(start, end, index) in ranges {
400 if start < furthest && owner != index {
401 return Err(overlapping(edits, owner, index));
402 }
403 if end > furthest {
404 furthest = end;
405 owner = index;
406 }
407 }
408 Ok(())
409}
410
411fn overlapping(edits: &[Edit], first: usize, second: usize) -> PlanError {
412 let describe_at = |index: usize| {
413 edits
414 .get(index)
415 .map_or_else(|| "unknown edit".to_owned(), describe)
416 };
417 PlanError::OverlappingEdits {
418 first: describe_at(first),
419 second: describe_at(second),
420 }
421}
422
423#[derive(Clone, Copy, PartialEq, Eq)]
424enum Unit {
425 Blocks,
426 Rows,
427}
428
429fn unit_indices(element: &Element, unit: Unit) -> Vec<usize> {
431 element
432 .children()
433 .iter()
434 .enumerate()
435 .filter(|(_, node)| match node {
436 Node::Element(child) => match unit {
437 Unit::Blocks => child.role().is_block(),
438 Unit::Rows => child.role() == Role::Row,
439 },
440 _ => false,
441 })
442 .map(|(index, _)| index)
443 .collect()
444}
445
446fn remove_range(
447 root: &mut Element,
448 parent: &NodePath,
449 range: &Range<usize>,
450 unit: Unit,
451 prefix: &str,
452) -> Result<(), ApplyError> {
453 let container = root
454 .at_mut(parent.as_slice())
455 .ok_or_else(|| ApplyError::MissingTarget {
456 path: parent.as_slice().to_vec(),
457 })?;
458
459 let indices = unit_indices(container, unit);
460 let selected: Vec<usize> = indices
461 .get(range.clone())
462 .map(<[usize]>::to_vec)
463 .unwrap_or_default();
464
465 if selected.is_empty() {
466 return Ok(());
467 }
468
469 if unit == Unit::Blocks && span_includes_section_properties(container, &selected) {
470 return Err(ApplyError::RangeIncludesSectionProperties {
471 path: parent.as_slice().to_vec(),
472 });
473 }
474
475 let last_row = if unit == Unit::Rows {
476 selected
477 .last()
478 .and_then(|index| container.children().get(*index))
479 .and_then(Node::as_element)
480 .cloned()
481 } else {
482 None
483 };
484
485 remove_children(container, &selected);
486
487 if container.role() == Role::Table && container.rows().next().is_none() {
488 let row = last_row.map_or_else(|| empty_row(prefix), |row| clear_row(&row, prefix));
489 container.push_child(Node::Element(row));
490 }
491
492 Ok(())
493}
494
495fn is_section_properties(container: &Element, index: usize) -> bool {
496 container
497 .children()
498 .get(index)
499 .and_then(Node::as_element)
500 .is_some_and(|element| element.role() == Role::SectionProps)
501}
502
503fn span_includes_section_properties(container: &Element, selected: &[usize]) -> bool {
505 let (Some(first), Some(last)) = (selected.first(), selected.last()) else {
506 return false;
507 };
508 (*first..=*last).any(|index| is_section_properties(container, index))
509}
510
511fn remove_children(container: &mut Element, indices: &[usize]) {
512 let mut children = container.children().to_vec();
513 for index in indices.iter().rev() {
514 if *index < children.len() {
515 children.remove(*index);
516 }
517 }
518 *container.children_mut() = children;
519}
520
521fn clear_row(row: &Element, prefix: &str) -> Element {
523 let mut row = row.clone();
524 for child in row.children_mut() {
525 if let Node::Element(cell) = child
526 && cell.role() == Role::Cell
527 {
528 let properties: Vec<Node> = cell
529 .children()
530 .iter()
531 .filter(|node| {
532 node.as_element()
533 .is_some_and(|element| element.role().is_property())
534 })
535 .cloned()
536 .collect();
537 let mut new_children = properties;
538 new_children.push(Node::Element(crate::domain::document::empty_paragraph(
539 prefix,
540 )));
541 *cell.children_mut() = new_children;
542 }
543 }
544 row
545}
546
547fn repeat(
548 root: &mut Element,
549 parent: &NodePath,
550 range: &Range<usize>,
551 iterations: &[Plan],
552 unit: Unit,
553 prefix: &str,
554 bookmarks: &mut BookmarkCounter,
555) -> Result<(), ApplyError> {
556 let container = root
557 .at_mut(parent.as_slice())
558 .ok_or_else(|| ApplyError::MissingTarget {
559 path: parent.as_slice().to_vec(),
560 })?;
561
562 let indices = unit_indices(container, unit);
563 let selected: Vec<usize> = indices
564 .get(range.clone())
565 .map(<[usize]>::to_vec)
566 .unwrap_or_default();
567
568 if selected.is_empty() {
569 return Ok(());
570 }
571
572 if unit == Unit::Blocks && span_includes_section_properties(container, &selected) {
573 return Err(ApplyError::RangeIncludesSectionProperties {
574 path: parent.as_slice().to_vec(),
575 });
576 }
577
578 let template: Vec<Node> = selected
579 .iter()
580 .filter_map(|index| container.children().get(*index).cloned())
581 .collect();
582
583 let mut output: Vec<Node> = Vec::new();
584 for plan in iterations {
585 let mut wrapper = container.clone();
586 *wrapper.children_mut() = template.clone();
587 apply_in_place(&mut wrapper, plan, prefix, bookmarks)?;
588 for node in wrapper.children() {
589 let mut node = node.clone();
590 if let Node::Element(element) = &mut node {
591 bookmarks.remap(element);
592 }
593 output.push(node);
594 }
595 }
596
597 let Some(insert_at) = selected.first().copied() else {
598 return Ok(());
599 };
600 let last_row = if unit == Unit::Rows && output.is_empty() {
601 selected
602 .last()
603 .and_then(|index| container.children().get(*index))
604 .and_then(Node::as_element)
605 .cloned()
606 } else {
607 None
608 };
609
610 remove_children(container, &selected);
611
612 let mut children = container.children().to_vec();
613 for (offset, node) in output.into_iter().enumerate() {
614 children.insert(insert_at + offset, node);
615 }
616 *container.children_mut() = children;
617
618 if container.role() == Role::Table && container.rows().next().is_none() {
619 let row = last_row.map_or_else(|| empty_row(prefix), |row| clear_row(&row, prefix));
620 container.push_child(Node::Element(row));
621 }
622
623 Ok(())
624}
625
626fn apply_text(
627 root: &mut Element,
628 target: &TextTarget,
629 fragments: &[InlineFragment],
630 preserve_space: bool,
631 prefix: &str,
632) -> Result<(), ApplyError> {
633 if target.slices.is_empty() {
634 return Ok(());
635 }
636
637 let has_paragraph_break = fragments
638 .iter()
639 .any(|fragment| matches!(fragment, InlineFragment::ParagraphBreak));
640 let has_inline_break = fragments
641 .iter()
642 .any(|fragment| matches!(fragment, InlineFragment::LineBreak | InlineFragment::Tab));
643
644 clear_other_slices(root, target)?;
647
648 if has_paragraph_break {
649 let text = fragments
650 .iter()
651 .map(InlineFragment::as_text)
652 .collect::<String>();
653 set_first_text(root, target, &text, preserve_space)?;
654 split_at_newlines(root, &target.paragraph)?;
655 return Ok(());
656 }
657
658 if has_inline_break {
659 rebuild_first_run(root, target, fragments, preserve_space, prefix)?;
660 prune_empty_runs(root, target, prefix)?;
661 return Ok(());
662 }
663
664 let text = fragments
665 .iter()
666 .map(InlineFragment::as_text)
667 .collect::<String>();
668 set_first_text(root, target, &text, preserve_space)?;
669 prune_empty_runs(root, target, prefix)
670}
671
672fn prune_empty_runs(
678 root: &mut Element,
679 target: &TextTarget,
680 prefix: &str,
681) -> Result<(), ApplyError> {
682 let paragraph =
683 root.at_mut(target.paragraph.as_slice())
684 .ok_or_else(|| ApplyError::MissingTarget {
685 path: target.paragraph.as_slice().to_vec(),
686 })?;
687
688 let mut covered: Vec<(&[usize], usize)> = Vec::with_capacity(target.slices.len());
689 for slice in &target.slices {
690 let Some((child_index, run_path)) = slice.element_path.split_last() else {
691 continue;
692 };
693 covered.push((run_path, *child_index));
694 }
695 covered.sort_unstable_by(|left, right| right.cmp(left));
697
698 for (run_path, child_index) in covered {
699 prune_one(paragraph, run_path, child_index);
700 }
701
702 let path = target.paragraph.as_slice();
703 let is_empty = root
704 .at(path)
705 .is_some_and(|paragraph| paragraph.children().is_empty());
706 if is_empty
707 && let Some((index, parent_path)) = path.split_last()
708 && let Some(parent) = root.at_mut(parent_path)
709 && let Some(slot) = parent.children_mut().get_mut(*index)
710 {
711 *slot = Node::Element(empty_paragraph(prefix));
712 }
713 Ok(())
714}
715
716fn prune_one(paragraph: &mut Element, run_path: &[usize], child_index: usize) {
717 let text_is_empty = paragraph
718 .at(run_path)
719 .and_then(|run| run.children().get(child_index))
720 .and_then(Node::as_element)
721 .is_some_and(|text| text.role() == Role::Text && text.text().is_empty());
722 if !text_is_empty {
723 return;
724 }
725
726 if let Some(run) = paragraph.at_mut(run_path)
727 && child_index < run.children().len()
728 {
729 run.children_mut().remove(child_index);
730 }
731
732 let run_is_empty = paragraph.at(run_path).is_some_and(|run| {
733 run.children().iter().all(|node| {
734 node.as_element()
735 .is_some_and(|element| element.role().is_property())
736 })
737 });
738 if !run_is_empty {
739 return;
740 }
741
742 if let Some((run_index, parent_path)) = run_path.split_last()
743 && let Some(parent) = paragraph.at_mut(parent_path)
744 && *run_index < parent.children().len()
745 {
746 parent.children_mut().remove(*run_index);
747 }
748}
749
750fn set_first_text(
752 root: &mut Element,
753 target: &TextTarget,
754 replacement: &str,
755 preserve_space: bool,
756) -> Result<(), ApplyError> {
757 let paragraph =
758 root.at_mut(target.paragraph.as_slice())
759 .ok_or_else(|| ApplyError::MissingTarget {
760 path: target.paragraph.as_slice().to_vec(),
761 })?;
762 let slice = target
763 .slices
764 .first()
765 .ok_or_else(|| ApplyError::MissingSlice {
766 path: target.paragraph.as_slice().to_vec(),
767 })?;
768 let node =
769 text_node_mut(paragraph, &slice.element_path, slice.node_index).ok_or_else(|| {
770 ApplyError::MissingSlice {
771 path: target.paragraph.as_slice().to_vec(),
772 }
773 })?;
774
775 let value = node.value().to_owned();
776 let before = value.get(..slice.start).unwrap_or_default();
777 let after = value.get(slice.end..).unwrap_or_default();
778 let text = format!("{before}{replacement}{after}");
779 node.set_value(text.clone());
780 node.set_preserve_space(preserve_space && has_edge_whitespace(&text));
781 Ok(())
782}
783
784fn clear_other_slices(root: &mut Element, target: &TextTarget) -> Result<(), ApplyError> {
786 let paragraph =
787 root.at_mut(target.paragraph.as_slice())
788 .ok_or_else(|| ApplyError::MissingTarget {
789 path: target.paragraph.as_slice().to_vec(),
790 })?;
791
792 for slice in target.slices.iter().skip(1) {
793 let node =
794 text_node_mut(paragraph, &slice.element_path, slice.node_index).ok_or_else(|| {
795 ApplyError::MissingSlice {
796 path: target.paragraph.as_slice().to_vec(),
797 }
798 })?;
799 let value = node.value().to_owned();
800 let before = value.get(..slice.start).unwrap_or_default();
801 let after = value.get(slice.end..).unwrap_or_default();
802 node.set_value(format!("{before}{after}"));
803 }
804
805 Ok(())
806}
807
808fn rebuild_first_run(
810 root: &mut Element,
811 target: &TextTarget,
812 fragments: &[InlineFragment],
813 preserve_space: bool,
814 prefix: &str,
815) -> Result<(), ApplyError> {
816 let paragraph =
817 root.at_mut(target.paragraph.as_slice())
818 .ok_or_else(|| ApplyError::MissingTarget {
819 path: target.paragraph.as_slice().to_vec(),
820 })?;
821 let Some(slice) = target.slices.first() else {
822 return Err(ApplyError::MissingSlice {
823 path: target.paragraph.as_slice().to_vec(),
824 });
825 };
826 let Some((child_index, run_path)) = slice.element_path.split_last() else {
827 return Err(ApplyError::MissingSlice {
828 path: target.paragraph.as_slice().to_vec(),
829 });
830 };
831
832 let run = paragraph
833 .at_mut(run_path)
834 .ok_or_else(|| ApplyError::MissingSlice {
835 path: target.paragraph.as_slice().to_vec(),
836 })?;
837 let Some(Node::Element(text_element)) = run.children().get(*child_index).cloned() else {
838 return Err(ApplyError::MissingSlice {
839 path: target.paragraph.as_slice().to_vec(),
840 });
841 };
842
843 let node = text_element
844 .children()
845 .get(slice.node_index)
846 .and_then(Node::as_text)
847 .ok_or_else(|| ApplyError::MissingSlice {
848 path: target.paragraph.as_slice().to_vec(),
849 })?;
850 let value = node.value().to_owned();
851 let before = value.get(..slice.start).unwrap_or_default().to_owned();
852 let after = value.get(slice.end..).unwrap_or_default().to_owned();
853
854 let mut segments: Vec<InlineFragment> = Vec::new();
857 push_text(&mut segments, &before);
858 for fragment in fragments {
859 match fragment {
860 InlineFragment::Text(text) => push_text(&mut segments, text),
861 other => segments.push(other.clone()),
862 }
863 }
864 push_text(&mut segments, &after);
865
866 let mut nodes: Vec<Node> = Vec::with_capacity(segments.len());
867 for segment in segments {
868 match segment {
869 InlineFragment::Text(text) => nodes.push(Node::Element(text_clone(
870 &text_element,
871 &text,
872 preserve_space,
873 ))),
874 InlineFragment::LineBreak => nodes.push(Node::Element(line_break_element(prefix))),
875 InlineFragment::Tab => nodes.push(Node::Element(break_element(prefix, "tab"))),
876 InlineFragment::ParagraphBreak => {}
877 }
878 }
879
880 let mut children = run.children().to_vec();
881 if *child_index < children.len() {
882 children.remove(*child_index);
883 for (offset, node) in nodes.into_iter().enumerate() {
884 children.insert(*child_index + offset, node);
885 }
886 }
887 *run.children_mut() = children;
888
889 Ok(())
890}
891
892fn push_text(segments: &mut Vec<InlineFragment>, text: &str) {
894 if text.is_empty() {
895 return;
896 }
897 if let Some(InlineFragment::Text(existing)) = segments.last_mut() {
898 existing.push_str(text);
899 } else {
900 segments.push(InlineFragment::Text(text.to_owned()));
901 }
902}
903
904fn text_clone(template: &Element, text: &str, preserve_space: bool) -> Element {
905 let mut element = template.clone();
906 let mut node = TextNode::generated(text.to_owned());
907 node.set_preserve_space(preserve_space && has_edge_whitespace(text));
908 *element.children_mut() = vec![Node::Text(node)];
909 element
910}
911
912fn break_element(prefix: &str, local: &str) -> Element {
913 Element::self_closing(
914 format!("{prefix}:{local}"),
915 Role::Opaque,
916 format!("<{prefix}:{local}/>").into_bytes(),
917 )
918}
919
920fn line_break_element(prefix: &str) -> Element {
922 Element::self_closing(
923 format!("{prefix}:br"),
924 Role::Opaque,
925 format!("<{prefix}:br {prefix}:type=\"textWrapping\"/>").into_bytes(),
926 )
927}
928
929fn has_edge_whitespace(text: &str) -> bool {
930 text.starts_with(char::is_whitespace) || text.ends_with(char::is_whitespace)
931}
932
933fn split_at_newlines(root: &mut Element, paragraph: &NodePath) -> Result<(), ApplyError> {
935 let path = paragraph.as_slice().to_vec();
936 let parent_path = path.split_last().map_or(&[][..], |(_, parent)| parent);
937 let index = path.last().copied().unwrap_or(0);
938 let mut current = index;
939
940 loop {
941 let element = root
942 .at(parent_path)
943 .and_then(|parent| parent.children().get(current))
944 .and_then(Node::as_element)
945 .ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
946
947 let projection = project(element);
948 let Some(position) = projection.text().find('\n') else {
949 break;
950 };
951 let slices = projection
952 .resolve(position, position + 1)
953 .map_err(|_| ApplyError::MissingSlice { path: path.clone() })?;
954 let Some(slice) = slices.first() else {
955 break;
956 };
957 let (child_index, run_path) = slice
958 .element_path
959 .split_last()
960 .map(|(child, run)| (*child, run.to_vec()))
961 .ok_or_else(|| ApplyError::MissingSlice { path: path.clone() })?;
962
963 let tail = {
964 let parent = root
965 .at_mut(parent_path)
966 .ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
967 let element = parent
968 .children_mut()
969 .get_mut(current)
970 .and_then(Node::as_element_mut)
971 .ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
972 split_paragraph(
973 element,
974 &run_path,
975 child_index,
976 slice.node_index,
977 slice.start,
978 )
979 };
980
981 let parent = root
982 .at_mut(parent_path)
983 .ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
984 let mut children = parent.children().to_vec();
985 children.insert(current + 1, Node::Element(tail));
986 *parent.children_mut() = children;
987 current += 1;
988 }
989
990 Ok(())
991}
992
993fn split_paragraph(
995 paragraph: &mut Element,
996 run_path: &[usize],
997 child_index: usize,
998 node_index: usize,
999 offset: usize,
1000) -> Element {
1001 let run_position = run_path.first().copied().unwrap_or(0);
1002 let mut tail = paragraph.clone();
1003
1004 if let Some(head_run) = paragraph.at_mut(run_path) {
1005 let head_children: Vec<Node> = head_run
1006 .children()
1007 .iter()
1008 .take(child_index + 1)
1009 .cloned()
1010 .collect();
1011 *head_run.children_mut() = head_children;
1012 truncate_text(head_run, child_index, node_index, offset);
1013 }
1014
1015 if let Some(tail_run) = tail.at_mut(run_path) {
1016 let mut tail_children: Vec<Node> = tail_run
1017 .children()
1018 .iter()
1019 .filter(|node| {
1020 node.as_element()
1021 .is_some_and(|element| element.role().is_property())
1022 })
1023 .cloned()
1024 .collect();
1025 tail_children.extend(tail_run.children().iter().skip(child_index).cloned());
1026 if let Some(Node::Element(text)) = tail_children.iter_mut().find(|node| {
1027 node.as_element()
1028 .is_some_and(|element| element.role() == Role::Text)
1029 }) {
1030 truncate_head(text, node_index, offset + 1);
1031 }
1032 *tail_run.children_mut() = tail_children;
1033 }
1034
1035 let properties: Vec<Node> = paragraph
1038 .children()
1039 .iter()
1040 .filter(|node| {
1041 node.as_element()
1042 .is_some_and(|element| element.role().is_property())
1043 })
1044 .cloned()
1045 .collect();
1046
1047 let mut tail_children = properties.clone();
1048 tail_children.extend(tail.children().iter().skip(run_position).cloned());
1049 *tail.children_mut() = tail_children;
1050
1051 let mut head_children = properties;
1052 head_children.extend(
1053 paragraph
1054 .children()
1055 .iter()
1056 .skip(run_position)
1057 .take(1)
1058 .cloned(),
1059 );
1060 *paragraph.children_mut() = head_children;
1061
1062 tail
1063}
1064
1065fn truncate_text(element: &mut Element, child_index: usize, node_index: usize, offset: usize) {
1066 if let Some(Node::Element(text)) = element.children_mut().get_mut(child_index)
1067 && let Some(Node::Text(node)) = text.children_mut().get_mut(node_index)
1068 {
1069 let value = node.value().to_owned();
1070 node.set_value(value.get(..offset).unwrap_or_default().to_owned());
1071 }
1072}
1073
1074fn truncate_head(element: &mut Element, node_index: usize, offset: usize) {
1075 if let Some(Node::Text(node)) = element.children_mut().get_mut(node_index) {
1076 let value = node.value().to_owned();
1077 node.set_value(value.get(offset..).unwrap_or_default().to_owned());
1078 }
1079}
1080
1081struct BookmarkCounter {
1083 next: u32,
1084}
1085
1086impl BookmarkCounter {
1087 fn scan(root: &Element) -> Self {
1088 Self {
1089 next: highest_bookmark_id(root).saturating_add(1),
1090 }
1091 }
1092
1093 fn remap(&mut self, element: &mut Element) {
1094 if is_bookmark(element.name())
1095 && let Some(id) = bookmark_id(element.raw_start())
1096 {
1097 let new_id = self.next;
1098 self.next = self.next.saturating_add(1);
1099 let raw = rewrite_bookmark_id(element.raw_start(), id, new_id);
1100 element.set_raw_start(raw);
1101 }
1102 for child in element.children_mut() {
1103 if let Node::Element(child) = child {
1104 self.remap(child);
1105 }
1106 }
1107 }
1108}
1109
1110fn is_bookmark(name: &str) -> bool {
1111 let local = name.rsplit(':').next().unwrap_or(name);
1112 matches!(local, "bookmarkStart" | "bookmarkEnd")
1113}
1114
1115fn bookmark_id(raw: &[u8]) -> Option<u32> {
1116 let text = String::from_utf8_lossy(raw);
1117 let marker = "w:id=\"";
1118 let start = text.find(marker)? + marker.len();
1119 let rest = &text[start..];
1120 let end = rest.find('"')?;
1121 rest[..end].parse().ok()
1122}
1123
1124fn rewrite_bookmark_id(raw: &[u8], old: u32, new: u32) -> Vec<u8> {
1125 let text = String::from_utf8_lossy(raw);
1126 let from = format!("w:id=\"{old}\"");
1127 let to = format!("w:id=\"{new}\"");
1128 text.replace(&from, &to).into_bytes()
1129}
1130
1131fn highest_bookmark_id(root: &Element) -> u32 {
1132 let mut highest = 0;
1133 walk_bookmarks(root, &mut highest);
1134 highest
1135}
1136
1137fn walk_bookmarks(element: &Element, highest: &mut u32) {
1138 if is_bookmark(element.name())
1139 && let Some(id) = bookmark_id(element.raw_start())
1140 {
1141 *highest = (*highest).max(id);
1142 }
1143 for child in element.children() {
1144 if let Node::Element(child) = child {
1145 walk_bookmarks(child, highest);
1146 }
1147 }
1148}
1149
1150pub(crate) fn normalize(root: &mut Element, document: &Document) {
1152 let prefix = document.word_prefix().to_owned();
1153 normalize_element(root, &prefix);
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158 #![allow(
1159 clippy::unwrap_used,
1160 clippy::expect_used,
1161 clippy::panic,
1162 clippy::indexing_slicing
1163 )]
1164
1165 use super::*;
1166 use crate::domain::document::TextNode;
1167
1168 fn element(name: &str, role: Role, children: Vec<Node>) -> Element {
1169 Element::new(
1170 name.to_owned(),
1171 role,
1172 format!("<{name}>").into_bytes(),
1173 format!("</{name}>").into_bytes(),
1174 false,
1175 children,
1176 )
1177 }
1178
1179 fn text(value: &str) -> Node {
1180 Node::Text(TextNode::original(
1181 value.as_bytes().to_vec(),
1182 value.to_owned(),
1183 ))
1184 }
1185
1186 fn run(value: &str) -> Node {
1187 Node::Element(element(
1188 "w:r",
1189 Role::Run,
1190 vec![Node::Element(element("w:t", Role::Text, vec![text(value)]))],
1191 ))
1192 }
1193
1194 fn paragraph(value: &str) -> Node {
1195 Node::Element(element("w:p", Role::Paragraph, vec![run(value)]))
1196 }
1197
1198 fn cell(paragraphs: Vec<Node>) -> Node {
1199 Node::Element(element("w:tc", Role::Cell, paragraphs))
1200 }
1201
1202 fn row(cells: Vec<Node>) -> Node {
1203 Node::Element(element("w:tr", Role::Row, cells))
1204 }
1205
1206 fn table(rows: Vec<Node>) -> Node {
1207 Node::Element(element("w:tbl", Role::Table, rows))
1208 }
1209
1210 fn body(children: Vec<Node>) -> Element {
1211 element("w:body", Role::Body, children)
1212 }
1213
1214 fn slice(path: Vec<usize>, start: usize, end: usize) -> ResolvedSlice {
1215 ResolvedSlice {
1216 element_path: path,
1217 node_index: 0,
1218 start,
1219 end,
1220 }
1221 }
1222
1223 fn text_edit(
1224 paragraph: Vec<usize>,
1225 slices: Vec<ResolvedSlice>,
1226 fragments: Vec<InlineFragment>,
1227 ) -> Edit {
1228 Edit::ReplaceText {
1229 target: TextTarget {
1230 paragraph: NodePath::new(paragraph),
1231 slices,
1232 },
1233 fragments,
1234 preserve_space: true,
1235 }
1236 }
1237
1238 fn plan(edits: Vec<Edit>) -> Plan {
1239 Plan::new(edits).unwrap()
1240 }
1241
1242 #[test]
1243 fn rejects_overlapping_ranges() {
1244 let error = Plan::new(vec![
1245 Edit::RemoveBlocks {
1246 parent: NodePath::new(vec![0]),
1247 range: 1..3,
1248 },
1249 Edit::RemoveBlocks {
1250 parent: NodePath::new(vec![0]),
1251 range: 2..4,
1252 },
1253 ])
1254 .unwrap_err();
1255 assert!(matches!(error, PlanError::OverlappingEdits { .. }));
1256 }
1257
1258 #[test]
1259 fn rejects_text_inside_a_removed_range() {
1260 let error = Plan::new(vec![
1261 Edit::RemoveBlocks {
1262 parent: NodePath::new(vec![0]),
1263 range: 0..2,
1264 },
1265 text_edit(vec![0, 1], vec![slice(vec![0, 0], 0, 1)], vec![]),
1266 ])
1267 .unwrap_err();
1268 assert!(matches!(error, PlanError::OverlappingEdits { .. }));
1269 }
1270
1271 #[test]
1272 fn rejects_overlapping_text_in_one_node() {
1273 let error = Plan::new(vec![
1274 text_edit(vec![0], vec![slice(vec![0, 0], 0, 5)], vec![]),
1275 text_edit(vec![0], vec![slice(vec![0, 0], 3, 8)], vec![]),
1276 ])
1277 .unwrap_err();
1278 assert!(matches!(error, PlanError::OverlappingEdits { .. }));
1279 }
1280
1281 #[test]
1282 fn accepts_thousands_of_disjoint_text_edits() {
1283 let edits = (0..5_000)
1284 .map(|index| text_edit(vec![index], vec![slice(vec![0, 0], 0, 8)], vec![]))
1285 .collect();
1286 assert!(Plan::new(edits).is_ok());
1287 }
1288
1289 #[test]
1290 fn reports_a_missing_target() {
1291 let root = body(vec![paragraph("hello")]);
1292 let plan = plan(vec![Edit::RemoveBlocks {
1293 parent: NodePath::new(vec![9]),
1294 range: 0..1,
1295 }]);
1296 assert!(matches!(
1297 apply(&root, &plan, "w"),
1298 Err(ApplyError::MissingTarget { .. })
1299 ));
1300 }
1301
1302 #[test]
1303 fn apply_order_does_not_matter() {
1304 let root = body(vec![paragraph("abcdefghij")]);
1305 let first = text_edit(
1306 vec![0],
1307 vec![slice(vec![0, 0], 0, 2)],
1308 vec![InlineFragment::Text("XY".to_owned())],
1309 );
1310 let second = text_edit(
1311 vec![0],
1312 vec![slice(vec![0, 0], 7, 9)],
1313 vec![InlineFragment::Text("PQ".to_owned())],
1314 );
1315
1316 let ascending = apply(&root, &plan(vec![first.clone(), second.clone()]), "w").unwrap();
1317 let descending = apply(&root, &plan(vec![second, first]), "w").unwrap();
1318 assert_eq!(ascending, descending);
1319 assert_eq!(ascending.text(), "XYcdefgPQj");
1320 }
1321
1322 #[test]
1323 fn text_edits_apply_right_to_left_when_lengths_change() {
1324 let root = body(vec![paragraph("a{{x}}b{{y}}c")]);
1325 let first = text_edit(
1326 vec![0],
1327 vec![slice(vec![0, 0], 1, 6)],
1328 vec![InlineFragment::Text("LONGER".to_owned())],
1329 );
1330 let second = text_edit(
1331 vec![0],
1332 vec![slice(vec![0, 0], 7, 12)],
1333 vec![InlineFragment::Text("Z".to_owned())],
1334 );
1335
1336 let ascending = apply(&root, &plan(vec![first.clone(), second.clone()]), "w").unwrap();
1337 let descending = apply(&root, &plan(vec![second, first]), "w").unwrap();
1338 assert_eq!(ascending, descending);
1339 assert_eq!(ascending.text(), "aLONGERbZc");
1340 }
1341
1342 #[test]
1343 fn repeat_produces_one_clone_per_iteration() {
1344 let root = body(vec![paragraph("{{name}}")]);
1345 let iteration = plan(vec![text_edit(
1346 vec![0],
1347 vec![slice(vec![0, 0], 0, 8)],
1348 vec![InlineFragment::Text("Ada".to_owned())],
1349 )]);
1350 let repeat = plan(vec![Edit::RepeatBlocks {
1351 parent: NodePath::new(vec![]),
1352 range: 0..1,
1353 iterations: vec![iteration.clone(), iteration],
1354 }]);
1355
1356 let rendered = apply(&root, &repeat, "w").unwrap();
1357 let blocks: Vec<&Element> = rendered.blocks().collect();
1358 assert_eq!(blocks.len(), 2);
1359 assert_eq!(blocks[0].text(), "Ada");
1360 assert_eq!(blocks[1].text(), "Ada");
1361 }
1362
1363 #[test]
1364 fn repeat_with_zero_iterations_removes_and_normalizes() {
1365 let root = body(vec![paragraph("gone")]);
1366 let repeat = plan(vec![Edit::RepeatBlocks {
1367 parent: NodePath::new(vec![]),
1368 range: 0..1,
1369 iterations: Vec::new(),
1370 }]);
1371
1372 let rendered = apply(&root, &repeat, "w").unwrap();
1373 let blocks: Vec<&Element> = rendered.blocks().collect();
1374 assert_eq!(blocks.len(), 1);
1375 assert_eq!(blocks[0].text(), "");
1376 }
1377
1378 #[test]
1379 fn an_emptied_table_keeps_one_empty_row() {
1380 let root = body(vec![table(vec![
1381 row(vec![cell(vec![paragraph("a")])]),
1382 row(vec![cell(vec![paragraph("b")])]),
1383 ])]);
1384 let repeat = plan(vec![Edit::RepeatRows {
1385 parent: NodePath::new(vec![0]),
1386 range: 0..2,
1387 iterations: Vec::new(),
1388 }]);
1389
1390 let rendered = apply(&root, &repeat, "w").unwrap();
1391 let table = rendered.blocks().next().unwrap();
1392 assert_eq!(table.rows().count(), 1);
1393 assert_eq!(table.rows().next().unwrap().text(), "");
1394 }
1395
1396 #[test]
1397 fn removing_section_properties_is_rejected() {
1398 let root = body(vec![
1399 paragraph("a"),
1400 Node::Element(element("w:sectPr", Role::SectionProps, vec![])),
1401 paragraph("b"),
1402 ]);
1403 let remove = plan(vec![Edit::RemoveBlocks {
1404 parent: NodePath::new(vec![]),
1405 range: 0..2,
1406 }]);
1407 assert!(matches!(
1408 apply(&root, &remove, "w"),
1409 Err(ApplyError::RangeIncludesSectionProperties { .. })
1410 ));
1411 }
1412
1413 #[test]
1414 fn cloned_bookmarks_get_unique_ids() {
1415 let bookmark = Node::Element(Element::self_closing(
1416 "w:bookmarkStart".to_owned(),
1417 Role::Opaque,
1418 br#"<w:bookmarkStart w:id="1" w:name="here"/>"#.to_vec(),
1419 ));
1420 let root = body(vec![Node::Element(element(
1421 "w:p",
1422 Role::Paragraph,
1423 vec![bookmark, run("x")],
1424 ))]);
1425 let repeat = plan(vec![Edit::RepeatBlocks {
1426 parent: NodePath::new(vec![]),
1427 range: 0..1,
1428 iterations: vec![Plan::empty(), Plan::empty()],
1429 }]);
1430
1431 let rendered = apply(&root, &repeat, "w").unwrap();
1432 let ids: Vec<u32> = rendered
1433 .blocks()
1434 .filter_map(|block| block.children().first())
1435 .filter_map(Node::as_element)
1436 .filter_map(|element| bookmark_id(element.raw_start()))
1437 .collect();
1438 assert_eq!(ids.len(), 2);
1439 assert_ne!(ids[0], ids[1]);
1440 assert!(ids.iter().all(|id| *id != 1));
1441 }
1442
1443 #[test]
1444 fn a_paragraph_break_splits_and_clones_properties() {
1445 let paragraph_properties = Node::Element(element("w:pPr", Role::ParagraphProps, vec![]));
1446 let run_properties = Node::Element(element("w:rPr", Role::RunProps, vec![]));
1447 let run_node = Node::Element(element(
1448 "w:r",
1449 Role::Run,
1450 vec![
1451 run_properties,
1452 Node::Element(element(
1453 "w:t",
1454 Role::Text,
1455 vec![text("Hello {{name}} world")],
1456 )),
1457 ],
1458 ));
1459 let root = body(vec![Node::Element(element(
1460 "w:p",
1461 Role::Paragraph,
1462 vec![paragraph_properties, run_node],
1463 ))]);
1464
1465 let edit = text_edit(
1466 vec![0],
1467 vec![slice(vec![1, 1], 6, 14)],
1468 vec![
1469 InlineFragment::Text("a".to_owned()),
1470 InlineFragment::ParagraphBreak,
1471 InlineFragment::Text("b".to_owned()),
1472 ],
1473 );
1474
1475 let rendered = apply(&root, &plan(vec![edit]), "w").unwrap();
1476 let blocks: Vec<&Element> = rendered.blocks().collect();
1477 assert_eq!(blocks.len(), 2);
1478 assert_eq!(blocks[0].text(), "Hello a");
1479 assert_eq!(blocks[1].text(), "b world");
1480 assert!(blocks[0].children().iter().any(|node| {
1481 node.as_element()
1482 .is_some_and(|e| e.role() == Role::ParagraphProps)
1483 }));
1484 assert!(blocks[1].children().iter().any(|node| {
1485 node.as_element()
1486 .is_some_and(|e| e.role() == Role::ParagraphProps)
1487 }));
1488 assert!(
1489 blocks[1]
1490 .children()
1491 .iter()
1492 .filter_map(Node::as_element)
1493 .any(|element| element.role() == Role::Run
1494 && element
1495 .children()
1496 .iter()
1497 .filter_map(Node::as_element)
1498 .any(|child| child.role() == Role::RunProps))
1499 );
1500 }
1501
1502 #[test]
1503 fn a_line_break_writes_a_word_break() {
1504 let root = body(vec![paragraph("a{{x}}b")]);
1505 let edit = text_edit(
1506 vec![0],
1507 vec![slice(vec![0, 0], 1, 6)],
1508 vec![
1509 InlineFragment::Text("one".to_owned()),
1510 InlineFragment::LineBreak,
1511 InlineFragment::Text("two".to_owned()),
1512 ],
1513 );
1514
1515 let rendered = apply(&root, &plan(vec![edit]), "w").unwrap();
1516 let paragraph = rendered.blocks().next().unwrap();
1517 let run = paragraph
1518 .children()
1519 .iter()
1520 .filter_map(Node::as_element)
1521 .find(|element| element.role() == Role::Run)
1522 .unwrap();
1523 let names: Vec<&str> = run
1524 .children()
1525 .iter()
1526 .filter_map(Node::as_element)
1527 .map(Element::name)
1528 .collect();
1529 assert!(names.contains(&"w:br"));
1530 assert_eq!(paragraph.text(), "aonetwob");
1531 }
1532}