#![allow(dead_code)]
use std::collections::BTreeMap;
use std::ops::Range;
use crate::domain::document::projection::{ResolvedSlice, project, text_node_mut};
use crate::domain::document::{
Document, Element, Node, Role, TextNode, empty_paragraph, empty_row, normalize_element,
};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub(crate) struct NodePath(Vec<usize>);
impl NodePath {
pub(crate) fn new(path: Vec<usize>) -> Self {
Self(path)
}
pub(crate) fn as_slice(&self) -> &[usize] {
&self.0
}
pub(crate) fn parent(&self) -> Self {
let mut path = self.0.clone();
path.pop();
Self(path)
}
pub(crate) fn index(&self) -> usize {
self.0.last().copied().unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InlineFragment {
Text(String),
LineBreak,
ParagraphBreak,
Tab,
}
impl InlineFragment {
pub(crate) fn as_text(&self) -> &str {
match self {
InlineFragment::Text(text) => text,
InlineFragment::LineBreak | InlineFragment::ParagraphBreak => "\n",
InlineFragment::Tab => "\t",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TextTarget {
pub(crate) paragraph: NodePath,
pub(crate) slices: Vec<ResolvedSlice>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Edit {
ReplaceText {
target: TextTarget,
fragments: Vec<InlineFragment>,
preserve_space: bool,
},
RemoveBlocks {
parent: NodePath,
range: Range<usize>,
},
RemoveRows {
parent: NodePath,
range: Range<usize>,
},
RepeatBlocks {
parent: NodePath,
range: Range<usize>,
iterations: Vec<Plan>,
},
RepeatRows {
parent: NodePath,
range: Range<usize>,
iterations: Vec<Plan>,
},
}
#[derive(Debug, Clone, PartialEq, Default)]
pub(crate) struct Plan {
edits: Vec<Edit>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PlanError {
#[error("overlapping edits: {first} and {second}")]
OverlappingEdits {
first: String,
second: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum ApplyError {
#[error("missing target at path {path:?}")]
MissingTarget {
path: Vec<usize>,
},
#[error("removal at path {path:?} would delete section properties")]
RangeIncludesSectionProperties {
path: Vec<usize>,
},
#[error("text slice at {path:?} no longer resolves")]
MissingSlice {
path: Vec<usize>,
},
}
impl Plan {
pub(crate) fn new(edits: Vec<Edit>) -> Result<Self, PlanError> {
check_overlaps(&edits)?;
Ok(Self { edits })
}
pub(crate) fn empty() -> Self {
Self { edits: Vec::new() }
}
pub(crate) fn edits(&self) -> &[Edit] {
&self.edits
}
pub(crate) fn is_empty(&self) -> bool {
self.edits.is_empty()
}
}
pub(crate) fn apply(root: &Element, plan: &Plan, prefix: &str) -> Result<Element, ApplyError> {
let mut root = root.clone();
let mut bookmarks = BookmarkCounter::scan(&root);
apply_in_place(&mut root, plan, prefix, &mut bookmarks)?;
Ok(root)
}
fn apply_in_place(
root: &mut Element,
plan: &Plan,
prefix: &str,
bookmarks: &mut BookmarkCounter,
) -> Result<(), ApplyError> {
let mut order: Vec<usize> = (0..plan.edits.len()).collect();
order.sort_by(|left, right| {
plan.edits
.get(*right)
.map(key)
.cmp(&plan.edits.get(*left).map(key))
});
for index in order {
let Some(edit) = plan.edits.get(index) else {
continue;
};
match edit {
Edit::ReplaceText {
target,
fragments,
preserve_space,
} => apply_text(root, target, fragments, *preserve_space, prefix)?,
Edit::RemoveBlocks { parent, range } => {
remove_range(root, parent, range, Unit::Blocks, prefix)?;
}
Edit::RemoveRows { parent, range } => {
remove_range(root, parent, range, Unit::Rows, prefix)?;
}
Edit::RepeatBlocks {
parent,
range,
iterations,
} => repeat(
root,
parent,
range,
iterations,
Unit::Blocks,
prefix,
bookmarks,
)?,
Edit::RepeatRows {
parent,
range,
iterations,
} => repeat(
root,
parent,
range,
iterations,
Unit::Rows,
prefix,
bookmarks,
)?,
}
}
normalize_element(root, prefix);
Ok(())
}
fn key(edit: &Edit) -> Vec<usize> {
match edit {
Edit::ReplaceText { target, .. } => {
let mut path = target.paragraph.as_slice().to_vec();
let offset = target.slices.first().map_or(0, |slice| slice.start);
path.push(offset);
path
}
Edit::RemoveBlocks { parent, range }
| Edit::RemoveRows { parent, range }
| Edit::RepeatBlocks { parent, range, .. }
| Edit::RepeatRows { parent, range, .. } => {
let mut path = parent.as_slice().to_vec();
path.push(range.start);
path
}
}
}
fn describe(edit: &Edit) -> String {
match edit {
Edit::ReplaceText { target, .. } => format!("text at {:?}", target.paragraph.as_slice()),
Edit::RemoveBlocks { parent, range } => {
format!("blocks {:?} at {:?}", range, parent.as_slice())
}
Edit::RemoveRows { parent, range } => {
format!("rows {:?} at {:?}", range, parent.as_slice())
}
Edit::RepeatBlocks { parent, range, .. } => {
format!("repeated blocks {:?} at {:?}", range, parent.as_slice())
}
Edit::RepeatRows { parent, range, .. } => {
format!("repeated rows {:?} at {:?}", range, parent.as_slice())
}
}
}
type RangeRecord = (usize, usize, usize);
type TextKey = (Vec<usize>, Vec<usize>, usize);
fn check_overlaps(edits: &[Edit]) -> Result<(), PlanError> {
let mut block_ranges: BTreeMap<Vec<usize>, Vec<RangeRecord>> = BTreeMap::new();
let mut text_ranges: BTreeMap<TextKey, Vec<RangeRecord>> = BTreeMap::new();
for (index, edit) in edits.iter().enumerate() {
match edit {
Edit::RemoveBlocks { parent, range }
| Edit::RemoveRows { parent, range }
| Edit::RepeatBlocks { parent, range, .. }
| Edit::RepeatRows { parent, range, .. } => {
block_ranges
.entry(parent.as_slice().to_vec())
.or_default()
.push((range.start, range.end, index));
}
Edit::ReplaceText { target, .. } => {
for slice in &target.slices {
text_ranges
.entry((
target.paragraph.as_slice().to_vec(),
slice.element_path.clone(),
slice.node_index,
))
.or_default()
.push((slice.start, slice.end, index));
}
}
}
}
for ranges in block_ranges.values_mut() {
ranges.sort_unstable();
reject_first_overlap(ranges, edits)?;
}
for ranges in text_ranges.values_mut() {
ranges.sort_unstable();
reject_first_overlap(ranges, edits)?;
}
for (index, edit) in edits.iter().enumerate() {
let Edit::ReplaceText { target, .. } = edit else {
continue;
};
let paragraph = target.paragraph.as_slice();
for level in 0..paragraph.len() {
let Some(prefix) = paragraph.get(..level) else {
continue;
};
let Some(ranges) = block_ranges.get(prefix) else {
continue;
};
let Some(&position) = paragraph.get(level) else {
continue;
};
let after = ranges.partition_point(|(start, _, _)| *start <= position);
if after == 0 {
continue;
}
let Some(&(_, end, other)) = ranges.get(after - 1) else {
continue;
};
if position < end && other != index {
return Err(overlapping(edits, other, index));
}
}
}
Ok(())
}
fn reject_first_overlap(ranges: &[(usize, usize, usize)], edits: &[Edit]) -> Result<(), PlanError> {
let mut furthest = 0;
let mut owner = usize::MAX;
for &(start, end, index) in ranges {
if start < furthest && owner != index {
return Err(overlapping(edits, owner, index));
}
if end > furthest {
furthest = end;
owner = index;
}
}
Ok(())
}
fn overlapping(edits: &[Edit], first: usize, second: usize) -> PlanError {
let describe_at = |index: usize| {
edits
.get(index)
.map_or_else(|| "unknown edit".to_owned(), describe)
};
PlanError::OverlappingEdits {
first: describe_at(first),
second: describe_at(second),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Unit {
Blocks,
Rows,
}
fn unit_indices(element: &Element, unit: Unit) -> Vec<usize> {
element
.children()
.iter()
.enumerate()
.filter(|(_, node)| match node {
Node::Element(child) => match unit {
Unit::Blocks => child.role().is_block(),
Unit::Rows => child.role() == Role::Row,
},
_ => false,
})
.map(|(index, _)| index)
.collect()
}
fn remove_range(
root: &mut Element,
parent: &NodePath,
range: &Range<usize>,
unit: Unit,
prefix: &str,
) -> Result<(), ApplyError> {
let container = root
.at_mut(parent.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: parent.as_slice().to_vec(),
})?;
let indices = unit_indices(container, unit);
let selected: Vec<usize> = indices
.get(range.clone())
.map(<[usize]>::to_vec)
.unwrap_or_default();
if selected.is_empty() {
return Ok(());
}
if unit == Unit::Blocks && span_includes_section_properties(container, &selected) {
return Err(ApplyError::RangeIncludesSectionProperties {
path: parent.as_slice().to_vec(),
});
}
let last_row = if unit == Unit::Rows {
selected
.last()
.and_then(|index| container.children().get(*index))
.and_then(Node::as_element)
.cloned()
} else {
None
};
remove_children(container, &selected);
if container.role() == Role::Table && container.rows().next().is_none() {
let row = last_row.map_or_else(|| empty_row(prefix), |row| clear_row(&row, prefix));
container.push_child(Node::Element(row));
}
Ok(())
}
fn is_section_properties(container: &Element, index: usize) -> bool {
container
.children()
.get(index)
.and_then(Node::as_element)
.is_some_and(|element| element.role() == Role::SectionProps)
}
fn span_includes_section_properties(container: &Element, selected: &[usize]) -> bool {
let (Some(first), Some(last)) = (selected.first(), selected.last()) else {
return false;
};
(*first..=*last).any(|index| is_section_properties(container, index))
}
fn remove_children(container: &mut Element, indices: &[usize]) {
let mut children = container.children().to_vec();
for index in indices.iter().rev() {
if *index < children.len() {
children.remove(*index);
}
}
*container.children_mut() = children;
}
fn clear_row(row: &Element, prefix: &str) -> Element {
let mut row = row.clone();
for child in row.children_mut() {
if let Node::Element(cell) = child
&& cell.role() == Role::Cell
{
let properties: Vec<Node> = cell
.children()
.iter()
.filter(|node| {
node.as_element()
.is_some_and(|element| element.role().is_property())
})
.cloned()
.collect();
let mut new_children = properties;
new_children.push(Node::Element(crate::domain::document::empty_paragraph(
prefix,
)));
*cell.children_mut() = new_children;
}
}
row
}
fn repeat(
root: &mut Element,
parent: &NodePath,
range: &Range<usize>,
iterations: &[Plan],
unit: Unit,
prefix: &str,
bookmarks: &mut BookmarkCounter,
) -> Result<(), ApplyError> {
let container = root
.at_mut(parent.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: parent.as_slice().to_vec(),
})?;
let indices = unit_indices(container, unit);
let selected: Vec<usize> = indices
.get(range.clone())
.map(<[usize]>::to_vec)
.unwrap_or_default();
if selected.is_empty() {
return Ok(());
}
if unit == Unit::Blocks && span_includes_section_properties(container, &selected) {
return Err(ApplyError::RangeIncludesSectionProperties {
path: parent.as_slice().to_vec(),
});
}
let template: Vec<Node> = selected
.iter()
.filter_map(|index| container.children().get(*index).cloned())
.collect();
let mut output: Vec<Node> = Vec::new();
for plan in iterations {
let mut wrapper = container.clone();
*wrapper.children_mut() = template.clone();
apply_in_place(&mut wrapper, plan, prefix, bookmarks)?;
for node in wrapper.children() {
let mut node = node.clone();
if let Node::Element(element) = &mut node {
bookmarks.remap(element);
}
output.push(node);
}
}
let Some(insert_at) = selected.first().copied() else {
return Ok(());
};
let last_row = if unit == Unit::Rows && output.is_empty() {
selected
.last()
.and_then(|index| container.children().get(*index))
.and_then(Node::as_element)
.cloned()
} else {
None
};
remove_children(container, &selected);
let mut children = container.children().to_vec();
for (offset, node) in output.into_iter().enumerate() {
children.insert(insert_at + offset, node);
}
*container.children_mut() = children;
if container.role() == Role::Table && container.rows().next().is_none() {
let row = last_row.map_or_else(|| empty_row(prefix), |row| clear_row(&row, prefix));
container.push_child(Node::Element(row));
}
Ok(())
}
fn apply_text(
root: &mut Element,
target: &TextTarget,
fragments: &[InlineFragment],
preserve_space: bool,
prefix: &str,
) -> Result<(), ApplyError> {
if target.slices.is_empty() {
return Ok(());
}
let has_paragraph_break = fragments
.iter()
.any(|fragment| matches!(fragment, InlineFragment::ParagraphBreak));
let has_inline_break = fragments
.iter()
.any(|fragment| matches!(fragment, InlineFragment::LineBreak | InlineFragment::Tab));
clear_other_slices(root, target)?;
if has_paragraph_break {
let text = fragments
.iter()
.map(InlineFragment::as_text)
.collect::<String>();
set_first_text(root, target, &text, preserve_space)?;
split_at_newlines(root, &target.paragraph)?;
return Ok(());
}
if has_inline_break {
rebuild_first_run(root, target, fragments, preserve_space, prefix)?;
prune_empty_runs(root, target, prefix)?;
return Ok(());
}
let text = fragments
.iter()
.map(InlineFragment::as_text)
.collect::<String>();
set_first_text(root, target, &text, preserve_space)?;
prune_empty_runs(root, target, prefix)
}
fn prune_empty_runs(
root: &mut Element,
target: &TextTarget,
prefix: &str,
) -> Result<(), ApplyError> {
let paragraph =
root.at_mut(target.paragraph.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: target.paragraph.as_slice().to_vec(),
})?;
let mut covered: Vec<(&[usize], usize)> = Vec::with_capacity(target.slices.len());
for slice in &target.slices {
let Some((child_index, run_path)) = slice.element_path.split_last() else {
continue;
};
covered.push((run_path, *child_index));
}
covered.sort_unstable_by(|left, right| right.cmp(left));
for (run_path, child_index) in covered {
prune_one(paragraph, run_path, child_index);
}
let path = target.paragraph.as_slice();
let is_empty = root
.at(path)
.is_some_and(|paragraph| paragraph.children().is_empty());
if is_empty
&& let Some((index, parent_path)) = path.split_last()
&& let Some(parent) = root.at_mut(parent_path)
&& let Some(slot) = parent.children_mut().get_mut(*index)
{
*slot = Node::Element(empty_paragraph(prefix));
}
Ok(())
}
fn prune_one(paragraph: &mut Element, run_path: &[usize], child_index: usize) {
let text_is_empty = paragraph
.at(run_path)
.and_then(|run| run.children().get(child_index))
.and_then(Node::as_element)
.is_some_and(|text| text.role() == Role::Text && text.text().is_empty());
if !text_is_empty {
return;
}
if let Some(run) = paragraph.at_mut(run_path)
&& child_index < run.children().len()
{
run.children_mut().remove(child_index);
}
let run_is_empty = paragraph.at(run_path).is_some_and(|run| {
run.children().iter().all(|node| {
node.as_element()
.is_some_and(|element| element.role().is_property())
})
});
if !run_is_empty {
return;
}
if let Some((run_index, parent_path)) = run_path.split_last()
&& let Some(parent) = paragraph.at_mut(parent_path)
&& *run_index < parent.children().len()
{
parent.children_mut().remove(*run_index);
}
}
fn set_first_text(
root: &mut Element,
target: &TextTarget,
replacement: &str,
preserve_space: bool,
) -> Result<(), ApplyError> {
let paragraph =
root.at_mut(target.paragraph.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: target.paragraph.as_slice().to_vec(),
})?;
let slice = target
.slices
.first()
.ok_or_else(|| ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
})?;
let node =
text_node_mut(paragraph, &slice.element_path, slice.node_index).ok_or_else(|| {
ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
}
})?;
let value = node.value().to_owned();
let before = value.get(..slice.start).unwrap_or_default();
let after = value.get(slice.end..).unwrap_or_default();
let text = format!("{before}{replacement}{after}");
node.set_value(text.clone());
node.set_preserve_space(preserve_space && has_edge_whitespace(&text));
Ok(())
}
fn clear_other_slices(root: &mut Element, target: &TextTarget) -> Result<(), ApplyError> {
let paragraph =
root.at_mut(target.paragraph.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: target.paragraph.as_slice().to_vec(),
})?;
for slice in target.slices.iter().skip(1) {
let node =
text_node_mut(paragraph, &slice.element_path, slice.node_index).ok_or_else(|| {
ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
}
})?;
let value = node.value().to_owned();
let before = value.get(..slice.start).unwrap_or_default();
let after = value.get(slice.end..).unwrap_or_default();
node.set_value(format!("{before}{after}"));
}
Ok(())
}
fn rebuild_first_run(
root: &mut Element,
target: &TextTarget,
fragments: &[InlineFragment],
preserve_space: bool,
prefix: &str,
) -> Result<(), ApplyError> {
let paragraph =
root.at_mut(target.paragraph.as_slice())
.ok_or_else(|| ApplyError::MissingTarget {
path: target.paragraph.as_slice().to_vec(),
})?;
let Some(slice) = target.slices.first() else {
return Err(ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
});
};
let Some((child_index, run_path)) = slice.element_path.split_last() else {
return Err(ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
});
};
let run = paragraph
.at_mut(run_path)
.ok_or_else(|| ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
})?;
let Some(Node::Element(text_element)) = run.children().get(*child_index).cloned() else {
return Err(ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
});
};
let node = text_element
.children()
.get(slice.node_index)
.and_then(Node::as_text)
.ok_or_else(|| ApplyError::MissingSlice {
path: target.paragraph.as_slice().to_vec(),
})?;
let value = node.value().to_owned();
let before = value.get(..slice.start).unwrap_or_default().to_owned();
let after = value.get(slice.end..).unwrap_or_default().to_owned();
let mut segments: Vec<InlineFragment> = Vec::new();
push_text(&mut segments, &before);
for fragment in fragments {
match fragment {
InlineFragment::Text(text) => push_text(&mut segments, text),
other => segments.push(other.clone()),
}
}
push_text(&mut segments, &after);
let mut nodes: Vec<Node> = Vec::with_capacity(segments.len());
for segment in segments {
match segment {
InlineFragment::Text(text) => nodes.push(Node::Element(text_clone(
&text_element,
&text,
preserve_space,
))),
InlineFragment::LineBreak => nodes.push(Node::Element(line_break_element(prefix))),
InlineFragment::Tab => nodes.push(Node::Element(break_element(prefix, "tab"))),
InlineFragment::ParagraphBreak => {}
}
}
let mut children = run.children().to_vec();
if *child_index < children.len() {
children.remove(*child_index);
for (offset, node) in nodes.into_iter().enumerate() {
children.insert(*child_index + offset, node);
}
}
*run.children_mut() = children;
Ok(())
}
fn push_text(segments: &mut Vec<InlineFragment>, text: &str) {
if text.is_empty() {
return;
}
if let Some(InlineFragment::Text(existing)) = segments.last_mut() {
existing.push_str(text);
} else {
segments.push(InlineFragment::Text(text.to_owned()));
}
}
fn text_clone(template: &Element, text: &str, preserve_space: bool) -> Element {
let mut element = template.clone();
let mut node = TextNode::generated(text.to_owned());
node.set_preserve_space(preserve_space && has_edge_whitespace(text));
*element.children_mut() = vec![Node::Text(node)];
element
}
fn break_element(prefix: &str, local: &str) -> Element {
Element::self_closing(
format!("{prefix}:{local}"),
Role::Opaque,
format!("<{prefix}:{local}/>").into_bytes(),
)
}
fn line_break_element(prefix: &str) -> Element {
Element::self_closing(
format!("{prefix}:br"),
Role::Opaque,
format!("<{prefix}:br {prefix}:type=\"textWrapping\"/>").into_bytes(),
)
}
fn has_edge_whitespace(text: &str) -> bool {
text.starts_with(char::is_whitespace) || text.ends_with(char::is_whitespace)
}
fn split_at_newlines(root: &mut Element, paragraph: &NodePath) -> Result<(), ApplyError> {
let path = paragraph.as_slice().to_vec();
let parent_path = path.split_last().map_or(&[][..], |(_, parent)| parent);
let index = path.last().copied().unwrap_or(0);
let mut current = index;
loop {
let element = root
.at(parent_path)
.and_then(|parent| parent.children().get(current))
.and_then(Node::as_element)
.ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
let projection = project(element);
let Some(position) = projection.text().find('\n') else {
break;
};
let slices = projection
.resolve(position, position + 1)
.map_err(|_| ApplyError::MissingSlice { path: path.clone() })?;
let Some(slice) = slices.first() else {
break;
};
let (child_index, run_path) = slice
.element_path
.split_last()
.map(|(child, run)| (*child, run.to_vec()))
.ok_or_else(|| ApplyError::MissingSlice { path: path.clone() })?;
let tail = {
let parent = root
.at_mut(parent_path)
.ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
let element = parent
.children_mut()
.get_mut(current)
.and_then(Node::as_element_mut)
.ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
split_paragraph(
element,
&run_path,
child_index,
slice.node_index,
slice.start,
)
};
let parent = root
.at_mut(parent_path)
.ok_or_else(|| ApplyError::MissingTarget { path: path.clone() })?;
let mut children = parent.children().to_vec();
children.insert(current + 1, Node::Element(tail));
*parent.children_mut() = children;
current += 1;
}
Ok(())
}
fn split_paragraph(
paragraph: &mut Element,
run_path: &[usize],
child_index: usize,
node_index: usize,
offset: usize,
) -> Element {
let run_position = run_path.first().copied().unwrap_or(0);
let mut tail = paragraph.clone();
if let Some(head_run) = paragraph.at_mut(run_path) {
let head_children: Vec<Node> = head_run
.children()
.iter()
.take(child_index + 1)
.cloned()
.collect();
*head_run.children_mut() = head_children;
truncate_text(head_run, child_index, node_index, offset);
}
if let Some(tail_run) = tail.at_mut(run_path) {
let mut tail_children: Vec<Node> = tail_run
.children()
.iter()
.filter(|node| {
node.as_element()
.is_some_and(|element| element.role().is_property())
})
.cloned()
.collect();
tail_children.extend(tail_run.children().iter().skip(child_index).cloned());
if let Some(Node::Element(text)) = tail_children.iter_mut().find(|node| {
node.as_element()
.is_some_and(|element| element.role() == Role::Text)
}) {
truncate_head(text, node_index, offset + 1);
}
*tail_run.children_mut() = tail_children;
}
let properties: Vec<Node> = paragraph
.children()
.iter()
.filter(|node| {
node.as_element()
.is_some_and(|element| element.role().is_property())
})
.cloned()
.collect();
let mut tail_children = properties.clone();
tail_children.extend(tail.children().iter().skip(run_position).cloned());
*tail.children_mut() = tail_children;
let mut head_children = properties;
head_children.extend(
paragraph
.children()
.iter()
.skip(run_position)
.take(1)
.cloned(),
);
*paragraph.children_mut() = head_children;
tail
}
fn truncate_text(element: &mut Element, child_index: usize, node_index: usize, offset: usize) {
if let Some(Node::Element(text)) = element.children_mut().get_mut(child_index)
&& let Some(Node::Text(node)) = text.children_mut().get_mut(node_index)
{
let value = node.value().to_owned();
node.set_value(value.get(..offset).unwrap_or_default().to_owned());
}
}
fn truncate_head(element: &mut Element, node_index: usize, offset: usize) {
if let Some(Node::Text(node)) = element.children_mut().get_mut(node_index) {
let value = node.value().to_owned();
node.set_value(value.get(offset..).unwrap_or_default().to_owned());
}
}
struct BookmarkCounter {
next: u32,
}
impl BookmarkCounter {
fn scan(root: &Element) -> Self {
Self {
next: highest_bookmark_id(root).saturating_add(1),
}
}
fn remap(&mut self, element: &mut Element) {
if is_bookmark(element.name())
&& let Some(id) = bookmark_id(element.raw_start())
{
let new_id = self.next;
self.next = self.next.saturating_add(1);
let raw = rewrite_bookmark_id(element.raw_start(), id, new_id);
element.set_raw_start(raw);
}
for child in element.children_mut() {
if let Node::Element(child) = child {
self.remap(child);
}
}
}
}
fn is_bookmark(name: &str) -> bool {
let local = name.rsplit(':').next().unwrap_or(name);
matches!(local, "bookmarkStart" | "bookmarkEnd")
}
fn bookmark_id(raw: &[u8]) -> Option<u32> {
let text = String::from_utf8_lossy(raw);
let marker = "w:id=\"";
let start = text.find(marker)? + marker.len();
let rest = &text[start..];
let end = rest.find('"')?;
rest[..end].parse().ok()
}
fn rewrite_bookmark_id(raw: &[u8], old: u32, new: u32) -> Vec<u8> {
let text = String::from_utf8_lossy(raw);
let from = format!("w:id=\"{old}\"");
let to = format!("w:id=\"{new}\"");
text.replace(&from, &to).into_bytes()
}
fn highest_bookmark_id(root: &Element) -> u32 {
let mut highest = 0;
walk_bookmarks(root, &mut highest);
highest
}
fn walk_bookmarks(element: &Element, highest: &mut u32) {
if is_bookmark(element.name())
&& let Some(id) = bookmark_id(element.raw_start())
{
*highest = (*highest).max(id);
}
for child in element.children() {
if let Node::Element(child) = child {
walk_bookmarks(child, highest);
}
}
}
pub(crate) fn normalize(root: &mut Element, document: &Document) {
let prefix = document.word_prefix().to_owned();
normalize_element(root, &prefix);
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::*;
use crate::domain::document::TextNode;
fn element(name: &str, role: Role, children: Vec<Node>) -> Element {
Element::new(
name.to_owned(),
role,
format!("<{name}>").into_bytes(),
format!("</{name}>").into_bytes(),
false,
children,
)
}
fn text(value: &str) -> Node {
Node::Text(TextNode::original(
value.as_bytes().to_vec(),
value.to_owned(),
))
}
fn run(value: &str) -> Node {
Node::Element(element(
"w:r",
Role::Run,
vec![Node::Element(element("w:t", Role::Text, vec![text(value)]))],
))
}
fn paragraph(value: &str) -> Node {
Node::Element(element("w:p", Role::Paragraph, vec![run(value)]))
}
fn cell(paragraphs: Vec<Node>) -> Node {
Node::Element(element("w:tc", Role::Cell, paragraphs))
}
fn row(cells: Vec<Node>) -> Node {
Node::Element(element("w:tr", Role::Row, cells))
}
fn table(rows: Vec<Node>) -> Node {
Node::Element(element("w:tbl", Role::Table, rows))
}
fn body(children: Vec<Node>) -> Element {
element("w:body", Role::Body, children)
}
fn slice(path: Vec<usize>, start: usize, end: usize) -> ResolvedSlice {
ResolvedSlice {
element_path: path,
node_index: 0,
start,
end,
}
}
fn text_edit(
paragraph: Vec<usize>,
slices: Vec<ResolvedSlice>,
fragments: Vec<InlineFragment>,
) -> Edit {
Edit::ReplaceText {
target: TextTarget {
paragraph: NodePath::new(paragraph),
slices,
},
fragments,
preserve_space: true,
}
}
fn plan(edits: Vec<Edit>) -> Plan {
Plan::new(edits).unwrap()
}
#[test]
fn rejects_overlapping_ranges() {
let error = Plan::new(vec![
Edit::RemoveBlocks {
parent: NodePath::new(vec![0]),
range: 1..3,
},
Edit::RemoveBlocks {
parent: NodePath::new(vec![0]),
range: 2..4,
},
])
.unwrap_err();
assert!(matches!(error, PlanError::OverlappingEdits { .. }));
}
#[test]
fn rejects_text_inside_a_removed_range() {
let error = Plan::new(vec![
Edit::RemoveBlocks {
parent: NodePath::new(vec![0]),
range: 0..2,
},
text_edit(vec![0, 1], vec![slice(vec![0, 0], 0, 1)], vec![]),
])
.unwrap_err();
assert!(matches!(error, PlanError::OverlappingEdits { .. }));
}
#[test]
fn rejects_overlapping_text_in_one_node() {
let error = Plan::new(vec![
text_edit(vec![0], vec![slice(vec![0, 0], 0, 5)], vec![]),
text_edit(vec![0], vec![slice(vec![0, 0], 3, 8)], vec![]),
])
.unwrap_err();
assert!(matches!(error, PlanError::OverlappingEdits { .. }));
}
#[test]
fn accepts_thousands_of_disjoint_text_edits() {
let edits = (0..5_000)
.map(|index| text_edit(vec![index], vec![slice(vec![0, 0], 0, 8)], vec![]))
.collect();
assert!(Plan::new(edits).is_ok());
}
#[test]
fn reports_a_missing_target() {
let root = body(vec![paragraph("hello")]);
let plan = plan(vec![Edit::RemoveBlocks {
parent: NodePath::new(vec![9]),
range: 0..1,
}]);
assert!(matches!(
apply(&root, &plan, "w"),
Err(ApplyError::MissingTarget { .. })
));
}
#[test]
fn apply_order_does_not_matter() {
let root = body(vec![paragraph("abcdefghij")]);
let first = text_edit(
vec![0],
vec![slice(vec![0, 0], 0, 2)],
vec![InlineFragment::Text("XY".to_owned())],
);
let second = text_edit(
vec![0],
vec![slice(vec![0, 0], 7, 9)],
vec![InlineFragment::Text("PQ".to_owned())],
);
let ascending = apply(&root, &plan(vec![first.clone(), second.clone()]), "w").unwrap();
let descending = apply(&root, &plan(vec![second, first]), "w").unwrap();
assert_eq!(ascending, descending);
assert_eq!(ascending.text(), "XYcdefgPQj");
}
#[test]
fn text_edits_apply_right_to_left_when_lengths_change() {
let root = body(vec![paragraph("a{{x}}b{{y}}c")]);
let first = text_edit(
vec![0],
vec![slice(vec![0, 0], 1, 6)],
vec![InlineFragment::Text("LONGER".to_owned())],
);
let second = text_edit(
vec![0],
vec![slice(vec![0, 0], 7, 12)],
vec![InlineFragment::Text("Z".to_owned())],
);
let ascending = apply(&root, &plan(vec![first.clone(), second.clone()]), "w").unwrap();
let descending = apply(&root, &plan(vec![second, first]), "w").unwrap();
assert_eq!(ascending, descending);
assert_eq!(ascending.text(), "aLONGERbZc");
}
#[test]
fn repeat_produces_one_clone_per_iteration() {
let root = body(vec![paragraph("{{name}}")]);
let iteration = plan(vec![text_edit(
vec![0],
vec![slice(vec![0, 0], 0, 8)],
vec![InlineFragment::Text("Ada".to_owned())],
)]);
let repeat = plan(vec![Edit::RepeatBlocks {
parent: NodePath::new(vec![]),
range: 0..1,
iterations: vec![iteration.clone(), iteration],
}]);
let rendered = apply(&root, &repeat, "w").unwrap();
let blocks: Vec<&Element> = rendered.blocks().collect();
assert_eq!(blocks.len(), 2);
assert_eq!(blocks[0].text(), "Ada");
assert_eq!(blocks[1].text(), "Ada");
}
#[test]
fn repeat_with_zero_iterations_removes_and_normalizes() {
let root = body(vec![paragraph("gone")]);
let repeat = plan(vec![Edit::RepeatBlocks {
parent: NodePath::new(vec![]),
range: 0..1,
iterations: Vec::new(),
}]);
let rendered = apply(&root, &repeat, "w").unwrap();
let blocks: Vec<&Element> = rendered.blocks().collect();
assert_eq!(blocks.len(), 1);
assert_eq!(blocks[0].text(), "");
}
#[test]
fn an_emptied_table_keeps_one_empty_row() {
let root = body(vec![table(vec![
row(vec![cell(vec![paragraph("a")])]),
row(vec![cell(vec![paragraph("b")])]),
])]);
let repeat = plan(vec![Edit::RepeatRows {
parent: NodePath::new(vec![0]),
range: 0..2,
iterations: Vec::new(),
}]);
let rendered = apply(&root, &repeat, "w").unwrap();
let table = rendered.blocks().next().unwrap();
assert_eq!(table.rows().count(), 1);
assert_eq!(table.rows().next().unwrap().text(), "");
}
#[test]
fn removing_section_properties_is_rejected() {
let root = body(vec![
paragraph("a"),
Node::Element(element("w:sectPr", Role::SectionProps, vec![])),
paragraph("b"),
]);
let remove = plan(vec![Edit::RemoveBlocks {
parent: NodePath::new(vec![]),
range: 0..2,
}]);
assert!(matches!(
apply(&root, &remove, "w"),
Err(ApplyError::RangeIncludesSectionProperties { .. })
));
}
#[test]
fn cloned_bookmarks_get_unique_ids() {
let bookmark = Node::Element(Element::self_closing(
"w:bookmarkStart".to_owned(),
Role::Opaque,
br#"<w:bookmarkStart w:id="1" w:name="here"/>"#.to_vec(),
));
let root = body(vec![Node::Element(element(
"w:p",
Role::Paragraph,
vec![bookmark, run("x")],
))]);
let repeat = plan(vec![Edit::RepeatBlocks {
parent: NodePath::new(vec![]),
range: 0..1,
iterations: vec![Plan::empty(), Plan::empty()],
}]);
let rendered = apply(&root, &repeat, "w").unwrap();
let ids: Vec<u32> = rendered
.blocks()
.filter_map(|block| block.children().first())
.filter_map(Node::as_element)
.filter_map(|element| bookmark_id(element.raw_start()))
.collect();
assert_eq!(ids.len(), 2);
assert_ne!(ids[0], ids[1]);
assert!(ids.iter().all(|id| *id != 1));
}
#[test]
fn a_paragraph_break_splits_and_clones_properties() {
let paragraph_properties = Node::Element(element("w:pPr", Role::ParagraphProps, vec![]));
let run_properties = Node::Element(element("w:rPr", Role::RunProps, vec![]));
let run_node = Node::Element(element(
"w:r",
Role::Run,
vec![
run_properties,
Node::Element(element(
"w:t",
Role::Text,
vec![text("Hello {{name}} world")],
)),
],
));
let root = body(vec![Node::Element(element(
"w:p",
Role::Paragraph,
vec![paragraph_properties, run_node],
))]);
let edit = text_edit(
vec![0],
vec![slice(vec![1, 1], 6, 14)],
vec![
InlineFragment::Text("a".to_owned()),
InlineFragment::ParagraphBreak,
InlineFragment::Text("b".to_owned()),
],
);
let rendered = apply(&root, &plan(vec![edit]), "w").unwrap();
let blocks: Vec<&Element> = rendered.blocks().collect();
assert_eq!(blocks.len(), 2);
assert_eq!(blocks[0].text(), "Hello a");
assert_eq!(blocks[1].text(), "b world");
assert!(blocks[0].children().iter().any(|node| {
node.as_element()
.is_some_and(|e| e.role() == Role::ParagraphProps)
}));
assert!(blocks[1].children().iter().any(|node| {
node.as_element()
.is_some_and(|e| e.role() == Role::ParagraphProps)
}));
assert!(
blocks[1]
.children()
.iter()
.filter_map(Node::as_element)
.any(|element| element.role() == Role::Run
&& element
.children()
.iter()
.filter_map(Node::as_element)
.any(|child| child.role() == Role::RunProps))
);
}
#[test]
fn a_line_break_writes_a_word_break() {
let root = body(vec![paragraph("a{{x}}b")]);
let edit = text_edit(
vec![0],
vec![slice(vec![0, 0], 1, 6)],
vec![
InlineFragment::Text("one".to_owned()),
InlineFragment::LineBreak,
InlineFragment::Text("two".to_owned()),
],
);
let rendered = apply(&root, &plan(vec![edit]), "w").unwrap();
let paragraph = rendered.blocks().next().unwrap();
let run = paragraph
.children()
.iter()
.filter_map(Node::as_element)
.find(|element| element.role() == Role::Run)
.unwrap();
let names: Vec<&str> = run
.children()
.iter()
.filter_map(Node::as_element)
.map(Element::name)
.collect();
assert!(names.contains(&"w:br"));
assert_eq!(paragraph.text(), "aonetwob");
}
}