use std::ops::Range;
use f_office_xml::{Document, NodeId};
use super::build::{is_other_story, prefix, text_element};
use super::{NamedError, NamedFault, Splice};
use crate::ns::{M, W};
const ONE_CHARACTER: [(&str, char); 4] =
[("tab", '\t'), ("ptab", '\t'), ("br", '\n'), ("cr", '\n')];
const NO_TEXT: [&str; 10] = [
"instrText",
"fldChar",
"sym",
"footnoteReference",
"endnoteReference",
"commentReference",
"noBreakHyphen",
"softHyphen",
"drawing",
"object",
];
const CONTAINERS: [&str; 5] = ["hyperlink", "sdt", "smartTag", "fldSimple", "customXml"];
const PROPERTIES: [&str; 4] = ["pPr", "rPr", "sdtPr", "sdtEndPr"];
struct Piece {
node: NodeId,
start: usize,
text: String,
containers: Vec<NodeId>,
}
struct Stop {
at: usize,
width: usize,
element: &'static str,
}
#[derive(Default)]
struct Walk {
text: String,
pieces: Vec<Piece>,
stops: Vec<Stop>,
equations: bool,
}
impl Walk {
fn of(doc: &Document, paragraph: NodeId) -> Self {
let mut walk = Self::default();
walk.visit(doc, paragraph, &mut Vec::new());
walk
}
fn visit(&mut self, doc: &Document, node: NodeId, containers: &mut Vec<NodeId>) {
for child in doc.child_elements(node) {
self.visit_element(doc, child, containers);
}
}
fn visit_element(&mut self, doc: &Document, node: NodeId, containers: &mut Vec<NodeId>) {
let local = doc
.element(node)
.map_or("", |element| element.name.local.as_str());
if doc.is(node, W, "t") {
let text = doc.text_content(node);
self.pieces.push(Piece {
node,
start: self.text.len(),
text: text.clone(),
containers: containers.clone(),
});
self.text.push_str(&text);
} else if let Some((element, character)) =
ONE_CHARACTER.iter().find(|(name, _)| doc.is(node, W, name))
{
self.stop(element, character.len_utf8());
self.text.push(*character);
} else if let Some(element) = NO_TEXT.iter().find(|name| doc.is(node, W, name)) {
self.stop(element, 0);
} else if doc.is(node, M, "oMath") || doc.is(node, M, "oMathPara") {
self.equations = true;
self.stop("oMath", 0);
} else if is_other_story(doc, node) {
self.stop("w:drawing", 0);
} else if PROPERTIES.iter().any(|name| doc.is(node, W, name)) {
} else if CONTAINERS.contains(&local) && doc.is(node, W, local) {
containers.push(node);
self.visit(doc, node, containers);
containers.pop();
} else {
self.visit(doc, node, containers);
}
}
fn stop(&mut self, element: &'static str, width: usize) {
let element = element_name(element);
self.stops.push(Stop {
at: self.text.len(),
width,
element,
});
}
fn find(&self, find: &str) -> Result<Range<usize>, NamedFault> {
let starts: Vec<usize> = self.text.match_indices(find).map(|(at, _)| at).collect();
match starts.as_slice() {
[] if self.equations => Err(NamedFault::TextNotFoundOutsideEquations),
[] => Err(NamedFault::TextNotFound),
[start] => Ok(*start..start + find.len()),
more => Err(NamedFault::TextAmbiguous { count: more.len() }),
}
}
fn check(&self, range: &Range<usize>, doc: &Document) -> Result<(), NamedFault> {
let crossed = self.stops.iter().find(|stop| {
if stop.width == 0 {
range.start < stop.at && stop.at < range.end
} else {
range.start <= stop.at && stop.at < range.end
}
});
if let Some(stop) = crossed {
return Err(NamedFault::MatchCrossesElement {
element: stop.element,
});
}
let mut touched = self.touched(range);
let Some(first) = touched.next() else {
return Ok(());
};
for piece in touched {
if piece.containers != first.containers {
let edge = first
.containers
.iter()
.zip(&piece.containers)
.find(|(a, b)| a != b)
.map(|(a, _)| *a)
.or_else(|| first.containers.last().copied())
.or_else(|| piece.containers.last().copied());
let element = edge
.and_then(|node| doc.element(node))
.map_or("w:hyperlink", |element| element_name(&element.name.local));
return Err(NamedFault::MatchCrossesEdge { element });
}
}
Ok(())
}
fn touched<'w>(&'w self, range: &'w Range<usize>) -> impl Iterator<Item = &'w Piece> + 'w {
self.pieces.iter().filter(move |piece| {
piece.start < range.end && range.start < piece.start + piece.text.len()
})
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct MatchEnd {
pub(super) node: NodeId,
pub(super) offset: usize,
pub(super) length: usize,
}
pub(super) fn match_ends(
doc: &Document,
paragraph: NodeId,
find: &str,
) -> Result<(MatchEnd, MatchEnd), NamedFault> {
if find.is_empty() {
return Err(NamedFault::EmptyFind);
}
let walk = Walk::of(doc, paragraph);
let range = walk.find(find)?;
walk.check(&range, doc)?;
let mut touched = walk.touched(&range);
let first = touched.next().ok_or(NamedFault::TextNotFound)?;
let last = touched.last().unwrap_or(first);
let end = |piece: &Piece, at: usize| MatchEnd {
node: piece.node,
offset: at - piece.start,
length: piece.text.len(),
};
Ok((end(first, range.start), end(last, range.end)))
}
fn element_name(local: &str) -> &'static str {
const NAMES: [&str; 21] = [
"w:tab",
"w:ptab",
"w:br",
"w:cr",
"w:instrText",
"w:fldChar",
"w:sym",
"w:footnoteReference",
"w:endnoteReference",
"w:commentReference",
"w:noBreakHyphen",
"w:softHyphen",
"w:drawing",
"w:object",
"w:hyperlink",
"w:sdt",
"w:smartTag",
"w:fldSimple",
"w:customXml",
"w:t",
"m:oMath",
];
let local = local.trim_start_matches("w:");
NAMES
.iter()
.find(|name| name.get(2..) == Some(local))
.copied()
.unwrap_or("w:drawing")
}
pub(super) fn check_characters(text: &str, tabs: bool) -> Result<(), NamedFault> {
match text
.chars()
.find(|&c| (c.is_control() && !(tabs && c == '\t')) || matches!(c, '\u{FFFE}' | '\u{FFFF}'))
{
Some(c) => Err(NamedFault::BadCharacter(c)),
None => Ok(()),
}
}
pub(super) fn replace(
doc: &Document,
paragraph: NodeId,
list: &[(usize, &str, &str)],
) -> Result<Vec<Splice>, NamedError> {
let at = |edit: usize| {
move |fault| NamedError {
edit: Some(edit),
fault,
}
};
let walk = Walk::of(doc, paragraph);
let mut matches: Vec<(Range<usize>, usize, &str)> = Vec::new();
for &(edit, find, with) in list {
let range = walk.find(find).map_err(at(edit))?;
walk.check(&range, doc).map_err(at(edit))?;
if let Some((_, other, _)) = matches
.iter()
.find(|(seen, _, _)| seen.start < range.end && range.start < seen.end)
{
return Err(NamedError {
edit: Some(edit),
fault: NamedFault::MatchesOverlap { other: *other },
});
}
matches.push((range, edit, with));
}
matches.sort_by_key(|(range, _, _)| range.start);
let w = prefix(doc, paragraph).map_err(at(list.first().map_or(0, |(edit, _, _)| *edit)))?;
let mut splices = Vec::new();
for piece in &walk.pieces {
let end = piece.start + piece.text.len();
let cuts: Vec<&(Range<usize>, usize, &str)> = matches
.iter()
.filter(|(range, _, _)| piece.start < range.end && range.start < end)
.collect();
let Some(first) = cuts.first() else {
continue;
};
let mut text = String::new();
let mut cursor = piece.start;
for (range, _, with) in &cuts {
let from = range.start.max(piece.start);
text.push_str(
piece
.text
.get(cursor - piece.start..from - piece.start)
.unwrap_or_default(),
);
if range.start >= piece.start {
text.push_str(with);
}
cursor = range.end.min(end);
}
text.push_str(piece.text.get(cursor - piece.start..).unwrap_or_default());
splices.push(Splice {
edit: first.1,
range: doc.span(piece.node).unwrap_or(0..0),
xml: text_element(&w, &text),
});
}
Ok(splices)
}